Path: blob/master/src/packages/frontend/editors/slate/edit-bar/marks.ts
1697 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { debounce } from "lodash";6import { useIsMountedRef, useMemo, useState } from "@cocalc/frontend/app-framework";7import { Editor } from "slate";8import { ReactEditor } from "../slate-react";910export interface Marks {11[mark: string]: boolean | undefined;12}1314export function getMarks(editor) {15try {16return Editor.marks(editor) ?? {};17} catch (err) {18// If the selection is at a non-leaf node somehow,19// then marks aren't defined and raises an error.20//console.log("Editor.marks", err);21return {};22}23}2425export const useMarks = (editor) => {26const isMountedRef = useIsMountedRef();2728const [marks, setMarks] = useState<Marks>(getMarks(editor));2930const updateMarks = useMemo(() => {31const f = () => {32if (!isMountedRef.current) return;33// NOTE: important to debounce, and that this update happens34// sometime in the near future and not immediately on any change!35// Don't do it in the update loop where it is requested36// since that causes issues, e.g.., try to move cursor out37// of a code block.38if (!ReactEditor.isFocused(editor)) {39setMarks({});40} else {41setMarks(getMarks(editor));42}43};44// We debounce to avoid any potential performance implications while45// typing and for the reason mentioned in the NOTE above. leading=false46// is the default, but I just want to be very clear about that below.47return debounce(f, 200, { leading: true }) as typeof f;48}, []);4950return { marks, updateMarks };51};525354