Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/edit-bar/marks.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
import { debounce } from "lodash";
7
import { useIsMountedRef, useMemo, useState } from "@cocalc/frontend/app-framework";
8
import { Editor } from "slate";
9
import { ReactEditor } from "../slate-react";
10
11
export interface Marks {
12
[mark: string]: boolean | undefined;
13
}
14
15
export function getMarks(editor) {
16
try {
17
return Editor.marks(editor) ?? {};
18
} catch (err) {
19
// If the selection is at a non-leaf node somehow,
20
// then marks aren't defined and raises an error.
21
//console.log("Editor.marks", err);
22
return {};
23
}
24
}
25
26
export const useMarks = (editor) => {
27
const isMountedRef = useIsMountedRef();
28
29
const [marks, setMarks] = useState<Marks>(getMarks(editor));
30
31
const updateMarks = useMemo(() => {
32
const f = () => {
33
if (!isMountedRef.current) return;
34
// NOTE: important to debounce, and that this update happens
35
// sometime in the near future and not immediately on any change!
36
// Don't do it in the update loop where it is requested
37
// since that causes issues, e.g.., try to move cursor out
38
// of a code block.
39
if (!ReactEditor.isFocused(editor)) {
40
setMarks({});
41
} else {
42
setMarks(getMarks(editor));
43
}
44
};
45
// We debounce to avoid any potential performance implications while
46
// typing and for the reason mentioned in the NOTE above. leading=false
47
// is the default, but I just want to be very clear about that below.
48
return debounce(f, 200, { leading: true }) as typeof f;
49
}, []);
50
51
return { marks, updateMarks };
52
};
53
54