Path: blob/master/src/packages/frontend/editors/slate/elements/checkbox/editable.tsx
1698 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import React from "react";6import { FOCUSED_COLOR } from "../../util";7import { Editor, Transforms } from "slate";8import { register, RenderElementProps } from "../register";9import { useFocused, useSelected, useSlate } from "../hooks";10import { Checkbox } from "antd";11import { useSetElement } from "../set-element";1213const Element: React.FC<RenderElementProps> = ({14attributes,15children,16element,17}) => {18if (element.type != "checkbox") {19throw Error("bug");20}21const focused = useFocused();22const selected = useSelected();23const editor = useSlate();24const setElement = useSetElement(editor, element);2526const border =27focused && selected28? `1px solid ${FOCUSED_COLOR}`29: `1px solid transparent`;3031return (32<span {...attributes}>33<Checkbox34style={{35border,36padding: "0 0.2em 0.2em 0.2em",37verticalAlign: "middle",38}}39checked={!!element.value}40onChange={(e) => {41setElement({ value: e.target.checked });42}}43/>44{children}45</span>46);47};4849register({50slateType: "checkbox",51Element,52fromSlate: ({ node }) => `[${node.value ? "x" : " "}]`,53});5455// Call this function to toggle the checked state of the checkbox...56// if it is currently selected. This is called elsewhere in our57// code when user hits the space bar, thus making it possible to58// toggle checkboxes from the keyboard. Returns true if it toggles59// a checkbox and false otherwise.60export function toggleCheckbox(editor: Editor): boolean {61let checkbox;62try {63checkbox = Editor.nodes(editor, {64match: (node) => node["type"] == "checkbox",65mode: "lowest",66}).next().value;67} catch (_) {68// this happens, when e.g., next() doesn't work due to69// change in document/focus wrt to what editor assumes.70return false;71}72if (checkbox != null && checkbox[0]["type"] == "checkbox") {73// toggle checkbox checked state74const value = !checkbox[0]["value"];75// @ts-ignore76Transforms.setNodes(editor, { value }, { at: checkbox[1] });77return true;78}79return false;80}818283