@devries-cameron20 / t3code Mirror · read-only / commits / 8f4166b28c
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 23:30 UTC

fix(web): convert composer list markers completed later (#22997)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 11, 2026 at 05:20 UTC 8f4166b28c530fea77685d82423033c7309e391b
2 files changed +417 -3
apps/web/src/composer-block-shortcuts.test.ts
+268 -3
@@ -1,7 +1,9 @@
1 -import { Editor } from "@tiptap/core";
1 +import { Editor, Extension, InputRule, type Extensions } from "@tiptap/core";
2 +import { closeHistory, redo, undo } from "@tiptap/pm/history";
3 +import { splitBlock } from "@tiptap/pm/commands";
4 import { TextSelection } from "@tiptap/pm/state";
5 import StarterKit from "@tiptap/starter-kit";
4 -import { describe, expect, it } from "vite-plus/test";
6 +import { describe, expect, it, onTestFinished, vi } from "vite-plus/test";
7
8 import {
9 buildDocJson,
@@ -32,7 +34,7 @@ function chord(spec: string) {
34 } as unknown as KeyboardEvent;
35 }
36
35 -function press(value: string, spec: string) {
37 +function createEditor(value: string, extra: Extensions = []) {
38 const editor = new Editor({
39 extensions: [
40 StarterKit.configure({
@@ -50,10 +52,27 @@ function press(value: string, spec: string) {
52 ...ComposerListExtensions,
53 ComposerTaskListExtension,
54 ComposerTaskItemExtension,
55 + ...extra,
56 ],
57 content: buildDocJson(value, (name) => ({ label: name, description: null })),
58 });
59 + // Headless editors need the plugins installed explicitly because there is no mounted view.
60 + editor.view.updateState(editor.state.reconfigure({ plugins: editor.extensionManager.plugins }));
61 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
62 + onTestFinished(() => editor.destroy());
63 + return editor;
64 +}
65 +
66 +function expectViewMatchesMarkdown(editor: Editor) {
67 + const markdown = serializeEditorDoc(editor.state.doc).value;
68 + const rebuilt = editor.schema.nodeFromJSON(
69 + buildDocJson(markdown, (name) => ({ label: name, description: null })),
70 + );
71 + expect(editor.state.doc.toString()).toBe(rebuilt.toString());
72 +}
73 +
74 +function press(value: string, spec: string) {
75 + const editor = createEditor(value);
76 const event = chord(spec);
77 const before = editor.state.doc;
78 const handled = editor.extensionManager.plugins.some((plugin) =>
@@ -92,3 +111,249 @@ describe("Tiptap's block shortcuts", () => {
111 expect(result.value).toBe(value);
112 });
113 });
114 +
115 +describe("composer list normalization", () => {
116 + it("converts a dash edited on an earlier line and keeps the view equal to Markdown", () => {
117 + const editor = createEditor("");
118 + editor.view.dispatch(editor.state.tr.insertText("-get md"));
119 + splitBlock(editor.state, editor.view.dispatch);
120 + editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 2)));
121 + editor.view.dispatch(editor.state.tr.insertText(" "));
122 + editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
123 +
124 + expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
125 + expect(editor.state.doc.firstChild?.firstChild?.textContent).toBe("get md");
126 + expect(serializeEditorDoc(editor.state.doc).value).toBe("- get md\n");
127 + expectViewMatchesMarkdown(editor);
128 + });
129 +
130 + it.each([
131 + ["- a\nb\n- c", "- "],
132 + ["* a\nb", "* "],
133 + ["1. a\nb", "2. "],
134 + ["- [ ] a\nb", "- [ ] "],
135 + ])("joins the converted line into the neighbouring list in %j", (value, marker) => {
136 + const editor = createEditor(value);
137 + let paragraph = 0;
138 + editor.state.doc.forEach((node, pos) => {
139 + if (node.type.name === "paragraph") paragraph = pos + 1;
140 + });
141 + editor.view.dispatch(editor.state.tr.insertText(marker, paragraph));
142 + expect(editor.state.doc.childCount).toBe(1);
143 + expectViewMatchesMarkdown(editor);
144 + });
145 +
146 + it("keeps a converted line apart from a list with another marker", () => {
147 + const editor = createEditor("* a\nb");
148 + editor.view.dispatch(
149 + editor.state.tr.insertText("- ", editor.state.doc.firstChild!.nodeSize + 1),
150 + );
151 + expect(editor.state.doc.childCount).toBe(2);
152 + expectViewMatchesMarkdown(editor);
153 + });
154 +
155 + it.each(["[link](url)", "[ordinary text]", "[x]text"])(
156 + "converts a dash before existing bracket-prefixed text %j",
157 + (text) => {
158 + const editor = createEditor(text);
159 + editor.view.dispatch(editor.state.tr.insertText("- ", 1));
160 + expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
161 + expect(editor.state.doc.firstChild?.firstChild?.textContent).toBe(text);
162 + expect(serializeEditorDoc(editor.state.doc).value).toBe(`- ${text}`);
163 + },
164 + );
165 +
166 + it.each(["- ", "* ", "+ ", "3) ", "4. ", "- [ ] ", "- [x] "])(
167 + "converts %j inserted in front of existing text",
168 + (marker) => {
169 + const editor = createEditor("existing text");
170 + editor.view.dispatch(editor.state.tr.insertText(marker, 1));
171 + const list = editor.state.doc.firstChild!;
172 + expect(list.type.name).toBe(
173 + marker.includes("[") ? "taskList" : /^\d/.test(marker) ? "orderedList" : "bulletList",
174 + );
175 + expect(list.firstChild?.textContent).toBe("existing text");
176 + expect(serializeEditorDoc(editor.state.doc).value).toBe(`${marker}existing text`);
177 + },
178 + );
179 +
180 + it.each(["a - b", "-x", "-"])("leaves %j as a paragraph", (text) => {
181 + const editor = createEditor("");
182 + editor.view.dispatch(editor.state.tr.insertText(text));
183 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
184 + expect(editor.state.doc.textContent).toBe(text);
185 + });
186 +
187 + it("undoes the insertion and conversion together and can redo them", () => {
188 + const editor = createEditor("existing text");
189 + editor.view.dispatch(closeHistory(editor.state.tr).insertText("- ", 1));
190 + expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
191 + expect(undo(editor.state, editor.view.dispatch)).toBe(true);
192 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
193 + expect(editor.state.doc.textContent).toBe("existing text");
194 + expect(redo(editor.state, editor.view.dispatch)).toBe(true);
195 + expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
196 + });
197 +
198 + it("keeps the dash gesture available until a task marker is complete", () => {
199 + const editor = createEditor("");
200 + for (const ch of "- [x]") {
201 + editor.view.dispatch(editor.state.tr.insertText(ch));
202 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
203 + }
204 + editor.view.dispatch(editor.state.tr.insertText(" "));
205 + expect(editor.state.doc.firstChild?.type.name).toBe("taskList");
206 + expect(editor.state.doc.firstChild?.firstChild?.attrs.checked).toBe(true);
207 + });
208 +
209 + it.each(["```\ncode\n```", "- outer\n - inner", "> quoted"])(
210 + "does not convert paragraphs inside %j",
211 + (value) => {
212 + const editor = createEditor(value);
213 + let position = 0;
214 + editor.state.doc.descendants((node, pos) => {
215 + if (node.isText) position = pos;
216 + });
217 + const before: string[] = [];
218 + editor.state.doc.descendants((node) => {
219 + before.push(node.type.name);
220 + });
221 + editor.view.dispatch(editor.state.tr.insertText("- ", position));
222 + const after: string[] = [];
223 + editor.state.doc.descendants((node) => {
224 + after.push(node.type.name);
225 + });
226 + expect(after).toEqual(before);
227 + expect(editor.state.doc.textContent).toContain("- ");
228 + },
229 + );
230 +
231 + it("waits for a non-composition transaction before changing paragraph structure", () => {
232 + const editor = createEditor("");
233 + editor.view.dispatch(editor.state.tr.insertText("- text").setMeta("composition", 1));
234 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
235 + editor.view.dispatch(editor.state.tr.insertText("日本語", 3, 7).setMeta("composition", 1));
236 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
237 + editor.view.dispatch(editor.state.tr.insertText("確定", 3, 6).setMeta("composition", 1));
238 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
239 + vi.useFakeTimers();
240 + onTestFinished(() => {
241 + vi.useRealTimers();
242 + });
243 + for (const plugin of editor.state.plugins) {
244 + plugin.props.handleDOMEvents?.compositionend?.call(
245 + plugin,
246 + editor.view,
247 + new Event("compositionend") as CompositionEvent,
248 + );
249 + }
250 + vi.runAllTimers();
251 + expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
252 + expect(serializeEditorDoc(editor.state.doc).value).toBe("- 確定");
253 + expect(undo(editor.state, editor.view.dispatch)).toBe(true);
254 + expect(editor.state.doc.textContent).toBe("");
255 + expect(redo(editor.state, editor.view.dispatch)).toBe(true);
256 + expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
257 + });
258 +
259 + it("does not immediately reconvert a literal marker restored by undo", () => {
260 + const editor = createEditor("");
261 + editor.view.dispatch(editor.state.tr.insertText("- "));
262 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
263 + editor.view.dispatch(closeHistory(editor.state.tr).insertText("text"));
264 + expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
265 + expect(undo(editor.state, editor.view.dispatch)).toBe(true);
266 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
267 + expect(editor.state.doc.textContent).toBe("- ");
268 + editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atStart(editor.state.doc)));
269 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
270 + });
271 +
272 + it("keeps the literal marker that Backspace restores from a list input rule", () => {
273 + // Mirrors the composer's `- ` + first character rule; the test editor keeps Tiptap's `- ` rule.
274 + const dashRule = Extension.create({
275 + name: "dashRule",
276 + addInputRules() {
277 + return [
278 + new InputRule({
279 + find: /^- (?<carried>\S)$/,
280 + handler: ({ range, match, chain }) => {
281 + chain()
282 + .deleteRange(range)
283 + .wrapInList("bulletList")
284 + .command(({ tr }) => {
285 + tr.insertText(match.groups?.carried ?? "");
286 + return true;
287 + })
288 + .run();
289 + },
290 + }),
291 + ];
292 + },
293 + });
294 + const editor = createEditor("", [dashRule]);
295 + const type = (text: string) => {
296 + const { from, to } = editor.state.selection;
297 + const insert = () => editor.state.tr.insertText(text, from, to);
298 + const handled = editor.state.plugins.some((plugin) =>
299 + plugin.props.handleTextInput?.call(plugin, editor.view, from, to, text, insert),
300 + );
301 + if (!handled) editor.view.dispatch(editor.state.tr.insertText(text, from, to));
302 + };
303 + editor.view.dispatch(editor.state.tr.insertText("- "));
304 + type("g");
305 + expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
306 + const backspace = chord("Backspace");
307 + expect(
308 + editor.state.plugins.some((plugin) =>
309 + plugin.props.handleKeyDown?.call(plugin, editor.view, backspace),
310 + ),
311 + ).toBe(true);
312 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
313 + expect(editor.state.doc.textContent).toBe("- g");
314 + type("o");
315 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
316 + expect(editor.state.doc.textContent).toBe("- go");
317 + });
318 +
319 + it("preserves formatting and the caret when removing the literal prefix", () => {
320 + const editor = createEditor("**text**");
321 + editor.view.dispatch(editor.state.tr.insert(1, editor.schema.text("- ")));
322 + expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
323 + expect(editor.state.selection.$from.parentOffset).toBe(4);
324 + expect(serializeEditorDoc(editor.state.doc).value).toBe("- **text**");
325 + });
326 +
327 + it("does not turn an inline code marker into a list", () => {
328 + const editor = createEditor("`-text`");
329 + editor.view.dispatch(editor.state.tr.insertText(" ", 2));
330 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
331 + expect(serializeEditorDoc(editor.state.doc).value).toBe("`- text`");
332 + });
333 +
334 + it.each(["**- x**", "*-* x", "~~- x~~", "a\n**1.** b"])(
335 + "preserves styled markers when restoring %j",
336 + (value) => {
337 + const editor = createEditor("");
338 + editor.commands.setContent(
339 + buildDocJson(value, (name) => ({ label: name, description: null })),
340 + { emitUpdate: false },
341 + );
342 + expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
343 + expect(editor.state.doc.lastChild?.type.name).toBe("paragraph");
344 + editor.view.dispatch(editor.state.tr.insertText("x", editor.state.doc.content.size - 1));
345 + expect(editor.state.doc.lastChild?.type.name).toBe("paragraph");
346 + },
347 + );
348 +
349 + it("only normalizes changed blocks", () => {
350 + const editor = createEditor("");
351 + editor.view.updateState(editor.state.reconfigure({ plugins: [] }));
352 + editor.view.dispatch(editor.state.tr.insertText("- untouched"));
353 + splitBlock(editor.state, editor.view.dispatch);
354 + editor.view.updateState(editor.state.reconfigure({ plugins: editor.extensionManager.plugins }));
355 + editor.view.dispatch(editor.state.tr.insertText("changed"));
356 + expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
357 + expect(editor.state.doc.firstChild?.textContent).toBe("- untouched");
358 + });
359 +});
apps/web/src/composer-rich-text-doc.ts
+149
@@ -18,6 +18,8 @@ import { Heading } from "@tiptap/extension-heading";
18 import { HorizontalRule } from "@tiptap/extension-horizontal-rule";
19 import { Italic, starInputRegex, starPasteRegex } from "@tiptap/extension-italic";
20 import {
21 + combineTransactionSteps,
22 + getChangedRanges,
23 type Command,
24 type Editor,
25 Extension,
@@ -26,6 +28,8 @@ import {
28 markPasteRule,
29 mergeAttributes,
30 } from "@tiptap/core";
31 +import { isHistoryTransaction } from "@tiptap/pm/history";
32 +import { canJoin, findWrapping } from "@tiptap/pm/transform";
33 import { BulletList, ListItem, OrderedList } from "@tiptap/extension-list";
34 import { Strike, inputRegex as strikeInputRegex } from "@tiptap/extension-strike";
35 import { TaskItem } from "@tiptap/extension-task-item";
@@ -479,6 +483,12 @@ const ComposerListItemExtension = ListItem.extend({
483
484 export const ComposerListExtensions = [
485 BulletList.extend({
486 + addProseMirrorPlugins() {
487 + return [
488 + ...(this.parent?.() ?? []),
489 + listNormalizationPlugin(() => this.editor.view.composing),
490 + ];
491 + },
492 addKeyboardShortcuts() {
493 return withoutBlockChords(this.parent?.(), ["Mod-Shift-8"]);
494 },
@@ -613,6 +623,145 @@ function parseListPrefix(line: string): { prefix: ListLinePrefix; markerLength:
623 return null;
624 }
625
626 +/** Only changed top-level paragraphs can acquire a literal list prefix outside an input rule. */
627 +function listNormalizationPlugin(isComposing: () => boolean) {
628 + let pending = new Set<number>();
629 + const key = new PluginKey("composerListNormalization");
630 + return new Plugin({
631 + key,
632 + props: {
633 + handleDOMEvents: {
634 + // ProseMirror tags the DOM flush after compositionend as composition, so nothing else would normalize.
635 + compositionend(view) {
636 + setTimeout(() => {
637 + if (!view.isDestroyed && !view.composing && pending.size > 0) {
638 + view.dispatch(view.state.tr);
639 + }
640 + });
641 + return false;
642 + },
643 + },
644 + },
645 + appendTransaction(transactions, oldState, state) {
646 + // Tiptap's undoInputRule (Backspace right after a rule) restores the typed text on purpose.
647 + const undoesInputRule = oldState.plugins.some(
648 + (plugin) => plugin.spec.isInputRules && plugin.getState(oldState),
649 + );
650 + if (undoesInputRule || transactions.some(isHistoryTransaction)) {
651 + pending.clear();
652 + return null;
653 + }
654 + if (pending.size === 0 && !transactions.some((tr) => tr.docChanged)) return null;
655 + const changes = combineTransactionSteps(oldState.doc, [...transactions]);
656 + pending = new Set(
657 + [...pending].flatMap((pos) => {
658 + const mapped = changes.mapping.mapResult(pos, 1);
659 + return mapped.deleted ? [] : [mapped.pos];
660 + }),
661 + );
662 + for (const { newRange } of getChangedRanges(changes)) {
663 + state.doc.nodesBetween(newRange.from, newRange.to, (node, pos) => {
664 + if (node.type.name !== "paragraph") return false;
665 + const parsed = parseListPrefix(paragraphText(node));
666 + // Typing after a marker left literal keeps it literal; only an edit reaching the marker converts.
667 + if (parsed && newRange.from <= pos + 1 + parsed.markerLength) pending.add(pos);
668 + return false;
669 + });
670 + }
671 + // The next non-composition transaction can normalize after the browser finishes its DOM edits.
672 + if (isComposing() || transactions.some((tr) => tr.getMeta("composition") != null))
673 + return null;
674 +
675 + const tr = state.tr;
676 + for (const pos of [...pending].sort((a, b) => b - a)) {
677 + pending.delete(pos);
678 + if (state.doc.resolve(pos).depth !== 0) continue;
679 + const node = state.doc.nodeAt(pos);
680 + if (node?.type.name !== "paragraph") continue;
681 + const text = paragraphText(node);
682 + const parsed = parseListPrefix(text);
683 + // Input rules only introduce unindented top-level lists; keep the same boundary here.
684 + if (!parsed || parsed.prefix.indent) continue;
685 + const { prefix, markerLength } = parsed;
686 + if (
687 + Object.values(state.schema.marks).some((mark) => node.rangeHasMark(0, markerLength, mark))
688 + )
689 + continue;
690 + const active = state.selection.$from.depth === 1 && state.selection.$from.before(1) === pos;
691 + const content = text.slice(markerLength);
692 + // Keep `- ` and unfinished task markers literal while the user is entering the gesture.
693 + if (
694 + active &&
695 + (prefix.kind === "task"
696 + ? !prefix.contentSpace
697 + : prefix.kind === "bullet" &&
698 + prefix.marker === "-" &&
699 + (!content || /^\[(?:[ xX]\]?)?$/.test(content)))
700 + ) {
701 + pending.add(pos);
702 + continue;
703 + }
704 + if (prefix.kind !== "task" && !prefix.space) continue;
705 + const listType =
706 + state.schema.nodes[
707 + prefix.kind === "task"
708 + ? "taskList"
709 + : prefix.kind === "ordered"
710 + ? "orderedList"
711 + : "bulletList"
712 + ];
713 + if (!listType) continue;
714 + const attrs =
715 + prefix.kind === "ordered" ? { start: Number.parseInt(prefix.marker, 10) || 1 } : {};
716 + const $from = tr.doc.resolve(pos + 1);
717 + const range = $from.blockRange();
718 + const wrapping = range && findWrapping(range, listType, attrs);
719 + if (!range || !wrapping) continue;
720 + tr.wrap(range, wrapping);
721 + tr.setNodeMarkup(
722 + pos + 1,
723 + undefined,
724 + prefix.kind === "task"
725 + ? {
726 + checked: prefix.checked,
727 + indent: prefix.indent,
728 + markerSpace: prefix.markerSpace,
729 + contentSpace: prefix.contentSpace,
730 + }
731 + : { indent: prefix.indent, marker: prefix.marker, space: prefix.space },
732 + );
733 + tr.delete(pos + 3, pos + 3 + markerLength);
734 + joinCompatibleLists(tr, pos + tr.doc.nodeAt(pos)!.nodeSize);
735 + joinCompatibleLists(tr, pos);
736 + }
737 + pending = new Set([...pending].map((pos) => tr.mapping.map(pos, 1)));
738 + return tr.docChanged ? tr : null;
739 + },
740 + });
741 +}
742 +
743 +function paragraphText(node: ProseMirrorNode): string {
744 + return node.textBetween(0, node.content.size, undefined, "\ufffc");
745 +}
746 +
747 +/** Rebuilding from Markdown merges adjacent lists of one type whose markers share a delimiter. */
748 +function joinCompatibleLists(tr: Transaction, pos: number): void {
749 + const $pos = tr.doc.resolve(pos);
750 + const before = $pos.nodeBefore;
751 + const after = $pos.nodeAfter;
752 + const delimiter = (list: ProseMirrorNode) =>
753 + String(list.firstChild?.attrs.marker ?? "").slice(-1);
754 + if (
755 + before &&
756 + after &&
757 + before.type === after.type &&
758 + delimiter(before) === delimiter(after) &&
759 + canJoin(tr.doc, pos)
760 + ) {
761 + tr.join(pos);
762 + }
763 +}
764 +
765 function listKey(prefix: ListLinePrefix): string {
766 if (prefix.kind === "task") return "task";
767 if (prefix.kind === "ordered") return `ordered:${prefix.marker.slice(-1)}`;