Skip to content

Commit 16de7fa

Browse files
committed
fix(web): group composer undo the way the Lexical composer did
ProseMirror's history only starts a new undo step after a pause or a non-adjacent edit, so typing, backspacing and typing again without pausing was one step, and a store rewrite such as autocomplete inserting a chip made every later edit adjacent and joined it. One undo could wipe a whole line. A dispatch middleware now closes the undo step when the kind of change switches between typing, deleting and one-off changes (a paste, a store rewrite, undo itself), and the pause that starts a new step is one second, both as Lexical had it. IME composition still counts as typing.
1 parent 08ea89f commit 16de7fa

3 files changed

Lines changed: 202 additions & 0 deletions

File tree

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ import {
6060
serializeEditorDoc,
6161
type SkillMeta,
6262
} from "~/composer-rich-text-doc";
63+
import {
64+
COMPOSER_UNDO_GROUP_DELAY,
65+
type ComposerChangeKind,
66+
groupUndoByChangeKind,
67+
} from "~/composer-undo-grouping";
6368
import {
6469
convertCodeFenceOnEnter,
6570
indentCodeBlock,
@@ -670,6 +675,26 @@ const headingInputRule = new InputRule({
670675
},
671676
});
672677

678+
/**
679+
* Starts a new undo step when the kind of change switches (typing, deleting,
680+
* a paste or a store rewrite), the way the Lexical composer grouped undo.
681+
* Runs as dispatch middleware because the grouping has to be decided before
682+
* the history plugin applies the transaction.
683+
*/
684+
const ComposerUndoGroupingExtension = Extension.create<
685+
Record<string, never>,
686+
{ previous: ComposerChangeKind | null }
687+
>({
688+
name: "composer-undo-grouping",
689+
addStorage() {
690+
return { previous: null };
691+
},
692+
dispatchTransaction({ transaction, next }) {
693+
this.storage.previous = groupUndoByChangeKind(transaction, this.storage.previous);
694+
next(transaction);
695+
},
696+
});
697+
673698
/** Whether the caret sits inside a fenced code block. */
674699
function isInCodeBlock(view: EditorView): boolean {
675700
return view.state.selection.$from.parent.type.spec.code === true;
@@ -954,9 +979,11 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
954979
gapcursor: false,
955980
trailingNode: false,
956981
code: false,
982+
undoRedo: { newGroupDelay: COMPOSER_UNDO_GROUP_DELAY },
957983
// Plain mode has no marks: typed markers stay literal characters.
958984
...(richText ? {} : { bold: false, italic: false, strike: false }),
959985
}),
986+
ComposerUndoGroupingExtension,
960987
ComposerMentionExtension,
961988
ComposerSkillExtension,
962989
ComposerCitationExtension,
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
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+
} from "./composer-undo-grouping";
12+
13+
const schema = getSchema([StarterKit]);
14+
15+
/**
16+
* A composer-shaped editor state with the real history plugin, dispatching
17+
* through the same grouping rule the composer's extension applies. Keystrokes
18+
* land 80ms apart unless a gap says otherwise.
19+
*/
20+
function composer(text = "") {
21+
let clock = 0;
22+
let previous: ComposerChangeKind | null = null;
23+
let state = EditorState.create({
24+
schema,
25+
doc: schema.node("doc", null, [
26+
schema.node("paragraph", null, text ? [schema.text(text)] : []),
27+
]),
28+
plugins: [history({ newGroupDelay: COMPOSER_UNDO_GROUP_DELAY })],
29+
});
30+
const dispatch = (tr: Transaction) => {
31+
tr.setTime(clock);
32+
previous = groupUndoByChangeKind(tr, previous);
33+
state = state.apply(tr);
34+
};
35+
dispatch(state.tr.setSelection(TextSelection.atEnd(state.doc)));
36+
const api = {
37+
text: () => state.doc.textContent,
38+
wait: (ms: number) => ((clock += ms), api),
39+
type: (s: string, gap = 80) => {
40+
for (const ch of s) {
41+
clock += gap;
42+
dispatch(state.tr.insertText(ch));
43+
}
44+
return api;
45+
},
46+
backspace: (n: number) => {
47+
for (let i = 0; i < n; i += 1) {
48+
clock += 80;
49+
const at = state.selection.from;
50+
dispatch(state.tr.delete(at - 1, at));
51+
}
52+
return api;
53+
},
54+
paste: (s: string) => {
55+
clock += 80;
56+
dispatch(state.tr.insertText(s).setMeta("uiEvent", "paste"));
57+
return api;
58+
},
59+
/** A store-driven rewrite: autocomplete inserting a chip, list continuation. */
60+
rewrite: (next: string) => {
61+
clock += 80;
62+
dispatch(
63+
state.tr.replaceWith(
64+
0,
65+
state.doc.content.size,
66+
schema.node("paragraph", null, [schema.text(next)]),
67+
),
68+
);
69+
dispatch(state.tr.setSelection(TextSelection.atEnd(state.doc)));
70+
return api;
71+
},
72+
/** IME input replaces its own range on every keystroke. */
73+
compose: (s: string) => {
74+
const start = state.selection.from;
75+
for (let i = 1; i <= s.length; i += 1) {
76+
clock += 80;
77+
dispatch(
78+
state.tr.insertText(s.slice(0, i), start, start + i - 1).setMeta("composition", 1),
79+
);
80+
}
81+
return api;
82+
},
83+
undo: () => (undo(state, dispatch), api),
84+
};
85+
return api;
86+
}
87+
88+
describe("composer undo grouping", () => {
89+
it("keeps a continuous run of typing as one step", () => {
90+
expect(composer().type("hello world").undo().text()).toBe("");
91+
});
92+
93+
it("starts a new step when typing turns into deleting, and back", () => {
94+
const editor = composer().type("hello world").backspace(5).type("there");
95+
expect(editor.text()).toBe("hello there");
96+
expect(editor.undo().text()).toBe("hello ");
97+
expect(editor.undo().text()).toBe("hello world");
98+
expect(editor.undo().text()).toBe("");
99+
});
100+
101+
it("gives a store rewrite its own step, and typing after it another", () => {
102+
const editor = composer("draft ").type("one").rewrite("draft one @chip ").type("then");
103+
expect(editor.undo().text()).toBe("draft one @chip ");
104+
expect(editor.undo().text()).toBe("draft one");
105+
expect(editor.undo().text()).toBe("draft ");
106+
});
107+
108+
it("gives a paste its own step", () => {
109+
const editor = composer().type("see ").paste("pasted text").type(" ok");
110+
expect(editor.undo().text()).toBe("see pasted text");
111+
expect(editor.undo().text()).toBe("see ");
112+
});
113+
114+
it("keeps IME composition as one run of typing", () => {
115+
expect(composer().type("go ").compose("にほん").undo().text()).toBe("");
116+
});
117+
118+
it("merges typing across a short pause and splits it across a long one", () => {
119+
expect(composer().type("hello").wait(700).type(" world").undo().text()).toBe("");
120+
expect(composer().type("hello").wait(1100).type(" world").undo().text()).toBe("hello");
121+
});
122+
});
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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+
function changeKindOf(tr: Transaction): ComposerChangeKind | null {
20+
if (!tr.docChanged) return null;
21+
const uiEvent = tr.getMeta("uiEvent");
22+
if (uiEvent === "paste" || uiEvent === "drop" || uiEvent === "cut") return "other";
23+
// IME input replaces its own range on each keystroke; it is still typing.
24+
if (tr.getMeta("composition") != null) return "insert";
25+
let kind: ComposerChangeKind | null = null;
26+
for (const step of tr.steps) {
27+
if (!(step instanceof ReplaceStep)) return "other";
28+
const inserts = step.slice.size > 0;
29+
const deletes = step.to > step.from;
30+
const stepKind = inserts && !deletes ? "insert" : deletes && !inserts ? "delete" : "other";
31+
if (kind !== null && kind !== stepKind) return "other";
32+
kind = stepKind;
33+
}
34+
return kind;
35+
}
36+
37+
/**
38+
* Closes the current undo step before `tr` when its kind of change differs
39+
* from the last one, or when it is a one-off change such as a paste or a
40+
* store rewrite, and returns the kind to remember for the next transaction.
41+
* Undo and redo themselves count as one-off, so typing after them starts a
42+
* fresh step. Must run before the transaction is applied.
43+
*/
44+
export function groupUndoByChangeKind(
45+
tr: Transaction,
46+
previous: ComposerChangeKind | null,
47+
): ComposerChangeKind | null {
48+
if (isHistoryTransaction(tr)) return "other";
49+
const kind = changeKindOf(tr);
50+
if (kind === null) return previous;
51+
if (previous !== null && (kind !== previous || kind === "other")) closeHistory(tr);
52+
return kind;
53+
}

0 commit comments

Comments
 (0)