Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/edit-bar/link-url.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 { useMemo, useState } from "@cocalc/frontend/app-framework";
8
import { Editor, Element, Range, Transforms } from "slate";
9
10
function getLinkURL(editor): string | undefined {
11
const { selection } = editor;
12
if (selection == null || !Range.isCollapsed(selection)) {
13
return;
14
}
15
try {
16
for (const [node] of Editor.nodes(editor, {
17
match: (node) => Element.isElement(node) && node.type == "link",
18
})) {
19
// @ts-ignore
20
return node.url;
21
}
22
} catch (_err) {
23
// This can happen right when the actual editor is closing...
24
return;
25
}
26
}
27
28
export function setLinkURL(editor, url: string): void {
29
const { selection } = editor;
30
if (selection == null || !Range.isCollapsed(selection)) {
31
return;
32
}
33
try {
34
for (const [, path] of Editor.nodes(editor, {
35
match: (node) => Element.isElement(node) && node.type == "link",
36
})) {
37
Transforms.setNodes(editor, { url }, { at: path });
38
return;
39
}
40
} catch (_err) {
41
// This can happen right when the actual editor is closing...
42
}
43
}
44
45
export const useLinkURL = (editor) => {
46
const [linkURL, setLinkURLState] = useState<string | undefined>(
47
getLinkURL(editor)
48
);
49
50
const updateLinkURL = useMemo(() => {
51
const f = () => {
52
setLinkURLState(getLinkURL(editor));
53
};
54
// We debounce to avoid any potential performance implications while
55
// typing and for the reason mentioned in the NOTE above.
56
return debounce(f, 200, { leading: true }) as typeof f;
57
}, []);
58
59
return { linkURL, updateLinkURL };
60
};
61
62