Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/patches.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 { Editor, Node } from "slate";
7
8
// The version of isNodeList in slate is **insanely** slow, and this hack
9
// is likely to be sufficient for our use.
10
// This makes a MASSIVE different for larger documents!
11
Node.isNodeList = (value: any): value is Node[] => {
12
return Array.isArray(value) && (value?.length == 0 || Node.isNode(value[0]));
13
};
14
15
// I have seen cocalc.com crash in production randomly when editing markdown
16
// when calling range. I think this happens when computing decorators, so
17
// it is way better to make it non-fatal for now.
18
export const withNonfatalRange = (editor) => {
19
const { range } = editor;
20
21
editor.range = (editor, at, to?) => {
22
try {
23
return range(editor, at, to);
24
} catch (err) {
25
console.log(`WARNING: range error ${err}`);
26
const anchor = Editor.first(editor, []);
27
return { anchor, focus: anchor };
28
}
29
};
30
31
return editor;
32
};
33
34
// We patch the Editor.string command so that if the input
35
// location is invalid, it returns "" instead of crashing.
36
// This is useful, since Editor.string is mainly used
37
// for heuristic selection adjustment, copy, etc.
38
// In theory it should never get invalid input, but due to
39
// the loose nature of Slate, it's difficult to ensure this.
40
const unpatchedEditorString = Editor.string;
41
Editor.string = function (...args): string {
42
try {
43
return unpatchedEditorString(...args);
44
} catch (err) {
45
console.warn("WARNING: slate Editor.string -- invalid range", err);
46
return "";
47
}
48
};
49
50