Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composer-rich-text-doc.test.ts

1,361 lines49.2 KB

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