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

composer-undo-grouping.ts

55 lines2.3 KB

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/**
14 * Tag custom paste/cut dispatches; ProseMirror only tags its built-in paths.
15 * Not `uiEvent`: Tiptap's paste rules would style the already parsed paste a second time.
16 */
17export function markAsClipboardEdit(tr: Transaction, event: "paste" | "cut"): Transaction {
18 return tr.setMeta(CLIPBOARD_EDIT_META, event);
20​
21/** Start a replacement undo group, keeping the IME edits together and prior typing separate. */
22export function markAsCompositionReplace(tr: Transaction): Transaction {
23 return closeHistory(tr).setMeta(COMPOSITION_REPLACE_META, true);
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 if (tr.getMeta(CLIPBOARD_EDIT_META) != null) return "other";
31 // IME input replaces its own range on each keystroke; it is still typing.
32 if (tr.getMeta("composition") != null || tr.getMeta(COMPOSITION_REPLACE_META)) return "insert";
33 let kind: ComposerChangeKind | null = null;
34 for (const step of tr.steps) {
35 if (!(step instanceof ReplaceStep)) return "other";
36 const inserts = step.slice.size > 0;
37 const deletes = step.to > step.from;
38 const stepKind = inserts && !deletes ? "insert" : deletes && !inserts ? "delete" : "other";
39 if (kind !== null && kind !== stepKind) return "other";
40 kind = stepKind;
41 }
42 return kind;
44​
45/** Must run before the transaction is applied. */
46export function groupUndoByChangeKind(
47 tr: Transaction,
48 previous: ComposerChangeKind | null,
49): ComposerChangeKind | null {
50 if (isHistoryTransaction(tr)) return "other";
51 const kind = changeKindOf(tr);
52 if (kind === null) return previous;
53 if (previous !== null && (kind !== previous || kind === "other")) closeHistory(tr);
54 return kind;