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

composer-rich-text-doc.test.ts

457 lines15.8 KB

1import { getSchemaByResolvedExtensions, Node, resolveExtensions } from "@tiptap/core";
2import StarterKit from "@tiptap/starter-kit";
3import { TaskList } from "@tiptap/extension-task-list";
4import { Node as ProseMirrorNode } from "@tiptap/pm/model";
5import { EditorState, TextSelection } from "@tiptap/pm/state";
6import { describe, expect, it } from "vite-plus/test";
7​
8import {
9 buildDocJson,
10 caretTakesMarksBefore,
11 collapsedToFlat,
12 ComposerCodeExtension,
13 ComposerTaskItemExtension,
14 flatToCollapsed,
15 flatToMarkdown,
16 flatToPm,
17 pmToFlat,
18 serializeEditorDoc,
19 stepCaretAcrossStyledEdge,
20} from "./composer-rich-text-doc";
21​
22function stubAtom(name: string, attrs: Record<string, { default: unknown }>) {
23 return Node.create({
24 name,
25 group: "inline",
26 inline: true,
27 atom: true,
28 addAttributes: () => attrs,
29 });
31​
32const schema = getSchemaByResolvedExtensions(
33 resolveExtensions([
34 StarterKit.configure({
35 blockquote: false,
36 bulletList: false,
37 codeBlock: false,
38 heading: false,
39 horizontalRule: false,
40 listItem: false,
41 orderedList: false,
42 dropcursor: false,
43 gapcursor: false,
44 trailingNode: false,
45 code: false,
46 }),
47 ComposerCodeExtension,
48 stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
49 stubAtom("composer-skill", {
50 skillName: { default: "" },
51 skillLabel: { default: "" },
52 skillDescription: { default: null },
53 }),
54 stubAtom("composer-citation", {
55 citation: { default: null },
56 source: { default: "" },
57 citeKey: { default: "" },
58 }),
59 stubAtom("composer-context-reference", {
60 kind: { default: "" },
61 contextId: { default: "" },
62 label: { default: "" },
63 source: { default: "" },
64 }),
65 TaskList,
66 ComposerTaskItemExtension,
67 ]),
68);
69​
70function roundTrip(value: string) {
71 const json = buildDocJson(value, (name) => ({ label: name, description: null }));
72 const doc = ProseMirrorNode.fromJSON(schema, json);
73 // `insertContent` validates every node against the schema; `fromJSON` does not.
74 doc.check();
75 return serializeEditorDoc(doc);
77​
78// Plain mode: the same engine with the mark extensions off. Markers stay
79// literal characters and task lines stay paragraphs.
80const plainSchema = getSchemaByResolvedExtensions(
81 resolveExtensions([
82 StarterKit.configure({
83 blockquote: false,
84 bulletList: false,
85 codeBlock: false,
86 heading: false,
87 horizontalRule: false,
88 listItem: false,
89 orderedList: false,
90 dropcursor: false,
91 gapcursor: false,
92 trailingNode: false,
93 bold: false,
94 italic: false,
95 strike: false,
96 code: false,
97 }),
98 stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
99 stubAtom("composer-skill", {
100 skillName: { default: "" },
101 skillLabel: { default: "" },
102 skillDescription: { default: null },
103 }),
104 stubAtom("composer-citation", {
105 citation: { default: null },
106 source: { default: "" },
107 citeKey: { default: "" },
108 }),
109 stubAtom("composer-context-reference", {
110 kind: { default: "" },
111 contextId: { default: "" },
112 label: { default: "" },
113 source: { default: "" },
114 }),
115 TaskList,
116 ComposerTaskItemExtension,
117 ]),
118);
119​
120function roundTripPlain(value: string) {
121 const json = buildDocJson(value, (name) => ({ label: name, description: null }), {
122 styling: false,
123 });
124 const doc = ProseMirrorNode.fromJSON(plainSchema, json);
125 return serializeEditorDoc(doc);
127​
128describe("composer rich text document model", () => {
129 it.each(["€", "£", "¥", "₹", "₩", "₿", "𑿝"])(
130 "canonicalizes %s skill aliases while preserving amounts",
131 (prefix) => {
132 const value = `Use ${prefix}my-skill for ${prefix}20 please`;
133 const expected = `Use $my-skill for ${prefix}20 please`;
134 expect(roundTrip(value).value).toBe(expected);
135 expect(roundTripPlain(value).value).toBe(expected);
136 },
137 );
138​
139 it.each([
140 "",
141 "\n\n",
142 "plain text",
143 "hello **bold** world",
144 "a *italic* word and `code` here",
145 "struck ~~out~~ now",
146 "**`x`**",
147 "*`x`*",
148 "~~`x`~~",
149 "**a `code` c**",
150 "***bold italic*** keeps nesting",
151 "line one\nline two",
152 "trailing newline\n",
153 "1. foo\n2. asdf\n",
154 "- [ ] buy milk",
155 "- [ ] buy milk",
156 "\t-\t[x]\t\titem",
157 "- [ ] ",
158 "- [ ]\n - [ ] child",
159 " - [ ] first\n - [ ] second\n - [ ] child",
160 "**before @README.md after**",
161 "*a **b** c*",
162 "*a**b***",
163 "**a*b***",
164 "**a *b* c**",
165 "literal \uFFFC **before @README.md after**",
166 "- [x] done\n- [ ] next",
167 "- [ ] parent\n - [ ] child\n - [ ] sibling\n- [ ] uncle",
168 "- [ ] empty task follows\n- [ ]",
169 "- [ ] **bold** task with @README.md",
170 "para\n- [ ] task\npara",
171 "- [ ]No space stays literal",
172 "-[ ] also literal",
173 "@README.md explain this",
174 '@"docs/My File.md" and $my-skill please',
175 "snake_case stays literal",
176 "unmatched ** stays literal",
177 "**bold** then @README.md then *italic*",
178 ])("round-trips %s through a real ProseMirror document", (value) => {
179 expect(roundTrip(value).value).toBe(value);
180 });
181​
182 it.each([
183 "",
184 "\n",
185 "text\n\n",
186 "- [ ]\n- [ ] next\n",
187 "- [ ] parent\n - [ ] child\n- [ ]",
188 "para\n- [ ] task\npara",
189 "**before @README.md after**",
190 ])("maps editable positions in %s", (value) => {
191 const doc = ProseMirrorNode.fromJSON(
192 schema,
193 buildDocJson(value, (name) => ({ label: name, description: null })),
194 );
195 const map = serializeEditorDoc(doc);
196 for (let flat = 0; flat <= map.docLength; flat += 1) {
197 const position = flatToPm(map, flat);
198 expect(doc.resolve(position).parent.isTextblock).toBe(true);
199 expect(pmToFlat(map, position)).toBe(flat);
200 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
201 }
202 });
203​
204 it("keeps the caret after a trailing hard break inside the same paragraph", () => {
205 const doc = schema.node("doc", null, [
206 schema.node("paragraph", null, [schema.text("a"), schema.node("hardBreak")]),
207 ]);
208 const map = serializeEditorDoc(doc);
209 expect(flatToPm(map, map.docLength)).toBe(3);
210 expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);
211 });
212​
213 it("renders a leading task dedent as siblings and nests under the new indent", () => {
214 const doc = ProseMirrorNode.fromJSON(
215 schema,
216 buildDocJson(" - [ ] first\n - [ ] second\n - [ ] child", (name) => ({
217 label: name,
218 description: null,
219 })),
220 );
221 const list = doc.firstChild!;
222 expect(list.childCount).toBe(2);
223 expect(list.child(0).childCount).toBe(1);
224 expect(list.child(1).child(1).firstChild!.textContent).toBe("child");
225 });
226​
227 it("applies a shared mark to text on both sides of a chip", () => {
228 const doc = ProseMirrorNode.fromJSON(
229 schema,
230 buildDocJson("**before @README.md after**", (name) => ({ label: name, description: null })),
231 );
232 expect(doc.firstChild!.childCount).toBe(3);
233 doc.firstChild!.forEach((child) =>
234 expect(child.marks.map((mark) => mark.type.name)).toContain("bold"),
235 );
236 expect(serializeEditorDoc(doc).value).toBe("**before @README.md after**");
237 });
238​
239 it.each([
240 [["bold"], ["bold", "italic"], ["italic"]],
241 [["italic"], ["bold", "italic"], ["bold"]],
242 [["bold"], ["bold", "strike"], ["strike"]],
243 [["strike"], ["bold", "strike"], ["bold"]],
244 ])("preserves crossing mark ranges %j through controlled rebuilds", (...marks) => {
245 const doc = schema.node("doc", null, [
246 schema.node(
247 "paragraph",
248 null,
249 marks.map((names, index) =>
250 schema.text(
251 String.fromCharCode(97 + index),
252 names.map((name) => schema.mark(name)),
253 ),
254 ),
255 ),
256 ]);
257 const serialized = serializeEditorDoc(doc).value;
258 const rebuilt = ProseMirrorNode.fromJSON(
259 schema,
260 buildDocJson(serialized, (name) => ({ label: name, description: null })),
261 );
262 expect(rebuilt.eq(doc)).toBe(true);
263 expect(serializeEditorDoc(rebuilt).value).toBe(serialized);
264 });
265​
266 it.each([
267 { parts: [{ text: "hello ", marks: ["bold"] }], expected: "**hello** " },
268 { parts: [{ text: " ", marks: ["bold"] }], expected: " " },
269 { parts: [{ text: " left ", marks: ["bold", "italic"] }], expected: " ***left*** " },
270 {
271 parts: [
272 { text: "one ", marks: ["bold"] },
273 { text: " two ", marks: ["bold", "italic"] },
274 { text: " three", marks: ["bold"] },
275 ],
276 expected: "**one *two* three**",
277 },
278 {
279 parts: [
280 { text: "hello ", marks: ["bold"] },
281 { text: "world ", marks: ["bold", "italic"] },
282 ],
283 expected: "**hello *world*** ",
284 },
285 { parts: [{ text: " hello ", marks: ["code"] }], expected: "` hello `" },
286 { parts: [{ text: " hello ", marks: ["bold", "code"] }], expected: "**` hello `**" },
287 { parts: [{ text: " ", marks: ["bold", "code"] }], expected: "**` `**" },
288 ])("keeps boundary whitespace outside emphasis in $expected", ({ parts, expected }) => {
289 const doc = schema.node("doc", null, [
290 schema.node(
291 "paragraph",
292 null,
293 parts.map(({ text, marks }) =>
294 schema.text(
295 text,
296 marks.map((name) => schema.mark(name)),
297 ),
298 ),
299 ),
300 ]);
301 const map = serializeEditorDoc(doc);
302 expect(map.value).toBe(expected);
303 const rebuilt = ProseMirrorNode.fromJSON(
304 schema,
305 buildDocJson(map.value, (name) => ({ label: name, description: null })),
306 );
307 expect(rebuilt.textContent).toBe(doc.textContent);
308 expect(serializeEditorDoc(rebuilt).value).toBe(map.value);
309 for (let flat = 0; flat <= map.docLength; flat += 1) {
310 expect(pmToFlat(map, flatToPm(map, flat))).toBe(flat);
311 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
312 if (flat < map.docLength && !/\s/.test(doc.textContent[flat]!)) {
313 expect(rebuilt.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name)).toEqual(
314 doc.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name),
315 );
316 }
317 }
318 });
319​
320 it("keeps chip sources canonical through the document", () => {
321 const map = roundTrip("explain @README.md with **care**\nsecond line *here*");
322 expect(map.value).toBe("explain @README.md with **care**\nsecond line *here*");
323 expect(
324 map.runs.some((run) => run.kind === "token" && run.nodeName === "composer-mention"),
325 ).toBe(true);
326 });
327​
328 it("normalizes uppercase checkboxes to lowercase", () => {
329 expect(roundTrip("- [X] done").value).toBe("- [x] done");
330 });
331​
332 it.each([
333 "plain text",
334 "hello **bold** stays literal",
335 "a *italic* stays literal",
336 "some `code` stays literal",
337 "struck ~~out~~ stays literal",
338 "- [ ] stays a paragraph",
339 "- [x] stays a paragraph",
340 "line one\nline two",
341 "@README.md explain this",
342 "**bold** then @README.md then *italic*",
343 ])("round-trips %s byte-identically in plain mode", (value) => {
344 expect(roundTripPlain(value).value).toBe(value);
345 });
346​
347 it("maps every document offset through collapsed coordinates and back", () => {
348 const value = "hi **bold** @README.md bye";
349 const map = roundTrip(value);
350 expect(map.value).toBe(value);
351 for (let flat = 0; flat <= map.docLength; flat += 1) {
352 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
353 }
354 });
355​
356 it("maps markdown offsets at styled edges onto document text", () => {
357 const value = "a **bold** c";
358 const map = roundTrip(value);
359 expect(map.value).toBe(value);
360 // document text is "a bold c" (flat), markdown has the markers.
361 expect(flatToMarkdown(map, 2)).toBe(4);
362 expect(flatToMarkdown(map, 6)).toBe(10);
363 expect(collapsedToFlat(map, 3)).toBe(2);
364 expect(collapsedToFlat(map, 9)).toBe(6);
365 });
366});
367​
368describe("caret stops at styled edges", () => {
369 function stateAt(value: string, pmPos: number) {
370 const doc = ProseMirrorNode.fromJSON(
371 schema,
372 buildDocJson(value, (name) => ({ label: name, description: null })),
373 );
374 return EditorState.create({ doc, selection: TextSelection.create(doc, pmPos) });
375 }
376​
377 function typed(state: EditorState, text: string) {
378 return serializeEditorDoc(state.apply(state.tr.insertText(text)).doc).value;
379 }
380​
381 it("lets the caret step out in front of bold that starts the line", () => {
382 const inside = stateAt("**bold** tail", 1);
383 expect(caretTakesMarksBefore(inside)).toBe(false);
384 expect(typed(inside, "x")).toBe("**xbold** tail");
385​
386 const step = stepCaretAcrossStyledEdge(inside, -1);
387 expect(step).not.toBeNull();
388 const outside = inside.apply(step!);
389 expect(caretTakesMarksBefore(outside)).toBe(true);
390 expect(typed(outside, "x")).toBe("x**bold** tail");
391 // Already outside: the next ArrowLeft moves the caret as usual.
392 expect(stepCaretAcrossStyledEdge(outside, -1)).toBeNull();
393​
394 const back = outside.apply(stepCaretAcrossStyledEdge(outside, 1)!);
395 expect(typed(back, "x")).toBe("**xbold** tail");
396 });
397​
398 it("lets the caret step out after bold that ends the line", () => {
399 const inside = stateAt("head **bold**", 10);
400 expect(caretTakesMarksBefore(inside)).toBe(true);
401 expect(typed(inside, "x")).toBe("head **boldx**");
402 expect(stepCaretAcrossStyledEdge(inside, -1)).toBeNull();
403​
404 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
405 expect(caretTakesMarksBefore(outside)).toBe(false);
406 expect(typed(outside, "x")).toBe("head **bold**x");
407 });
408​
409 it("offers both stops where styled text meets plain text mid-line", () => {
410 // Caret after "a ": types plain until ArrowRight steps into the bold.
411 const plain = stateAt("a **b** c", 3);
412 expect(caretTakesMarksBefore(plain)).toBe(true);
413 expect(typed(plain, "x")).toBe("a x**b** c");
414 const bold = plain.apply(stepCaretAcrossStyledEdge(plain, 1)!);
415 expect(typed(bold, "x")).toBe("a **xb** c");
416 });
417​
418 it("offers the plain stop between bold text and a chip right after it", () => {
419 // Markdown needs a space before a mention, but deleting it leaves them adjacent.
420 const doc = schema.node("doc", null, [
421 schema.node("paragraph", null, [
422 schema.text("bold", [schema.marks.bold!.create()]),
423 schema.nodes["composer-mention"]!.create({ path: "README.md", source: "@README.md" }),
424 ]),
425 ]);
426 const inside = EditorState.create({ doc, selection: TextSelection.create(doc, 5) });
427 expect(caretTakesMarksBefore(inside)).toBe(true);
428 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
429 expect(caretTakesMarksBefore(outside)).toBe(false);
430 const withText = outside.apply(outside.tr.insertText("x")).doc;
431 expect(withText.child(0).child(1).text).toBe("x");
432 expect(withText.child(0).child(1).marks).toEqual([]);
433 });
434​
435 it("steps out of inline code at the end of a line without inserting a space", () => {
436 expect(ComposerCodeExtension.config.exitable).toBe(false);
437 const inside = stateAt("`code`", 5);
438 const outside = inside.apply(stepCaretAcrossStyledEdge(inside, 1)!);
439 expect(typed(outside, "x")).toBe("`code`x");
440 expect(stepCaretAcrossStyledEdge(outside, 1)).toBeNull();
441 });
442​
443 it("keeps marks the user toggled at an edge and lets the arrow move", () => {
444 const inside = stateAt("a **b** c", 3);
445 const toggled = inside.apply(
446 inside.tr.setStoredMarks([schema.marks.bold!.create(), schema.marks.italic!.create()]),
447 );
448 expect(stepCaretAcrossStyledEdge(toggled, 1)).toBeNull();
449 expect(stepCaretAcrossStyledEdge(toggled, -1)).toBeNull();
450 });
451​
452 it("leaves arrow keys alone away from styled edges", () => {
453 expect(stepCaretAcrossStyledEdge(stateAt("**bold** tail", 3), -1)).toBeNull();
454 expect(stepCaretAcrossStyledEdge(stateAt("plain text", 1), -1)).toBeNull();
455 expect(caretTakesMarksBefore(stateAt("plain text", 1))).toBe(false);
456 });
457});