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

composer-rich-text-doc.test.ts

1,097 lines37.5 KB

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 });
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);
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);
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\nafter",
476 "> quote\n\n> another",
477 "- item\n> quote after list",
478 ])("round-trips the quote %s through a real ProseMirror document", (value) => {
479 expect(roundTrip(value).value).toBe(value);
480 });
481​
482 it.each([
483 "---",
484 "***",
485 "___",
486 "- - -",
487 "* * *",
488 "-----",
489 "--- ",
490 "text\n---\nmore",
491 "- item\n---\n- item two",
492 "```\n---\n```",
493 "--",
494 "-- -",
495 "---text",
496 ])("round-trips the rule %s through a real ProseMirror document", (value) => {
497 expect(roundTrip(value).value).toBe(value);
498 });
499​
500 it("parses rules ahead of lists and emphasis", () => {
501 const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({
502 label: n,
503 description: null,
504 }));
505 expect(json.content.map((block) => block.type)).toEqual([
506 "horizontalRule",
507 "horizontalRule",
508 "horizontalRule",
509 "paragraph",
510 "horizontalRule",
511 "bulletList",
512 ]);
513 });
514​
515 it.each([
516 "# Heading",
517 "## Two",
518 "###### Six",
519 "####### seven hashes stays a paragraph",
520 "# two spaces",
521 "#\tTab",
522 "# Trailing hashes stay literal #",
523 "#1234",
524 "#1234 is a pull request, not a heading",
525 "# Heading with **bold** and @README.md",
526 "#",
527 "# ",
528 "text\n# Heading\ntext",
529 "# Heading\n- item\n> quote\n---",
530 ])("round-trips the heading %s through a real ProseMirror document", (value) => {
531 expect(roundTrip(value).value).toBe(value);
532 });
533​
534 it.each(["> quoted", "> a\n>b", "---", "- - -", "# Heading", "#1234"])(
535 "keeps the block %s literal in plain mode",
536 (value) => {
537 expect(roundTripPlain(value).value).toBe(value);
538 },
539 );
540​
541 it("parses the blocks it renders as the right node types", () => {
542 const json = buildDocJson("# Title\n> quote\n---\n#1234 ref\n- - -", (n) => ({
543 label: n,
544 description: null,
545 }));
546 expect(json.content.map((block) => block.type)).toEqual([
547 "heading",
548 "blockquote",
549 "horizontalRule",
550 "paragraph",
551 "horizontalRule",
552 "paragraph",
553 ]);
554 });
555​
556 it.each([
557 ["---", "---"],
558 ["a\n---", "a\n---"],
559 ["---\n", "---"],
560 ])("gives the caret a line after the final rule of %j, written %j", (value, expected) => {
561 const map = roundTrip(value);
562 expect(map.value).toBe(expected);
563 const json = buildDocJson(value, () => ({ label: "", description: null }));
564 const doc = ProseMirrorNode.fromJSON(schema, json);
565 expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);
566 });
567​
568 it("parses rules ahead of lists and emphasis", () => {
569 const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({
570 label: n,
571 description: null,
572 }));
573 expect(json.content.map((block) => block.type)).toEqual([
574 "horizontalRule",
575 "horizontalRule",
576 "horizontalRule",
577 "paragraph",
578 "horizontalRule",
579 "bulletList",
580 ]);
581 });
582​
583 it.each([
584 "# Heading",
585 "## Two",
586 "###### Six",
587 "####### seven hashes stays a paragraph",
588 "# two spaces",
589 "#\tTab",
590 "# Trailing hashes stay literal #",
591 "#1234",
592 "#1234 is a pull request, not a heading",
593 "# Heading with **bold** and @README.md",
594 "#",
595 "# ",
596 "text\n# Heading\ntext",
597 "# Heading\n- item\n> quote\n---",
598 ])("round-trips the heading %s through a real ProseMirror document", (value) => {
599 expect(roundTrip(value).value).toBe(value);
600 });
601​
602 it.each(["> quoted", "> a\n>b", "---", "- - -", "# Heading", "#1234"])(
603 "keeps the block %s literal in plain mode",
604 (value) => {
605 expect(roundTripPlain(value).value).toBe(value);
606 },
607 );
608​
609 it("parses a quote as a blockquote of one paragraph per line", () => {
610 const json = buildDocJson("> a\n> b\n>c", (n) => ({ label: n, description: null }));
611 expect(json.content.map((block) => block.type)).toEqual(["blockquote", "blockquote"]);
612 expect((json.content[0] as { content: unknown[] }).content).toHaveLength(2);
613 });
614​
615 it.each([
616 "> a\n> b",
617 "> **q** @README.md",
618 "text\n---\nmore",
619 "---\ntext",
620 "# Heading text",
621 "## **b** @README.md",
622 ])(
623 "maps every document offset of the block %s through collapsed coordinates and back",
624 (value) => {
625 const map = roundTrip(value);
626 expect(map.value).toBe(value);
627 for (let flat = 0; flat <= map.docLength; flat += 1) {
628 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
629 }
630 },
631 );
632​
633 it("clamps offsets inside a quote or heading marker to the start of the text", () => {
634 for (const [value, prefix] of [
635 ["> quoted", "> "],
636 ["# Heading", "# "],
637 ] as const) {
638 const map = roundTrip(value);
639 for (let collapsed = 0; collapsed <= prefix.length; collapsed += 1) {
640 expect(collapsedToFlat(map, collapsed)).toBe(0);
641 }
642 expect(flatToCollapsed(map, 0)).toBe(prefix.length);
643 }
644 });
645​
646 it.each([
647 "```\ncode\n```",
648 "```ts\nconst a = 1;\n```",
649 "```ts\nconst a = 1;\n```\n",
650 "before\n```ts\nconst a = 1;\n```\nafter",
651 "```\n```",
652 "```ts\nline one\nline two\nline three\n```",
653 "```ts\n indented\n deeper\n```",
654 "```js title=example\ncode\n```",
655 "~~~py\ncode\n~~~",
656 "````\n```\n````",
657 "```ts\ncode without a closing fence",
658 "```",
659 "```ts\n**not bold** and @README.md stay literal\n```",
660 "```ts\ncode\n````",
661 "- [ ] task\n```ts\ncode\n```\n- [ ] after",
662 " ```ts\nindented fence stays a paragraph\n ```",
663 ])("round-trips the fenced block %s", (value) => {
664 expect(roundTrip(value).value).toBe(value);
665 });
666​
667 it.each(["```ts\nconst a = 1;\n```", "```\n```", "before\n```ts\ncode\n```\nafter"])(
668 "maps every document offset of %s through collapsed coordinates and back",
669 (value) => {
670 const map = roundTrip(value);
671 expect(map.value).toBe(value);
672 for (let flat = 0; flat <= map.docLength; flat += 1) {
673 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
674 }
675 },
676 );
677​
678 it("reads blocks written with CRLF line endings", () => {
679 const value = "# Title\r\n> quote\r\n---\r\n```ts\r\nconst a = 1;\r\n```\r\nafter";
680 const doc = buildDocJson(value, () => ({ label: "", description: null }));
681 expect(doc.content.map((block) => block.type)).toEqual([
682 "heading",
683 "blockquote",
684 "horizontalRule",
685 "codeBlock",
686 "paragraph",
687 ]);
688 expect(roundTrip(value).value).toBe(value);
689 });
690​
691 it("keeps the end of the code inside the fence rather than after it", () => {
692 const value = "```ts\nfunc();\n```";
693 const map = roundTrip(value);
694 const endOfCode = "func();".length;
695 expect(flatToCollapsed(map, endOfCode)).toBe("```ts\nfunc();".length);
696 expect(flatToMarkdown(map, endOfCode)).toBe("```ts\nfunc();".length);
697 expect(collapsedToFlat(map, flatToCollapsed(map, endOfCode))).toBe(endOfCode);
698 });
699​
700 it("keeps the caret inside an empty fence", () => {
701 const value = "before\n```\n```";
702 const map = roundTrip(value);
703 const inside = "before\n".length;
704 expect(flatToCollapsed(map, inside)).toBe("before\n```".length);
705 expect(collapsedToFlat(map, flatToCollapsed(map, inside))).toBe(inside);
706 });
707​
708 it("still places the end of an inline mark after its markers", () => {
709 const map = roundTrip("a **bold** c");
710 expect(flatToMarkdown(map, 6)).toBe(10);
711 });
712​
713 it("clamps offsets inside a fence to the edge of the code", () => {
714 const value = "```ts\nab\n```";
715 const map = roundTrip(value);
716 expect(map.value).toBe(value);
717 for (let collapsed = 0; collapsed <= "```ts\n".length; collapsed += 1) {
718 expect(collapsedToFlat(map, collapsed)).toBe(0);
719 }
720 expect(collapsedToFlat(map, "```ts\na".length)).toBe(1);
721 for (let collapsed = "```ts\nab".length; collapsed <= value.length; collapsed += 1) {
722 expect(collapsedToFlat(map, collapsed)).toBe(2);
723 }
724 });
725​
726 it.each([
727 ["```\n\n```", "```\n```"],
728 ["```\n", "```"],
729 ])("canonicalizes the empty fence %s", (value, expected) => {
730 expect(roundTrip(value).value).toBe(expected);
731 });
732​
733 it("keeps a chip in a fence info string as source and keeps later chips aligned", () => {
734 const value = "```@README.md\ncode\n```\n$my-skill after";
735 expect(roundTrip(value).value).toBe(value);
736 const json = buildDocJson(value, (n) => ({ label: n, description: null }));
737 const after = json.content[1] as {
738 content: { type: string; attrs?: { skillName?: string } }[];
739 };
740 expect(after.content.map((n) => n.type)).toEqual(["composer-skill", "text"]);
741 expect(after.content[0]?.attrs?.skillName).toBe("my-skill");
742 });
743​
744 it("keeps chips in a fence's info string and body each in their own place", () => {
745 const value = "``` @a.md\nsee @b.md\n```";
746 expect(roundTrip(value).value).toBe(value);
747 const json = buildDocJson(value, (n) => ({ label: n, description: null }));
748 const code = json.content[0] as { attrs: { language: string } };
749 expect(code.attrs.language).toBe(" @a.md");
750 });
751​
752 it.each([
753 ["listItem", { marker: "-", space: "" }, "bulletList", "- text"],
754 ["listItem", { marker: "1.", space: "" }, "orderedList", "1. text"],
755 ])("gives a bare %s a space once it has text", (item, attrs, list, expected) => {
756 const doc = ProseMirrorNode.fromJSON(schema, {
757 type: "doc",
758 content: [
759 {
760 type: list,
761 content: [
762 {
763 type: item,
764 attrs,
765 content: [{ type: "paragraph", content: [{ type: "text", text: "text" }] }],
766 },
767 ],
768 },
769 ],
770 });
771 expect(serializeEditorDoc(doc).value).toBe(expected);
772 expect(roundTrip("-").value).toBe("-");
773 });
774​
775 it("writes code holding a closing fence inside a longer fence", () => {
776 const doc = ProseMirrorNode.fromJSON(schema, {
777 type: "doc",
778 content: [
779 {
780 type: "codeBlock",
781 attrs: { fence: "```", close: "\n```" },
782 content: [{ type: "text", text: "initial\n```\nsecret" }],
783 },
784 ],
785 });
786 const stored = serializeEditorDoc(doc).value;
787 expect(stored).toBe("````\ninitial\n```\nsecret\n````");
788 expect(buildDocJson(stored, () => ({ label: "", description: null })).content).toHaveLength(1);
789 expect(roundTrip(stored).value).toBe(stored);
790 });
791​
792 it("closes an unclosed fence that has a block after it", () => {
793 const doc = ProseMirrorNode.fromJSON(schema, {
794 type: "doc",
795 content: [
796 { type: "codeBlock", attrs: { close: "" }, content: [{ type: "text", text: "code" }] },
797 { type: "paragraph", content: [{ type: "text", text: "after" }] },
798 ],
799 });
800 expect(serializeEditorDoc(doc).value).toBe("```\ncode\n```\nafter");
801 expect(roundTrip("```\ncode").value).toBe("```\ncode");
802 });
803​
804 it("counts a chip's source in a fence as one cursor position, as the draft store does", () => {
805 const value = "```\nsee @b.md now\n```\nafter";
806 const map = roundTrip(value);
807 expect(map.value).toBe(value);
808 for (let flat = 0; flat <= map.docLength; flat += 1) {
809 expect(flatToCollapsed(map, flat)).toBe(
810 collapseExpandedComposerCursor(value, flatToMarkdown(map, flat)),
811 );
812 }
813 const afterChip = "see @b.md".length;
814 expect(collapsedToFlat(map, flatToCollapsed(map, afterChip))).toBe(afterChip);
815 const end = map.docLength;
816 expect(collapsedToFlat(map, flatToCollapsed(map, end))).toBe(end);
817 });
818​
819 it("keeps fences literal in plain mode", () => {
820 const value = "```ts\nconst a = 1;\n```";
821 expect(roundTripPlain(value).value).toBe(value);
822 });
823​
824 it("maps every document offset through collapsed coordinates and back", () => {
825 const value = "hi **bold** @README.md bye";
826 const map = roundTrip(value);
827 expect(map.value).toBe(value);
828 for (let flat = 0; flat <= map.docLength; flat += 1) {
829 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
830 }
831 });
832​
833 it.each([
834 "plain prose with no styling at all",
835 "a chip @README.md counts one character in both modes",
836 "$my-skill leads the line",
837 "trailing newline\n",
838 ])("resolves a collapsed cursor identically in both modes for %s", (value) => {
839 const rich = roundTrip(value);
840 const plain = roundTripPlain(value);
841 expect(rich.value).toBe(value);
842 expect(plain.value).toBe(value);
843 for (let collapsed = 0; collapsed <= value.length; collapsed += 1) {
844 expect(flatToMarkdown(rich, collapsedToFlat(rich, collapsed))).toBe(
845 flatToMarkdown(plain, collapsedToFlat(plain, collapsed)),
846 );
847 }
848 });
849​
850 it("clamps a cursor that was sitting inside a marker onto the styled text", () => {
851 const value = "a **bold** c";
852 const plain = roundTripPlain(value);
853 const rich = roundTrip(value);
854 expect(flatToMarkdown(plain, collapsedToFlat(plain, 3))).toBe(3);
855 expect(flatToMarkdown(rich, collapsedToFlat(rich, 3))).toBe(4);
856 });
857​
858 it("maps markdown offsets at styled edges onto document text", () => {
859 const value = "a **bold** c";
860 const map = roundTrip(value);
861 expect(map.value).toBe(value);
862 expect(flatToMarkdown(map, 2)).toBe(4);
863 expect(flatToMarkdown(map, 6)).toBe(10);
864 expect(collapsedToFlat(map, 3)).toBe(2);
865 expect(collapsedToFlat(map, 9)).toBe(6);
866 });
867});
868​
869describe("serializeSelection", () => {
870 function copy(value: string, first: string, last: string) {
871 const doc = ProseMirrorNode.fromJSON(
872 schema,
873 buildDocJson(value, (name) => ({ label: name, description: null })),
874 );
875 let from = -1;
876 let to = -1;
877 doc.descendants((node, pos) => {
878 if (!node.isText) return true;
879 const text = node.text ?? "";
880 if (from < 0 && text.includes(first)) from = pos + text.indexOf(first);
881 if (text.includes(last)) to = pos + text.lastIndexOf(last) + last.length;
882 return false;
883 });
884 return serializeSelection(doc, from, to);
885 }
886​
887 it("keeps the markers of the list items it spans", () => {
888 expect(copy("- one\n- two\n- three", "one", "two")).toBe("- one\n- two");
889 expect(copy("3) one\n4) two", "one", "two")).toBe("3) one\n4) two");
890 expect(copy("- [ ] one\n- [x] two", "one", "two")).toBe("- [ ] one\n- [x] two");
891 });
892​
893 it("keeps the nesting of an item and its children", () => {
894 expect(copy("- p\n - a\n - b", "p", "a")).toBe("- p\n - a");
895 });
896​
897 it("keeps the prefix of the quote lines it spans", () => {
898 expect(copy("> one\n> two", "one", "two")).toBe("> one\n> two");
899 });
900​
901 it("copies text within one block without its marker", () => {
902 expect(copy("- one two", "one", "one")).toBe("one");
903 });
904​
905 it("copies across blocks as they are written", () => {
906 expect(copy("intro\n- one", "intro", "one")).toBe("intro\n- one");
907 });
908});
909​
910describe("pasting into a list item or quote", () => {
911 it("keeps inline marks but builds no blocks", () => {
912 const content = buildTiptapContent(
913 "**bold** text\n- item\n> quote",
914 () => ({ label: "", description: null }),
915 { styling: true, blocks: false },
916 );
917 expect(content.map((block) => block.type)).toEqual(["paragraph", "paragraph", "paragraph"]);
918 const first = content[0] as { content: { text: string; marks?: { type: string }[] }[] };
919 expect(first.content[0]).toMatchObject({ text: "bold", marks: [{ type: "bold" }] });
920 expect(JSON.stringify(content[1])).toContain("- item");
921 expect(JSON.stringify(content[2])).toContain("> quote");
922 });
923});
924​
925describe("pasting into a path query", () => {
926 const skillLabelFor = (name: string) => ({ label: name, description: null });
927​
928 function paste(prompt: string | ProseMirrorNode, pasted: string, pathQueryActive = true) {
929 const promptDoc =
930 typeof prompt === "string"
931 ? ProseMirrorNode.fromJSON(schema, buildDocJson(prompt, skillLabelFor))
932 : prompt;
933 const line = promptDoc.lastChild!;
934 const lineBefore = line.textBetween(0, line.content.size, undefined, "\uFFFC");
935 const literalLength = pastedPathQueryLength(lineBefore, pasted, pathQueryActive);
936 const blocks = buildTiptapContent(pasted, skillLabelFor, { literalLength });
937 const [first, ...rest] = blocks.map((block) => ProseMirrorNode.fromJSON(schema, block));
938 const head = promptDoc.lastChild!.content.append(first!.content);
939 const doc = schema.node("doc", null, [first!.copy(head), ...rest]);
940 doc.check();
941 return doc;
942 }
943​
944 function boldText(doc: ProseMirrorNode) {
945 const bold: string[] = [];
946 doc.descendants((node) => {
947 if (node.isText && node.marks.some((mark) => mark.type.name === "bold")) {
948 bold.push(node.text!);
949 }
950 });
951 return bold;
952 }
953​
954 it.each(["src/__test__.tsx", "src/__tests__/a.ts", "pkg/__init__.py", "a/**b**/c"])(
955 "keeps %s literal after @ so file search can match it",
956 (path) => {
957 const doc = paste("Open @", path);
958 expect(boldText(doc)).toEqual([]);
959 expect(serializeEditorDoc(doc).value).toBe(`Open @${path}`);
960 },
961 );
962​
963 it("still styles the text after the path", () => {
964 const doc = paste("Open @", "src/__test__.tsx and **this**\n- [ ] then __that__");
965 expect(boldText(doc)).toEqual(["this", "that"]);
966 expect(doc.lastChild!.type.name).toBe("taskList");
967 expect(serializeEditorDoc(doc).value).toBe(
968 "Open @src/__test__.tsx and **this**\n- [ ] then **that**",
969 );
970 });
971​
972 it("parses markdown after Escape dismisses the path query", () => {
973 const doc = paste("Open @", "__hello__ world", false);
974 expect(boldText(doc)).toEqual(["hello"]);
975 expect(serializeEditorDoc(doc).value).toBe("Open @**hello** world");
976 });
977​
978 it("keeps the rest of the path's line on that line", () => {
979 const doc = paste("Open @", "src/a.ts - not a list item");
980 expect(doc.childCount).toBe(1);
981 expect(serializeEditorDoc(doc).value).toBe("Open @src/a.ts - not a list item");
982 });
983​
984 it("parses markdown when the paste does not continue a path query", () => {
985 expect(boldText(paste("Open ", "src/__test__.tsx"))).toEqual(["test"]);
986 expect(boldText(paste("Open @a ", "__b__"))).toEqual(["b"]);
987 expect(boldText(paste("Open @", " __b__"))).toEqual(["b"]);
988 });
989​
990 it("keeps a path literal after a partly styled query", () => {
991 const doc = paste("Open @**src/**", "__test__.tsx");
992 expect(boldText(doc)).toEqual(["src/"]);
993 expect(serializeEditorDoc(doc).value).toBe("Open @**src/**__test__.tsx");
994 });
995​
996 it("parses markdown pasted right after a mention chip", () => {
997 const withSpace = ProseMirrorNode.fromJSON(
998 schema,
999 buildDocJson("Open @README.md ", skillLabelFor),
1000 );
1001 const paragraph = withSpace.firstChild!;
1002 expect(paragraph.lastChild!.text).toBe(" ");
1003 const chipLast = schema.node("doc", null, [
1004 paragraph.copy(paragraph.content.cut(0, paragraph.content.size - 1)),
1005 ]);
1006 expect(chipLast.firstChild!.lastChild!.type.name).toBe("composer-mention");
1007 expect(boldText(paste(chipLast, "__b__"))).toEqual(["b"]);
1008 });
1009});
1010​
1011describe("caret stops at styled edges", () => {
1012 function stateAt(value: string, pmPos: number) {
1013 const doc = ProseMirrorNode.fromJSON(
1014 schema,
1015 buildDocJson(value, (name) => ({ label: name, description: null })),
1016 );
1017 return EditorState.create({ doc, selection: TextSelection.create(doc, pmPos) });
1019​
1020 function typed(state: EditorState, text: string) {
1021 return serializeEditorDoc(state.apply(state.tr.insertText(text)).doc).value;
1023​
1024 it("lets the caret step out in front of bold that starts the line", () => {
1025 const inside = stateAt("**bold** tail", 1);
1026 expect(caretTakesMarksBefore(inside)).toBe(false);
1027 expect(typed(inside, "x")).toBe("**xbold** tail");
1028​
1029 const step = stepCaretAcrossStyledEdge(inside, -1);
1030 expect(step).not.toBeNull();
1031 const outside = inside.apply(step!);
1032 expect(caretTakesMarksBefore(outside)).toBe(true);
1033 expect(typed(outside, "x")).toBe("x**bold** tail");
1034 expect(stepCaretAcrossStyledEdge(outside, -1)).toBeNull();
1035​
1036 const back = outside.apply(stepCaretAcrossStyledEdge(outside, 1)!);
1037 expect(typed(back, "x")).toBe("**xbold** tail");
1038 });
1039​
1040 it("lets the caret step out after bold that ends the line", () => {
1041 const inside = stateAt("head **bold**", 10);
1042 expect(caretTakesMarksBefore(inside)).toBe(true);
1043 expect(typed(inside, "x")).toBe("head **boldx**");
1044 expect(stepCaretAcrossStyledEdge(inside, -1)).toBeNull();
1045​
1046 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1047 expect(caretTakesMarksBefore(outside)).toBe(false);
1048 expect(typed(outside, "x")).toBe("head **bold**x");
1049 });
1050​
1051 it("offers both stops where styled text meets plain text mid-line", () => {
1052 const plain = stateAt("a **b** c", 3);
1053 expect(caretTakesMarksBefore(plain)).toBe(true);
1054 expect(typed(plain, "x")).toBe("a x**b** c");
1055 const bold = plain.apply(stepCaretAcrossStyledEdge(plain, 1)!);
1056 expect(typed(bold, "x")).toBe("a **xb** c");
1057 });
1058​
1059 it("offers the plain stop between bold text and a chip right after it", () => {
1060 const doc = schema.node("doc", null, [
1061 schema.node("paragraph", null, [
1062 schema.text("bold", [schema.marks.bold!.create()]),
1063 schema.nodes["composer-mention"]!.create({ path: "README.md", source: "@README.md" }),
1064 ]),
1065 ]);
1066 const inside = EditorState.create({ doc, selection: TextSelection.create(doc, 5) });
1067 expect(caretTakesMarksBefore(inside)).toBe(true);
1068 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1069 expect(caretTakesMarksBefore(outside)).toBe(false);
1070 const withText = outside.apply(outside.tr.insertText("x")).doc;
1071 expect(withText.child(0).child(1).text).toBe("x");
1072 expect(withText.child(0).child(1).marks).toEqual([]);
1073 });
1074​
1075 it("steps out of inline code at the end of a line without inserting a space", () => {
1076 expect(ComposerCodeExtension.config.exitable).toBe(false);
1077 const inside = stateAt("`code`", 5);
1078 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1079 expect(typed(outside, "x")).toBe("`code`x");
1080 expect(stepCaretAcrossStyledEdge(outside, 1)).toBeNull();
1081 });
1082​
1083 it("keeps marks the user toggled at an edge and lets the arrow move", () => {
1084 const inside = stateAt("a **b** c", 3);
1085 const toggled = inside.apply(
1086 inside.tr.setStoredMarks([schema.marks.bold!.create(), schema.marks.italic!.create()]),
1087 );
1088 expect(stepCaretAcrossStyledEdge(toggled, 1)).toBeNull();
1089 expect(stepCaretAcrossStyledEdge(toggled, -1)).toBeNull();
1090 });
1091​
1092 it("leaves arrow keys alone away from styled edges", () => {
1093 expect(stepCaretAcrossStyledEdge(stateAt("**bold** tail", 3), -1)).toBeNull();
1094 expect(stepCaretAcrossStyledEdge(stateAt("plain text", 1), -1)).toBeNull();
1095 expect(caretTakesMarksBefore(stateAt("plain text", 1))).toBe(false);
1096 });
1097});