Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/elements/checkbox/editable.tsx
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 React from "react";
7
import { FOCUSED_COLOR } from "../../util";
8
import { Editor, Transforms } from "slate";
9
import { register, RenderElementProps } from "../register";
10
import { useFocused, useSelected, useSlate } from "../hooks";
11
import { Checkbox } from "antd";
12
import { useSetElement } from "../set-element";
13
14
const Element: React.FC<RenderElementProps> = ({
15
attributes,
16
children,
17
element,
18
}) => {
19
if (element.type != "checkbox") {
20
throw Error("bug");
21
}
22
const focused = useFocused();
23
const selected = useSelected();
24
const editor = useSlate();
25
const setElement = useSetElement(editor, element);
26
27
const border =
28
focused && selected
29
? `1px solid ${FOCUSED_COLOR}`
30
: `1px solid transparent`;
31
32
return (
33
<span {...attributes}>
34
<Checkbox
35
style={{
36
border,
37
padding: "0 0.2em 0.2em 0.2em",
38
verticalAlign: "middle",
39
}}
40
checked={!!element.value}
41
onChange={(e) => {
42
setElement({ value: e.target.checked });
43
}}
44
/>
45
{children}
46
</span>
47
);
48
};
49
50
register({
51
slateType: "checkbox",
52
Element,
53
fromSlate: ({ node }) => `[${node.value ? "x" : " "}]`,
54
});
55
56
// Call this function to toggle the checked state of the checkbox...
57
// if it is currently selected. This is called elsewhere in our
58
// code when user hits the space bar, thus making it possible to
59
// toggle checkboxes from the keyboard. Returns true if it toggles
60
// a checkbox and false otherwise.
61
export function toggleCheckbox(editor: Editor): boolean {
62
let checkbox;
63
try {
64
checkbox = Editor.nodes(editor, {
65
match: (node) => node["type"] == "checkbox",
66
mode: "lowest",
67
}).next().value;
68
} catch (_) {
69
// this happens, when e.g., next() doesn't work due to
70
// change in document/focus wrt to what editor assumes.
71
return false;
72
}
73
if (checkbox != null && checkbox[0]["type"] == "checkbox") {
74
// toggle checkbox checked state
75
const value = !checkbox[0]["value"];
76
// @ts-ignore
77
Transforms.setNodes(editor, { value }, { at: checkbox[1] });
78
return true;
79
}
80
return false;
81
}
82
83