The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { closeHistory, isHistoryTransaction } from "@tiptap/pm/history"; |
| 2 | import type { Transaction } from "@tiptap/pm/state"; |
| 3 | import { ReplaceStep } from "@tiptap/pm/transform"; |
| 4 | |
| 5 | // Whole-draft rewrites make all edits adjacent; explicit boundaries keep change kinds separate. |
| 6 | export const COMPOSER_UNDO_GROUP_DELAY = 1000; |
| 7 | |
| 8 | export type ComposerChangeKind = "insert" | "delete" | "other"; |
| 9 | |
| 10 | const CLIPBOARD_EDIT_META = "composerClipboardEdit"; |
| 11 | |
| 12 | /** |
| 13 | * Tag custom paste/cut dispatches; ProseMirror only tags its built-in paths. |
| 14 | * Not `uiEvent`: Tiptap's paste rules would style the already parsed paste a second time. |
| 15 | */ |
| 16 | export function markAsClipboardEdit(tr: Transaction, event: "paste" | "cut"): Transaction { |
| 17 | return tr.setMeta(CLIPBOARD_EDIT_META, event); |
| 18 | } |
| 19 | |
| 20 | function changeKindOf(tr: Transaction): ComposerChangeKind | null { |
| 21 | if (!tr.docChanged) return null; |
| 22 | const uiEvent = tr.getMeta("uiEvent"); |
| 23 | if (uiEvent === "paste" || uiEvent === "drop" || uiEvent === "cut") return "other"; |
| 24 | if (tr.getMeta(CLIPBOARD_EDIT_META) != null) return "other"; |
| 25 | // IME input replaces its own range on each keystroke; it is still typing. |
| 26 | if (tr.getMeta("composition") != null) return "insert"; |
| 27 | let kind: ComposerChangeKind | null = null; |
| 28 | for (const step of tr.steps) { |
| 29 | if (!(step instanceof ReplaceStep)) return "other"; |
| 30 | const inserts = step.slice.size > 0; |
| 31 | const deletes = step.to > step.from; |
| 32 | const stepKind = inserts && !deletes ? "insert" : deletes && !inserts ? "delete" : "other"; |
| 33 | if (kind !== null && kind !== stepKind) return "other"; |
| 34 | kind = stepKind; |
| 35 | } |
| 36 | return kind; |
| 37 | } |
| 38 | |
| 39 | /** Must run before the transaction is applied. */ |
| 40 | export function groupUndoByChangeKind( |
| 41 | tr: Transaction, |
| 42 | previous: ComposerChangeKind | null, |
| 43 | ): ComposerChangeKind | null { |
| 44 | if (isHistoryTransaction(tr)) return "other"; |
| 45 | const kind = changeKindOf(tr); |
| 46 | if (kind === null) return previous; |
| 47 | if (previous !== null && (kind !== previous || kind === "other")) closeHistory(tr); |
| 48 | return kind; |
| 49 | } |