Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerAttachmentInsertion.ts

106 lines4.3 KB

1import type { Editor, EditorEvents } from "@tiptap/core";
2import {
3 flatToMarkdown,
4 flatToPm,
5 markdownToFlat,
6 pmToFlat,
7 serializeEditorDoc,
8} from "../composer-rich-text-doc";
9import {
10 type ComposerContextReference,
11 formatInlineContextReference,
12 inlineContextReferenceReplacement,
13} from "../lib/composerContextReferences";
14import { markAsClipboardEdit } from "../composer-undo-grouping";
15​
16const INSERTION_ORDER_META = "composerAttachmentInsertionOrder";
17let nextInsertionOrder = 0;
18​
19export function captureComposerAttachmentInsertion(editor: Editor, readDraftKey: () => string) {
20 const order = nextInsertionOrder++;
21 const draftKey = readDraftKey();
22 let { from, to } = editor.state.selection;
23 let lost = false;
24 let doc = editor.state.doc;
25 // Switching threads swaps the draft without a transaction, so positions follow only this
26 // draft's edits and carry across a swap back through its unchanged Markdown.
27 const followDraft = (current: typeof doc) => {
28 if (readDraftKey() !== draftKey) return false;
29 if (current === doc) return true;
30 const before = serializeEditorDoc(doc);
31 const after = serializeEditorDoc(current);
32 const carry = (pos: number) =>
33 flatToPm(after, markdownToFlat(after, flatToMarkdown(before, pmToFlat(before, pos))));
34 lost ||= before.value !== after.value;
35 from = carry(from);
36 to = carry(to);
37 doc = current;
38 return true;
39 };
40 const track = ({ transaction, appendedTransactions }: EditorEvents["transaction"]) => {
41 for (const tr of [transaction, ...appendedTransactions]) {
42 if (!followDraft(tr.before)) continue;
43 doc = tr.doc;
44 // Stay before text typed at the paste point, but after an earlier capture's references.
45 const insertion: { order: number; from: number; end: number } | undefined =
46 tr.getMeta(INSERTION_ORDER_META);
47 const followsEarlier = insertion !== undefined && insertion.order < order;
48 const start = tr.mapping.mapResult(from, followsEarlier ? 1 : -1);
49 const end = tr.mapping.mapResult(to, followsEarlier ? 1 : -1);
50 // Replacing the following space maps its start left regardless of association.
51 if (followsEarlier && from === to && from === insertion.from) {
52 from = to = insertion.end;
53 continue;
54 }
55 // A replacement spanning the paste point (such as a controlled setContent) leaves no
56 // position to keep, so the caller falls back to the current caret.
57 lost ||= start.deletedAcross || end.deletedAcross;
58 from = start.pos;
59 to = start.deletedAfter || end.deletedBefore ? from : end.pos;
60 }
61 };
62 editor.on("transaction", track);
63 const dispose = () => {
64 editor.off("transaction", track);
65 };
66 return {
67 insert: (references: ReadonlyArray<ComposerContextReference>): boolean => {
68 dispose();
69 if (editor.isDestroyed || !followDraft(editor.state.doc)) return false;
70 if (lost || references.length === 0) return false;
71 const nodeType = editor.schema.nodes["composer-context-reference"];
72 if (!nodeType) return false;
73 const map = serializeEditorDoc(editor.state.doc);
74 const edit = inlineContextReferenceReplacement(
75 map.value,
76 {
77 start: flatToMarkdown(map, pmToFlat(map, from)),
78 end: flatToMarkdown(map, pmToFlat(map, to)),
79 },
80 references,
81 );
82 const acceptsReference =
83 editor.state.doc.resolve(from).parent.type.contentMatch.matchType(nodeType) !== null;
84 const content = acceptsReference
85 ? references.flatMap((reference) => [
86 nodeType.create({ ...reference, source: formatInlineContextReference(reference) }),
87 editor.schema.text(" "),
88 ])
89 : [editor.schema.text(edit.text)];
90 if (acceptsReference && edit.text.startsWith(" ")) content.unshift(editor.schema.text(" "));
91 const replaceEnd = flatToPm(map, markdownToFlat(map, edit.end));
92 const tr = editor.state.tr.replaceWith(from, replaceEnd, content);
93 editor.view.dispatch(
94 markAsClipboardEdit(tr, "paste").setMeta(INSERTION_ORDER_META, {
95 order,
96 from,
97 end: tr.mapping.map(replaceEnd, 1),
98 }),
99 );
100 return true;
101 },
102 dispose,
103 };
105​
106export type ComposerAttachmentInsertion = ReturnType<typeof captureComposerAttachmentInsertion>;