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

composer-rich-text-doc.test.ts

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