Skip to content

Commit 12e8bbd

Browse files
committed
fix(web): group composer undo the way the Lexical composer did
The Tiptap composer used ProseMirror's history defaults: a 500ms group delay with adjacency grouping, so typing, deleting and pasting in one burst undid together. Lexical's history started a new step when the kind of change switched, with a one-second delay. A dispatch middleware now closes the history group on a switch between inserting, deleting and anything else, and the composer's own paste handler tags its transactions as pastes so a paste is one step.
1 parent a3abb52 commit 12e8bbd

3 files changed

Lines changed: 229 additions & 1 deletion

File tree

‎apps/web/src/components/ComposerPromptEditorTiptap.tsx‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,12 @@ import {
5656
serializeEditorDoc,
5757
type SkillMeta,
5858
} from "~/composer-rich-text-doc";
59+
import {
60+
COMPOSER_UNDO_GROUP_DELAY,
61+
type ComposerChangeKind,
62+
groupUndoByChangeKind,
63+
markAsPaste,
64+
} from "~/composer-undo-grouping";
5965
import { collectInlineContextIds } from "~/lib/composerContextReferences";
6066
import { cn, isMacPlatform } from "~/lib/utils";
6167
import { basenameOfPath } from "~/pierre-icons";
@@ -586,6 +592,26 @@ export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) {
586592
);
587593
}
588594

