Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/elements/details/editable.tsx
1702 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 { useEffect, useRef, useState } from "react";
7
import { register } from "../register";
8
import { Details } from "./index";
9
import { useSlate } from "../hooks";
10
import { useSetElement } from "../set-element";
11
12
import { STYLE } from "./index";
13
14
register({
15
slateType: "details",
16
17
Element: ({ attributes, children, element }) => {
18
const node = element as Details;
19
const ref = useRef<any>(undefined);
20
const [open, setOpen] = useState<boolean>(!!node.open);
21
useEffect(() => {
22
if (open != node.open) {
23
setOpen(!!node.open);
24
}
25
}, [node.open]);
26
const editor = useSlate();
27
const setElement = useSetElement(editor, element);
28
const details = (
29
<details
30
ref={ref}
31
style={STYLE}
32
open={open}
33
onToggle={() => {
34
if (ref.current?.open != open) {
35
setOpen(!open);
36
setElement({ open: !open });
37
}
38
}}
39
>
40
{node.summary /* whiteSpace inherits something weird from some css */ && (
41
<summary
42
contentEditable={false}
43
style={{
44
whiteSpace: "normal",
45
cursor: "pointer",
46
display: "list-item",
47
}}
48
>
49
{node.summary}
50
</summary>
51
)}
52
{children}
53
</details>
54
);
55
return node.isInline ? (
56
<span {...attributes}>{details}</span>
57
) : (
58
<div {...attributes}>{details}</div>
59
);
60
},
61
62
fromSlate: ({ node, children }) => {
63
return `<details${node.open ? " open" : ""}>${
64
node.summary ? "\n <summary>" + node.summary + "</summary>" : ""
65
}${node.isInline ? "" : "\n\n"}${children.trim()}${
66
node.isInline ? "" : "\n\n"
67
}</details>${node.isInline ? "" : "\n\n"}`;
68
},
69
});
70
71