Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/keyboard/shift-enter.ts
1697 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
// What happens when you hit shift+enter key.
7
8
import { Editor, Node, Transforms } from "slate";
9
import { isElementOfType } from "../elements";
10
import { register } from "./register";
11
import { hardbreak } from "../elements/break";
12
import { isWhitespaceParagraph, isWhitespaceText } from "../padding";
13
14
register({ key: "Enter", shift: true }, ({ editor, extra }) => {
15
// Configured editor so shift+enter does some action, e.g., "submit chat".
16
// In this case, we do that instead of the various things below involving
17
// newlines, which can instead be done with control+enter.
18
const shiftEnter = extra?.actions?.shiftEnter;
19
if (shiftEnter != null) {
20
shiftEnter(editor.getMarkdownValue());
21
return true;
22
}
23
return softBreak({ editor });
24
});
25
26
function softBreak({ editor }) {
27
// In a table, the only option is to insert a <br/>.
28
const fragment = editor.getFragment();
29
if (isElementOfType(fragment?.[0], "table")) {
30
const br = {
31
isInline: true,
32
isVoid: true,
33
type: "html_inline",
34
html: "<br />",
35
children: [{ text: " " }],
36
} as Node;
37
Transforms.insertNodes(editor, [br]);
38
// Also, move cursor forward so it is *after* the br.
39
Transforms.move(editor, { distance: 1 });
40
return true;
41
}
42
43
// Not in a table, so possibly insert a hard break instead of a new
44
// paragraph...
45
const prev = Editor.previous(editor);
46
if (prev == null) return false;
47
if (isWhitespaceParagraph(prev[0])) {
48
// do nothing.
49
return true;
50
}
51
if (isElementOfType(prev[0], "hardbreak")) {
52
// do nothing
53
return true;
54
}
55
if (isWhitespaceText(prev[0])) {
56
const prev2 = Editor.previous(editor, { at: prev[1] });
57
if (prev2 != null && isElementOfType(prev2[0], "hardbreak")) {
58
// do nothing
59
return true;
60
}
61
}
62
Transforms.insertNodes(editor, [hardbreak()]);
63
Transforms.move(editor, { distance: 1 });
64
return true;
65
}
66
67
register({ key: "Enter", ctrl: true }, softBreak);
68
69