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