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