595+
/**
596+
* Starts a new undo step when the kind of change switches (typing, deleting,
597+
* a paste or a store rewrite), the way the Lexical composer grouped undo.
598+
* Runs as dispatch middleware because the grouping has to be decided before
599+
* the history plugin applies the transaction.
600+
*/
601+
const ComposerUndoGroupingExtension = Extension.create<
602+
Record<string, never>,
603+
{ previous: ComposerChangeKind | null }
604+
>({
605+
name: "composer-undo-grouping",
606+
addStorage() {
607+
return { previous: null };
608+
},
609+
dispatchTransaction({ transaction, next }) {
610+
this.storage.previous = groupUndoByChangeKind(transaction, this.storage.previous);
611+
next(transaction);
612+
},
613+
});
614+
589615
function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
590616
const {
591617
value,
@@ -798,9 +824,11 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
798824
gapcursor: false,
799825
trailingNode: false,
800826
code: false,
827+
undoRedo: { newGroupDelay: COMPOSER_UNDO_GROUP_DELAY },
801828
// Plain mode has no marks: typed markers stay literal characters.
802829
...(richText ? {} : { bold: false, italic: false, strike: false }),
803830
}),
831+
ComposerUndoGroupingExtension,
804832
ComposerMentionExtension,
805833
ComposerSkillExtension,
806834
ComposerCitationExtension,
@@ -1048,7 +1076,16 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
10481076
const editorInstance = editorHolder.current;
10491077
if (editorInstance) {
10501078
insertMarkdownParagraphs(text, skillLabelFor, { styling: richText }, (content) => {
1051-
editorInstance.commands.insertContent(content);
1079+
// Tagged on the same transaction insertContent builds, so the
1080+
// paste is one undo step of its own.
1081+
editorInstance
1082+
.chain()
1083+
.command(({ tr }) => {
1084+
markAsPaste(tr);
1085+
return true;
1086+
})
1087+
.insertContent(content)
1088+
.run();
10521089
});
10531090
scrollTiptapCaretIntoView(editorInstance);
10541091
}
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import { getSchema } from "@tiptap/core";
2+
import { history, undo } from "@tiptap/pm/history";
3+
import { EditorState, TextSelection, type Transaction } from "@tiptap/pm/state";
4+
import StarterKit from "@tiptap/starter-kit";
5+
import { describe, expect, it } from "vite-plus/test";
6+
7+
import {
8+
COMPOSER_UNDO_GROUP_DELAY,
9+
type ComposerChangeKind,
10+
groupUndoByChangeKind,
11+
markAsPaste,
12+
} from "./composer-undo-grouping";
13+
14+
const schema = getSchema([StarterKit]);
15+
16+
/**
17+
* A composer-shaped editor state with the real history plugin, dispatching
18+
* through the same grouping rule the composer's extension applies. Keystrokes
19+
* land 80ms apart unless a gap says otherwise.
20+
*/
21+
function composer(text = "") {
22+
let clock = 0;
23+
let previous: ComposerChangeKind | null = null;
24+
let state = EditorState.create({
25+
schema,
26+
doc: schema.node("doc", null, [
27+
schema.node("paragraph", null, text ? [schema.text(text)] : []),
28+
]),
29+
plugins: [history({ newGroupDelay: COMPOSER_UNDO_GROUP_DELAY })],
30+
});
31+
const dispatch = (tr: Transaction) => {
32+
tr.setTime(clock);
33+
previous = groupUndoByChangeKind(tr, previous);
34+
state = state.apply(tr);
35+
};
36+
dispatch(state.tr.setSelection(TextSelection.atEnd(state.doc)));
37+
const api = {
38+
text: () => state.doc.textContent,
39+
wait: (ms: number) => ((clock += ms), api),
40+
type: (s: string, gap = 80) => {
41+
for (const ch of s) {
42+
clock += gap;
43+
dispatch(state.tr.insertText(ch));
44+
}
45+
return api;
46+
},
47+
backspace: (n: number) => {
48+
for (let i = 0; i < n; i += 1) {
49+
clock += 80;
50+
const at = state.selection.from;
51+
dispatch(state.tr.delete(at - 1, at));
52+
}
53+
return api;
54+
},
55+
/**
56+
* The transaction the composer's `handlePaste` dispatches: a plain insert,
57+
* tagged by `markAsPaste`. ProseMirror's own paste path would tag it, but
58+
* the composer takes every text paste before that path runs.
59+
*/
60+
paste: (s: string) => {
61+
clock += 80;
62+
dispatch(markAsPaste(state.tr.insertText(s)));
63+
return api;
64+
},
65+
/** A store-driven rewrite: autocomplete inserting a chip, list continuation. */
66+
rewrite: (next: string) => {
67+
clock += 80;
68+
dispatch(
69+
state.tr.replaceWith(
70+
0,
71+
state.doc.content.size,
72+
schema.node("paragraph", null, [schema.text(next)]),
73+
),
74+
);
75+
dispatch(state.tr.setSelection(TextSelection.atEnd(state.doc)));
76+
return api;
77+
},
78+
/** IME input replaces its own range on every keystroke. */
79+
compose: (s: string) => {
80+
const start = state.selection.from;
81+
for (let i = 1; i <= s.length; i += 1) {
82+
clock += 80;
83+
dispatch(
84+
state.tr.insertText(s.slice(0, i), start, start + i - 1).setMeta("composition", 1),
85+
);
86+
}
87+
return api;
88+
},
89+
undo: () => (undo(state, dispatch), api),
90+
};
91+
return api;
92+
}
93+
94+
describe("composer undo grouping", () => {
95+
it("keeps a continuous run of typing as one step", () => {
96+
expect(composer().type("hello world").undo().text()).toBe("");
97+
});
98+
99+
it("starts a new step when typing turns into deleting, and back", () => {
100+
const editor = composer().type("hello world").backspace(5).type("there");
101+
expect(editor.text()).toBe("hello there");
102+
expect(editor.undo().text()).toBe("hello ");
103+
expect(editor.undo().text()).toBe("hello world");
104+
expect(editor.undo().text()).toBe("");
105+
});
106+
107+
it("gives a store rewrite its own step, and typing after it another", () => {
108+
const editor = composer("draft ").type("one").rewrite("draft one @chip ").type("then");
109+
expect(editor.undo().text()).toBe("draft one @chip ");
110+
expect(editor.undo().text()).toBe("draft one");
111+
expect(editor.undo().text()).toBe("draft ");
112+
});
113+
114+
it("gives a paste its own step", () => {
115+
const editor = composer().type("see ").paste("pasted text").type(" ok");
116+
expect(editor.undo().text()).toBe("see pasted text");
117+
expect(editor.undo().text()).toBe("see ");
118+
});
119+
120+
it("keeps IME composition as one run of typing", () => {
121+
expect(composer().type("go ").compose("にほん").undo().text()).toBe("");
122+
});
123+
124+
it("merges typing across a short pause and splits it across a long one", () => {
125+
expect(composer().type("hello").wait(700).type(" world").undo().text()).toBe("");
126+
expect(composer().type("hello").wait(1100).type(" world").undo().text()).toBe("hello");
127+
});
128+
});
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
/**
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+
*/
15+
export const COMPOSER_UNDO_GROUP_DELAY = 1000;
16+
17+
export type ComposerChangeKind = "insert" | "delete" | "other";
18+
19+
/**
20+
* Tags a transaction as a paste, so it becomes its own undo step. ProseMirror
21+
* tags pastes itself only on its built-in paste path; the composer's
22+
* `handlePaste` takes every text paste before that path runs, so each of its
23+
* dispatches must call this, or the paste merges with the typing around it.
24+
*/
25+
export function markAsPaste(tr: Transaction): Transaction {
26+
return tr.setMeta("uiEvent", "paste");
27+
}
28+
29+
function changeKindOf(tr: Transaction): ComposerChangeKind | null {
30+
if (!tr.docChanged) return null;
31+
const uiEvent = tr.getMeta("uiEvent");
32+
if (uiEvent === "paste" || uiEvent === "drop" || uiEvent === "cut") return "other";
33+
// IME input replaces its own range on each keystroke; it is still typing.
34+
if (tr.getMeta("composition") != null) return "insert";
35+
let kind: ComposerChangeKind | null = null;
36+
for (const step of tr.steps) {
37+
if (!(step instanceof ReplaceStep)) return "other";
38+
const inserts = step.slice.size > 0;
39+
const deletes = step.to > step.from;
40+
const stepKind = inserts && !deletes ? "insert" : deletes && !inserts ? "delete" : "other";
41+
if (kind !== null && kind !== stepKind) return "other";
42+
kind = stepKind;
43+
}
44+
return kind;
45+
}
46+
47+
/**
48+
* Closes the current undo step before `tr` when its kind of change differs
49+
* from the last one, or when it is a one-off change such as a paste or a
50+
* store rewrite, and returns the kind to remember for the next transaction.
51+
* Undo and redo themselves count as one-off, so typing after them starts a
52+
* fresh step. Must run before the transaction is applied.
53+
*/
54+
export function groupUndoByChangeKind(
55+
tr: Transaction,
56+
previous: ComposerChangeKind | null,
57+
): ComposerChangeKind | null {
58+
if (isHistoryTransaction(tr)) return "other";
59+
const kind = changeKindOf(tr);
60+
if (kind === null) return previous;
61+
if (previous !== null && (kind !== previous || kind === "other")) closeHistory(tr);
62+
return kind;
63+
}

0 commit comments

Comments
 (0)