@devries-cameron20 / t3code Mirror · read-only
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, 03:37 UTC

main
ts 1,529 lines 55.8 KB
Raw
1 import { Editor, getSchemaByResolvedExtensions, Node, resolveExtensions } from "@tiptap/core";
2 import StarterKit from "@tiptap/starter-kit";
3 import { TaskList } from "@tiptap/extension-task-list";
4 import { Node as ProseMirrorNode } from "@tiptap/pm/model";
5 import { EditorState, TextSelection } from "@tiptap/pm/state";
6 import { splitBlockKeepMarks } from "@tiptap/pm/commands";
7 import { describe, expect, it, onTestFinished } from "vite-plus/test";
8 import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
9
10 import {
11 collapseExpandedComposerCursor,
12 expandCollapsedComposerCursor,
13 pastedPathQueryLength,
14 } from "./composer-logic";
15
16 import {
17 buildDocJson,
18 buildTiptapContent,
19 caretTakesMarksBefore,
20 ComposerBlockExtensions,
21 ComposerCodeBlockExtension,
22 ComposerListExtensions,
23 ComposerBoldExtension,
24 ComposerCodeExtension,
25 ComposerItalicExtension,
26 ComposerStrikeExtension,
27 ComposerTaskItemExtension,
28 flatToMarkdown,
29 flatToPm,
30 markdownToFlat,
31 pmToFlat,
32 serializeEditorDoc,
33 serializedMarkdownOffset,
34 serializeSelection,
35 skillChipReplacements,
36 stepCaretAcrossStyledEdge,
37 surroundSelectionWithMark,
38 } from "./composer-rich-text-doc";
39
40 function stubAtom(name: string, attrs: Record<string, { default: unknown }>) {
41 return Node.create({
42 name,
43 group: "inline",
44 inline: true,
45 atom: true,
46 addAttributes: () => attrs,
47 });
48 }
49
50 const schema = getSchemaByResolvedExtensions(
51 resolveExtensions([
52 StarterKit.configure({
53 blockquote: false,
54 bulletList: false,
55 codeBlock: false,
56 heading: false,
57 horizontalRule: false,
58 listItem: false,
59 orderedList: false,
60 dropcursor: false,
61 gapcursor: false,
62 trailingNode: false,
63 code: false,
64 }),
65 ComposerCodeExtension,
66 stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
67 stubAtom("composer-skill", {
68 skillName: { default: "" },
69 skillLabel: { default: "" },
70 skillDescription: { default: null },
71 }),
72 stubAtom("composer-model", {
73 instanceId: { default: "" },
74 model: { default: "" },
75 source: { default: "" },
76 }),
77 stubAtom("composer-citation", {
78 citation: { default: null },
79 source: { default: "" },
80 citeKey: { default: "" },
81 }),
82 stubAtom("composer-context-reference", {
83 kind: { default: "" },
84 contextId: { default: "" },
85 label: { default: "" },
86 source: { default: "" },
87 }),
88 TaskList,
89 ComposerTaskItemExtension,
90 ComposerCodeBlockExtension,
91 ...ComposerListExtensions,
92 ...ComposerBlockExtensions,
93 ]),
94 );
95
96 function roundTrip(value: string) {
97 const json = buildDocJson(value, (name) => ({ label: name, description: null }));
98 const doc = ProseMirrorNode.fromJSON(schema, json);
99 // `insertContent` validates every node against the schema; `fromJSON` does not.
100 doc.check();
101 return serializeEditorDoc(doc);
102 }
103
104 describe("editable math source", () => {
105 it.each(["app/routes/posts.$postId.tsx", "pages/posts/[id].tsx"])(
106 "keeps a mentioned file whose name looks like TeX as a chip: %s",
107 (path) => {
108 const source = `fix ${serializeComposerFileLink(path)} please`;
109 const map = roundTrip(source);
110 expect(map.value).toBe(source);
111 expect(
112 map.runs.filter((run) => run.kind === "token" && run.nodeName === "composer-mention"),
113 ).toHaveLength(1);
114 },
115 );
116
117 it.each([
118 "before $x + @README.md$ after",
119 "before \\(x + @README.md\\) after",
120 "\\[x + @README.md\\] after",
121 ])("keeps a mention that ends a formula inside the formula: %s", (source) => {
122 const map = roundTrip(source);
123 expect(map.value).toBe(source);
124 expect(map.runs.some((run) => run.kind === "token")).toBe(false);
125 });
126
127 it.each([
128 "Area $x_i^2$ after",
129 "before \\(\\frac{1}{2}\\) after",
130 "before $$x^2$$ after",
131 "\\[\nx = 1\ny = 2\n\\]",
132 "\\[\\text{use $browser then @README.md and **literal**}\\]",
133 "```math\nx_i + y_i\n```",
134 "- **use** $x_i$ then @README.md",
135 "**$x_i$** and **A $x_i$ B**",
136 "| Name | Formula |\n| --- | --- |\n| Norm | $|x|$ |",
137 "| Name | Formula |\n| --- | --- |\n| Norm | \\(\\|x\\|\\) |",
138 ])("keeps TeX editable and round trips its source: %s", (source) => {
139 const map = roundTrip(source);
140 expect(map.value).toBe(source);
141 expect(map.runs.some((run) => run.nodeName === "composer-math")).toBe(false);
142 const doc = schema.nodeFromJSON(
143 buildDocJson(source, (name) => ({ label: name, description: null })),
144 );
145 expect(serializeSelection(doc, 1, doc.content.size - 1)).toBe(source);
146 });
147
148 it("edits a command character directly without replacing a formula node", () => {
149 const source = "before \\(\\frac{a}{b}\\) after";
150 const doc = schema.nodeFromJSON(
151 buildDocJson(source, (name) => ({ label: name, description: null })),
152 );
153 const map = serializeEditorDoc(doc);
154 const offset = source.indexOf("{a}") + 1;
155 const position = flatToPm(map, offset);
156 const state = EditorState.create({ doc });
157 const next = state.apply(state.tr.insertText("c", position, position + 1));
158 expect(serializeEditorDoc(next.doc).value).toBe(source.replace("{a}", "{c}"));
159 });
160 it("preserves formula source as text when styling is disabled", () => {
161 const source =
162 "\\[\n\\text{use $browser, @README.md and [file](t3-context://v1/file/ctx_1)}\n\\]";
163 const doc = plainSchema.nodeFromJSON(
164 buildDocJson(source, (name) => ({ label: name, description: null }), { styling: false }),
165 );
166 const map = serializeEditorDoc(doc);
167 expect(map.value).toBe(source);
168 expect(map.runs.some((run) => run.kind === "token")).toBe(false);
169 });
170 });
171
172 // Plain mode: the same engine with the mark extensions off. Markers stay
173 // literal characters and task lines stay paragraphs.
174 const plainSchema = getSchemaByResolvedExtensions(
175 resolveExtensions([
176 StarterKit.configure({
177 blockquote: false,
178 bulletList: false,
179 codeBlock: false,
180 heading: false,
181 horizontalRule: false,
182 listItem: false,
183 orderedList: false,
184 dropcursor: false,
185 gapcursor: false,
186 trailingNode: false,
187 bold: false,
188 italic: false,
189 strike: false,
190 code: false,
191 }),
192 stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
193 stubAtom("composer-skill", {
194 skillName: { default: "" },
195 skillLabel: { default: "" },
196 skillDescription: { default: null },
197 }),
198 stubAtom("composer-model", {
199 instanceId: { default: "" },
200 model: { default: "" },
201 source: { default: "" },
202 }),
203 stubAtom("composer-citation", {
204 citation: { default: null },
205 source: { default: "" },
206 citeKey: { default: "" },
207 }),
208 stubAtom("composer-context-reference", {
209 kind: { default: "" },
210 contextId: { default: "" },
211 label: { default: "" },
212 source: { default: "" },
213 }),
214 TaskList,
215 ComposerTaskItemExtension,
216 ]),
217 );
218
219 function roundTripPlain(value: string) {
220 const json = buildDocJson(value, (name) => ({ label: name, description: null }), {
221 styling: false,
222 });
223 const doc = ProseMirrorNode.fromJSON(plainSchema, json);
224 return serializeEditorDoc(doc);
225 }
226
227 describe("literal editor answers", () => {
228 const makeDoc = (value: string) =>
229 ProseMirrorNode.fromJSON(
230 plainSchema,
231 buildDocJson(value, (name) => ({ label: name, description: null }), {
232 literalText: true,
233 }),
234 );
235
236 it.each([
237 "",
238 "\n\n",
239 " - [X] done\n\n**keep** €my-skill @README.md \n",
240 "line one\r\nline two\r\n",
241 `- [X] done\n${" detail €my-skill @README.md\n".repeat(100)}`,
242 ])("preserves the complete answer through selection and serialization", (value) => {
243 const doc = makeDoc(value);
244 doc.check();
245 const serialized = serializeEditorDoc(doc);
246 expect(serialized.value).toBe(value);
247 expect(serialized.contextIds).toEqual([]);
248 expect(serializeSelection(doc, 1, doc.content.size - 1)).toBe(value);
249 for (let offset = 0; offset <= value.length; offset += 1) {
250 expect(collapseExpandedComposerCursor(value, flatToMarkdown(serialized, offset), true)).toBe(
251 offset,
252 );
253 }
254 });
255
256 it("edits literal Markdown, inserts a newline, and preserves an explicitly cleared answer", () => {
257 const value = " - [X] done €my-skill @README.md ";
258 const doc = makeDoc(value);
259 let state = EditorState.create({
260 doc,
261 selection: TextSelection.create(doc, doc.content.size - 1),
262 });
263 state = state.apply(state.tr.insertText(" edited"));
264 expect(
265 splitBlockKeepMarks(state, (transaction) => {
266 state = state.apply(transaction);
267 }),
268 ).toBe(true);
269 state = state.apply(state.tr.insertText("second line "));
270 expect(serializeEditorDoc(state.doc).value).toBe(`${value} edited\nsecond line `);
271 state = state.apply(state.tr.delete(1, state.doc.content.size - 1));
272 expect(serializeEditorDoc(state.doc).value).toBe("");
273 });
274 });
275
276 describe("composer rich text document model", () => {
277 it.each(["€", "£", "¥", "₹", "₩", "₿", "𑿝"])(
278 "canonicalizes %s skill aliases while preserving amounts",
279 (prefix) => {
280 const value = `Use ${prefix}my-skill for ${prefix}20 please`;
281 const expected = `Use $my-skill for ${prefix}20 please`;
282 expect(roundTrip(value).value).toBe(expected);
283 expect(roundTripPlain(value).value).toBe(expected);
284 },
285 );
286
287 it.each([
288 "",
289 "\n\n",
290 "plain text",
291 "hello **bold** world",
292 "a *italic* word and `code` here",
293 "struck ~~out~~ now",
294 "**`x`**",
295 "*`x`*",
296 "~~`x`~~",
297 "**a `code` c**",
298 "***bold italic*** keeps nesting",
299 "line one\nline two",
300 "trailing newline\n",
301 "1. foo\n2. asdf\n",
302 "- [ ] buy milk",
303 "- [ ] buy milk",
304 "\t-\t[x]\t\titem",
305 "- [ ] ",
306 "- [ ]\n - [ ] child",
307 " - [ ] first\n - [ ] second\n - [ ] child",
308 "**before @README.md after**",
309 "*a **b** c*",
310 "*a**b***",
311 "**a*b***",
312 "**a *b* c**",
313 "literal \uFFFC **before @README.md after**",
314 "- [x] done\n- [ ] next",
315 "- [ ] parent\n - [ ] child\n - [ ] sibling\n- [ ] uncle",
316 "- [ ] empty task follows\n- [ ]",
317 "- [ ] **bold** task with @README.md",
318 "para\n- [ ] task\n\npara",
319 "- [ ]No space stays literal",
320 "-[ ] also literal",
321 "@README.md explain this",
322 '@"docs/My File.md" and $my-skill please',
323 "snake_case stays literal",
324 "unmatched ** stays literal",
325 "**bold** then @README.md then *italic*",
326 ])("round-trips %s through a real ProseMirror document", (value) => {
327 expect(roundTrip(value).value).toBe(value);
328 });
329
330 it.each([
331 "",
332 "\n",
333 "text\n\n",
334 "- [ ]\n- [ ] next\n",
335 "- [ ] parent\n - [ ] child\n- [ ]",
336 "para\n- [ ] task\npara",
337 "**before @README.md after**",
338 ])("maps editable positions in %s", (value) => {
339 const doc = ProseMirrorNode.fromJSON(
340 schema,
341 buildDocJson(value, (name) => ({ label: name, description: null })),
342 );
343 const map = serializeEditorDoc(doc);
344 for (let flat = 0; flat <= map.docLength; flat += 1) {
345 const position = flatToPm(map, flat);
346 expect(doc.resolve(position).parent.isTextblock).toBe(true);
347 expect(pmToFlat(map, position)).toBe(flat);
348 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
349 }
350 });
351
352 it("keeps the caret after a trailing hard break inside the same paragraph", () => {
353 const doc = schema.node("doc", null, [
354 schema.node("paragraph", null, [schema.text("a"), schema.node("hardBreak")]),
355 ]);
356 const map = serializeEditorDoc(doc);
357 expect(flatToPm(map, map.docLength)).toBe(3);
358 expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);
359 });
360
361 it("renders a leading task dedent as siblings and nests under the new indent", () => {
362 const doc = ProseMirrorNode.fromJSON(
363 schema,
364 buildDocJson(" - [ ] first\n - [ ] second\n - [ ] child", (name) => ({
365 label: name,
366 description: null,
367 })),
368 );
369 const list = doc.firstChild!;
370 expect(list.childCount).toBe(2);
371 expect(list.child(0).childCount).toBe(1);
372 expect(list.child(1).child(1).firstChild!.textContent).toBe("child");
373 });
374
375 it("applies a shared mark to text on both sides of a chip", () => {
376 const doc = ProseMirrorNode.fromJSON(
377 schema,
378 buildDocJson("**before @README.md after**", (name) => ({ label: name, description: null })),
379 );
380 expect(doc.firstChild!.childCount).toBe(3);
381 doc.firstChild!.forEach((child) =>
382 expect(child.marks.map((mark) => mark.type.name)).toContain("bold"),
383 );
384 expect(serializeEditorDoc(doc).value).toBe("**before @README.md after**");
385 });
386
387 it.each([
388 [["bold"], ["bold", "italic"], ["italic"]],
389 [["italic"], ["bold", "italic"], ["bold"]],
390 [["bold"], ["bold", "strike"], ["strike"]],
391 [["strike"], ["bold", "strike"], ["bold"]],
392 ])("preserves crossing mark ranges %j through controlled rebuilds", (...marks) => {
393 const doc = schema.node("doc", null, [
394 schema.node(
395 "paragraph",
396 null,
397 marks.map((names, index) =>
398 schema.text(
399 String.fromCharCode(97 + index),
400 names.map((name) => schema.mark(name)),
401 ),
402 ),
403 ),
404 ]);
405 const serialized = serializeEditorDoc(doc).value;
406 const rebuilt = ProseMirrorNode.fromJSON(
407 schema,
408 buildDocJson(serialized, (name) => ({ label: name, description: null })),
409 );
410 expect(rebuilt.eq(doc)).toBe(true);
411 expect(serializeEditorDoc(rebuilt).value).toBe(serialized);
412 });
413
414 it.each([
415 { parts: [{ text: "hello ", marks: ["bold"] }], expected: "**hello** " },
416 { parts: [{ text: " ", marks: ["bold"] }], expected: " " },
417 { parts: [{ text: " left ", marks: ["bold", "italic"] }], expected: " ***left*** " },
418 {
419 parts: [
420 { text: "one ", marks: ["bold"] },
421 { text: " two ", marks: ["bold", "italic"] },
422 { text: " three", marks: ["bold"] },
423 ],
424 expected: "**one *two* three**",
425 },
426 {
427 parts: [
428 { text: "hello ", marks: ["bold"] },
429 { text: "world ", marks: ["bold", "italic"] },
430 ],
431 expected: "**hello *world*** ",
432 },
433 { parts: [{ text: " hello ", marks: ["code"] }], expected: "` hello `" },
434 { parts: [{ text: " hello ", marks: ["bold", "code"] }], expected: "**` hello `**" },
435 { parts: [{ text: " ", marks: ["bold", "code"] }], expected: "**` `**" },
436 ])("keeps boundary whitespace outside emphasis in $expected", ({ parts, expected }) => {
437 const doc = schema.node("doc", null, [
438 schema.node(
439 "paragraph",
440 null,
441 parts.map(({ text, marks }) =>
442 schema.text(
443 text,
444 marks.map((name) => schema.mark(name)),
445 ),
446 ),
447 ),
448 ]);
449 const map = serializeEditorDoc(doc);
450 expect(map.value).toBe(expected);
451 const rebuilt = ProseMirrorNode.fromJSON(
452 schema,
453 buildDocJson(map.value, (name) => ({ label: name, description: null })),
454 );
455 expect(rebuilt.textContent).toBe(doc.textContent);
456 expect(serializeEditorDoc(rebuilt).value).toBe(map.value);
457 for (let flat = 0; flat <= map.docLength; flat += 1) {
458 expect(pmToFlat(map, flatToPm(map, flat))).toBe(flat);
459 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
460 if (flat < map.docLength && !/\s/.test(doc.textContent[flat]!)) {
461 expect(rebuilt.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name)).toEqual(
462 doc.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name),
463 );
464 }
465 }
466 });
467
468 it.each([
469 "plain text",
470 "hello **bold** stays literal",
471 "a *italic* stays literal",
472 "some `code` stays literal",
473 "struck ~~out~~ stays literal",
474 "- [ ] stays a paragraph",
475 "- [x] stays a paragraph",
476 "line one\nline two",
477 "@README.md explain this",
478 "**bold** then @README.md then *italic*",
479 ])("round-trips %s byte-identically in plain mode", (value) => {
480 expect(roundTripPlain(value).value).toBe(value);
481 });
482
483 it.each([
484 "- one\n- two",
485 "* star\n* star two",
486 "+ plus",
487 "* star\n+ plus",
488 "1. first\n2. second",
489 "1) paren\n2) paren",
490 "3. starts at three\n4. four",
491 "01. zero padded\n02. two",
492 "- parent\n - child\n - sibling\n- uncle",
493 "1. ordered\n - bullet child\n2. next",
494 "- outer\n 1. inner ordered\n 2. more\n- outer again",
495 "- wide space item",
496 "-",
497 "1.",
498 "- \n- second",
499 "- **bold** item with @README.md",
500 "- [ ] task\n- bullet after",
501 "- bullet\n- [x] task after",
502 "para\n- item\n\npara",
503 "\t- tab indented\n\t- again",
504 " - leading indent only",
505 "- item\n\n- after a blank",
506 "- item one\n```ts\ncode\n```\n- item two",
507 "-no space stays literal",
508 "1.no space stays literal",
509 "10. ten\n11. eleven",
510 ])("round-trips the list %s through a real ProseMirror document", (value) => {
511 expect(roundTrip(value).value).toBe(value);
512 });
513
514 it("clamps offsets inside a list marker to the start of the item text", () => {
515 const value = "- item";
516 const map = roundTrip(value);
517 for (let markdown = 0; markdown <= "- ".length; markdown += 1) {
518 expect(markdownToFlat(map, markdown)).toBe(0);
519 }
520 expect(markdownToFlat(map, "- it".length)).toBe(2);
521 expect(flatToMarkdown(map, 0)).toBe("- ".length);
522 });
523
524 it.each([
525 "> quoted",
526 "> line one\n> line two",
527 ">no space",
528 "> two spaces",
529 "> a\n>b",
530 ">",
531 "> **bold** and @README.md inside",
532 "> - looks like a list but stays quote text",
533 "> > nested stays literal inside the quote",
534 "before\n> quoted",
535 "> quote\n\n> another",
536 "- item\n> quote after list",
537 "> quoted\n\ncomment",
538 "> line one\n> line two\n\ncomment",
539 ])("round-trips the quote %s through a real ProseMirror document", (value) => {
540 expect(roundTrip(value).value).toBe(value);
541 });
542
543 describe("a paragraph after a quote", () => {
544 const paragraph = (text?: string) => ({
545 type: "paragraph",
546 ...(text ? { content: [{ type: "text", text }] } : {}),
547 });
548 const quote = (...lines: string[]) => ({
549 type: "blockquote",
550 attrs: { prefix: "> " },
551 content: lines.map((line) => paragraph(line)),
552 });
553 const serialize = (...content: object[]) => {
554 const doc = ProseMirrorNode.fromJSON(schema, { type: "doc", content });
555 doc.check();
556 return { doc, map: serializeEditorDoc(doc) };
557 };
558
559 it("is written after a blank line, or Markdown folds it into the quote", () => {
560 expect(serialize(quote("quoted"), paragraph("Comment to it")).map.value).toBe(
561 "> quoted\n\nComment to it",
562 );
563 expect(serialize(quote("a", "b"), paragraph("comment")).map.value).toBe(
564 "> a\n> b\n\ncomment",
565 );
566 });
567
568 it("does not double up on the empty line the user left themselves", () => {
569 expect(serialize(quote("quoted"), paragraph(), paragraph("Comment to it")).map.value).toBe(
570 "> quoted\n\nComment to it",
571 );
572 });
573
574 it("reopens without an empty line between the quote and the comment", () => {
575 const { doc, map } = serialize(quote("quoted"), paragraph("Comment to it"));
576 const reopened = ProseMirrorNode.fromJSON(
577 schema,
578 buildDocJson(map.value, (name) => ({ label: name, description: null })),
579 );
580 expect(reopened.toJSON()).toEqual(doc.toJSON());
581 });
582
583 it("settles on the blank line when a draft glued it to the quote", () => {
584 const settled = "before\n> quoted\n\nafter";
585 expect(roundTrip("before\n> quoted\nafter").value).toBe(settled);
586 expect(roundTrip(settled).value).toBe(settled);
587 });
588
589 it.each(["# Heading", "- item", "3. item", "---", "```\ncode\n```"])(
590 "leaves %s on the next line, since it opens its own block",
591 (next) => {
592 const value = `> quoted\n${next}`;
593 expect(roundTrip(value).value).toBe(value);
594 },
595 );
596
597 it("keeps every offset mapped through the blank line", () => {
598 const { doc, map } = serialize(quote("quoted"), paragraph("Comment"));
599 for (let flat = 0; flat <= map.docLength; flat += 1) {
600 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
601 }
602 // The caret on the end of the quote stays on it, and the blank line is
603 // not a place to type: it clamps to the start of the comment.
604 expect(flatToMarkdown(map, "quoted".length)).toBe("> quoted".length);
605 expect(markdownToFlat(map, "> quoted\n".length)).toBe("quoted".length + 1);
606 expect(flatToMarkdown(map, "quoted".length + 1)).toBe("> quoted\n\n".length);
607 expect(flatToPm(map, "quoted".length + 1)).toBe(doc.child(0).nodeSize + 1);
608 });
609 });
610
611 describe("a paragraph after a list", () => {
612 const skillLabelFor = (name: string) => ({ label: name, description: null });
613 it.each([
614 ["a numbered list", "1. a\n2. b\n3. c", 0],
615 ["a bullet list", "- a\n- b", 0],
616 ["a task list", "- [ ] a", 0],
617 ["a bullet list and an empty line", "- a", 1],
618 ])(
619 "is written after a blank line after %s, or Markdown folds it into the last item",
620 (_kind, list, emptyLines) => {
621 const listJson = buildDocJson(list, skillLabelFor);
622 const doc = ProseMirrorNode.fromJSON(schema, {
623 type: "doc",
624 content: [
625 ...listJson.content,
626 ...Array.from({ length: emptyLines }, () => ({ type: "paragraph" })),
627 { type: "paragraph", content: [{ type: "text", text: "d" }] },
628 ],
629 });
630 doc.check();
631 expect(doc.childCount).toBe(2 + emptyLines);
632 const { value } = serializeEditorDoc(doc);
633 expect(value).toBe(`${list}\n\n${"\n".repeat(emptyLines)}d`);
634 const reopened = ProseMirrorNode.fromJSON(schema, buildDocJson(value, skillLabelFor));
635 expect(reopened.toJSON()).toEqual(doc.toJSON());
636 },
637 );
638 });
639
640 describe("a dash rule after a paragraph", () => {
641 const paragraph = (text: string) => ({ type: "paragraph", content: [{ type: "text", text }] });
642 const rule = (source: string) => ({ type: "horizontalRule", attrs: { source } });
643 const serialize = (...content: object[]) => {
644 const doc = ProseMirrorNode.fromJSON(schema, { type: "doc", content });
645 doc.check();
646 return { doc, map: serializeEditorDoc(doc) };
647 };
648
649 it("is written after a blank line, or Markdown reads the paragraph as a heading", () => {
650 const settled = "text\n\n---\nmore";
651 expect(roundTrip("text\n---\nmore").value).toBe(settled);
652 expect(roundTrip(settled).value).toBe(settled);
653 });
654
655 it("keeps every offset mapped through the blank line", () => {
656 const { doc, map } = serialize(paragraph("text"), rule("---"), paragraph("more"));
657 expect(map.value).toBe("text\n\n---\nmore");
658 for (let flat = 0; flat <= map.docLength; flat += 1) {
659 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
660 }
661 // The blank line is not a place to type: it clamps to the rule.
662 expect(flatToMarkdown(map, "text".length)).toBe("text".length);
663 expect(markdownToFlat(map, "text\n".length)).toBe("text".length + 1);
664 expect(flatToMarkdown(map, "text".length + 1)).toBe("text\n\n---".length);
665 expect(flatToPm(map, "text".length + 1)).toBe(doc.child(0).nodeSize + doc.child(1).nodeSize);
666 });
667 });
668
669 it.each([
670 ["text\n---\nmore", "text\n---\nm".length, "text\n\n---\nm".length],
671 ["before\n> quoted\nafter", "before\n> quoted\na".length, "before\n> quoted\n\na".length],
672 ["__x__\n---\nmore", "__x__\n---\nm".length, "**x**\n\n---\nm".length],
673 [
674 "*a*_b_\n> q\nx\n> q\nabcde",
675 "*a*_b_\n> q\nx\n> q\na".length,
676 "*a*_b_\n> q\nx\n> q\na".length,
677 ],
678 ["a\n---\n", "a".length, "a".length],
679 ])("restores a caret in the glued draft %j on the same character", (value, caret, settled) => {
680 const map = roundTrip(value);
681 const restore = (offset: number) =>
682 markdownToFlat(map, serializedMarkdownOffset(value, map.value, offset));
683 expect(restore(value.length)).toBe(map.docLength);
684 expect(restore(caret)).toBe(markdownToFlat(map, settled));
685 });
686
687 it.each([
688 "---",
689 "***",
690 "___",
691 "- - -",
692 "* * *",
693 "-----",
694 "--- ",
695 "text\n***\nmore",
696 "text\n- - -\nmore",
697 "- item\n---\n- item two",
698 "```\n---\n```",
699 "--",
700 "-- -",
701 "---text",
702 ])("round-trips the rule %s through a real ProseMirror document", (value) => {
703 expect(roundTrip(value).value).toBe(value);
704 });
705
706 it("parses rules ahead of lists and emphasis", () => {
707 const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({
708 label: n,
709 description: null,
710 }));
711 expect(json.content.map((block) => block.type)).toEqual([
712 "horizontalRule",
713 "horizontalRule",
714 "horizontalRule",
715 "paragraph",
716 "horizontalRule",
717 "bulletList",
718 ]);
719 });
720
721 it.each([
722 "# Heading",
723 "## Two",
724 "###### Six",
725 "####### seven hashes stays a paragraph",
726 "# two spaces",
727 "#\tTab",
728 "# Trailing hashes stay literal #",
729 "#1234",
730 "#1234 is a pull request, not a heading",
731 "# Heading with **bold** and @README.md",
732 "#",
733 "# ",
734 "text\n# Heading\ntext",
735 "# Heading\n- item\n> quote\n---",
736 ])("round-trips the heading %s through a real ProseMirror document", (value) => {
737 expect(roundTrip(value).value).toBe(value);
738 });
739
740 it.each([
741 ["---", "---"],
742 ["a\n---", "a\n\n---"],
743 ["---\n", "---"],
744 ])("gives the caret a line after the final rule of %j, written %j", (value, expected) => {
745 const map = roundTrip(value);
746 expect(map.value).toBe(expected);
747 const json = buildDocJson(value, () => ({ label: "", description: null }));
748 const doc = ProseMirrorNode.fromJSON(schema, json);
749 expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);
750 });
751
752 it.each([
753 "```\ncode\n```",
754 "```ts\nconst a = 1;\n```",
755 "```ts\nconst a = 1;\n```\n",
756 "before\n```ts\nconst a = 1;\n```\nafter",
757 "```\n```",
758 "```ts\nline one\nline two\nline three\n```",
759 "```ts\n indented\n deeper\n```",
760 "```js title=example\ncode\n```",
761 "~~~py\ncode\n~~~",
762 "````\n```\n````",
763 "```ts\ncode without a closing fence",
764 "```",
765 "```ts\n**not bold** and @README.md stay literal\n```",
766 "```ts\ncode\n````",
767 "- [ ] task\n```ts\ncode\n```\n- [ ] after",
768 " ```ts\nindented fence stays a paragraph\n ```",
769 ])("round-trips the fenced block %s", (value) => {
770 expect(roundTrip(value).value).toBe(value);
771 });
772
773 it("reads blocks written with CRLF line endings", () => {
774 const value = "# Title\r\n> quote\r\n---\r\n```ts\r\nconst a = 1;\r\n```\r\nafter";
775 const doc = buildDocJson(value, () => ({ label: "", description: null }));
776 expect(doc.content.map((block) => block.type)).toEqual([
777 "heading",
778 "blockquote",
779 "horizontalRule",
780 "codeBlock",
781 "paragraph",
782 ]);
783 expect(roundTrip(value).value).toBe(value);
784 });
785
786 it("keeps the caret inside an empty fence", () => {
787 const value = "before\n```\n```";
788 const map = roundTrip(value);
789 const inside = "before\n".length;
790 expect(flatToMarkdown(map, inside)).toBe("before\n```".length);
791 expect(markdownToFlat(map, flatToMarkdown(map, inside))).toBe(inside);
792 });
793
794 it("clamps offsets inside a fence to the edge of the code", () => {
795 const value = "```ts\nab\n```";
796 const map = roundTrip(value);
797 expect(map.value).toBe(value);
798 for (let markdown = 0; markdown <= "```ts\n".length; markdown += 1) {
799 expect(markdownToFlat(map, markdown)).toBe(0);
800 }
801 expect(markdownToFlat(map, "```ts\na".length)).toBe(1);
802 for (let markdown = "```ts\nab".length; markdown <= value.length; markdown += 1) {
803 expect(markdownToFlat(map, markdown)).toBe(2);
804 }
805 });
806
807 it("keeps a chip in a fence info string as source and keeps later chips aligned", () => {
808 const value = "```@README.md\ncode\n```\n$my-skill after";
809 expect(roundTrip(value).value).toBe(value);
810 const json = buildDocJson(value, (n) => ({ label: n, description: null }));
811 const after = json.content[1] as {
812 content: { type: string; attrs?: { skillName?: string } }[];
813 };
814 expect(after.content.map((n) => n.type)).toEqual(["composer-skill", "text"]);
815 expect(after.content[0]?.attrs?.skillName).toBe("my-skill");
816 });
817
818 it("writes code holding a closing fence inside a longer fence", () => {
819 const doc = ProseMirrorNode.fromJSON(schema, {
820 type: "doc",
821 content: [
822 {
823 type: "codeBlock",
824 attrs: { fence: "```", close: "\n```" },
825 content: [{ type: "text", text: "initial\n```\nsecret" }],
826 },
827 ],
828 });
829 const stored = serializeEditorDoc(doc).value;
830 expect(stored).toBe("````\ninitial\n```\nsecret\n````");
831 expect(buildDocJson(stored, () => ({ label: "", description: null })).content).toHaveLength(1);
832 expect(roundTrip(stored).value).toBe(stored);
833 });
834
835 it("closes an unclosed fence that has a block after it", () => {
836 const doc = ProseMirrorNode.fromJSON(schema, {
837 type: "doc",
838 content: [
839 { type: "codeBlock", attrs: { close: "" }, content: [{ type: "text", text: "code" }] },
840 { type: "paragraph", content: [{ type: "text", text: "after" }] },
841 ],
842 });
843 expect(serializeEditorDoc(doc).value).toBe("```\ncode\n```\nafter");
844 expect(roundTrip("```\ncode").value).toBe("```\ncode");
845 });
846
847 it("keeps a chip's source in a fence as literal text", () => {
848 const value = "```\nsee @b.md and $babysit now model:codex/gpt-6.1 ok\n```\nafter";
849 const known = () => ({ label: "Babysit", description: null });
850 const anyModel = () => true;
851 const doc = ProseMirrorNode.fromJSON(
852 schema,
853 buildDocJson(value, known, { isKnownModel: anyModel }),
854 );
855 const map = serializeEditorDoc(doc);
856 expect(map.value).toBe(value);
857 expect(map.runs.filter((run) => run.kind === "token")).toEqual([]);
858 for (let flat = 0; flat <= map.docLength; flat += 1) {
859 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
860 }
861 // Reconciling against the provider's skills and models leaves the code alone too.
862 expect(skillChipReplacements(doc, known, anyModel)).toEqual([]);
863 });
864
865 it.each([
866 "plain prose with no styling at all",
867 "a chip @README.md counts one character in both modes",
868 "$my-skill leads the line",
869 "trailing newline\n",
870 ])("resolves a collapsed cursor identically in both modes for %s", (value) => {
871 const rich = roundTrip(value);
872 const plain = roundTripPlain(value);
873 expect(rich.value).toBe(value);
874 expect(plain.value).toBe(value);
875 for (let collapsed = 0; collapsed <= value.length; collapsed += 1) {
876 const markdown = expandCollapsedComposerCursor(value, collapsed);
877 expect(flatToMarkdown(rich, markdownToFlat(rich, markdown))).toBe(
878 flatToMarkdown(plain, markdownToFlat(plain, markdown)),
879 );
880 }
881 });
882
883 it("clamps a cursor that was sitting inside a marker onto the styled text", () => {
884 const value = "a **bold** c";
885 const plain = roundTripPlain(value);
886 const rich = roundTrip(value);
887 expect(flatToMarkdown(plain, markdownToFlat(plain, 3))).toBe(3);
888 expect(flatToMarkdown(rich, markdownToFlat(rich, 3))).toBe(4);
889 });
890 });
891
892 describe("serializeSelection", () => {
893 function copy(value: string, first: string, last: string) {
894 const doc = ProseMirrorNode.fromJSON(
895 schema,
896 buildDocJson(value, (name) => ({ label: name, description: null })),
897 );
898 let from = -1;
899 let to = -1;
900 doc.descendants((node, pos) => {
901 if (!node.isText) return true;
902 const text = node.text ?? "";
903 if (from < 0 && text.includes(first)) from = pos + text.indexOf(first);
904 if (text.includes(last)) to = pos + text.lastIndexOf(last) + last.length;
905 return false;
906 });
907 return serializeSelection(doc, from, to);
908 }
909
910 it("keeps the markers of the list items it spans", () => {
911 expect(copy("- one\n- two\n- three", "one", "two")).toBe("- one\n- two");
912 expect(copy("3) one\n4) two", "one", "two")).toBe("3) one\n4) two");
913 expect(copy("- [ ] one\n- [x] two", "one", "two")).toBe("- [ ] one\n- [x] two");
914 });
915
916 it("keeps the nesting of an item and its children", () => {
917 expect(copy("- p\n - a\n - b", "p", "a")).toBe("- p\n - a");
918 });
919 });
920
921 describe("pasting into a list item or quote", () => {
922 it("keeps inline marks but builds no blocks", () => {
923 const content = buildTiptapContent(
924 "**bold** text\n- item\n> quote",
925 () => ({ label: "", description: null }),
926 { styling: true, blocks: false },
927 );
928 expect(content.map((block) => block.type)).toEqual(["paragraph", "paragraph", "paragraph"]);
929 const first = content[0] as { content: { text: string; marks?: { type: string }[] }[] };
930 expect(first.content[0]).toMatchObject({ text: "bold", marks: [{ type: "bold" }] });
931 expect(JSON.stringify(content[1])).toContain("- item");
932 expect(JSON.stringify(content[2])).toContain("> quote");
933 });
934 });
935
936 describe("model mention chips", () => {
937 const skillLabelFor = (name: string) => ({ label: name, description: null });
938 const isCodexModel = (instanceId: string, model: string) =>
939 instanceId === "codex" && model === "gpt-6.1";
940 const modelAttrs = (doc: ProseMirrorNode) => {
941 const attrs: unknown[] = [];
942 doc.descendants((node) => {
943 if (node.type.name === "composer-model") attrs.push(node.attrs);
944 });
945 return attrs;
946 };
947 const replace = (doc: ProseMirrorNode, isKnownModel?: typeof isCodexModel) => {
948 const transaction = EditorState.create({ doc }).tr;
949 for (const { from, to, node } of skillChipReplacements(doc, skillLabelFor, isKnownModel)) {
950 transaction.replaceWith(from, to, node);
951 }
952 return transaction.doc;
953 };
954 const chip = { instanceId: "codex", model: "gpt-6.1", source: "model:codex/gpt-6.1" };
955
956 it.each([
957 ["Ask model:codex/gpt-6.1 now", [chip]],
958 ["Ask model:openai/gpt-4o now", []],
959 // Still being typed: `gpt-6` must not chip on the way to `gpt-6.1`.
960 ["Ask model:codex/gpt-6.1", []],
961 ])("chips only a known reference followed by whitespace: %s", (value, expected) => {
962 const doc = ProseMirrorNode.fromJSON(
963 schema,
964 buildDocJson(value, skillLabelFor, { isKnownModel: isCodexModel }),
965 );
966 doc.check();
967 expect(modelAttrs(doc)).toEqual(expected);
968 expect(serializeEditorDoc(doc).value).toBe(value);
969 });
970
971 it("reconciles references when the environment's models load or change", () => {
972 const value = "Ask model:codex/gpt-6.1 now";
973 const text = ProseMirrorNode.fromJSON(schema, buildDocJson(value, skillLabelFor));
974 expect(modelAttrs(text)).toEqual([]);
975 const loaded = replace(text, isCodexModel);
976 expect(modelAttrs(loaded)).toEqual([chip]);
977 expect(serializeEditorDoc(loaded).value).toBe(value);
978 const removed = replace(loaded);
979 expect(modelAttrs(removed)).toEqual([]);
980 expect(serializeEditorDoc(removed).value).toBe(value);
981 });
982 });
983
984 describe("pasting into a path query", () => {
985 const skillLabelFor = (name: string) => ({ label: name, description: null });
986
987 function paste(prompt: string | ProseMirrorNode, pasted: string, pathQueryActive = true) {
988 const promptDoc =
989 typeof prompt === "string"
990 ? ProseMirrorNode.fromJSON(schema, buildDocJson(prompt, skillLabelFor))
991 : prompt;
992 const line = promptDoc.lastChild!;
993 const lineBefore = line.textBetween(0, line.content.size, undefined, "\uFFFC");
994 const literalLength = pastedPathQueryLength(lineBefore, pasted, pathQueryActive);
995 const blocks = buildTiptapContent(pasted, skillLabelFor, { literalLength });
996 const [first, ...rest] = blocks.map((block) => ProseMirrorNode.fromJSON(schema, block));
997 const head = promptDoc.lastChild!.content.append(first!.content);
998 const doc = schema.node("doc", null, [first!.copy(head), ...rest]);
999 doc.check();
1000 return doc;
1001 }
1002
1003 function boldText(doc: ProseMirrorNode) {
1004 const bold: string[] = [];
1005 doc.descendants((node) => {
1006 if (node.isText && node.marks.some((mark) => mark.type.name === "bold")) {
1007 bold.push(node.text!);
1008 }
1009 });
1010 return bold;
1011 }
1012
1013 it.each(["src/__test__.tsx", "src/__tests__/a.ts", "pkg/__init__.py", "a/**b**/c"])(
1014 "keeps %s literal after @ so file search can match it",
1015 (path) => {
1016 const doc = paste("Open @", path);
1017 expect(boldText(doc)).toEqual([]);
1018 expect(serializeEditorDoc(doc).value).toBe(`Open @${path}`);
1019 },
1020 );
1021
1022 it("still styles the text after the path", () => {
1023 const doc = paste("Open @", "src/__test__.tsx and **this**\n- [ ] then __that__");
1024 expect(boldText(doc)).toEqual(["this", "that"]);
1025 expect(doc.lastChild!.type.name).toBe("taskList");
1026 expect(serializeEditorDoc(doc).value).toBe(
1027 "Open @src/__test__.tsx and **this**\n- [ ] then **that**",
1028 );
1029 });
1030
1031 it("parses markdown after Escape dismisses the path query", () => {
1032 const doc = paste("Open @", "__hello__ world", false);
1033 expect(boldText(doc)).toEqual(["hello"]);
1034 expect(serializeEditorDoc(doc).value).toBe("Open @**hello** world");
1035 });
1036
1037 it("keeps the rest of the path's line on that line", () => {
1038 const doc = paste("Open @", "src/a.ts - not a list item");
1039 expect(doc.childCount).toBe(1);
1040 expect(serializeEditorDoc(doc).value).toBe("Open @src/a.ts - not a list item");
1041 });
1042
1043 it("parses markdown when the paste does not continue a path query", () => {
1044 expect(boldText(paste("Open ", "__test__ now"))).toEqual(["test"]);
1045 expect(boldText(paste("Open @a ", "__b__"))).toEqual(["b"]);
1046 expect(boldText(paste("Open @", " __b__"))).toEqual(["b"]);
1047 });
1048
1049 it("keeps a path literal after a partly styled query", () => {
1050 const doc = paste("Open @**src/**", "__test__.tsx");
1051 expect(boldText(doc)).toEqual(["src/"]);
1052 expect(serializeEditorDoc(doc).value).toBe("Open @**src/**__test__.tsx");
1053 });
1054
1055 // regression: #16619 paths pasted after @ lost their underscores to markdown parsing
1056 it("parses markdown pasted right after a mention chip", () => {
1057 const withSpace = ProseMirrorNode.fromJSON(
1058 schema,
1059 buildDocJson("Open @README.md ", skillLabelFor),
1060 );
1061 const paragraph = withSpace.firstChild!;
1062 expect(paragraph.lastChild!.text).toBe(" ");
1063 const chipLast = schema.node("doc", null, [
1064 paragraph.copy(paragraph.content.cut(0, paragraph.content.size - 1)),
1065 ]);
1066 expect(chipLast.firstChild!.lastChild!.type.name).toBe("composer-mention");
1067 expect(boldText(paste(chipLast, "__b__"))).toEqual(["b"]);
1068 });
1069 });
1070
1071 describe("caret stops at styled edges", () => {
1072 function stateAt(value: string, pmPos: number) {
1073 const doc = ProseMirrorNode.fromJSON(
1074 schema,
1075 buildDocJson(value, (name) => ({ label: name, description: null })),
1076 );
1077 return EditorState.create({ doc, selection: TextSelection.create(doc, pmPos) });
1078 }
1079
1080 function typed(state: EditorState, text: string) {
1081 return serializeEditorDoc(state.apply(state.tr.insertText(text)).doc).value;
1082 }
1083
1084 it("lets the caret step out in front of bold that starts the line", () => {
1085 const inside = stateAt("**bold** tail", 1);
1086 expect(caretTakesMarksBefore(inside)).toBe(false);
1087 expect(typed(inside, "x")).toBe("**xbold** tail");
1088
1089 const step = stepCaretAcrossStyledEdge(inside, -1);
1090 expect(step).not.toBeNull();
1091 const outside = inside.apply(step!);
1092 expect(caretTakesMarksBefore(outside)).toBe(true);
1093 expect(typed(outside, "x")).toBe("x**bold** tail");
1094 expect(stepCaretAcrossStyledEdge(outside, -1)).toBeNull();
1095
1096 const back = outside.apply(stepCaretAcrossStyledEdge(outside, 1)!);
1097 expect(typed(back, "x")).toBe("**xbold** tail");
1098 });
1099
1100 it("lets the caret step out after bold that ends the line", () => {
1101 const inside = stateAt("head **bold**", 10);
1102 expect(caretTakesMarksBefore(inside)).toBe(true);
1103 expect(typed(inside, "x")).toBe("head **boldx**");
1104 expect(stepCaretAcrossStyledEdge(inside, -1)).toBeNull();
1105
1106 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1107 expect(caretTakesMarksBefore(outside)).toBe(false);
1108 expect(typed(outside, "x")).toBe("head **bold**x");
1109 });
1110
1111 // regression: #13217 could not type in front of bold that starts a composer line
1112 it("offers both stops where styled text meets plain text mid-line", () => {
1113 const plain = stateAt("a **b** c", 3);
1114 expect(caretTakesMarksBefore(plain)).toBe(true);
1115 expect(typed(plain, "x")).toBe("a x**b** c");
1116 const bold = plain.apply(stepCaretAcrossStyledEdge(plain, 1)!);
1117 expect(typed(bold, "x")).toBe("a **xb** c");
1118 });
1119
1120 it("offers the plain stop between bold text and a chip right after it", () => {
1121 const doc = schema.node("doc", null, [
1122 schema.node("paragraph", null, [
1123 schema.text("bold", [schema.marks.bold!.create()]),
1124 schema.nodes["composer-mention"]!.create({ path: "README.md", source: "@README.md" }),
1125 ]),
1126 ]);
1127 const inside = EditorState.create({ doc, selection: TextSelection.create(doc, 5) });
1128 expect(caretTakesMarksBefore(inside)).toBe(true);
1129 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1130 expect(caretTakesMarksBefore(outside)).toBe(false);
1131 const withText = outside.apply(outside.tr.insertText("x")).doc;
1132 expect(withText.child(0).child(1).text).toBe("x");
1133 expect(withText.child(0).child(1).marks).toEqual([]);
1134 });
1135
1136 it("steps out of inline code at the end of a line without inserting a space", () => {
1137 expect(ComposerCodeExtension.config.exitable).toBe(false);
1138 const inside = stateAt("`code`", 5);
1139 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1140 expect(typed(outside, "x")).toBe("`code`x");
1141 expect(stepCaretAcrossStyledEdge(outside, 1)).toBeNull();
1142 });
1143
1144 it("keeps marks the user toggled at an edge and lets the arrow move", () => {
1145 const inside = stateAt("a **b** c", 3);
1146 const toggled = inside.apply(
1147 inside.tr.setStoredMarks([schema.marks.bold!.create(), schema.marks.italic!.create()]),
1148 );
1149 expect(stepCaretAcrossStyledEdge(toggled, 1)).toBeNull();
1150 expect(stepCaretAcrossStyledEdge(toggled, -1)).toBeNull();
1151 });
1152 });
1153
1154 describe("inline code entry", () => {
1155 function editorFor(block = "paragraph", mark?: string) {
1156 const editor = new Editor({
1157 element: null,
1158 extensions: [
1159 StarterKit.configure({
1160 bold: false,
1161 code: false,
1162 codeBlock: false,
1163 italic: false,
1164 strike: false,
1165 trailingNode: false,
1166 }),
1167 ComposerBoldExtension,
1168 ComposerItalicExtension,
1169 ComposerStrikeExtension,
1170 ComposerCodeExtension,
1171 ComposerCodeBlockExtension,
1172 stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
1173 ],
1174 content: { type: "doc", content: [{ type: block }] },
1175 });
1176 // Unmounted editors need the same plugins that Tiptap installs on mount.
1177 editor.view.updateState(editor.state.reconfigure({ plugins: editor.extensionManager.plugins }));
1178 if (mark) editor.commands.setMark(mark);
1179 onTestFinished(() => editor.destroy());
1180 return editor;
1181 }
1182
1183 function type(editor: Editor, text: string) {
1184 for (const ch of text) {
1185 const { from, to } = editor.state.selection;
1186 const insert = () => editor.state.tr.insertText(ch, from, to);
1187 const handled = editor.state.plugins.some((plugin) =>
1188 plugin.props.handleTextInput?.call(plugin, editor.view, from, to, ch, insert),
1189 );
1190 if (!handled) editor.view.dispatch(insert());
1191 }
1192 }
1193
1194 it.each(["", "this is a "])(
1195 "formats code after %j when the opening backtick is typed last",
1196 (prefix) => {
1197 const editor = editorFor();
1198 type(editor, `${prefix}test\` after`);
1199 editor.commands.setTextSelection(prefix.length + 1);
1200 type(editor, "`");
1201
1202 expect(editor.state.doc.textContent).toBe(`${prefix}test after`);
1203 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`test\` after`);
1204 expect(editor.state.selection.from).toBe(prefix.length + 1);
1205 type(editor, "new ");
1206 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`new test\` after`);
1207 editor.commands.setTextSelection(editor.state.doc.content.size - 1);
1208 type(editor, " plain");
1209 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`new test\` after plain`);
1210 const formatted = editor.state.doc.toJSON();
1211 let undos = 0;
1212 while (editor.commands.undo()) undos += 1;
1213 expect(undos).toBeGreaterThan(0);
1214 expect(editor.state.doc.textContent).toBe("");
1215 for (let i = 0; i < undos; i += 1) expect(editor.commands.redo()).toBe(true);
1216 expect(editor.state.doc.toJSON()).toEqual(formatted);
1217 },
1218 );
1219
1220 it.each([
1221 { name: "doubled closing ticks", text: "test``" },
1222 { name: "a code block", text: "test`", block: "codeBlock" },
1223 { name: "bold text", text: "test`", mark: "bold" },
1224 { name: "existing inline code", text: "test`", mark: "code" },
1225 ])("keeps an opening tick literal before $name", ({ text, block, mark }) => {
1226 const editor = editorFor(block, mark);
1227 type(editor, text);
1228 editor.commands.setTextSelection(1);
1229 type(editor, "`");
1230 expect(editor.state.doc.textContent).toBe(`\`${text}`);
1231 });
1232
1233 it.each(["hardBreak", "composer-mention"])("does not pair ticks across a %s", (nodeType) => {
1234 const editor = editorFor();
1235 type(editor, "before");
1236 editor.commands.insertContent({ type: nodeType });
1237 type(editor, "after`");
1238 editor.commands.setTextSelection(1);
1239 type(editor, "`");
1240 expect(editor.state.doc.firstChild?.firstChild?.marks).toEqual([]);
1241 expect(editor.state.doc.textContent).toBe("`beforeafter`");
1242
1243 const local = editorFor();
1244 type(local, "a ` ");
1245 local.commands.insertContent({ type: nodeType });
1246 type(local, "`local`");
1247 expect(local.state.doc.firstChild?.lastChild?.toJSON()).toEqual({
1248 type: "text",
1249 marks: [{ type: "code" }],
1250 text: "local",
1251 });
1252 });
1253
1254 it.each(["", "prefix ", "@README.md", "a ``` "])(
1255 "formats a filled pair after %j, leaves following text plain, and keeps the normal input rule",
1256 (prefix) => {
1257 const editor = editorFor();
1258 if (prefix === "@README.md") {
1259 editor.commands.insertContent({
1260 type: "composer-mention",
1261 attrs: { path: "README.md", source: prefix },
1262 });
1263 } else {
1264 type(editor, prefix);
1265 }
1266 const offset = editor.state.selection.from - 1;
1267 type(editor, "``");
1268 editor.commands.setTextSelection(offset + 2);
1269 type(editor, "hello world");
1270 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`hello world\``);
1271 expect(editor.state.doc.firstChild?.lastChild?.marks).toEqual([]);
1272
1273 editor.commands.setTextSelection(offset + 14);
1274 expect(editor.state.doc.textContent).toBe(
1275 `${prefix === "@README.md" ? "" : prefix}hello world`,
1276 );
1277 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`hello world\``);
1278 type(editor, " next `typed`");
1279 expect(serializeEditorDoc(editor.state.doc).value).toBe(
1280 `${prefix}\`hello world\` next \`typed\``,
1281 );
1282 const formatted = editor.state.doc.toJSON();
1283 let undos = 0;
1284 while (editor.commands.undo()) undos += 1;
1285 expect(undos).toBeGreaterThan(0);
1286 expect(serializeEditorDoc(editor.state.doc).value).toBe("");
1287 for (let i = 0; i < undos; i += 1) expect(editor.commands.redo()).toBe(true);
1288 expect(editor.state.doc.toJSON()).toEqual(formatted);
1289 },
1290 );
1291
1292 it.each([
1293 [
1294 "formats a pair",
1295 "do ",
1296 [
1297 { type: "text", text: "do " },
1298 { type: "text", marks: [{ type: "code" }], text: "xyz" },
1299 ],
1300 ],
1301 [
1302 "keeps a pair literal after an unmatched backtick",
1303 "a ` ",
1304 [{ type: "text", text: "a ` `xyz`" }],
1305 ],
1306 ])("%s whose backticks came from a dead key", (_name, prefix, content) => {
1307 const editor = editorFor();
1308 type(editor, prefix);
1309 editor.view.dispatch(editor.state.tr.insertText("`").setMeta("composition", 1));
1310 editor.view.dispatch(editor.state.tr.insertText("`").setMeta("composition", 2));
1311 editor.commands.setTextSelection(prefix.length + 2);
1312 type(editor, "xyz");
1313 expect(editor.state.doc.textContent).toBe(`${prefix}\`xyz\``);
1314
1315 editor.commands.setTextSelection(prefix.length + 6);
1316 expect(editor.state.doc.firstChild?.toJSON().content).toEqual(content);
1317 });
1318
1319 it("does not reuse the closing backtick of a literal pair to open code", () => {
1320 const editor = editorFor();
1321 editor.view.dispatch(editor.state.tr.insertText("is `enabled`", 1));
1322 type(editor, " and `");
1323 expect(editor.state.doc.firstChild?.toJSON().content).toEqual([
1324 { type: "text", text: "is `enabled` and `" },
1325 ]);
1326
1327 type(editor, "persist`");
1328 expect(editor.state.doc.firstChild?.toJSON().content).toEqual([
1329 { type: "text", text: "is `enabled` and " },
1330 { type: "text", marks: [{ type: "code" }], text: "persist" },
1331 ]);
1332 });
1333
1334 it("keeps composition edits literal until the caret leaves the typed pair", () => {
1335 const editor = editorFor();
1336 type(editor, "``");
1337 editor.commands.setTextSelection(2);
1338 editor.view.dispatch(editor.state.tr.insertText("世").setMeta("composition", 1));
1339 editor.view.dispatch(editor.state.tr.insertText("世界", 2, 3).setMeta("composition", 1));
1340 expect(editor.state.doc.textContent).toBe("`世界`");
1341 expect(editor.state.doc.firstChild?.firstChild?.marks).toEqual([]);
1342 editor.commands.setTextSelection(5);
1343 expect(editor.state.doc.textContent).toBe("世界");
1344 expect(serializeEditorDoc(editor.state.doc).value).toBe("`世界`");
1345 });
1346
1347 it.each(["paste", "setContent"])("keeps a %s pair literal after moving through it", (source) => {
1348 const editor = editorFor();
1349 const literal = "`literal`";
1350 if (source === "paste") {
1351 editor.view.dispatch(editor.state.tr.insertText(literal).setMeta("uiEvent", "paste"));
1352 } else {
1353 type(editor, "``");
1354 editor.commands.setContent({
1355 type: "doc",
1356 content: [{ type: "paragraph", content: [{ type: "text", text: literal }] }],
1357 });
1358 }
1359 const before = editor.state.doc.toJSON();
1360 editor.commands.setTextSelection(2);
1361 editor.commands.setTextSelection(literal.length + 1);
1362 expect(editor.state.doc.toJSON()).toEqual(before);
1363 });
1364
1365 it.each([
1366 { name: "doubled delimiters", delimiters: "````", caret: 3 },
1367 { name: "doubled closing delimiters", delimiters: "```", caret: 2 },
1368 { name: "bold text", delimiters: "``", caret: 2, mark: "bold" },
1369 { name: "existing inline code", delimiters: "``", caret: 2, mark: "code" },
1370 { name: "a code block", delimiters: "``", caret: 2, block: "codeBlock" },
1371 ])("leaves $name unchanged on caret movement", ({ delimiters, caret, mark, block }) => {
1372 const editor = editorFor(block, mark);
1373 type(editor, delimiters);
1374 editor.commands.setTextSelection(caret);
1375 type(editor, "literal");
1376 const before = editor.state.doc.toJSON();
1377 // Visit both the gap between closing ticks and the end of the pair.
1378 editor.commands.setTextSelection(caret + "literal".length + 1);
1379 expect(editor.state.doc.toJSON()).toEqual(before);
1380 editor.commands.setTextSelection(editor.state.doc.content.size - 1);
1381 expect(editor.state.doc.toJSON()).toEqual(before);
1382 });
1383
1384 function marked(editor: Editor, name: string) {
1385 const text: string[] = [];
1386 editor.state.doc.descendants((node) => {
1387 if (node.isText && node.marks.some((mark) => mark.type.name === name)) {
1388 text.push(node.text ?? "");
1389 }
1390 });
1391 return text;
1392 }
1393
1394 /** Types `text` into a backtick pair and steps the caret out so it formats. */
1395 function typeCode(editor: Editor, text: string) {
1396 const offset = editor.state.selection.from;
1397 type(editor, "``");
1398 editor.commands.setTextSelection(offset + 1);
1399 type(editor, text);
1400 editor.commands.setTextSelection(offset + text.length + 2);
1401 expect(marked(editor, "code")).toContain(text);
1402 }
1403
1404 it.each([
1405 { mark: "italic", open: "*" },
1406 { mark: "bold", open: "**" },
1407 { mark: "strike", open: "~~" },
1408 ])("keeps a $mark delimiter inside an earlier code span literal", ({ mark, open }) => {
1409 const editor = editorFor();
1410 typeCode(editor, `${open}foo`);
1411 type(editor, ` bar \`${open}`);
1412 expect(serializeEditorDoc(editor.state.doc).value).toBe(`\`${open}foo\` bar \`${open}`);
1413 expect(marked(editor, mark)).toEqual([]);
1414 expect(marked(editor, "code")).toEqual([`${open}foo`]);
1415 });
1416
1417 it.each([
1418 { mark: "italic", open: "*" },
1419 { mark: "bold", open: "**" },
1420 { mark: "strike", open: "~~" },
1421 ])("still wraps a code span in $mark when both delimiters are outside it", ({ mark, open }) => {
1422 const editor = editorFor();
1423 type(editor, open);
1424 typeCode(editor, "foo");
1425 type(editor, ` bar${open}`);
1426 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${open}\`foo\` bar${open}`);
1427 expect(marked(editor, mark)).toEqual(["foo", " bar"]);
1428
1429 editor.commands.setContent({
1430 type: "doc",
1431 content: [
1432 {
1433 type: "paragraph",
1434 content: [
1435 { type: "text", text: `${open}foo tail ` },
1436 { type: "text", text: "x", marks: [{ type: "code" }] },
1437 ],
1438 },
1439 ],
1440 });
1441 editor.commands.setTextSelection({
1442 from: open.length + 4,
1443 to: editor.state.doc.content.size - 1,
1444 });
1445 type(editor, open);
1446 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${open}foo${open}`);
1447 expect(marked(editor, mark)).toEqual(["foo"]);
1448 });
1449 });
1450
1451 describe("surroundSelectionWithMark", () => {
1452 it("keeps markers inside math literal across draft restoration", () => {
1453 const doc = schema.node("doc", null, [schema.node("paragraph", null, schema.text("$x$"))]);
1454 const state = EditorState.create({ doc, selection: TextSelection.create(doc, 2, 3) });
1455 expect(surroundSelectionWithMark(state, 2, 3, "*")).toBeNull();
1456 });
1457
1458 it.each([
1459 ["`", "hello", "say `hello` now"],
1460 ["*", "hello", "say *hello* now"],
1461 ["_", "hello", "say *hello* now"],
1462 ["`", " ", "say ` ` now"],
1463 ])("formats a selection with %s like typed markers (%j)", (marker, selected, expected) => {
1464 const doc = schema.node("doc", null, [
1465 schema.node("paragraph", null, schema.text(`say ${selected} now`)),
1466 ]);
1467 const to = 5 + selected.length;
1468 const state = EditorState.create({ doc, selection: TextSelection.create(doc, 5, to) });
1469 const tr = surroundSelectionWithMark(state, 5, to, marker);
1470 expect(tr).not.toBeNull();
1471 const formatted = state.apply(tr!);
1472 const typed = ProseMirrorNode.fromJSON(
1473 schema,
1474 buildDocJson(`say ${marker}${selected}${marker} now`, (name) => ({
1475 label: name,
1476 description: null,
1477 })),
1478 );
1479 expect(formatted.doc.eq(typed)).toBe(true);
1480 expect(serializeEditorDoc(formatted.doc).value).toBe(expected);
1481 expect(formatted.doc.textBetween(formatted.selection.from, formatted.selection.to)).toBe(
1482 selected,
1483 );
1484 });
1485
1486 it.each([
1487 ["*", " "],
1488 ["_", " "],
1489 ["*", "a*b"],
1490 ["`", "foo`bar"],
1491 ])("leaves %s around %j to literal wrapping when the mark cannot round-trip", (marker, text) => {
1492 const doc = schema.node("doc", null, [schema.node("paragraph", null, schema.text(text))]);
1493 const to = 1 + text.length;
1494 const state = EditorState.create({ doc, selection: TextSelection.create(doc, 1, to) });
1495 expect(surroundSelectionWithMark(state, 1, to, marker)).toBeNull();
1496 });
1497
1498 it.each([
1499 [
1500 "plain mode",
1501 plainSchema.node("doc", null, [plainSchema.node("paragraph", null, plainSchema.text("one"))]),
1502 ],
1503 [
1504 "paragraphs",
1505 schema.node("doc", null, [
1506 schema.node("paragraph", null, schema.text("one")),
1507 schema.node("paragraph", null, schema.text("two")),
1508 ]),
1509 ],
1510 [
1511 "a hard break",
1512 schema.node("doc", null, [
1513 schema.node("paragraph", null, [
1514 schema.text("one"),
1515 schema.node("hardBreak"),
1516 schema.text("two"),
1517 ]),
1518 ]),
1519 ],
1520 [
1521 "a code block",
1522 schema.node("doc", null, [schema.node("codeBlock", null, schema.text("one"))]),
1523 ],
1524 ])("leaves selections in %s to literal wrapping", (_, doc) => {
1525 doc.check();
1526 const state = EditorState.create({ doc });
1527 expect(surroundSelectionWithMark(state, 1, doc.content.size - 1, "`")).toBeNull();
1528 });
1529 });