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