Open History to see the last commit
1import { closeHistory, isHistoryTransaction } from "@tiptap/pm/history";
2import type { Transaction } from "@tiptap/pm/state";
3import { ReplaceStep } from "@tiptap/pm/transform";
4
5// Whole-draft rewrites make all edits adjacent; explicit boundaries keep change kinds separate.
6export const COMPOSER_UNDO_GROUP_DELAY = 1000;
7
8export type ComposerChangeKind = "insert" | "delete" | "other";
9
10const CLIPBOARD_EDIT_META = "composerClipboardEdit";
11const COMPOSITION_REPLACE_META = "composerCompositionReplace";
12
13/** Tag custom paste/cut dispatches; ProseMirror only tags its built-in paths. */
14export function markAsClipboardEdit(tr: Transaction, event: "paste" | "cut"): Transaction {
15 return tr.setMeta(CLIPBOARD_EDIT_META, event);
16}
17
18export function isPasteTransaction(tr: Transaction): boolean {
19 return tr.getMeta("uiEvent") === "paste" || tr.getMeta(CLIPBOARD_EDIT_META) === "paste";
20}
21
22/** Start a replacement undo group, keeping the IME edits together and prior typing separate. */
23export function markAsCompositionReplace(tr: Transaction): Transaction {
24 return closeHistory(tr).setMeta(COMPOSITION_REPLACE_META, true);
25}
26
27function changeKindOf(tr: Transaction): ComposerChangeKind | null {
28 if (!tr.docChanged) return null;
29 const uiEvent = tr.getMeta("uiEvent");
30 if (uiEvent === "paste" || uiEvent === "drop" || uiEvent === "cut") return "other";
31 if (tr.getMeta(CLIPBOARD_EDIT_META) != null) return "other";
32 // IME input replaces its own range on each keystroke; it is still typing.
33 if (tr.getMeta("composition") != null || tr.getMeta(COMPOSITION_REPLACE_META)) return "insert";
34 let kind: ComposerChangeKind | null = null;
35 for (const step of tr.steps) {
36 if (!(step instanceof ReplaceStep)) return "other";
37 const inserts = step.slice.size > 0;
38 const deletes = step.to > step.from;
39 const stepKind = inserts && !deletes ? "insert" : deletes && !inserts ? "delete" : "other";
40 if (kind !== null && kind !== stepKind) return "other";
41 kind = stepKind;
42 }
43 return kind;
44}
45
46/** Must run before the transaction is applied. */
47export function groupUndoByChangeKind(
48 tr: Transaction,
49 previous: ComposerChangeKind | null,
50): ComposerChangeKind | null {
51 if (isHistoryTransaction(tr)) return "other";
52 const kind = changeKindOf(tr);
53 if (kind === null) return previous;
54 if (previous !== null && (kind !== previous || kind === "other")) closeHistory(tr);
55 return kind;
56}