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