Open History to see the last commit
1import { 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 } from "vite-plus/test";
8
9import { collapseExpandedComposerCursor, pastedPathQueryLength } from "./composer-logic";
10
11import {
12 buildDocJson,
13 buildTiptapContent,
14 caretTakesMarksBefore,
15 ComposerBlockExtensions,
16 ComposerCodeBlockExtension,
17 ComposerListExtensions,
18 collapsedToFlat,
19 ComposerCodeExtension,
20 ComposerTaskItemExtension,
21 flatToCollapsed,
22 flatToMarkdown,
23 flatToPm,
24 pmToFlat,
25 serializeEditorDoc,
26 serializeSelection,
27 stepCaretAcrossStyledEdge,
28} from "./composer-rich-text-doc";
29
30function stubAtom(name: string, attrs: Record<string, { default: unknown }>) {
31 return Node.create({
32 name,
33 group: "inline",
34 inline: true,
35 atom: true,
36 addAttributes: () => attrs,
37 });
38}
39
40const schema = getSchemaByResolvedExtensions(
41 resolveExtensions([
42 StarterKit.configure({
43 blockquote: false,
44 bulletList: false,
45 codeBlock: false,
46 heading: false,
47 horizontalRule: false,
48 listItem: false,
49 orderedList: false,
50 dropcursor: false,
51 gapcursor: false,
52 trailingNode: false,
53 code: false,
54 }),
55 ComposerCodeExtension,
56 stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
57 stubAtom("composer-skill", {
58 skillName: { default: "" },
59 skillLabel: { default: "" },
60 skillDescription: { default: null },
61 }),
62 stubAtom("composer-citation", {
63 citation: { default: null },
64 source: { default: "" },
65 citeKey: { default: "" },
66 }),
67 stubAtom("composer-context-reference", {
68 kind: { default: "" },
69 contextId: { default: "" },
70 label: { default: "" },
71 source: { default: "" },
72 }),
73 TaskList,
74 ComposerTaskItemExtension,
75 ComposerCodeBlockExtension,
76 ...ComposerListExtensions,
77 ...ComposerBlockExtensions,
78 ]),
79);
80
81function roundTrip(value: string) {
82 const json = buildDocJson(value, (name) => ({ label: name, description: null }));
83 const doc = ProseMirrorNode.fromJSON(schema, json);
84 // `insertContent` validates every node against the schema; `fromJSON` does not.
85 doc.check();
86 return serializeEditorDoc(doc);
87}
88
89// Plain mode: the same engine with the mark extensions off. Markers stay
90// literal characters and task lines stay paragraphs.
91const plainSchema = getSchemaByResolvedExtensions(
92 resolveExtensions([
93 StarterKit.configure({
94 blockquote: false,
95 bulletList: false,
96 codeBlock: false,
97 heading: false,
98 horizontalRule: false,
99 listItem: false,
100 orderedList: false,
101 dropcursor: false,
102 gapcursor: false,
103 trailingNode: false,
104 bold: false,
105 italic: false,
106 strike: false,
107 code: false,
108 }),
109 stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
110 stubAtom("composer-skill", {
111 skillName: { default: "" },
112 skillLabel: { default: "" },
113 skillDescription: { default: null },
114 }),
115 stubAtom("composer-citation", {
116 citation: { default: null },
117 source: { default: "" },
118 citeKey: { default: "" },
119 }),
120 stubAtom("composer-context-reference", {
121 kind: { default: "" },
122 contextId: { default: "" },
123 label: { default: "" },
124 source: { default: "" },
125 }),
126 TaskList,
127 ComposerTaskItemExtension,
128 ]),
129);
130
131function roundTripPlain(value: string) {
132 const json = buildDocJson(value, (name) => ({ label: name, description: null }), {
133 styling: false,
134 });
135 const doc = ProseMirrorNode.fromJSON(plainSchema, json);
136 return serializeEditorDoc(doc);
137}
138
139describe("literal editor answers", () => {
140 const makeDoc = (value: string) =>
141 ProseMirrorNode.fromJSON(
142 plainSchema,
143 buildDocJson(value, (name) => ({ label: name, description: null }), {
144 literalText: true,
145 }),
146 );
147
148 it.each([
149 "",
150 "\n\n",
151 " - [X] done\n\n**keep** €my-skill @README.md \n",
152 "line one\r\nline two\r\n",
153 `- [X] done\n${" detail €my-skill @README.md\n".repeat(100)}`,
154 ])("preserves the complete answer through selection and serialization", (value) => {
155 const doc = makeDoc(value);
156 doc.check();
157 const serialized = serializeEditorDoc(doc);
158 expect(serialized.value).toBe(value);
159 expect(serialized.contextIds).toEqual([]);
160 expect(serializeSelection(doc, 1, doc.content.size - 1)).toBe(value);
161 for (let offset = 0; offset <= value.length; offset += 1) {
162 expect(flatToCollapsed(serialized, offset)).toBe(offset);
163 }
164 });
165
166 it("edits literal Markdown, inserts a newline, and preserves an explicitly cleared answer", () => {
167 const value = " - [X] done €my-skill @README.md ";
168 const doc = makeDoc(value);
169 let state = EditorState.create({
170 doc,
171 selection: TextSelection.create(doc, doc.content.size - 1),
172 });
173 state = state.apply(state.tr.insertText(" edited"));
174 expect(
175 splitBlockKeepMarks(state, (transaction) => {
176 state = state.apply(transaction);
177 }),
178 ).toBe(true);
179 state = state.apply(state.tr.insertText("second line "));
180 expect(serializeEditorDoc(state.doc).value).toBe(`${value} edited\nsecond line `);
181 state = state.apply(state.tr.delete(1, state.doc.content.size - 1));
182 expect(serializeEditorDoc(state.doc).value).toBe("");
183 });
184});
185
186describe("composer rich text document model", () => {
187 it.each(["€", "£", "¥", "₹", "₩", "₿", "𑿝"])(
188 "canonicalizes %s skill aliases while preserving amounts",
189 (prefix) => {
190 const value = `Use ${prefix}my-skill for ${prefix}20 please`;
191 const expected = `Use $my-skill for ${prefix}20 please`;
192 expect(roundTrip(value).value).toBe(expected);
193 expect(roundTripPlain(value).value).toBe(expected);
194 },
195 );
196
197 it.each([
198 "",
199 "\n\n",
200 "plain text",
201 "hello **bold** world",
202 "a *italic* word and `code` here",
203 "struck ~~out~~ now",
204 "**`x`**",
205 "*`x`*",
206 "~~`x`~~",
207 "**a `code` c**",
208 "***bold italic*** keeps nesting",
209 "line one\nline two",
210 "trailing newline\n",
211 "1. foo\n2. asdf\n",
212 "- [ ] buy milk",
213 "- [ ] buy milk",
214 "\t-\t[x]\t\titem",
215 "- [ ] ",
216 "- [ ]\n - [ ] child",
217 " - [ ] first\n - [ ] second\n - [ ] child",
218 "**before @README.md after**",
219 "*a **b** c*",
220 "*a**b***",
221 "**a*b***",
222 "**a *b* c**",
223 "literal \uFFFC **before @README.md after**",
224 "- [x] done\n- [ ] next",
225 "- [ ] parent\n - [ ] child\n - [ ] sibling\n- [ ] uncle",
226 "- [ ] empty task follows\n- [ ]",
227 "- [ ] **bold** task with @README.md",
228 "para\n- [ ] task\npara",
229 "- [ ]No space stays literal",
230 "-[ ] also literal",
231 "@README.md explain this",
232 '@"docs/My File.md" and $my-skill please',
233 "snake_case stays literal",
234 "unmatched ** stays literal",
235 "**bold** then @README.md then *italic*",
236 ])("round-trips %s through a real ProseMirror document", (value) => {
237 expect(roundTrip(value).value).toBe(value);
238 });
239
240 it.each([
241 "",
242 "\n",
243 "text\n\n",
244 "- [ ]\n- [ ] next\n",
245 "- [ ] parent\n - [ ] child\n- [ ]",
246 "para\n- [ ] task\npara",
247 "**before @README.md after**",
248 ])("maps editable positions in %s", (value) => {
249 const doc = ProseMirrorNode.fromJSON(
250 schema,
251 buildDocJson(value, (name) => ({ label: name, description: null })),
252 );
253 const map = serializeEditorDoc(doc);
254 for (let flat = 0; flat <= map.docLength; flat += 1) {
255 const position = flatToPm(map, flat);
256 expect(doc.resolve(position).parent.isTextblock).toBe(true);
257 expect(pmToFlat(map, position)).toBe(flat);
258 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
259 }
260 });
261
262 it("keeps the caret after a trailing hard break inside the same paragraph", () => {
263 const doc = schema.node("doc", null, [
264 schema.node("paragraph", null, [schema.text("a"), schema.node("hardBreak")]),
265 ]);
266 const map = serializeEditorDoc(doc);
267 expect(flatToPm(map, map.docLength)).toBe(3);
268 expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);
269 });
270
271 it("renders a leading task dedent as siblings and nests under the new indent", () => {
272 const doc = ProseMirrorNode.fromJSON(
273 schema,
274 buildDocJson(" - [ ] first\n - [ ] second\n - [ ] child", (name) => ({
275 label: name,
276 description: null,
277 })),
278 );
279 const list = doc.firstChild!;
280 expect(list.childCount).toBe(2);
281 expect(list.child(0).childCount).toBe(1);
282 expect(list.child(1).child(1).firstChild!.textContent).toBe("child");
283 });
284
285 it("applies a shared mark to text on both sides of a chip", () => {
286 const doc = ProseMirrorNode.fromJSON(
287 schema,
288 buildDocJson("**before @README.md after**", (name) => ({ label: name, description: null })),
289 );
290 expect(doc.firstChild!.childCount).toBe(3);
291 doc.firstChild!.forEach((child) =>
292 expect(child.marks.map((mark) => mark.type.name)).toContain("bold"),
293 );
294 expect(serializeEditorDoc(doc).value).toBe("**before @README.md after**");
295 });
296
297 it.each([
298 [["bold"], ["bold", "italic"], ["italic"]],
299 [["italic"], ["bold", "italic"], ["bold"]],
300 [["bold"], ["bold", "strike"], ["strike"]],
301 [["strike"], ["bold", "strike"], ["bold"]],
302 ])("preserves crossing mark ranges %j through controlled rebuilds", (...marks) => {
303 const doc = schema.node("doc", null, [
304 schema.node(
305 "paragraph",
306 null,
307 marks.map((names, index) =>
308 schema.text(
309 String.fromCharCode(97 + index),
310 names.map((name) => schema.mark(name)),
311 ),
312 ),
313 ),
314 ]);
315 const serialized = serializeEditorDoc(doc).value;
316 const rebuilt = ProseMirrorNode.fromJSON(
317 schema,
318 buildDocJson(serialized, (name) => ({ label: name, description: null })),
319 );
320 expect(rebuilt.eq(doc)).toBe(true);
321 expect(serializeEditorDoc(rebuilt).value).toBe(serialized);
322 });
323
324 it.each([
325 { parts: [{ text: "hello ", marks: ["bold"] }], expected: "**hello** " },
326 { parts: [{ text: " ", marks: ["bold"] }], expected: " " },
327 { parts: [{ text: " left ", marks: ["bold", "italic"] }], expected: " ***left*** " },
328 {
329 parts: [
330 { text: "one ", marks: ["bold"] },
331 { text: " two ", marks: ["bold", "italic"] },
332 { text: " three", marks: ["bold"] },
333 ],
334 expected: "**one *two* three**",
335 },
336 {
337 parts: [
338 { text: "hello ", marks: ["bold"] },
339 { text: "world ", marks: ["bold", "italic"] },
340 ],
341 expected: "**hello *world*** ",
342 },
343 { parts: [{ text: " hello ", marks: ["code"] }], expected: "` hello `" },
344 { parts: [{ text: " hello ", marks: ["bold", "code"] }], expected: "**` hello `**" },
345 { parts: [{ text: " ", marks: ["bold", "code"] }], expected: "**` `**" },
346 ])("keeps boundary whitespace outside emphasis in $expected", ({ parts, expected }) => {
347 const doc = schema.node("doc", null, [
348 schema.node(
349 "paragraph",
350 null,
351 parts.map(({ text, marks }) =>
352 schema.text(
353 text,
354 marks.map((name) => schema.mark(name)),
355 ),
356 ),
357 ),
358 ]);
359 const map = serializeEditorDoc(doc);
360 expect(map.value).toBe(expected);
361 const rebuilt = ProseMirrorNode.fromJSON(
362 schema,
363 buildDocJson(map.value, (name) => ({ label: name, description: null })),
364 );
365 expect(rebuilt.textContent).toBe(doc.textContent);
366 expect(serializeEditorDoc(rebuilt).value).toBe(map.value);
367 for (let flat = 0; flat <= map.docLength; flat += 1) {
368 expect(pmToFlat(map, flatToPm(map, flat))).toBe(flat);
369 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
370 if (flat < map.docLength && !/\s/.test(doc.textContent[flat]!)) {
371 expect(rebuilt.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name)).toEqual(
372 doc.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name),
373 );
374 }
375 }
376 });
377
378 it("keeps chip sources canonical through the document", () => {
379 const map = roundTrip("explain @README.md with **care**\nsecond line *here*");
380 expect(map.value).toBe("explain @README.md with **care**\nsecond line *here*");
381 expect(
382 map.runs.some((run) => run.kind === "token" && run.nodeName === "composer-mention"),
383 ).toBe(true);
384 });
385
386 it("normalizes uppercase checkboxes to lowercase", () => {
387 expect(roundTrip("- [X] done").value).toBe("- [x] done");
388 });
389
390 it.each([
391 "plain text",
392 "hello **bold** stays literal",
393 "a *italic* stays literal",
394 "some `code` stays literal",
395 "struck ~~out~~ stays literal",
396 "- [ ] stays a paragraph",
397 "- [x] stays a paragraph",
398 "line one\nline two",
399 "@README.md explain this",
400 "**bold** then @README.md then *italic*",
401 ])("round-trips %s byte-identically in plain mode", (value) => {
402 expect(roundTripPlain(value).value).toBe(value);
403 });
404
405 it.each([
406 "- one\n- two",
407 "* star\n* star two",
408 "+ plus",
409 "* star\n+ plus",
410 "1. first\n2. second",
411 "1) paren\n2) paren",
412 "3. starts at three\n4. four",
413 "01. zero padded\n02. two",
414 "- parent\n - child\n - sibling\n- uncle",
415 "1. ordered\n - bullet child\n2. next",
416 "- outer\n 1. inner ordered\n 2. more\n- outer again",
417 "- wide space item",
418 "-",
419 "1.",
420 "- \n- second",
421 "- **bold** item with @README.md",
422 "- [ ] task\n- bullet after",
423 "- bullet\n- [x] task after",
424 "para\n- item\npara",
425 "\t- tab indented\n\t- again",
426 " - leading indent only",
427 "- item\n\n- after a blank",
428 "- item one\n```ts\ncode\n```\n- item two",
429 "-no space stays literal",
430 "1.no space stays literal",
431 "10. ten\n11. eleven",
432 ])("round-trips the list %s through a real ProseMirror document", (value) => {
433 expect(roundTrip(value).value).toBe(value);
434 });
435
436 it.each([
437 "- one\n- two",
438 "1. first\n2. second",
439 "- parent\n - child",
440 "* star\n+ plus",
441 "-no space stays literal",
442 ])("keeps the list %s literal in plain mode", (value) => {
443 expect(roundTripPlain(value).value).toBe(value);
444 });
445
446 it.each(["- one\n- two", "1. a\n - b\n2. c", "- **bold** @README.md tail", "-"])(
447 "maps every document offset of the list %s through collapsed coordinates and back",
448 (value) => {
449 const map = roundTrip(value);
450 expect(map.value).toBe(value);
451 for (let flat = 0; flat <= map.docLength; flat += 1) {
452 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
453 }
454 },
455 );
456
457 it("clamps offsets inside a list marker to the start of the item text", () => {
458 const value = "- item";
459 const map = roundTrip(value);
460 // The marker owns no document characters, like a checkbox.
461 for (let collapsed = 0; collapsed <= "- ".length; collapsed += 1) {
462 expect(collapsedToFlat(map, collapsed)).toBe(0);
463 }
464 expect(collapsedToFlat(map, "- it".length)).toBe(2);
465 expect(flatToCollapsed(map, 0)).toBe("- ".length);
466 });
467
468 it.each([
469 "> quoted",
470 "> line one\n> line two",
471 ">no space",
472 "> two spaces",
473 "> a\n>b",
474 ">",
475 "> **bold** and @README.md inside",
476 "> - looks like a list but stays quote text",
477 "> > nested stays literal inside the quote",
478 "before\n> quoted\nafter",
479 "> quote\n\n> another",
480 "- item\n> quote after list",
481 ])("round-trips the quote %s through a real ProseMirror document", (value) => {
482 expect(roundTrip(value).value).toBe(value);
483 });
484
485 it.each([
486 "---",
487 "***",
488 "___",
489 "- - -",
490 "* * *",
491 "-----",
492 "--- ",
493 "text\n---\nmore",
494 "- item\n---\n- item two",
495 "```\n---\n```",
496 "--",
497 "-- -",
498 "---text",
499 ])("round-trips the rule %s through a real ProseMirror document", (value) => {
500 expect(roundTrip(value).value).toBe(value);
501 });
502
503 it("parses rules ahead of lists and emphasis", () => {
504 const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({
505 label: n,
506 description: null,
507 }));
508 expect(json.content.map((block) => block.type)).toEqual([
509 "horizontalRule",
510 "horizontalRule",
511 "horizontalRule",
512 "paragraph",
513 "horizontalRule",
514 "bulletList",
515 ]);
516 });
517
518 it.each([
519 "# Heading",
520 "## Two",
521 "###### Six",
522 "####### seven hashes stays a paragraph",
523 "# two spaces",
524 "#\tTab",
525 "# Trailing hashes stay literal #",
526 "#1234",
527 "#1234 is a pull request, not a heading",
528 "# Heading with **bold** and @README.md",
529 "#",
530 "# ",
531 "text\n# Heading\ntext",
532 "# Heading\n- item\n> quote\n---",
533 ])("round-trips the heading %s through a real ProseMirror document", (value) => {
534 expect(roundTrip(value).value).toBe(value);
535 });
536
537 it.each(["> quoted", "> a\n>b", "---", "- - -", "# Heading", "#1234"])(
538 "keeps the block %s literal in plain mode",
539 (value) => {
540 expect(roundTripPlain(value).value).toBe(value);
541 },
542 );
543
544 it("parses the blocks it renders as the right node types", () => {
545 const json = buildDocJson("# Title\n> quote\n---\n#1234 ref\n- - -", (n) => ({
546 label: n,
547 description: null,
548 }));
549 expect(json.content.map((block) => block.type)).toEqual([
550 "heading",
551 "blockquote",
552 "horizontalRule",
553 "paragraph",
554 "horizontalRule",
555 // The empty line a final rule keeps for the caret.
556 "paragraph",
557 ]);
558 });
559
560 it.each([
561 ["---", "---"],
562 ["a\n---", "a\n---"],
563 // That line and a trailing newline are the same document; the newline goes.
564 ["---\n", "---"],
565 ])("gives the caret a line after the final rule of %j, written %j", (value, expected) => {
566 const map = roundTrip(value);
567 expect(map.value).toBe(expected);
568 const json = buildDocJson(value, () => ({ label: "", description: null }));
569 const doc = ProseMirrorNode.fromJSON(schema, json);
570 expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);
571 });
572
573 it("parses rules ahead of lists and emphasis", () => {
574 const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({
575 label: n,
576 description: null,
577 }));
578 expect(json.content.map((block) => block.type)).toEqual([
579 "horizontalRule",
580 "horizontalRule",
581 "horizontalRule",
582 "paragraph",
583 "horizontalRule",
584 "bulletList",
585 ]);
586 });
587
588 it.each([
589 "# Heading",
590 "## Two",
591 "###### Six",
592 "####### seven hashes stays a paragraph",
593 "# two spaces",
594 "#\tTab",
595 "# Trailing hashes stay literal #",
596 "#1234",
597 "#1234 is a pull request, not a heading",
598 "# Heading with **bold** and @README.md",
599 "#",
600 "# ",
601 "text\n# Heading\ntext",
602 "# Heading\n- item\n> quote\n---",
603 ])("round-trips the heading %s through a real ProseMirror document", (value) => {
604 expect(roundTrip(value).value).toBe(value);
605 });
606
607 it.each(["> quoted", "> a\n>b", "---", "- - -", "# Heading", "#1234"])(
608 "keeps the block %s literal in plain mode",
609 (value) => {
610 expect(roundTripPlain(value).value).toBe(value);
611 },
612 );
613
614 it("parses a quote as a blockquote of one paragraph per line", () => {
615 const json = buildDocJson("> a\n> b\n>c", (n) => ({ label: n, description: null }));
616 expect(json.content.map((block) => block.type)).toEqual(["blockquote", "blockquote"]);
617 expect((json.content[0] as { content: unknown[] }).content).toHaveLength(2);
618 });
619
620 it.each([
621 "> a\n> b",
622 "> **q** @README.md",
623 "text\n---\nmore",
624 "---\ntext",
625 "# Heading text",
626 "## **b** @README.md",
627 ])(
628 "maps every document offset of the block %s through collapsed coordinates and back",
629 (value) => {
630 const map = roundTrip(value);
631 expect(map.value).toBe(value);
632 for (let flat = 0; flat <= map.docLength; flat += 1) {
633 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
634 }
635 },
636 );
637
638 it("clamps offsets inside a quote or heading marker to the start of the text", () => {
639 for (const [value, prefix] of [
640 ["> quoted", "> "],
641 ["# Heading", "# "],
642 ] as const) {
643 const map = roundTrip(value);
644 for (let collapsed = 0; collapsed <= prefix.length; collapsed += 1) {
645 expect(collapsedToFlat(map, collapsed)).toBe(0);
646 }
647 expect(flatToCollapsed(map, 0)).toBe(prefix.length);
648 }
649 });
650
651 it.each([
652 "```\ncode\n```",
653 "```ts\nconst a = 1;\n```",
654 "```ts\nconst a = 1;\n```\n",
655 "before\n```ts\nconst a = 1;\n```\nafter",
656 "```\n```",
657 "```ts\nline one\nline two\nline three\n```",
658 "```ts\n indented\n deeper\n```",
659 "```js title=example\ncode\n```",
660 "~~~py\ncode\n~~~",
661 "````\n```\n````",
662 "```ts\ncode without a closing fence",
663 "```",
664 "```ts\n**not bold** and @README.md stay literal\n```",
665 "```ts\ncode\n````",
666 "- [ ] task\n```ts\ncode\n```\n- [ ] after",
667 " ```ts\nindented fence stays a paragraph\n ```",
668 ])("round-trips the fenced block %s", (value) => {
669 expect(roundTrip(value).value).toBe(value);
670 });
671
672 it.each(["```ts\nconst a = 1;\n```", "```\n```", "before\n```ts\ncode\n```\nafter"])(
673 "maps every document offset of %s through collapsed coordinates and back",
674 (value) => {
675 const map = roundTrip(value);
676 expect(map.value).toBe(value);
677 for (let flat = 0; flat <= map.docLength; flat += 1) {
678 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
679 }
680 },
681 );
682
683 it("reads blocks written with CRLF line endings", () => {
684 const value = "# Title\r\n> quote\r\n---\r\n```ts\r\nconst a = 1;\r\n```\r\nafter";
685 const doc = buildDocJson(value, () => ({ label: "", description: null }));
686 expect(doc.content.map((block) => block.type)).toEqual([
687 "heading",
688 "blockquote",
689 "horizontalRule",
690 "codeBlock",
691 "paragraph",
692 ]);
693 expect(roundTrip(value).value).toBe(value);
694 });
695
696 it("keeps the end of the code inside the fence rather than after it", () => {
697 const value = "```ts\nfunc();\n```";
698 const map = roundTrip(value);
699 const endOfCode = "func();".length;
700 // Not the end of the string: the closing fence is a line of its own.
701 expect(flatToCollapsed(map, endOfCode)).toBe("```ts\nfunc();".length);
702 expect(flatToMarkdown(map, endOfCode)).toBe("```ts\nfunc();".length);
703 expect(collapsedToFlat(map, flatToCollapsed(map, endOfCode))).toBe(endOfCode);
704 });
705
706 it("keeps the caret inside an empty fence", () => {
707 const value = "before\n```\n```";
708 const map = roundTrip(value);
709 const inside = "before\n".length;
710 expect(flatToCollapsed(map, inside)).toBe("before\n```".length);
711 expect(collapsedToFlat(map, flatToCollapsed(map, inside))).toBe(inside);
712 });
713
714 it("still places the end of an inline mark after its markers", () => {
715 // The fence rule must not leak into inline marks, whose trailing edge is
716 // deliberately the position after the closing delimiter.
717 const map = roundTrip("a **bold** c");
718 expect(flatToMarkdown(map, 6)).toBe(10);
719 });
720
721 it("clamps offsets inside a fence to the edge of the code", () => {
722 const value = "```ts\nab\n```";
723 const map = roundTrip(value);
724 expect(map.value).toBe(value);
725 // The opening fence owns no document characters, so every offset in it
726 // lands on the first character of the code.
727 for (let collapsed = 0; collapsed <= "```ts\n".length; collapsed += 1) {
728 expect(collapsedToFlat(map, collapsed)).toBe(0);
729 }
730 expect(collapsedToFlat(map, "```ts\na".length)).toBe(1);
731 // Everything from the closing newline onwards clamps to the code's end.
732 for (let collapsed = "```ts\nab".length; collapsed <= value.length; collapsed += 1) {
733 expect(collapsedToFlat(map, collapsed)).toBe(2);
734 }
735 });
736
737 it.each([
738 ["```\n\n```", "```\n```"],
739 ["```\n", "```"],
740 ])("canonicalizes the empty fence %s", (value, expected) => {
741 expect(roundTrip(value).value).toBe(expected);
742 });
743
744 it("keeps a chip in a fence info string as source and keeps later chips aligned", () => {
745 const value = "```@README.md\ncode\n```\n$my-skill after";
746 expect(roundTrip(value).value).toBe(value);
747 const json = buildDocJson(value, (n) => ({ label: n, description: null }));
748 const after = json.content[1] as {
749 content: { type: string; attrs?: { skillName?: string } }[];
750 };
751 expect(after.content.map((n) => n.type)).toEqual(["composer-skill", "text"]);
752 expect(after.content[0]?.attrs?.skillName).toBe("my-skill");
753 });
754
755 it("keeps chips in a fence's info string and body each in their own place", () => {
756 const value = "``` @a.md\nsee @b.md\n```";
757 expect(roundTrip(value).value).toBe(value);
758 const json = buildDocJson(value, (n) => ({ label: n, description: null }));
759 const code = json.content[0] as { attrs: { language: string } };
760 expect(code.attrs.language).toBe(" @a.md");
761 });
762
763 it.each([
764 ["listItem", { marker: "-", space: "" }, "bulletList", "- text"],
765 ["listItem", { marker: "1.", space: "" }, "orderedList", "1. text"],
766 ])("gives a bare %s a space once it has text", (item, attrs, list, expected) => {
767 const doc = ProseMirrorNode.fromJSON(schema, {
768 type: "doc",
769 content: [
770 {
771 type: list,
772 content: [
773 {
774 type: item,
775 attrs,
776 content: [{ type: "paragraph", content: [{ type: "text", text: "text" }] }],
777 },
778 ],
779 },
780 ],
781 });
782 expect(serializeEditorDoc(doc).value).toBe(expected);
783 expect(roundTrip("-").value).toBe("-");
784 });
785
786 it("writes code holding a closing fence inside a longer fence", () => {
787 const doc = ProseMirrorNode.fromJSON(schema, {
788 type: "doc",
789 content: [
790 {
791 type: "codeBlock",
792 attrs: { fence: "```", close: "\n```" },
793 content: [{ type: "text", text: "initial\n```\nsecret" }],
794 },
795 ],
796 });
797 const stored = serializeEditorDoc(doc).value;
798 expect(stored).toBe("````\ninitial\n```\nsecret\n````");
799 expect(buildDocJson(stored, () => ({ label: "", description: null })).content).toHaveLength(1);
800 expect(roundTrip(stored).value).toBe(stored);
801 });
802
803 it("closes an unclosed fence that has a block after it", () => {
804 const doc = ProseMirrorNode.fromJSON(schema, {
805 type: "doc",
806 content: [
807 { type: "codeBlock", attrs: { close: "" }, content: [{ type: "text", text: "code" }] },
808 { type: "paragraph", content: [{ type: "text", text: "after" }] },
809 ],
810 });
811 expect(serializeEditorDoc(doc).value).toBe("```\ncode\n```\nafter");
812 // At the end of the draft it stays unclosed, as it was written.
813 expect(roundTrip("```\ncode").value).toBe("```\ncode");
814 });
815
816 it("counts a chip's source in a fence as one cursor position, as the draft store does", () => {
817 const value = "```\nsee @b.md now\n```\nafter";
818 const map = roundTrip(value);
819 expect(map.value).toBe(value);
820 for (let flat = 0; flat <= map.docLength; flat += 1) {
821 expect(flatToCollapsed(map, flat)).toBe(
822 collapseExpandedComposerCursor(value, flatToMarkdown(map, flat)),
823 );
824 }
825 const afterChip = "see @b.md".length;
826 expect(collapsedToFlat(map, flatToCollapsed(map, afterChip))).toBe(afterChip);
827 const end = map.docLength;
828 expect(collapsedToFlat(map, flatToCollapsed(map, end))).toBe(end);
829 });
830
831 it("keeps fences literal in plain mode", () => {
832 const value = "```ts\nconst a = 1;\n```";
833 expect(roundTripPlain(value).value).toBe(value);
834 });
835
836 it("maps every document offset through collapsed coordinates and back", () => {
837 const value = "hi **bold** @README.md bye";
838 const map = roundTrip(value);
839 expect(map.value).toBe(value);
840 for (let flat = 0; flat <= map.docLength; flat += 1) {
841 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
842 }
843 });
844
845 // Flipping the rich text setting remounts the editor, and the caret is
846 // restored from the stored collapsed cursor. That only works because the
847 // coordinate means the same thing on both sides of the flip.
848 it.each([
849 "plain prose with no styling at all",
850 "a chip @README.md counts one character in both modes",
851 "$my-skill leads the line",
852 "trailing newline\n",
853 ])("resolves a collapsed cursor identically in both modes for %s", (value) => {
854 const rich = roundTrip(value);
855 const plain = roundTripPlain(value);
856 expect(rich.value).toBe(value);
857 expect(plain.value).toBe(value);
858 for (let collapsed = 0; collapsed <= value.length; collapsed += 1) {
859 expect(flatToMarkdown(rich, collapsedToFlat(rich, collapsed))).toBe(
860 flatToMarkdown(plain, collapsedToFlat(plain, collapsed)),
861 );
862 }
863 });
864
865 it("clamps a cursor that was sitting inside a marker onto the styled text", () => {
866 const value = "a **bold** c";
867 const plain = roundTripPlain(value);
868 const rich = roundTrip(value);
869 // Between the two asterisks: a real caret position in plain mode, and no
870 // position at all in rich mode, where it lands on the first styled
871 // character instead. The flip moves the caret by a marker's width at most.
872 expect(flatToMarkdown(plain, collapsedToFlat(plain, 3))).toBe(3);
873 expect(flatToMarkdown(rich, collapsedToFlat(rich, 3))).toBe(4);
874 });
875
876 it("maps markdown offsets at styled edges onto document text", () => {
877 const value = "a **bold** c";
878 const map = roundTrip(value);
879 expect(map.value).toBe(value);
880 // document text is "a bold c" (flat), markdown has the markers.
881 expect(flatToMarkdown(map, 2)).toBe(4);
882 expect(flatToMarkdown(map, 6)).toBe(10);
883 expect(collapsedToFlat(map, 3)).toBe(2);
884 expect(collapsedToFlat(map, 9)).toBe(6);
885 });
886});
887
888describe("serializeSelection", () => {
889 /** The stored Markdown of the selection from the start of `first` to the end of `last`. */
890 function copy(value: string, first: string, last: string) {
891 const doc = ProseMirrorNode.fromJSON(
892 schema,
893 buildDocJson(value, (name) => ({ label: name, description: null })),
894 );
895 let from = -1;
896 let to = -1;
897 doc.descendants((node, pos) => {
898 if (!node.isText) return true;
899 const text = node.text ?? "";
900 if (from < 0 && text.includes(first)) from = pos + text.indexOf(first);
901 if (text.includes(last)) to = pos + text.lastIndexOf(last) + last.length;
902 return false;
903 });
904 return serializeSelection(doc, from, to);
905 }
906
907 it("keeps the markers of the list items it spans", () => {
908 expect(copy("- one\n- two\n- three", "one", "two")).toBe("- one\n- two");
909 expect(copy("3) one\n4) two", "one", "two")).toBe("3) one\n4) two");
910 expect(copy("- [ ] one\n- [x] two", "one", "two")).toBe("- [ ] one\n- [x] two");
911 });
912
913 it("keeps the nesting of an item and its children", () => {
914 expect(copy("- p\n - a\n - b", "p", "a")).toBe("- p\n - a");
915 });
916
917 it("keeps the prefix of the quote lines it spans", () => {
918 expect(copy("> one\n> two", "one", "two")).toBe("> one\n> two");
919 });
920
921 it("copies text within one block without its marker", () => {
922 expect(copy("- one two", "one", "one")).toBe("one");
923 });
924
925 it("copies across blocks as they are written", () => {
926 expect(copy("intro\n- one", "intro", "one")).toBe("intro\n- one");
927 });
928});
929
930describe("pasting into a list item or quote", () => {
931 it("keeps inline marks but builds no blocks", () => {
932 const content = buildTiptapContent(
933 "**bold** text\n- item\n> quote",
934 () => ({ label: "", description: null }),
935 { styling: true, blocks: false },
936 );
937 expect(content.map((block) => block.type)).toEqual(["paragraph", "paragraph", "paragraph"]);
938 const first = content[0] as { content: { text: string; marks?: { type: string }[] }[] };
939 expect(first.content[0]).toMatchObject({ text: "bold", marks: [{ type: "bold" }] });
940 expect(JSON.stringify(content[1])).toContain("- item");
941 expect(JSON.stringify(content[2])).toContain("> quote");
942 });
943});
944
945describe("pasting into a path query", () => {
946 const skillLabelFor = (name: string) => ({ label: name, description: null });
947
948 // Inserts `pasted` at the end of a one-line prompt the way the composer's
949 // paste handler does. `prompt` may be a document, to place the caret after a chip.
950 function paste(prompt: string | ProseMirrorNode, pasted: string, pathQueryActive = true) {
951 const promptDoc =
952 typeof prompt === "string"
953 ? ProseMirrorNode.fromJSON(schema, buildDocJson(prompt, skillLabelFor))
954 : prompt;
955 const line = promptDoc.lastChild!;
956 const lineBefore = line.textBetween(0, line.content.size, undefined, "\uFFFC");
957 const literalLength = pastedPathQueryLength(lineBefore, pasted, pathQueryActive);
958 const blocks = buildTiptapContent(pasted, skillLabelFor, { literalLength });
959 const [first, ...rest] = blocks.map((block) => ProseMirrorNode.fromJSON(schema, block));
960 const head = promptDoc.lastChild!.content.append(first!.content);
961 const doc = schema.node("doc", null, [first!.copy(head), ...rest]);
962 doc.check();
963 return doc;
964 }
965
966 function boldText(doc: ProseMirrorNode) {
967 const bold: string[] = [];
968 doc.descendants((node) => {
969 if (node.isText && node.marks.some((mark) => mark.type.name === "bold")) {
970 bold.push(node.text!);
971 }
972 });
973 return bold;
974 }
975
976 it.each(["src/__test__.tsx", "src/__tests__/a.ts", "pkg/__init__.py", "a/**b**/c"])(
977 "keeps %s literal after @ so file search can match it",
978 (path) => {
979 const doc = paste("Open @", path);
980 expect(boldText(doc)).toEqual([]);
981 expect(serializeEditorDoc(doc).value).toBe(`Open @${path}`);
982 },
983 );
984
985 it("still styles the text after the path", () => {
986 const doc = paste("Open @", "src/__test__.tsx and **this**\n- [ ] then __that__");
987 expect(boldText(doc)).toEqual(["this", "that"]);
988 expect(doc.lastChild!.type.name).toBe("taskList");
989 expect(serializeEditorDoc(doc).value).toBe(
990 "Open @src/__test__.tsx and **this**\n- [ ] then **that**",
991 );
992 });
993
994 it("parses markdown after Escape dismisses the path query", () => {
995 const doc = paste("Open @", "__hello__ world", false);
996 expect(boldText(doc)).toEqual(["hello"]);
997 expect(serializeEditorDoc(doc).value).toBe("Open @**hello** world");
998 });
999
1000 it("keeps the rest of the path's line on that line", () => {
1001 const doc = paste("Open @", "src/a.ts - not a list item");
1002 expect(doc.childCount).toBe(1);
1003 expect(serializeEditorDoc(doc).value).toBe("Open @src/a.ts - not a list item");
1004 });
1005
1006 it("parses markdown when the paste does not continue a path query", () => {
1007 expect(boldText(paste("Open ", "src/__test__.tsx"))).toEqual(["test"]);
1008 expect(boldText(paste("Open @a ", "__b__"))).toEqual(["b"]);
1009 expect(boldText(paste("Open @", " __b__"))).toEqual(["b"]);
1010 });
1011
1012 it("keeps a path literal after a partly styled query", () => {
1013 const doc = paste("Open @**src/**", "__test__.tsx");
1014 expect(boldText(doc)).toEqual(["src/"]);
1015 expect(serializeEditorDoc(doc).value).toBe("Open @**src/**__test__.tsx");
1016 });
1017
1018 it("parses markdown pasted right after a mention chip", () => {
1019 const withSpace = ProseMirrorNode.fromJSON(
1020 schema,
1021 buildDocJson("Open @README.md ", skillLabelFor),
1022 );
1023 const paragraph = withSpace.firstChild!;
1024 expect(paragraph.lastChild!.text).toBe(" ");
1025 const chipLast = schema.node("doc", null, [
1026 paragraph.copy(paragraph.content.cut(0, paragraph.content.size - 1)),
1027 ]);
1028 expect(chipLast.firstChild!.lastChild!.type.name).toBe("composer-mention");
1029 expect(boldText(paste(chipLast, "__b__"))).toEqual(["b"]);
1030 });
1031});
1032
1033describe("caret stops at styled edges", () => {
1034 function stateAt(value: string, pmPos: number) {
1035 const doc = ProseMirrorNode.fromJSON(
1036 schema,
1037 buildDocJson(value, (name) => ({ label: name, description: null })),
1038 );
1039 return EditorState.create({ doc, selection: TextSelection.create(doc, pmPos) });
1040 }
1041
1042 function typed(state: EditorState, text: string) {
1043 return serializeEditorDoc(state.apply(state.tr.insertText(text)).doc).value;
1044 }
1045
1046 it("lets the caret step out in front of bold that starts the line", () => {
1047 const inside = stateAt("**bold** tail", 1);
1048 expect(caretTakesMarksBefore(inside)).toBe(false);
1049 expect(typed(inside, "x")).toBe("**xbold** tail");
1050
1051 const step = stepCaretAcrossStyledEdge(inside, -1);
1052 expect(step).not.toBeNull();
1053 const outside = inside.apply(step!);
1054 expect(caretTakesMarksBefore(outside)).toBe(true);
1055 expect(typed(outside, "x")).toBe("x**bold** tail");
1056 // Already outside: the next ArrowLeft moves the caret as usual.
1057 expect(stepCaretAcrossStyledEdge(outside, -1)).toBeNull();
1058
1059 const back = outside.apply(stepCaretAcrossStyledEdge(outside, 1)!);
1060 expect(typed(back, "x")).toBe("**xbold** tail");
1061 });
1062
1063 it("lets the caret step out after bold that ends the line", () => {
1064 const inside = stateAt("head **bold**", 10);
1065 expect(caretTakesMarksBefore(inside)).toBe(true);
1066 expect(typed(inside, "x")).toBe("head **boldx**");
1067 expect(stepCaretAcrossStyledEdge(inside, -1)).toBeNull();
1068
1069 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1070 expect(caretTakesMarksBefore(outside)).toBe(false);
1071 expect(typed(outside, "x")).toBe("head **bold**x");
1072 });
1073
1074 it("offers both stops where styled text meets plain text mid-line", () => {
1075 // Caret after "a ": types plain until ArrowRight steps into the bold.
1076 const plain = stateAt("a **b** c", 3);
1077 expect(caretTakesMarksBefore(plain)).toBe(true);
1078 expect(typed(plain, "x")).toBe("a x**b** c");
1079 const bold = plain.apply(stepCaretAcrossStyledEdge(plain, 1)!);
1080 expect(typed(bold, "x")).toBe("a **xb** c");
1081 });
1082
1083 it("offers the plain stop between bold text and a chip right after it", () => {
1084 // Markdown needs a space before a mention, but deleting it leaves them adjacent.
1085 const doc = schema.node("doc", null, [
1086 schema.node("paragraph", null, [
1087 schema.text("bold", [schema.marks.bold!.create()]),
1088 schema.nodes["composer-mention"]!.create({ path: "README.md", source: "@README.md" }),
1089 ]),
1090 ]);
1091 const inside = EditorState.create({ doc, selection: TextSelection.create(doc, 5) });
1092 expect(caretTakesMarksBefore(inside)).toBe(true);
1093 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1094 expect(caretTakesMarksBefore(outside)).toBe(false);
1095 const withText = outside.apply(outside.tr.insertText("x")).doc;
1096 expect(withText.child(0).child(1).text).toBe("x");
1097 expect(withText.child(0).child(1).marks).toEqual([]);
1098 });
1099
1100 it("steps out of inline code at the end of a line without inserting a space", () => {
1101 expect(ComposerCodeExtension.config.exitable).toBe(false);
1102 const inside = stateAt("`code`", 5);
1103 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1104 expect(typed(outside, "x")).toBe("`code`x");
1105 expect(stepCaretAcrossStyledEdge(outside, 1)).toBeNull();
1106 });
1107
1108 it("keeps marks the user toggled at an edge and lets the arrow move", () => {
1109 const inside = stateAt("a **b** c", 3);
1110 const toggled = inside.apply(
1111 inside.tr.setStoredMarks([schema.marks.bold!.create(), schema.marks.italic!.create()]),
1112 );
1113 expect(stepCaretAcrossStyledEdge(toggled, 1)).toBeNull();
1114 expect(stepCaretAcrossStyledEdge(toggled, -1)).toBeNull();
1115 });
1116
1117 it("leaves arrow keys alone away from styled edges", () => {
1118 expect(stepCaretAcrossStyledEdge(stateAt("**bold** tail", 3), -1)).toBeNull();
1119 expect(stepCaretAcrossStyledEdge(stateAt("plain text", 1), -1)).toBeNull();
1120 expect(caretTakesMarksBefore(stateAt("plain text", 1))).toBe(false);
1121 });
1122});