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

composer-undo-grouping.ts

64 lines2.7 KB

1import { closeHistory, isHistoryTransaction } from "@tiptap/pm/history";
2import type { Transaction } from "@tiptap/pm/state";
3import { ReplaceStep } from "@tiptap/pm/transform";
4​
5/**
6 * Undo grouping matching the Lexical composer it replaced.
7 *
8 * ProseMirror's history only starts a new undo step after a pause or when an
9 * edit is not next to the last one, so typing, backspacing and typing again
10 * without pausing is one step, and a store rewrite of the whole document
11 * (autocomplete inserting a chip, list continuation) makes every later edit
12 * "adjacent" and joins it. Lexical instead started a new step whenever the
13 * kind of change switched, and after one second without changes.
14 */
15export const COMPOSER_UNDO_GROUP_DELAY = 1000;
16​
17export type ComposerChangeKind = "insert" | "delete" | "other";
18​
19/**
20 * Tags a transaction as a paste or cut, so it becomes its own undo step.
21 * ProseMirror tags these itself only on its built-in clipboard paths; the
22 * composer's `handlePaste` and cut handler replace those paths, so each of
23 * their dispatches must call this, or the change merges with the typing or
24 * deleting around it.
25 */
26export function markAsClipboardEdit(tr: Transaction, event: "paste" | "cut"): Transaction {
27 return tr.setMeta("uiEvent", event);
29​
30function changeKindOf(tr: Transaction): ComposerChangeKind | null {
31 if (!tr.docChanged) return null;
32 const uiEvent = tr.getMeta("uiEvent");
33 if (uiEvent === "paste" || uiEvent === "drop" || uiEvent === "cut") return "other";
34 // IME input replaces its own range on each keystroke; it is still typing.
35 if (tr.getMeta("composition") != null) return "insert";
36 let kind: ComposerChangeKind | null = null;
37 for (const step of tr.steps) {
38 if (!(step instanceof ReplaceStep)) return "other";
39 const inserts = step.slice.size > 0;
40 const deletes = step.to > step.from;
41 const stepKind = inserts && !deletes ? "insert" : deletes && !inserts ? "delete" : "other";
42 if (kind !== null && kind !== stepKind) return "other";
43 kind = stepKind;
44 }
45 return kind;
47​
48/**
49 * Closes the current undo step before `tr` when its kind of change differs
50 * from the last one, or when it is a one-off change such as a paste or a
51 * store rewrite, and returns the kind to remember for the next transaction.
52 * Undo and redo themselves count as one-off, so typing after them starts a
53 * fresh step. Must run before the transaction is applied.
54 */
55export function groupUndoByChangeKind(
56 tr: Transaction,
57 previous: ComposerChangeKind | null,
58): ComposerChangeKind | null {
59 if (isHistoryTransaction(tr)) return "other";
60 const kind = changeKindOf(tr);
61 if (kind === null) return previous;
62 if (previous !== null && (kind !== previous || kind === "other")) closeHistory(tr);
63 return kind;