Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/format/insert-link.ts
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 { Transforms, Element } from "slate";
7
import {
8
get_insert_link_opts_from_user,
9
Options,
10
} from "@cocalc/frontend/codemirror/extensions/insert-link";
11
import { alert_message } from "@cocalc/frontend/alerts";
12
import { getSelection, selectionToText } from "./commands";
13
import { delay } from "awaiting";
14
15
export async function insertLink(editor): Promise<void> {
16
let opts: Options | undefined = undefined;
17
// insertLink is typically called from formatAction, which
18
// restores the selection -- however, that restore doesn't
19
// impact the DOM until the next render loop. Since the whole
20
// insertLink is async and involves a modal dialog, it's fine
21
// to wait until the DOM selection is set before getting
22
// the selected text (otherwise it is blank).
23
await delay(0);
24
try {
25
opts = await get_insert_link_opts_from_user(selectionToText(editor), false);
26
} catch (err) {
27
alert_message({ type: "error", message: err.errorFields[0]?.errors });
28
return;
29
}
30
if (opts == null) return; // user canceled.
31
32
const node = {
33
type: "link",
34
isInline: true,
35
url: opts.url,
36
title: opts.title,
37
children: [{ text: opts.displayed_text }],
38
} as Element;
39
Transforms.insertFragment(editor, [node], { at: getSelection(editor) });
40
}
41
42