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

composer-rich-text-doc.test.ts

354 lines11.4 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 { describe, expect, it } from "vite-plus/test";
6​
7import {
8 buildDocJson,
9 collapsedToFlat,
10 ComposerTaskItemExtension,
11 flatToCollapsed,
12 flatToMarkdown,
13 flatToPm,
14 pmToFlat,
15 serializeEditorDoc,
16} from "./composer-rich-text-doc";
17​
18function stubAtom(name: string, attrs: Record<string, { default: unknown }>) {
19 return Node.create({
20 name,
21 group: "inline",
22 inline: true,
23 atom: true,
24 addAttributes: () => attrs,
25 });
27​
28const schema = getSchemaByResolvedExtensions(
29 resolveExtensions([
30 StarterKit.configure({
31 blockquote: false,
32 bulletList: false,
33 codeBlock: false,
34 heading: false,
35 horizontalRule: false,
36 listItem: false,
37 orderedList: false,
38 dropcursor: false,
39 gapcursor: false,
40 trailingNode: false,
41 }),
42 stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
43 stubAtom("composer-skill", {
44 skillName: { default: "" },
45 skillLabel: { default: "" },
46 skillDescription: { default: null },
47 }),
48 stubAtom("composer-citation", {
49 citation: { default: null },
50 source: { default: "" },
51 citeKey: { default: "" },
52 }),
53 stubAtom("composer-context-reference", {
54 kind: { default: "" },
55 contextId: { default: "" },
56 label: { default: "" },
57 source: { default: "" },
58 }),
59 TaskList,
60 ComposerTaskItemExtension,
61 ]),
62);
63​
64function roundTrip(value: string) {
65 const json = buildDocJson(value, (name) => ({ label: name, description: null }));
66 const doc = ProseMirrorNode.fromJSON(schema, json);
67 return serializeEditorDoc(doc);
69​
70// Plain mode: the same engine with the mark extensions off. Markers stay
71// literal characters and task lines stay paragraphs.
72const plainSchema = getSchemaByResolvedExtensions(
73 resolveExtensions([
74 StarterKit.configure({
75 blockquote: false,
76 bulletList: false,
77 codeBlock: false,
78 heading: false,
79 horizontalRule: false,
80 listItem: false,
81 orderedList: false,
82 dropcursor: false,
83 gapcursor: false,
84 trailingNode: false,
85 bold: false,
86 italic: false,
87 strike: false,
88 code: false,
89 }),
90 stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
91 stubAtom("composer-skill", {
92 skillName: { default: "" },
93 skillLabel: { default: "" },
94 skillDescription: { default: null },
95 }),
96 stubAtom("composer-citation", {
97 citation: { default: null },
98 source: { default: "" },
99 citeKey: { default: "" },
100 }),
101 stubAtom("composer-context-reference", {
102 kind: { default: "" },
103 contextId: { default: "" },
104 label: { default: "" },
105 source: { default: "" },
106 }),
107 TaskList,
108 ComposerTaskItemExtension,
109 ]),
110);
111​
112function roundTripPlain(value: string) {
113 const json = buildDocJson(value, (name) => ({ label: name, description: null }), {
114 styling: false,
115 });
116 const doc = ProseMirrorNode.fromJSON(plainSchema, json);
117 return serializeEditorDoc(doc);
119​
120describe("composer rich text document model", () => {
121 it.each(["€", "£", "¥", "₹", "₩", "₿", "𑿝"])(
122 "canonicalizes %s skill aliases while preserving amounts",
123 (prefix) => {
124 const value = `Use ${prefix}my-skill for ${prefix}20 please`;
125 const expected = `Use $my-skill for ${prefix}20 please`;
126 expect(roundTrip(value).value).toBe(expected);
127 expect(roundTripPlain(value).value).toBe(expected);
128 },
129 );
130​
131 it.each([
132 "",
133 "\n\n",
134 "plain text",
135 "hello **bold** world",
136 "a *italic* word and `code` here",
137 "struck ~~out~~ now",
138 "***bold italic*** keeps nesting",
139 "line one\nline two",
140 "trailing newline\n",
141 "1. foo\n2. asdf\n",
142 "- [ ] buy milk",
143 "- [ ] buy milk",
144 "\t-\t[x]\t\titem",
145 "- [ ] ",
146 "- [ ]\n - [ ] child",
147 " - [ ] first\n - [ ] second\n - [ ] child",
148 "**before @README.md after**",
149 "*a **b** c*",
150 "*a**b***",
151 "**a*b***",
152 "**a *b* c**",
153 "literal \uFFFC **before @README.md after**",
154 "- [x] done\n- [ ] next",
155 "- [ ] parent\n - [ ] child\n - [ ] sibling\n- [ ] uncle",
156 "- [ ] empty task follows\n- [ ]",
157 "- [ ] **bold** task with @README.md",
158 "para\n- [ ] task\npara",
159 "- [ ]No space stays literal",
160 "-[ ] also literal",
161 "@README.md explain this",
162 '@"docs/My File.md" and $my-skill please',
163 "snake_case stays literal",
164 "unmatched ** stays literal",
165 "**bold** then @README.md then *italic*",
166 ])("round-trips %s through a real ProseMirror document", (value) => {
167 expect(roundTrip(value).value).toBe(value);
168 });
169​
170 it.each([
171 "",
172 "\n",
173 "text\n\n",
174 "- [ ]\n- [ ] next\n",
175 "- [ ] parent\n - [ ] child\n- [ ]",
176 "para\n- [ ] task\npara",
177 "**before @README.md after**",
178 ])("maps editable positions in %s", (value) => {
179 const doc = ProseMirrorNode.fromJSON(
180 schema,
181 buildDocJson(value, (name) => ({ label: name, description: null })),
182 );
183 const map = serializeEditorDoc(doc);
184 for (let flat = 0; flat <= map.docLength; flat += 1) {
185 const position = flatToPm(map, flat);
186 expect(doc.resolve(position).parent.isTextblock).toBe(true);
187 expect(pmToFlat(map, position)).toBe(flat);
188 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
189 }
190 });
191​
192 it("keeps the caret after a trailing hard break inside the same paragraph", () => {
193 const doc = schema.node("doc", null, [
194 schema.node("paragraph", null, [schema.text("a"), schema.node("hardBreak")]),
195 ]);
196 const map = serializeEditorDoc(doc);
197 expect(flatToPm(map, map.docLength)).toBe(3);
198 expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);
199 });
200​
201 it("renders a leading task dedent as siblings and nests under the new indent", () => {
202 const doc = ProseMirrorNode.fromJSON(
203 schema,
204 buildDocJson(" - [ ] first\n - [ ] second\n - [ ] child", (name) => ({
205 label: name,
206 description: null,
207 })),
208 );
209 const list = doc.firstChild!;
210 expect(list.childCount).toBe(2);
211 expect(list.child(0).childCount).toBe(1);
212 expect(list.child(1).child(1).firstChild!.textContent).toBe("child");
213 });
214​
215 it("applies a shared mark to text on both sides of a chip", () => {
216 const doc = ProseMirrorNode.fromJSON(
217 schema,
218 buildDocJson("**before @README.md after**", (name) => ({ label: name, description: null })),
219 );
220 expect(doc.firstChild!.childCount).toBe(3);
221 doc.firstChild!.forEach((child) =>
222 expect(child.marks.map((mark) => mark.type.name)).toContain("bold"),
223 );
224 expect(serializeEditorDoc(doc).value).toBe("**before @README.md after**");
225 });
226​
227 it.each([
228 [["bold"], ["bold", "italic"], ["italic"]],
229 [["italic"], ["bold", "italic"], ["bold"]],
230 [["bold"], ["bold", "strike"], ["strike"]],
231 [["strike"], ["bold", "strike"], ["bold"]],
232 ])("preserves crossing mark ranges %j through controlled rebuilds", (...marks) => {
233 const doc = schema.node("doc", null, [
234 schema.node(
235 "paragraph",
236 null,
237 marks.map((names, index) =>
238 schema.text(
239 String.fromCharCode(97 + index),
240 names.map((name) => schema.mark(name)),
241 ),
242 ),
243 ),
244 ]);
245 const serialized = serializeEditorDoc(doc).value;
246 const rebuilt = ProseMirrorNode.fromJSON(
247 schema,
248 buildDocJson(serialized, (name) => ({ label: name, description: null })),
249 );
250 expect(rebuilt.eq(doc)).toBe(true);
251 expect(serializeEditorDoc(rebuilt).value).toBe(serialized);
252 });
253​
254 it.each([
255 { parts: [{ text: "hello ", marks: ["bold"] }], expected: "**hello** " },
256 { parts: [{ text: " ", marks: ["bold"] }], expected: " " },
257 { parts: [{ text: " left ", marks: ["bold", "italic"] }], expected: " ***left*** " },
258 {
259 parts: [
260 { text: "one ", marks: ["bold"] },
261 { text: " two ", marks: ["bold", "italic"] },
262 { text: " three", marks: ["bold"] },
263 ],
264 expected: "**one *two* three**",
265 },
266 {
267 parts: [
268 { text: "hello ", marks: ["bold"] },
269 { text: "world ", marks: ["bold", "italic"] },
270 ],
271 expected: "**hello *world*** ",
272 },
273 { parts: [{ text: " hello ", marks: ["code"] }], expected: "` hello `" },
274 { parts: [{ text: " hello ", marks: ["bold", "code"] }], expected: "**` hello `**" },
275 { parts: [{ text: " ", marks: ["bold", "code"] }], expected: "**` `**" },
276 ])("keeps boundary whitespace outside emphasis in $expected", ({ parts, expected }) => {
277 const doc = schema.node("doc", null, [
278 schema.node(
279 "paragraph",
280 null,
281 parts.map(({ text, marks }) =>
282 schema.text(
283 text,
284 marks.map((name) => schema.mark(name)),
285 ),
286 ),
287 ),
288 ]);
289 const map = serializeEditorDoc(doc);
290 expect(map.value).toBe(expected);
291 const rebuilt = ProseMirrorNode.fromJSON(
292 schema,
293 buildDocJson(map.value, (name) => ({ label: name, description: null })),
294 );
295 expect(rebuilt.textContent).toBe(doc.textContent);
296 expect(serializeEditorDoc(rebuilt).value).toBe(map.value);
297 for (let flat = 0; flat <= map.docLength; flat += 1) {
298 expect(pmToFlat(map, flatToPm(map, flat))).toBe(flat);
299 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
300 if (flat < map.docLength && !/\s/.test(doc.textContent[flat]!)) {
301 expect(rebuilt.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name)).toEqual(
302 doc.resolve(flat + 1).nodeAfter!.marks.map((mark) => mark.type.name),
303 );
304 }
305 }
306 });
307​
308 it("keeps chip sources canonical through the document", () => {
309 const map = roundTrip("explain @README.md with **care**\nsecond line *here*");
310 expect(map.value).toBe("explain @README.md with **care**\nsecond line *here*");
311 expect(
312 map.runs.some((run) => run.kind === "token" && run.nodeName === "composer-mention"),
313 ).toBe(true);
314 });
315​
316 it("normalizes uppercase checkboxes to lowercase", () => {
317 expect(roundTrip("- [X] done").value).toBe("- [x] done");
318 });
319​
320 it.each([
321 "plain text",
322 "hello **bold** stays literal",
323 "a *italic* stays literal",
324 "some `code` stays literal",
325 "struck ~~out~~ stays literal",
326 "- [ ] stays a paragraph",
327 "- [x] stays a paragraph",
328 "line one\nline two",
329 "@README.md explain this",
330 "**bold** then @README.md then *italic*",
331 ])("round-trips %s byte-identically in plain mode", (value) => {
332 expect(roundTripPlain(value).value).toBe(value);
333 });
334​
335 it("maps every document offset through collapsed coordinates and back", () => {
336 const value = "hi **bold** @README.md bye";
337 const map = roundTrip(value);
338 expect(map.value).toBe(value);
339 for (let flat = 0; flat <= map.docLength; flat += 1) {
340 expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);
341 }
342 });
343​
344 it("maps markdown offsets at styled edges onto document text", () => {
345 const value = "a **bold** c";
346 const map = roundTrip(value);
347 expect(map.value).toBe(value);
348 // document text is "a bold c" (flat), markdown has the markers.
349 expect(flatToMarkdown(map, 2)).toBe(4);
350 expect(flatToMarkdown(map, 6)).toBe(10);
351 expect(collapsedToFlat(map, 3)).toBe(2);
352 expect(collapsedToFlat(map, 9)).toBe(6);
353 });
354});