Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/format/delete-backward.ts
1698 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 { Range, Editor, Element, Path, Point, Text, Transforms } from "slate";
7
8
export const withDeleteBackward = (editor) => {
9
const { deleteBackward } = editor;
10
11
editor.deleteBackward = (...args) => {
12
if (!customDeleteBackwards(editor)) {
13
// no custom handling, so just do the default:
14
deleteBackward(...args);
15
}
16
};
17
18
return editor;
19
};
20
21
function customDeleteBackwards(editor: Editor): boolean | undefined {
22
// Figure out first if we should so something special:
23
const { selection } = editor;
24
if (selection == null || !Range.isCollapsed(selection)) return;
25
26
const above = Editor.above(editor, {
27
match: (node) => Element.isElement(node) && Editor.isBlock(editor, node) && node.type != "paragraph",
28
});
29
if (above == null) return;
30
const [block, path] = above;
31
if (Editor.isEditor(block) || !Element.isElement(block)) {
32
return;
33
}
34
const start = Editor.start(editor, path);
35
if (!Point.equals(selection.anchor, start)) return;
36
37
// This is where we actually might do something special, finally.
38
// Cursor is at the beginning of a non-paragraph block-level
39
// element, so maybe do something special.
40
switch (block.type) {
41
case "heading":
42
deleteBackwardsHeading(editor, block, path);
43
return true;
44
}
45
}
46
47
// Special handling at beginning of heading.
48
function deleteBackwardsHeading(editor: Editor, block: Element, path: Path) {
49
if (Text.isText(block.children[0])) {
50
Transforms.setNodes(
51
editor,
52
{
53
type: "paragraph",
54
},
55
{ at: path }
56
);
57
} else {
58
Transforms.unwrapNodes(editor, {
59
match: (node) => Element.isElement(node),
60
split: true,
61
mode: "lowest",
62
at: path,
63
});
64
}
65
}
66
67