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

composer-rich-text-doc.test.ts

1,330 lines47.2 KB

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 });
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);
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);
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("keeps chip sources canonical through the document", () => {
431 const map = roundTrip("explain @README.md with **care**\nsecond line *here*");
432 expect(map.value).toBe("explain @README.md with **care**\nsecond line *here*");
433 expect(
434 map.runs.some((run) => run.kind === "token" && run.nodeName === "composer-mention"),
435 ).toBe(true);
436 });
437​
438 it("normalizes uppercase checkboxes to lowercase", () => {
439 expect(roundTrip("- [X] done").value).toBe("- [x] done");
440 });
441​
442 it.each([
443 "plain text",
444 "hello **bold** stays literal",
445 "a *italic* stays literal",
446 "some `code` stays literal",
447 "struck ~~out~~ stays literal",
448 "- [ ] stays a paragraph",
449 "- [x] stays a paragraph",
450 "line one\nline two",
451 "@README.md explain this",
452 "**bold** then @README.md then *italic*",
453 ])("round-trips %s byte-identically in plain mode", (value) => {
454 expect(roundTripPlain(value).value).toBe(value);
455 });
456​
457 it.each([
458 "- one\n- two",
459 "* star\n* star two",
460 "+ plus",
461 "* star\n+ plus",
462 "1. first\n2. second",
463 "1) paren\n2) paren",
464 "3. starts at three\n4. four",
465 "01. zero padded\n02. two",
466 "- parent\n - child\n - sibling\n- uncle",
467 "1. ordered\n - bullet child\n2. next",
468 "- outer\n 1. inner ordered\n 2. more\n- outer again",
469 "- wide space item",
470 "-",
471 "1.",
472 "- \n- second",
473 "- **bold** item with @README.md",
474 "- [ ] task\n- bullet after",
475 "- bullet\n- [x] task after",
476 "para\n- item\npara",
477 "\t- tab indented\n\t- again",
478 " - leading indent only",
479 "- item\n\n- after a blank",
480 "- item one\n```ts\ncode\n```\n- item two",
481 "-no space stays literal",
482 "1.no space stays literal",
483 "10. ten\n11. eleven",
484 ])("round-trips the list %s through a real ProseMirror document", (value) => {
485 expect(roundTrip(value).value).toBe(value);
486 });
487​
488 it.each([
489 "- one\n- two",
490 "1. first\n2. second",
491 "- parent\n - child",
492 "* star\n+ plus",
493 "-no space stays literal",
494 ])("keeps the list %s literal in plain mode", (value) => {
495 expect(roundTripPlain(value).value).toBe(value);
496 });
497​
498 it.each(["- one\n- two", "1. a\n - b\n2. c", "- **bold** @README.md tail", "-"])(
499 "maps every document offset of the list %s through markdown coordinates and back",
500 (value) => {
501 const map = roundTrip(value);
502 expect(map.value).toBe(value);
503 for (let flat = 0; flat <= map.docLength; flat += 1) {
504 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
505 }
506 },
507 );
508​
509 it("clamps offsets inside a list marker to the start of the item text", () => {
510 const value = "- item";
511 const map = roundTrip(value);
512 for (let markdown = 0; markdown <= "- ".length; markdown += 1) {
513 expect(markdownToFlat(map, markdown)).toBe(0);
514 }
515 expect(markdownToFlat(map, "- it".length)).toBe(2);
516 expect(flatToMarkdown(map, 0)).toBe("- ".length);
517 });
518​
519 it.each([
520 "> quoted",
521 "> line one\n> line two",
522 ">no space",
523 "> two spaces",
524 "> a\n>b",
525 ">",
526 "> **bold** and @README.md inside",
527 "> - looks like a list but stays quote text",
528 "> > nested stays literal inside the quote",
529 "before\n> quoted",
530 "> quote\n\n> another",
531 "- item\n> quote after list",
532 "> quoted\n\ncomment",
533 "> line one\n> line two\n\ncomment",
534 ])("round-trips the quote %s through a real ProseMirror document", (value) => {
535 expect(roundTrip(value).value).toBe(value);
536 });
537​
538 describe("a paragraph after a quote", () => {
539 const paragraph = (text?: string) => ({
540 type: "paragraph",
541 ...(text ? { content: [{ type: "text", text }] } : {}),
542 });
543 const quote = (...lines: string[]) => ({
544 type: "blockquote",
545 attrs: { prefix: "> " },
546 content: lines.map((line) => paragraph(line)),
547 });
548 const serialize = (...content: object[]) => {
549 const doc = ProseMirrorNode.fromJSON(schema, { type: "doc", content });
550 doc.check();
551 return { doc, map: serializeEditorDoc(doc) };
552 };
553​
554 it("is written after a blank line, or Markdown folds it into the quote", () => {
555 expect(serialize(quote("quoted"), paragraph("Comment to it")).map.value).toBe(
556 "> quoted\n\nComment to it",
557 );
558 expect(serialize(quote("a", "b"), paragraph("comment")).map.value).toBe(
559 "> a\n> b\n\ncomment",
560 );
561 });
562​
563 it("does not double up on the empty line the user left themselves", () => {
564 expect(serialize(quote("quoted"), paragraph(), paragraph("Comment to it")).map.value).toBe(
565 "> quoted\n\nComment to it",
566 );
567 });
568​
569 it("settles on the blank line when a draft glued it to the quote", () => {
570 const settled = "before\n> quoted\n\nafter";
571 expect(roundTrip("before\n> quoted\nafter").value).toBe(settled);
572 expect(roundTrip(settled).value).toBe(settled);
573 });
574​
575 it.each(["# Heading", "- item", "3. item", "---", "```\ncode\n```"])(
576 "leaves %s on the next line, since it opens its own block",
577 (next) => {
578 const value = `> quoted\n${next}`;
579 expect(roundTrip(value).value).toBe(value);
580 },
581 );
582​
583 it("keeps every offset mapped through the blank line", () => {
584 const { doc, map } = serialize(quote("quoted"), paragraph("Comment"));
585 for (let flat = 0; flat <= map.docLength; flat += 1) {
586 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
587 }
588 // The caret on the end of the quote stays on it, and the blank line is
589 // not a place to type: it clamps to the start of the comment.
590 expect(flatToMarkdown(map, "quoted".length)).toBe("> quoted".length);
591 expect(markdownToFlat(map, "> quoted\n".length)).toBe("quoted".length + 1);
592 expect(flatToMarkdown(map, "quoted".length + 1)).toBe("> quoted\n\n".length);
593 expect(flatToPm(map, "quoted".length + 1)).toBe(doc.child(0).nodeSize + 1);
594 });
595 });
596​
597 it.each([
598 "---",
599 "***",
600 "___",
601 "- - -",
602 "* * *",
603 "-----",
604 "--- ",
605 "text\n---\nmore",
606 "- item\n---\n- item two",
607 "```\n---\n```",
608 "--",
609 "-- -",
610 "---text",
611 ])("round-trips the rule %s through a real ProseMirror document", (value) => {
612 expect(roundTrip(value).value).toBe(value);
613 });
614​
615 it("parses rules ahead of lists and emphasis", () => {
616 const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({
617 label: n,
618 description: null,
619 }));
620 expect(json.content.map((block) => block.type)).toEqual([
621 "horizontalRule",
622 "horizontalRule",
623 "horizontalRule",
624 "paragraph",
625 "horizontalRule",
626 "bulletList",
627 ]);
628 });
629​
630 it.each([
631 "# Heading",
632 "## Two",
633 "###### Six",
634 "####### seven hashes stays a paragraph",
635 "# two spaces",
636 "#\tTab",
637 "# Trailing hashes stay literal #",
638 "#1234",
639 "#1234 is a pull request, not a heading",
640 "# Heading with **bold** and @README.md",
641 "#",
642 "# ",
643 "text\n# Heading\ntext",
644 "# Heading\n- item\n> quote\n---",
645 ])("round-trips the heading %s through a real ProseMirror document", (value) => {
646 expect(roundTrip(value).value).toBe(value);
647 });
648​
649 it.each(["> quoted", "> a\n>b", "---", "- - -", "# Heading", "#1234"])(
650 "keeps the block %s literal in plain mode",
651 (value) => {
652 expect(roundTripPlain(value).value).toBe(value);
653 },
654 );
655​
656 it("parses the blocks it renders as the right node types", () => {
657 const json = buildDocJson("# Title\n> quote\n---\n#1234 ref\n- - -", (n) => ({
658 label: n,
659 description: null,
660 }));
661 expect(json.content.map((block) => block.type)).toEqual([
662 "heading",
663 "blockquote",
664 "horizontalRule",
665 "paragraph",
666 "horizontalRule",
667 "paragraph",
668 ]);
669 });
670​
671 it.each([
672 ["---", "---"],
673 ["a\n---", "a\n---"],
674 ["---\n", "---"],
675 ])("gives the caret a line after the final rule of %j, written %j", (value, expected) => {
676 const map = roundTrip(value);
677 expect(map.value).toBe(expected);
678 const json = buildDocJson(value, () => ({ label: "", description: null }));
679 const doc = ProseMirrorNode.fromJSON(schema, json);
680 expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);
681 });
682​
683 it("parses rules ahead of lists and emphasis", () => {
684 const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({
685 label: n,
686 description: null,
687 }));
688 expect(json.content.map((block) => block.type)).toEqual([
689 "horizontalRule",
690 "horizontalRule",
691 "horizontalRule",
692 "paragraph",
693 "horizontalRule",
694 "bulletList",
695 ]);
696 });
697​
698 it.each([
699 "# Heading",
700 "## Two",
701 "###### Six",
702 "####### seven hashes stays a paragraph",
703 "# two spaces",
704 "#\tTab",
705 "# Trailing hashes stay literal #",
706 "#1234",
707 "#1234 is a pull request, not a heading",
708 "# Heading with **bold** and @README.md",
709 "#",
710 "# ",
711 "text\n# Heading\ntext",
712 "# Heading\n- item\n> quote\n---",
713 ])("round-trips the heading %s through a real ProseMirror document", (value) => {
714 expect(roundTrip(value).value).toBe(value);
715 });
716​
717 it.each(["> quoted", "> a\n>b", "---", "- - -", "# Heading", "#1234"])(
718 "keeps the block %s literal in plain mode",
719 (value) => {
720 expect(roundTripPlain(value).value).toBe(value);
721 },
722 );
723​
724 it("parses a quote as a blockquote of one paragraph per line", () => {
725 const json = buildDocJson("> a\n> b\n>c", (n) => ({ label: n, description: null }));
726 expect(json.content.map((block) => block.type)).toEqual(["blockquote", "blockquote"]);
727 expect((json.content[0] as { content: unknown[] }).content).toHaveLength(2);
728 });
729​
730 it.each([
731 "> a\n> b",
732 "> **q** @README.md",
733 "text\n---\nmore",
734 "---\ntext",
735 "# Heading text",
736 "## **b** @README.md",
737 ])(
738 "maps every document offset of the block %s through markdown coordinates and back",
739 (value) => {
740 const map = roundTrip(value);
741 expect(map.value).toBe(value);
742 for (let flat = 0; flat <= map.docLength; flat += 1) {
743 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
744 }
745 },
746 );
747​
748 it("clamps offsets inside a quote or heading marker to the start of the text", () => {
749 for (const [value, prefix] of [
750 ["> quoted", "> "],
751 ["# Heading", "# "],
752 ] as const) {
753 const map = roundTrip(value);
754 for (let markdown = 0; markdown <= prefix.length; markdown += 1) {
755 expect(markdownToFlat(map, markdown)).toBe(0);
756 }
757 expect(flatToMarkdown(map, 0)).toBe(prefix.length);
758 }
759 });
760​
761 it.each([
762 "```\ncode\n```",
763 "```ts\nconst a = 1;\n```",
764 "```ts\nconst a = 1;\n```\n",
765 "before\n```ts\nconst a = 1;\n```\nafter",
766 "```\n```",
767 "```ts\nline one\nline two\nline three\n```",
768 "```ts\n indented\n deeper\n```",
769 "```js title=example\ncode\n```",
770 "~~~py\ncode\n~~~",
771 "````\n```\n````",
772 "```ts\ncode without a closing fence",
773 "```",
774 "```ts\n**not bold** and @README.md stay literal\n```",
775 "```ts\ncode\n````",
776 "- [ ] task\n```ts\ncode\n```\n- [ ] after",
777 " ```ts\nindented fence stays a paragraph\n ```",
778 ])("round-trips the fenced block %s", (value) => {
779 expect(roundTrip(value).value).toBe(value);
780 });
781​
782 it.each(["```ts\nconst a = 1;\n```", "```\n```", "before\n```ts\ncode\n```\nafter"])(
783 "maps every document offset of %s through markdown coordinates and back",
784 (value) => {
785 const map = roundTrip(value);
786 expect(map.value).toBe(value);
787 for (let flat = 0; flat <= map.docLength; flat += 1) {
788 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
789 }
790 },
791 );
792​
793 it("reads blocks written with CRLF line endings", () => {
794 const value = "# Title\r\n> quote\r\n---\r\n```ts\r\nconst a = 1;\r\n```\r\nafter";
795 const doc = buildDocJson(value, () => ({ label: "", description: null }));
796 expect(doc.content.map((block) => block.type)).toEqual([
797 "heading",
798 "blockquote",
799 "horizontalRule",
800 "codeBlock",
801 "paragraph",
802 ]);
803 expect(roundTrip(value).value).toBe(value);
804 });
805​
806 it("keeps the end of the code inside the fence rather than after it", () => {
807 const value = "```ts\nfunc();\n```";
808 const map = roundTrip(value);
809 const endOfCode = "func();".length;
810 expect(flatToMarkdown(map, endOfCode)).toBe("```ts\nfunc();".length);
811 expect(markdownToFlat(map, flatToMarkdown(map, endOfCode))).toBe(endOfCode);
812 });
813​
814 it("keeps the caret inside an empty fence", () => {
815 const value = "before\n```\n```";
816 const map = roundTrip(value);
817 const inside = "before\n".length;
818 expect(flatToMarkdown(map, inside)).toBe("before\n```".length);
819 expect(markdownToFlat(map, flatToMarkdown(map, inside))).toBe(inside);
820 });
821​
822 it("still places the end of an inline mark after its markers", () => {
823 const map = roundTrip("a **bold** c");
824 expect(flatToMarkdown(map, 6)).toBe(10);
825 });
826​
827 it("clamps offsets inside a fence to the edge of the code", () => {
828 const value = "```ts\nab\n```";
829 const map = roundTrip(value);
830 expect(map.value).toBe(value);
831 for (let markdown = 0; markdown <= "```ts\n".length; markdown += 1) {
832 expect(markdownToFlat(map, markdown)).toBe(0);
833 }
834 expect(markdownToFlat(map, "```ts\na".length)).toBe(1);
835 for (let markdown = "```ts\nab".length; markdown <= value.length; markdown += 1) {
836 expect(markdownToFlat(map, markdown)).toBe(2);
837 }
838 });
839​
840 it.each([
841 ["```\n\n```", "```\n```"],
842 ["```\n", "```"],
843 ])("canonicalizes the empty fence %s", (value, expected) => {
844 expect(roundTrip(value).value).toBe(expected);
845 });
846​
847 it("keeps a chip in a fence info string as source and keeps later chips aligned", () => {
848 const value = "```@README.md\ncode\n```\n$my-skill after";
849 expect(roundTrip(value).value).toBe(value);
850 const json = buildDocJson(value, (n) => ({ label: n, description: null }));
851 const after = json.content[1] as {
852 content: { type: string; attrs?: { skillName?: string } }[];
853 };
854 expect(after.content.map((n) => n.type)).toEqual(["composer-skill", "text"]);
855 expect(after.content[0]?.attrs?.skillName).toBe("my-skill");
856 });
857​
858 it("keeps chips in a fence's info string and body each in their own place", () => {
859 const value = "``` @a.md\nsee @b.md\n```";
860 expect(roundTrip(value).value).toBe(value);
861 const json = buildDocJson(value, (n) => ({ label: n, description: null }));
862 const code = json.content[0] as { attrs: { language: string } };
863 expect(code.attrs.language).toBe(" @a.md");
864 });
865​
866 it.each([
867 ["listItem", { marker: "-", space: "" }, "bulletList", "- text"],
868 ["listItem", { marker: "1.", space: "" }, "orderedList", "1. text"],
869 ])("gives a bare %s a space once it has text", (item, attrs, list, expected) => {
870 const doc = ProseMirrorNode.fromJSON(schema, {
871 type: "doc",
872 content: [
873 {
874 type: list,
875 content: [
876 {
877 type: item,
878 attrs,
879 content: [{ type: "paragraph", content: [{ type: "text", text: "text" }] }],
880 },
881 ],
882 },
883 ],
884 });
885 expect(serializeEditorDoc(doc).value).toBe(expected);
886 expect(roundTrip("-").value).toBe("-");
887 });
888​
889 it("writes code holding a closing fence inside a longer fence", () => {
890 const doc = ProseMirrorNode.fromJSON(schema, {
891 type: "doc",
892 content: [
893 {
894 type: "codeBlock",
895 attrs: { fence: "```", close: "\n```" },
896 content: [{ type: "text", text: "initial\n```\nsecret" }],
897 },
898 ],
899 });
900 const stored = serializeEditorDoc(doc).value;
901 expect(stored).toBe("````\ninitial\n```\nsecret\n````");
902 expect(buildDocJson(stored, () => ({ label: "", description: null })).content).toHaveLength(1);
903 expect(roundTrip(stored).value).toBe(stored);
904 });
905​
906 it("closes an unclosed fence that has a block after it", () => {
907 const doc = ProseMirrorNode.fromJSON(schema, {
908 type: "doc",
909 content: [
910 { type: "codeBlock", attrs: { close: "" }, content: [{ type: "text", text: "code" }] },
911 { type: "paragraph", content: [{ type: "text", text: "after" }] },
912 ],
913 });
914 expect(serializeEditorDoc(doc).value).toBe("```\ncode\n```\nafter");
915 expect(roundTrip("```\ncode").value).toBe("```\ncode");
916 });
917​
918 it("keeps a chip's source in a fence as literal text", () => {
919 const value = "```\nsee @b.md and $babysit now\n```\nafter";
920 const known = () => ({ label: "Babysit", description: null });
921 const doc = ProseMirrorNode.fromJSON(schema, buildDocJson(value, known));
922 const map = serializeEditorDoc(doc);
923 expect(map.value).toBe(value);
924 expect(map.runs.filter((run) => run.kind === "token")).toEqual([]);
925 for (let flat = 0; flat <= map.docLength; flat += 1) {
926 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
927 }
928 // Reconciling against the provider's skills leaves the code alone too.
929 expect(skillChipReplacements(doc, known)).toEqual([]);
930 });
931​
932 it("keeps fences literal in plain mode", () => {
933 const value = "```ts\nconst a = 1;\n```";
934 expect(roundTripPlain(value).value).toBe(value);
935 });
936​
937 it("maps every document offset through markdown coordinates and back", () => {
938 const value = "hi **bold** @README.md bye";
939 const map = roundTrip(value);
940 expect(map.value).toBe(value);
941 for (let flat = 0; flat <= map.docLength; flat += 1) {
942 expect(markdownToFlat(map, flatToMarkdown(map, flat))).toBe(flat);
943 }
944 });
945​
946 it.each([
947 "plain prose with no styling at all",
948 "a chip @README.md counts one character in both modes",
949 "$my-skill leads the line",
950 "trailing newline\n",
951 ])("resolves a collapsed cursor identically in both modes for %s", (value) => {
952 const rich = roundTrip(value);
953 const plain = roundTripPlain(value);
954 expect(rich.value).toBe(value);
955 expect(plain.value).toBe(value);
956 for (let collapsed = 0; collapsed <= value.length; collapsed += 1) {
957 const markdown = expandCollapsedComposerCursor(value, collapsed);
958 expect(flatToMarkdown(rich, markdownToFlat(rich, markdown))).toBe(
959 flatToMarkdown(plain, markdownToFlat(plain, markdown)),
960 );
961 }
962 });
963​
964 it("clamps a cursor that was sitting inside a marker onto the styled text", () => {
965 const value = "a **bold** c";
966 const plain = roundTripPlain(value);
967 const rich = roundTrip(value);
968 expect(flatToMarkdown(plain, markdownToFlat(plain, 3))).toBe(3);
969 expect(flatToMarkdown(rich, markdownToFlat(rich, 3))).toBe(4);
970 });
971​
972 it("maps markdown offsets at styled edges onto document text", () => {
973 const value = "a **bold** c";
974 const map = roundTrip(value);
975 expect(map.value).toBe(value);
976 expect(flatToMarkdown(map, 2)).toBe(4);
977 expect(flatToMarkdown(map, 6)).toBe(10);
978 expect(markdownToFlat(map, 3)).toBe(2);
979 expect(markdownToFlat(map, 9)).toBe(6);
980 });
981});
982​
983describe("serializeSelection", () => {
984 function copy(value: string, first: string, last: string) {
985 const doc = ProseMirrorNode.fromJSON(
986 schema,
987 buildDocJson(value, (name) => ({ label: name, description: null })),
988 );
989 let from = -1;
990 let to = -1;
991 doc.descendants((node, pos) => {
992 if (!node.isText) return true;
993 const text = node.text ?? "";
994 if (from < 0 && text.includes(first)) from = pos + text.indexOf(first);
995 if (text.includes(last)) to = pos + text.lastIndexOf(last) + last.length;
996 return false;
997 });
998 return serializeSelection(doc, from, to);
999 }
1000​
1001 it("keeps the markers of the list items it spans", () => {
1002 expect(copy("- one\n- two\n- three", "one", "two")).toBe("- one\n- two");
1003 expect(copy("3) one\n4) two", "one", "two")).toBe("3) one\n4) two");
1004 expect(copy("- [ ] one\n- [x] two", "one", "two")).toBe("- [ ] one\n- [x] two");
1005 });
1006​
1007 it("keeps the nesting of an item and its children", () => {
1008 expect(copy("- p\n - a\n - b", "p", "a")).toBe("- p\n - a");
1009 });
1010​
1011 it("keeps the prefix of the quote lines it spans", () => {
1012 expect(copy("> one\n> two", "one", "two")).toBe("> one\n> two");
1013 });
1014​
1015 it("copies text within one block without its marker", () => {
1016 expect(copy("- one two", "one", "one")).toBe("one");
1017 });
1018​
1019 it("copies across blocks as they are written", () => {
1020 expect(copy("intro\n- one", "intro", "one")).toBe("intro\n- one");
1021 });
1022});
1023​
1024describe("pasting into a list item or quote", () => {
1025 it("keeps inline marks but builds no blocks", () => {
1026 const content = buildTiptapContent(
1027 "**bold** text\n- item\n> quote",
1028 () => ({ label: "", description: null }),
1029 { styling: true, blocks: false },
1030 );
1031 expect(content.map((block) => block.type)).toEqual(["paragraph", "paragraph", "paragraph"]);
1032 const first = content[0] as { content: { text: string; marks?: { type: string }[] }[] };
1033 expect(first.content[0]).toMatchObject({ text: "bold", marks: [{ type: "bold" }] });
1034 expect(JSON.stringify(content[1])).toContain("- item");
1035 expect(JSON.stringify(content[2])).toContain("> quote");
1036 });
1037});
1038​
1039describe("pasting into a path query", () => {
1040 const skillLabelFor = (name: string) => ({ label: name, description: null });
1041​
1042 function paste(prompt: string | ProseMirrorNode, pasted: string, pathQueryActive = true) {
1043 const promptDoc =
1044 typeof prompt === "string"
1045 ? ProseMirrorNode.fromJSON(schema, buildDocJson(prompt, skillLabelFor))
1046 : prompt;
1047 const line = promptDoc.lastChild!;
1048 const lineBefore = line.textBetween(0, line.content.size, undefined, "\uFFFC");
1049 const literalLength = pastedPathQueryLength(lineBefore, pasted, pathQueryActive);
1050 const blocks = buildTiptapContent(pasted, skillLabelFor, { literalLength });
1051 const [first, ...rest] = blocks.map((block) => ProseMirrorNode.fromJSON(schema, block));
1052 const head = promptDoc.lastChild!.content.append(first!.content);
1053 const doc = schema.node("doc", null, [first!.copy(head), ...rest]);
1054 doc.check();
1055 return doc;
1057​
1058 function boldText(doc: ProseMirrorNode) {
1059 const bold: string[] = [];
1060 doc.descendants((node) => {
1061 if (node.isText && node.marks.some((mark) => mark.type.name === "bold")) {
1062 bold.push(node.text!);
1064 });
1065 return bold;
1067​
1068 it.each(["src/__test__.tsx", "src/__tests__/a.ts", "pkg/__init__.py", "a/**b**/c"])(
1069 "keeps %s literal after @ so file search can match it",
1070 (path) => {
1071 const doc = paste("Open @", path);
1072 expect(boldText(doc)).toEqual([]);
1073 expect(serializeEditorDoc(doc).value).toBe(`Open @${path}`);
1074 },
1075 );
1076​
1077 it("still styles the text after the path", () => {
1078 const doc = paste("Open @", "src/__test__.tsx and **this**\n- [ ] then __that__");
1079 expect(boldText(doc)).toEqual(["this", "that"]);
1080 expect(doc.lastChild!.type.name).toBe("taskList");
1081 expect(serializeEditorDoc(doc).value).toBe(
1082 "Open @src/__test__.tsx and **this**\n- [ ] then **that**",
1083 );
1084 });
1085​
1086 it("parses markdown after Escape dismisses the path query", () => {
1087 const doc = paste("Open @", "__hello__ world", false);
1088 expect(boldText(doc)).toEqual(["hello"]);
1089 expect(serializeEditorDoc(doc).value).toBe("Open @**hello** world");
1090 });
1091​
1092 it("keeps the rest of the path's line on that line", () => {
1093 const doc = paste("Open @", "src/a.ts - not a list item");
1094 expect(doc.childCount).toBe(1);
1095 expect(serializeEditorDoc(doc).value).toBe("Open @src/a.ts - not a list item");
1096 });
1097​
1098 it("parses markdown when the paste does not continue a path query", () => {
1099 expect(boldText(paste("Open ", "src/__test__.tsx"))).toEqual(["test"]);
1100 expect(boldText(paste("Open @a ", "__b__"))).toEqual(["b"]);
1101 expect(boldText(paste("Open @", " __b__"))).toEqual(["b"]);
1102 });
1103​
1104 it("keeps a path literal after a partly styled query", () => {
1105 const doc = paste("Open @**src/**", "__test__.tsx");
1106 expect(boldText(doc)).toEqual(["src/"]);
1107 expect(serializeEditorDoc(doc).value).toBe("Open @**src/**__test__.tsx");
1108 });
1109​
1110 it("parses markdown pasted right after a mention chip", () => {
1111 const withSpace = ProseMirrorNode.fromJSON(
1112 schema,
1113 buildDocJson("Open @README.md ", skillLabelFor),
1114 );
1115 const paragraph = withSpace.firstChild!;
1116 expect(paragraph.lastChild!.text).toBe(" ");
1117 const chipLast = schema.node("doc", null, [
1118 paragraph.copy(paragraph.content.cut(0, paragraph.content.size - 1)),
1119 ]);
1120 expect(chipLast.firstChild!.lastChild!.type.name).toBe("composer-mention");
1121 expect(boldText(paste(chipLast, "__b__"))).toEqual(["b"]);
1122 });
1123});
1124​
1125describe("caret stops at styled edges", () => {
1126 function stateAt(value: string, pmPos: number) {
1127 const doc = ProseMirrorNode.fromJSON(
1128 schema,
1129 buildDocJson(value, (name) => ({ label: name, description: null })),
1130 );
1131 return EditorState.create({ doc, selection: TextSelection.create(doc, pmPos) });
1133​
1134 function typed(state: EditorState, text: string) {
1135 return serializeEditorDoc(state.apply(state.tr.insertText(text)).doc).value;
1137​
1138 it("lets the caret step out in front of bold that starts the line", () => {
1139 const inside = stateAt("**bold** tail", 1);
1140 expect(caretTakesMarksBefore(inside)).toBe(false);
1141 expect(typed(inside, "x")).toBe("**xbold** tail");
1142​
1143 const step = stepCaretAcrossStyledEdge(inside, -1);
1144 expect(step).not.toBeNull();
1145 const outside = inside.apply(step!);
1146 expect(caretTakesMarksBefore(outside)).toBe(true);
1147 expect(typed(outside, "x")).toBe("x**bold** tail");
1148 expect(stepCaretAcrossStyledEdge(outside, -1)).toBeNull();
1149​
1150 const back = outside.apply(stepCaretAcrossStyledEdge(outside, 1)!);
1151 expect(typed(back, "x")).toBe("**xbold** tail");
1152 });
1153​
1154 it("lets the caret step out after bold that ends the line", () => {
1155 const inside = stateAt("head **bold**", 10);
1156 expect(caretTakesMarksBefore(inside)).toBe(true);
1157 expect(typed(inside, "x")).toBe("head **boldx**");
1158 expect(stepCaretAcrossStyledEdge(inside, -1)).toBeNull();
1159​
1160 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1161 expect(caretTakesMarksBefore(outside)).toBe(false);
1162 expect(typed(outside, "x")).toBe("head **bold**x");
1163 });
1164​
1165 it("offers both stops where styled text meets plain text mid-line", () => {
1166 const plain = stateAt("a **b** c", 3);
1167 expect(caretTakesMarksBefore(plain)).toBe(true);
1168 expect(typed(plain, "x")).toBe("a x**b** c");
1169 const bold = plain.apply(stepCaretAcrossStyledEdge(plain, 1)!);
1170 expect(typed(bold, "x")).toBe("a **xb** c");
1171 });
1172​
1173 it("offers the plain stop between bold text and a chip right after it", () => {
1174 const doc = schema.node("doc", null, [
1175 schema.node("paragraph", null, [
1176 schema.text("bold", [schema.marks.bold!.create()]),
1177 schema.nodes["composer-mention"]!.create({ path: "README.md", source: "@README.md" }),
1178 ]),
1179 ]);
1180 const inside = EditorState.create({ doc, selection: TextSelection.create(doc, 5) });
1181 expect(caretTakesMarksBefore(inside)).toBe(true);
1182 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1183 expect(caretTakesMarksBefore(outside)).toBe(false);
1184 const withText = outside.apply(outside.tr.insertText("x")).doc;
1185 expect(withText.child(0).child(1).text).toBe("x");
1186 expect(withText.child(0).child(1).marks).toEqual([]);
1187 });
1188​
1189 it("steps out of inline code at the end of a line without inserting a space", () => {
1190 expect(ComposerCodeExtension.config.exitable).toBe(false);
1191 const inside = stateAt("`code`", 5);
1192 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
1193 expect(typed(outside, "x")).toBe("`code`x");
1194 expect(stepCaretAcrossStyledEdge(outside, 1)).toBeNull();
1195 });
1196​
1197 it("keeps marks the user toggled at an edge and lets the arrow move", () => {
1198 const inside = stateAt("a **b** c", 3);
1199 const toggled = inside.apply(
1200 inside.tr.setStoredMarks([schema.marks.bold!.create(), schema.marks.italic!.create()]),
1201 );
1202 expect(stepCaretAcrossStyledEdge(toggled, 1)).toBeNull();
1203 expect(stepCaretAcrossStyledEdge(toggled, -1)).toBeNull();
1204 });
1205​
1206 it("leaves arrow keys alone away from styled edges", () => {
1207 expect(stepCaretAcrossStyledEdge(stateAt("**bold** tail", 3), -1)).toBeNull();
1208 expect(stepCaretAcrossStyledEdge(stateAt("plain text", 1), -1)).toBeNull();
1209 expect(caretTakesMarksBefore(stateAt("plain text", 1))).toBe(false);
1210 });
1211});
1212​
1213describe("inline code entry", () => {
1214 function editorFor(block = "paragraph", mark?: string) {
1215 const editor = new Editor({
1216 element: null,
1217 extensions: [
1218 StarterKit.configure({ code: false, codeBlock: false, trailingNode: false }),
1219 ComposerCodeExtension,
1220 ComposerCodeBlockExtension,
1221 stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
1222 ],
1223 content: { type: "doc", content: [{ type: block }] },
1224 });
1225 // Unmounted editors need the same plugins that Tiptap installs on mount.
1226 editor.view.updateState(editor.state.reconfigure({ plugins: editor.extensionManager.plugins }));
1227 if (mark) editor.commands.setMark(mark);
1228 onTestFinished(() => editor.destroy());
1229 return editor;
1231​
1232 function type(editor: Editor, text: string) {
1233 for (const ch of text) {
1234 const { from, to } = editor.state.selection;
1235 const insert = () => editor.state.tr.insertText(ch, from, to);
1236 const handled = editor.state.plugins.some((plugin) =>
1237 plugin.props.handleTextInput?.call(plugin, editor.view, from, to, ch, insert),
1238 );
1239 if (!handled) editor.view.dispatch(insert());
1242​
1243 it.each(["", "prefix ", "@README.md"])(
1244 "formats a filled pair after %j, leaves following text plain, and keeps the normal input rule",
1245 (prefix) => {
1246 const editor = editorFor();
1247 if (prefix === "@README.md") {
1248 editor.commands.insertContent({
1249 type: "composer-mention",
1250 attrs: { path: "README.md", source: prefix },
1251 });
1252 } else {
1253 type(editor, prefix);
1255 const offset = editor.state.selection.from - 1;
1256 type(editor, "``");
1257 editor.commands.setTextSelection(offset + 2);
1258 type(editor, "hello world");
1259 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`hello world\``);
1260 expect(editor.state.doc.firstChild?.lastChild?.marks).toEqual([]);
1261​
1262 editor.commands.setTextSelection(offset + 14);
1263 expect(editor.state.doc.textContent).toBe(
1264 `${prefix === "@README.md" ? "" : prefix}hello world`,
1265 );
1266 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`hello world\``);
1267 type(editor, " next `typed`");
1268 expect(serializeEditorDoc(editor.state.doc).value).toBe(
1269 `${prefix}\`hello world\` next \`typed\``,
1270 );
1271 const formatted = editor.state.doc.toJSON();
1272 let undos = 0;
1273 while (editor.commands.undo()) undos += 1;
1274 expect(undos).toBeGreaterThan(0);
1275 expect(serializeEditorDoc(editor.state.doc).value).toBe("");
1276 for (let i = 0; i < undos; i += 1) expect(editor.commands.redo()).toBe(true);
1277 expect(editor.state.doc.toJSON()).toEqual(formatted);
1278 },
1279 );
1280​
1281 it("keeps composition edits literal until the caret leaves the typed pair", () => {
1282 const editor = editorFor();
1283 type(editor, "``");
1284 editor.commands.setTextSelection(2);
1285 editor.view.dispatch(editor.state.tr.insertText("世").setMeta("composition", 1));
1286 editor.view.dispatch(editor.state.tr.insertText("世界", 2, 3).setMeta("composition", 1));
1287 expect(editor.state.doc.textContent).toBe("`世界`");
1288 expect(editor.state.doc.firstChild?.firstChild?.marks).toEqual([]);
1289 editor.commands.setTextSelection(5);
1290 expect(editor.state.doc.textContent).toBe("世界");
1291 expect(serializeEditorDoc(editor.state.doc).value).toBe("`世界`");
1292 });
1293​
1294 it.each(["paste", "setContent"])("keeps a %s pair literal after moving through it", (source) => {
1295 const editor = editorFor();
1296 const literal = "`literal`";
1297 if (source === "paste") {
1298 editor.view.dispatch(editor.state.tr.insertText(literal).setMeta("uiEvent", "paste"));
1299 } else {
1300 type(editor, "``");
1301 editor.commands.setContent({
1302 type: "doc",
1303 content: [{ type: "paragraph", content: [{ type: "text", text: literal }] }],
1304 });
1306 const before = editor.state.doc.toJSON();
1307 editor.commands.setTextSelection(2);
1308 editor.commands.setTextSelection(literal.length + 1);
1309 expect(editor.state.doc.toJSON()).toEqual(before);
1310 });
1311​
1312 it.each([
1313 { name: "doubled delimiters", delimiters: "````", caret: 3 },
1314 { name: "doubled closing delimiters", delimiters: "```", caret: 2 },
1315 { name: "bold text", delimiters: "``", caret: 2, mark: "bold" },
1316 { name: "existing inline code", delimiters: "``", caret: 2, mark: "code" },
1317 { name: "a code block", delimiters: "``", caret: 2, block: "codeBlock" },
1318 ])("leaves $name unchanged on caret movement", ({ delimiters, caret, mark, block }) => {
1319 const editor = editorFor(block, mark);
1320 type(editor, delimiters);
1321 editor.commands.setTextSelection(caret);
1322 type(editor, "literal");
1323 const before = editor.state.doc.toJSON();
1324 // Visit both the gap between closing ticks and the end of the pair.
1325 editor.commands.setTextSelection(caret + "literal".length + 1);
1326 expect(editor.state.doc.toJSON()).toEqual(before);
1327 editor.commands.setTextSelection(editor.state.doc.content.size - 1);
1328 expect(editor.state.doc.toJSON()).toEqual(before);
1329 });
1330});