Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/slate-util.ts
1691 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
import { Node, Location, Editor, Element, Range, Path } from "slate";
7
8
export function containingBlock(editor: Editor): undefined | [Node, Location] {
9
for (const x of Editor.nodes(editor, {
10
match: (node) => Element.isElement(node) && Editor.isBlock(editor, node),
11
})) {
12
return x;
13
}
14
}
15
16
export function getNodeAt(editor: Editor, path: Path): undefined | Node {
17
try {
18
return Editor.node(editor, path)[0];
19
} catch (_) {
20
return;
21
}
22
}
23
24
// Range that contains the entire document.
25
export function rangeAll(editor: Editor): Range {
26
const first = Editor.first(editor, []);
27
const last = Editor.last(editor, []);
28
const offset = last[0]["text"]?.length ?? 0; // TODO: not 100% that this is right
29
return {
30
anchor: { path: first[1], offset: 0 },
31
focus: { path: last[1], offset },
32
};
33
}
34
35
// Range that goes from selection focus to
36
// end of the document.
37
export function rangeToEnd(editor: Editor): Range {
38
if (editor.selection == null) return rangeAll(editor);
39
const last = Editor.last(editor, []);
40
const offset = last[0]["text"]?.length ?? 0;
41
return {
42
anchor: editor.selection.focus,
43
focus: { path: last[1], offset },
44
};
45
}
46
47
export function rangeFromStart(editor: Editor): Range {
48
if (editor.selection == null) return rangeAll(editor);
49
const first = Editor.first(editor, []);
50
return {
51
anchor: { path: first[1], offset: 0 },
52
focus: editor.selection.focus,
53
};
54
}
55
56