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