Path: blob/master/src/packages/frontend/editors/slate/format/insert-link.ts
1698 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { Transforms, Element } from "slate";6import {7get_insert_link_opts_from_user,8Options,9} from "@cocalc/frontend/codemirror/extensions/insert-link";10import { alert_message } from "@cocalc/frontend/alerts";11import { getSelection, selectionToText } from "./commands";12import { delay } from "awaiting";1314export async function insertLink(editor): Promise<void> {15let opts: Options | undefined = undefined;16// insertLink is typically called from formatAction, which17// restores the selection -- however, that restore doesn't18// impact the DOM until the next render loop. Since the whole19// insertLink is async and involves a modal dialog, it's fine20// to wait until the DOM selection is set before getting21// the selected text (otherwise it is blank).22await delay(0);23try {24opts = await get_insert_link_opts_from_user(selectionToText(editor), false);25} catch (err) {26alert_message({ type: "error", message: err.errorFields[0]?.errors });27return;28}29if (opts == null) return; // user canceled.3031const node = {32type: "link",33isInline: true,34url: opts.url,35title: opts.title,36children: [{ text: opts.displayed_text }],37} as Element;38Transforms.insertFragment(editor, [node], { at: getSelection(editor) });39}404142