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/**
6 * ProseMirror's history only starts a new undo step after a pause or when an
7 * edit is not next to the last one, so typing, backspacing and typing again
8 * without pausing is one step, and a store rewrite of the whole document
9 * (autocomplete inserting a chip, list continuation) makes every later edit
10 * "adjacent" and joins it.
11 */
12export const COMPOSER_UNDO_GROUP_DELAY = 1000;
13
14export type ComposerChangeKind = "insert" | "delete" | "other";
15
16/**
17 * ProseMirror tags these itself only on its built-in clipboard paths; the
18 * composer's `handlePaste` and cut handler replace those paths, so each of
19 * their dispatches must call this, or the change merges with the typing or
20 * deleting around it.
21 */
22export function markAsClipboardEdit(tr: Transaction, event: "paste" | "cut"): Transaction {
23 return tr.setMeta("uiEvent", event);
24}
25
26function changeKindOf(tr: Transaction): ComposerChangeKind | null {
27 if (!tr.docChanged) return null;
28 const uiEvent = tr.getMeta("uiEvent");
29 if (uiEvent === "paste" || uiEvent === "drop" || uiEvent === "cut") return "other";
30 // IME input replaces its own range on each keystroke; it is still typing.
31 if (tr.getMeta("composition") != null) return "insert";
32 let kind: ComposerChangeKind | null = null;
33 for (const step of tr.steps) {
34 if (!(step instanceof ReplaceStep)) return "other";
35 const inserts = step.slice.size > 0;
36 const deletes = step.to > step.from;
37 const stepKind = inserts && !deletes ? "insert" : deletes && !inserts ? "delete" : "other";
38 if (kind !== null && kind !== stepKind) return "other";
39 kind = stepKind;
40 }
41 return kind;
42}
43
44/**
45 * Must run before the transaction is applied.
46 */
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}