Skip to content

Commit 1141225

Browse files
committed
fix(web): the stored draft matches the editor after list and fence edits
List items and quotes could hold blocks the Markdown can't write, and Tiptap's list keys moved items without updating their indent or marker, so the draft the agent receives drifted from what the editor showed. - List items hold only their line and nested lists; quotes only lines. - Backspace and Delete across lists lift or join with the indent correction Shift+Enter uses. StarterKit's list keymap is off. - Backspace at the start of a fence turns it back into lines, and Delete never pulls a fence's code into the line above. - List and task input rules only fire at top level. - Enter after a typed closing fence ends the block. Code holding a closing fence is written inside a longer one, and an unclosed fence with a block after it is written closed. - Enter on a fence line keeps a chip's source in the info string. - A paste ending in a rule leaves the caret after it, a chip in a fence counts as one cursor position as the store expects, and the highlighter scans only top-level blocks.
1 parent 9797a72 commit 1141225

8 files changed

Lines changed: 492 additions & 52 deletions

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

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tip
33
import StarterKit from "@tiptap/starter-kit";
44
import { type Node as ProseMirrorNode } from "@tiptap/pm/model";
55
import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands";
6-
import { Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";
6+
import { NodeSelection, Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";
77
import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view";
8-
import type { ResolvedPos } from "@tiptap/pm/model";
8+
import type { NodeType, ResolvedPos } from "@tiptap/pm/model";
99
import type {
1010
AssistantCitation,
1111
ComposerContextClipboardFragment,
@@ -64,6 +64,7 @@ import {
6464
} from "~/composer-rich-text-doc";
6565
import {
6666
convertCodeFenceOnEnter,
67+
exitCodeBlockOnClosingFence,
6768
exitCodeBlockOnTrailingBlankLines,
6869
indentCodeBlock,
6970
indentedNewlineInCodeBlock,
@@ -552,8 +553,10 @@ function listMarkerInputRule(find: RegExp, listType: "bulletList" | "orderedList
552553
const marker = match.groups?.marker ?? "-";
553554
const space = match.groups?.space ?? " ";
554555
const carried = match.groups?.carried ?? "";
556+
// Top-level paragraphs only: inside an item or a quote the new list
557+
// would nest under a line the stored draft writes flat.
555558
const $from = state.doc.resolve(range.from);
556-
if ($from.parent.type.name !== "paragraph" || hasAncestor($from, "blockquote")) return null;
559+
if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;
557560
const command = chain()
558561
.deleteRange(range)
559562
.wrapInList(
@@ -591,6 +594,20 @@ const bulletToTaskInputRule = new InputRule({
591594
},
592595
});
593596

597+
/** `- [ ] ` or `- [x] ` at a top-level paragraph, for the same reason as the list markers. */
598+
function taskInputRule(type: NodeType): InputRule {
599+
const rule = wrappingInputRule({
600+
find: /^- \[([ xX])\] $/,
601+
type,
602+
getAttributes: (match) => ({ checked: match[1]?.toLowerCase() === "x" }),
603+
});
604+
return new InputRule({
605+
find: rule.find,
606+
handler: (props) =>
607+
props.state.doc.resolve(props.range.from).depth === 1 ? rule.handler(props) : null,
608+
});
609+
}
610+
594611
function hasAncestor($pos: ResolvedPos, name: string): boolean {
595612
for (let depth = $pos.depth; depth > 0; depth -= 1) {
596613
if ($pos.node(depth).type.name === name) return true;
@@ -978,6 +995,8 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
978995
gapcursor: false,
979996
trailingNode: false,
980997
code: false,
998+
// The list extensions handle Backspace and Delete themselves.
999+
listKeymap: false,
9811000
undoRedo: { newGroupDelay: COMPOSER_UNDO_GROUP_DELAY },
9821001
// Plain mode has no marks: typed markers stay literal characters.
9831002
...(richText ? {} : { bold: false, italic: false, strike: false }),
@@ -1062,14 +1081,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
10621081
ComposerTaskListExtension,
10631082
ComposerTaskItemExtension.extend({
10641083
addInputRules() {
1065-
return [
1066-
wrappingInputRule({
1067-
find: /^- \[([ xX])\] $/,
1068-
type: this.type,
1069-
getAttributes: (match) => ({ checked: match[1]?.toLowerCase() === "x" }),
1070-
}),
1071-
bulletToTaskInputRule,
1072-
];
1084+
return [taskInputRule(this.type), bulletToTaskInputRule];
10731085
},
10741086
}),
10751087
]
@@ -1228,6 +1240,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
12281240
event.stopPropagation();
12291241
const dispatch = (tr: typeof view.state.tr) => view.dispatch(tr.scrollIntoView());
12301242
return (
1243+
exitCodeBlockOnClosingFence(view.state, dispatch) ||
12311244
exitCodeBlockOnTrailingBlankLines(view) ||
12321245
indentedNewlineInCodeBlock(view.state, dispatch) ||
12331246
newlineInCode(view.state, dispatch)
@@ -1368,6 +1381,20 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
13681381
return true;
13691382
})
13701383
.insertContent(content)
1384+
.command(({ tr }) => {
1385+
// A paste ending in a rule leaves the rule selected, and
1386+
// the next keystroke would replace it. The caret goes to
1387+
// the line after it, which is added when there is none.
1388+
const { selection } = tr;
1389+
if (!(selection instanceof NodeSelection) || !selection.node.isBlock) {
1390+
return true;
1391+
}
1392+
if (!tr.doc.resolve(selection.to).nodeAfter?.isTextblock) {
1393+
tr.insert(selection.to, tr.doc.type.schema.nodes.paragraph!.create());
1394+
}
1395+
tr.setSelection(TextSelection.create(tr.doc, selection.to + 1));
1396+
return true;
1397+
})
13711398
.run();
13721399
},
13731400
);

‎apps/web/src/components/composerCodeBlockHighlight.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,14 @@ function blockSignature(node: ProseMirrorNode, theme: DiffThemeName): string {
3232
return [theme, String(node.attrs.language ?? ""), node.textContent].join("\u0000");
3333
}
3434

35+
/**
36+
* The composer's code blocks, which are always top-level: list items and
37+
* quotes cannot hold one. Scanning only the top level keeps a keystroke in a
38+
* long draft from walking every node in it.
39+
*/
3540
function collectCodeBlocks(state: EditorState): Array<{ node: ProseMirrorNode; pos: number }> {
3641
const blocks: Array<{ node: ProseMirrorNode; pos: number }> = [];
37-
state.doc.descendants((node, pos) => {
42+
state.doc.forEach((node, pos) => {
3843
if (node.type.name === "codeBlock") blocks.push({ node, pos });
3944
});
4045
return blocks;

‎apps/web/src/composer-code-block.test.ts‎

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "vite-plus/test";
2-
import { Editor } from "@tiptap/core";
2+
import { Editor, Node } from "@tiptap/core";
33
import { newlineInCode } from "@tiptap/pm/commands";
44
import { TextSelection } from "@tiptap/pm/state";
55

@@ -8,19 +8,31 @@ import {
88
indentCodeBlock,
99
indentLines,
1010
convertCodeFenceOnEnter,
11+
exitCodeBlockOnClosingFence,
1112
exitCodeBlockOnTrailingBlankLines,
1213
indentedNewlineInCodeBlock,
1314
leadingWhitespace,
1415
outdentLine,
1516
} from "./composer-code-block";
1617
import StarterKit from "@tiptap/starter-kit";
1718

18-
import { ComposerCodeBlockExtension, ComposerListExtensions } from "./composer-rich-text-doc";
19+
import {
20+
ComposerCodeBlockExtension,
21+
ComposerListExtensions,
22+
serializeEditorDoc,
23+
} from "./composer-rich-text-doc";
1924

2025
const extensions = [
2126
StarterKit.configure({ codeBlock: false, trailingNode: false }),
2227
ComposerCodeBlockExtension,
2328
...ComposerListExtensions,
29+
Node.create({
30+
name: "composer-mention",
31+
group: "inline",
32+
inline: true,
33+
atom: true,
34+
addAttributes: () => ({ path: { default: "" }, source: { default: "" } }),
35+
}),
2436
];
2537

2638
describe("leadingWhitespace", () => {
@@ -183,6 +195,36 @@ describe("exitCodeBlockOnTrailingBlankLines", () => {
183195
});
184196
});
185197

198+
describe("exitCodeBlockOnClosingFence", () => {
199+
const exit = (editor: Editor) =>
200+
exitCodeBlockOnClosingFence(editor.state, (tr) => editor.view.dispatch(tr));
201+
202+
it("ends the block at a typed closing fence and starts a line after it", () => {
203+
const editor = codeEditor("const a = 1\n```");
204+
editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "language", "ts"));
205+
expect(exit(editor)).toBe(true);
206+
editor.view.dispatch(editor.state.tr.insertText("explain this"));
207+
expect(serializeEditorDoc(editor.state.doc).value).toBe(
208+
"```ts\nconst a = 1\n```\nexplain this",
209+
);
210+
});
211+
212+
it("moves the lines after the fence out of the block", () => {
213+
const editor = codeEditor("a\n```\nb", { from: "a\n```".length });
214+
expect(exit(editor)).toBe(true);
215+
expect(serializeEditorDoc(editor.state.doc).value).toBe("```\na\n```\n\nb");
216+
expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
217+
expect(editor.state.selection.$from.parent.textContent).toBe("");
218+
});
219+
220+
it.each([
221+
["a line that cannot close the fence", "a\n``", undefined],
222+
["a caret before the end of the line", "a\n```", { from: "a\n``".length }],
223+
])("ignores %s", (_, code, at) => {
224+
expect(exit(codeEditor(code, at))).toBe(false);
225+
});
226+
});
227+
186228
describe("indentCodeBlock", () => {
187229
it("inserts an indent at a collapsed caret", () => {
188230
const editor = codeEditor("ab", { from: 1 });
@@ -320,6 +362,27 @@ describe("convertCodeFenceOnEnter", () => {
320362
expect(editor.getJSON()).toEqual(before);
321363
});
322364

365+
it("keeps a chip's source in the info string", () => {
366+
const editor = new Editor({
367+
extensions,
368+
content: {
369+
type: "doc",
370+
content: [
371+
{
372+
type: "paragraph",
373+
content: [
374+
{ type: "text", text: "```ts " },
375+
{ type: "composer-mention", attrs: { path: "a.md", source: "@a.md" } },
376+
],
377+
},
378+
],
379+
},
380+
});
381+
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
382+
expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);
383+
expect(editor.state.doc.firstChild?.attrs.language).toBe("ts @a.md");
384+
});
385+
323386
it("ignores a fence with the caret before its end", () => {
324387
const editor = paragraphEditor("```ts");
325388
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3)));

‎apps/web/src/composer-code-block.ts‎

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { EditorState, Transaction } from "@tiptap/pm/state";
33
import { TextSelection } from "@tiptap/pm/state";
44
import type { EditorView } from "@tiptap/pm/view";
55

6-
import { parseOpeningFence } from "~/composer-rich-text-doc";
6+
import { isClosingFence, parseOpeningFence, serializeSelection } from "~/composer-rich-text-doc";
77

88
/**
99
* Spaces rather than a tab: the fence round-trips through Markdown on its way
@@ -119,6 +119,48 @@ export function exitCodeBlockOnTrailingBlankLines(view: EditorView): boolean {
119119
return exitCode(view.state, (tr) => view.dispatch(tr.scrollIntoView()));
120120
}
121121

122+
/**
123+
* Enter at the end of a line that would close the fence, such as ```` ``` ````
124+
* typed under the code, ends the block there. That line becomes the closing
125+
* fence, and any lines after it continue as paragraphs after a new empty one,
126+
* which is how the stored draft reads them.
127+
*/
128+
export function exitCodeBlockOnClosingFence(
129+
state: EditorState,
130+
dispatch?: (transaction: Transaction) => void,
131+
): boolean {
132+
const block = codeBlockRange(state);
133+
if (!block || !state.selection.empty) return false;
134+
const caret = state.selection.from - block.from;
135+
const lineStart = block.text.lastIndexOf("\n", caret - 1) + 1;
136+
const newlineAfter = block.text.indexOf("\n", caret);
137+
const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
138+
const line = block.text.slice(lineStart, lineEnd);
139+
const node = state.selection.$from.parent;
140+
if (caret !== lineEnd || !isClosingFence(line, String(node.attrs.fence))) return false;
141+
142+
if (dispatch) {
143+
const { schema } = state;
144+
const paragraph = (text: string) =>
145+
schema.nodes.paragraph!.create(null, text ? schema.text(text) : null);
146+
const code = block.text.slice(0, Math.max(0, lineStart - 1));
147+
const rest = newlineAfter === -1 ? [] : block.text.slice(newlineAfter + 1).split("\n");
148+
const closed = node.type.create(
149+
{ ...node.attrs, close: `\n${line}` },
150+
code ? schema.text(code) : null,
151+
);
152+
const start = state.selection.$from.before();
153+
const transaction = state.tr.replaceWith(start, start + node.nodeSize, [
154+
closed,
155+
paragraph(""),
156+
...rest.map(paragraph),
157+
]);
158+
transaction.setSelection(TextSelection.create(transaction.doc, start + closed.nodeSize + 1));
159+
dispatch(transaction.scrollIntoView());
160+
}
161+
return true;
162+
}
163+
122164
/**
123165
* Tab and Shift+Tab inside a fence. A collapsed cursor indents at the caret so
124166
* Tab works mid-line the way typing does; any selection spanning text indents
@@ -190,9 +232,10 @@ export function convertCodeFenceOnEnter(
190232
// to write a fence into, so one created inside them would vanish.
191233
if (!empty || $from.parent.type.name !== "paragraph" || $from.depth !== 1) return false;
192234
if ($from.parentOffset !== $from.parent.content.size) return false;
193-
// The parser's own grammar, so a line Enter turns into a fence is exactly
194-
// one the stored draft reads back as a fence, info string and all.
195-
const opening = parseOpeningFence($from.parent.textContent);
235+
// The parser's own grammar, read from the line's stored source, so a line
236+
// Enter turns into a fence is exactly one the stored draft reads back as a
237+
// fence, info string and all, including any chip's source in it.
238+
const opening = parseOpeningFence(serializeSelection(state.doc, $from.start(), $from.end()));
196239
const codeBlock = state.schema.nodes.codeBlock;
197240
if (!opening || !codeBlock) return false;
198241

0 commit comments

Comments
 (0)