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

markdown-clipboard.test.ts

1,119 lines41.9 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2​
3import {
4 serializeCodeBlockToMarkdown,
5 serializeRenderedMarkdownFragment,
6 serializeTableElementForChat,
7 serializeTableElementToCsv,
8 serializeTableElementToHtml,
9 serializeTableElementToMarkdown,
10} from "./markdown-clipboard";
11import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
12import {
13 collectAssistantCitations,
14 serializeAssistantCitation,
15} from "@t3tools/shared/assistantCitations";
16import type { Element as HastElement, ElementContent, Root } from "hast";
17​
18import { markdownTree } from "./markdown/wordsHast";
19​
20// Copied Markdown read back as the chat reads it, to check it says what was copied.
21const elementsOf = (node: Root | HastElement) =>
22 (node.children as ElementContent[]).filter(
23 (child): child is HastElement => child.type === "element",
24 );
25const textOf = (node: ElementContent): string =>
26 node.type === "text"
27 ? node.value
28 : node.type === "element"
29 ? node.children.map(textOf).join("")
30 : "";
31const readBack = (markdown: string, options?: Parameters<typeof markdownTree>[1]) =>
32 elementsOf(markdownTree(markdown, options))[0]!;
33// A user message's reading: a single `~` stays text.
34const readUserBack = (markdown: string) => readBack(markdown, { singleTilde: false });
35const inline = (node: ElementContent) =>
36 node.type === "element" ? [node.tagName, textOf(node)] : [node.type, textOf(node)];
37​
38const TEXT_NODE = 3;
39const ELEMENT_NODE = 1;
40​
41class FakeText {
42 readonly nodeType = TEXT_NODE;
43 readonly childNodes: ReadonlyArray<never> = [];
44​
45 constructor(readonly textContent: string) {}
47​
48class FakeElement {
49 readonly nodeType = ELEMENT_NODE;
50 checked = false;
51 readonly childNodes: Array<FakeElement | FakeText> = [];
52 readonly classList = {
53 contains: (name: string) => this.classNames.includes(name),
54 };
55​
56 constructor(
57 readonly tagName: string,
58 private readonly classNames: ReadonlyArray<string> = [],
59 private readonly attributes: Readonly<Record<string, string>> = {},
60 ) {}
61​
62 get localName(): string {
63 return this.tagName.toLowerCase();
64 }
65​
66 get textContent(): string {
67 return this.childNodes.map((child) => child.textContent).join("");
68 }
69​
70 get children(): ReadonlyArray<FakeElement> {
71 return this.childNodes.filter((child): child is FakeElement => child instanceof FakeElement);
72 }
73​
74 append(...children: Array<FakeElement | FakeText>): this {
75 this.childNodes.push(...children);
76 return this;
77 }
78​
79 getAttribute(name: string): string | null {
80 return this.attributes[name] ?? null;
81 }
82​
83 hasAttribute(name: string): boolean {
84 return Object.hasOwn(this.attributes, name);
85 }
86​
87 closest(): FakeElement | null {
88 return null;
89 }
90​
91 querySelector(selector: string): FakeElement | null {
92 if (selector.includes(", ")) {
93 for (const part of selector.split(", ")) {
94 const match = this.querySelector(part);
95 if (match) return match;
96 }
97 return null;
98 }
99 const childOnly = selector.startsWith(":scope > ");
100 const [target, ...rest] = (childOnly ? selector.slice(":scope > ".length) : selector).split(
101 " > ",
102 );
103 const matches = (element: FakeElement): boolean => {
104 if (target === 'input[type="checkbox"]') {
105 return element.tagName === "INPUT" && element.getAttribute("type") === "checkbox";
106 }
107 return element.tagName === target?.toUpperCase();
108 };
109 const search = (parent: FakeElement): FakeElement | null => {
110 for (const child of parent.childNodes) {
111 if (!(child instanceof FakeElement)) continue;
112 if (matches(child)) {
113 if (rest.length === 0) return child;
114 const nested = child.querySelector(`:scope > ${rest.join(" > ")}`);
115 if (nested) return nested;
116 }
117 if (!childOnly) {
118 const nested = search(child);
119 if (nested) return nested;
120 }
121 }
122 return null;
123 };
124 return search(this);
125 }
126​
127 /** Supports the `:scope > a > b` child paths the table serializer queries. */
128 querySelectorAll(selector: string): FakeElement[] {
129 return selector.split(", ").flatMap((part) =>
130 part
131 .replace(/^:scope > /, "")
132 .split(" > ")
133 .reduce<FakeElement[]>(
134 (level, tag) =>
135 level.flatMap((element) =>
136 element.children.filter((child) => child.tagName === tag.toUpperCase()),
137 ),
138 [this],
139 ),
140 );
141 }
143​
144function asNode(element: FakeElement): Node {
145 return element as unknown as Node;
147​
148function shikiCodeLine(text: string): FakeElement {
149 const token = new FakeElement("SPAN").append(new FakeText(text));
150 return new FakeElement("SPAN", ["line"]).append(token);
152​
153function renderedCodeBlock(lines: ReadonlyArray<string>): FakeElement {
154 const code = new FakeElement("CODE");
155 lines.forEach((line, index) => {
156 if (index > 0) code.append(new FakeText("\n"));
157 code.append(shikiCodeLine(line));
158 });
159 return new FakeElement("DIV", ["chat-markdown-codeblock"]).append(
160 new FakeElement("DIV", ["chat-markdown-codeblock-header", "select-none"]).append(
161 new FakeText("sh"),
162 ),
163 new FakeElement("DIV", ["chat-markdown-shiki"]).append(new FakeElement("PRE").append(code)),
164 );
166​
167describe("serializeRenderedMarkdownFragment", () => {
168 it("copies a popover context reference once, without its details or nested label", () => {
169 const reference = "[Review comment](t3-context://v1/review-comment/review-1)";
170 const container = new FakeElement("DIV").append(
171 new FakeText("Fix "),
172 new FakeElement("BUTTON", [], { "data-markdown-copy": reference }).append(
173 new FakeElement("SPAN", [], { "data-markdown-copy": reference }).append(
174 new FakeText("Review comment"),
175 ),
176 ),
177 new FakeText(" please"),
178 );
179​
180 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(`Fix ${reference} please`);
181 });
182​
183 beforeEach(() => {
184 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
185 });
186​
187 afterEach(() => {
188 vi.unstubAllGlobals();
189 });
190​
191 it.each([
192 ["Use #", String.raw`Use \#`],
193 ["Comments start with ###", String.raw`Comments start with \###`],
194 ["#", String.raw`\#`],
195 ])("keeps trailing hashes in copied headings: %s", (heading, escaped) => {
196 const container = new FakeElement("DIV").append(
197 new FakeElement("H2").append(new FakeText(heading)),
198 new FakeElement("P").append(new FakeText("Score: 5 #")),
199 );
200 const copied = serializeRenderedMarkdownFragment(asNode(container));
201​
202 expect({ copied, heading: inline(readBack(copied)) }).toEqual({
203 copied: `## ${escaped}\n\nScore: 5 #`,
204 heading: ["h2", heading],
205 });
206 });
207​
208 it("copies the complete quote, source, and comment instead of the comment-only chip label", () => {
209 const citation = {
210 version: 1 as const,
211 environmentId: EnvironmentId.make("environment-one"),
212 threadId: ThreadId.make("thread-one"),
213 messageId: MessageId.make("assistant-one"),
214 text: "A complete quote, including the part hidden by the chip preview.",
215 comment: "What does this mean?\nPlease expand on the hidden part.",
216 start: 0,
217 end: 66,
218 prefix: "",
219 suffix: "",
220 };
221 const anchor = new FakeElement("A", [], {
222 "data-markdown-copy": serializeAssistantCitation(citation),
223 href: "/environment-one/thread-one#citation",
224 }).append(new FakeText("What does this mean?…"));
225 const chip = new FakeElement("SPAN", [], {
226 "data-markdown-copy": serializeAssistantCitation(citation),
227 }).append(anchor, new FakeElement("BUTTON").append(new FakeText("Edit comment")));
228 const container = new FakeElement("DIV").append(new FakeText("Explain "), chip);
229 const copied = serializeRenderedMarkdownFragment(asNode(container));
230 expect(copied).toBe(`Explain ${serializeAssistantCitation(citation)}`);
231 expect(collectAssistantCitations(copied).map((entry) => entry.citation)).toEqual([citation]);
232 });
233​
234 it("keeps a multi-line code selection plain instead of inline-wrapping it", () => {
235 const code = new FakeElement("CODE").append(new FakeText("first line\nsecond line"));
236 const container = new FakeElement("DIV").append(code);
237​
238 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line");
239 });
240​
241 it.each([
242 ["backtick edges", "`value`"],
243 ["space edges", " value "],
244 ["only spaces", " "],
245 ])("copies inline code that parses back unchanged: %s", (_, value) => {
246 const container = new FakeElement("DIV").append(
247 new FakeElement("P").append(
248 new FakeText("Use "),
249 new FakeElement("CODE").append(new FakeText(value)),
250 new FakeText(" here."),
251 ),
252 );
253 const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container)));
254 const code = elementsOf(paragraph).find((child) => child.tagName === "code");
255 expect(paragraph.tagName).toBe("p");
256 expect(code && textOf(code)).toBe(value);
257 });
258​
259 it.each([
260 String.raw`see C:\me\.t3\shot.png`,
261 String.raw`C:\work\_build`,
262 "C:/work/_build/out.txt",
263 String.raw`C:\work\a-_b.txt`,
264 "a*word*b and a_word_b; ~~literal~~ and ~single~",
265 String.raw`before\ after\ end`,
266 "- item\n+ item\n* item",
267 "# heading\n> quote",
268 "> quote\nfirst\n- item\n# heading",
269 "first\n1. ordered\n1) ordered",
270 "---\nfirst\n---\n--\n- - -\nlast",
271 "===\nfirst\n===\n=",
272 "___\n***\nfirst\n* * *\n_ _ _\nlast",
273 "~~~\nfirst\n~~~ js\n~~~\n~~~\nlast",
274 "a | b\n---|---",
275 "| a | b |\n| --- | --- |",
276 "a | b\n:--- | ---:\nc | d",
277 "| a |\n| - |",
278 "a\n:---\nb\n---:",
279 ])("copies prose that parses back unchanged: %s", (value) => {
280 const container = new FakeElement("DIV").append(new FakeText(value));
281 const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container)));
282 expect(paragraph.tagName).toBe("p");
283 expect(paragraph.children.map(inline)).toEqual([["text", value]]);
284 });
285​
286 it.each(["Type &copy; for the sign", "Use &#35; or &amp; here"])(
287 "copies a literal character reference that the chat shows as text: %s",
288 (value) => {
289 const container = new FakeElement("DIV").append(new FakeText(value));
290 const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container)));
291 expect(paragraph.children.map(inline)).toEqual([["text", value]]);
292 },
293 );
294​
295 // Pull request comments read raw HTML, both in the editor preview and on the forge.
296 it.each([
297 "Literal <em>not emphasized</em> here",
298 "Keep <!-- note -->, <br/> and <?pi?> or a < b<c",
299 ])("copies literal tags that a pull request comment shows as text: %s", (value) => {
300 const container = new FakeElement("DIV").append(new FakeText(value));
301 const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container)));
302 expect(paragraph.children.map(inline)).toEqual([["text", value]]);
303 });
304​
305 it("copies bracketed prose that does not read back as display math", () => {
306 const value = "Tags [WIP] and [done]";
307 const container = new FakeElement("DIV").append(new FakeText(value));
308 const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container)), {
309 math: true,
310 });
311 expect(paragraph.children.map(inline)).toEqual([["text", value]]);
312 });
313​
314 it("escapes literal block starts across containers without escaping real blocks or verbatim spans", () => {
315 const el = (tag: string, ...children: Array<FakeElement | string>) =>
316 new FakeElement(tag).append(
317 ...children.map((c) => (typeof c === "string" ? new FakeText(c) : c)),
318 );
319 const copy = (node: FakeElement) => serializeRenderedMarkdownFragment(asNode(node));
320 const displayMath = new FakeElement("SPAN", [], {
321 "data-markdown-math": "display",
322 "data-markdown-copy": "\\[\n- x\n\\]\n\n",
323 }).append(new FakeText("- x"));
324 const rawCopy = new FakeElement("SPAN", [], { "data-markdown-copy": "- raw" }).append(
325 new FakeText("raw"),
326 );
327​
328 for (const [node, expected] of [
329 [el("P", "first", el("BR"), "- second"), [["text", "first\n- second"]]],
330 [el("DIV", "# literal"), [["text", "# literal"]]],
331 [el("P", el("SPAN", "#"), " not a heading"), [["text", "# not a heading"]]],
332 [el("P", el("SPAN", "1"), ". not numbered"), [["text", "1. not numbered"]]],
333 [el("P", el("STRONG", "a", el("BR"), "- b")), [["strong", "a\n- b"]]],
334 [
335 el("P", "- prose ", el("CODE", "x\u2028- flag"), " ", el("CODE", "x\u2029# title")),
336 [
337 ["text", "- prose "],
338 ["code", "x\u2028- flag"],
339 ["text", " "],
340 ["code", "x\u2029# title"],
341 ],
342 ],
343 ] as const) {
344 expect(readUserBack(copy(el("DIV", node))).children.map(inline)).toEqual(expected);
345 }
346​
347 for (const [node, tag, children] of [
348 [el("UL", el("LI", "- literal"), el("LI", "1. literal")), "ul", ["- literal", "1. literal"]],
349 [el("BLOCKQUOTE", "- literal"), "blockquote", ["- literal"]],
350 [el("BLOCKQUOTE", el("P", "# literal")), "blockquote", ["# literal"]],
351 ] as const) {
352 const parsed = readUserBack(copy(el("DIV", node)));
353 expect(parsed.tagName).toBe(tag);
354 expect(elementsOf(parsed).map(textOf)).toEqual(children);
355 }
356​
357 const table = renderedTable(
358 [new FakeText("- col"), new FakeText("# col")],
359 [new FakeText("- cell"), new FakeText("1. cell")],
360 );
361 const expectedTable = "| - col | # col |\n| --- | --- |\n| - cell | 1. cell |";
362 for (const [node, expected] of [
363 [el("DIV", el("H2", "Title", el("BR"), "- x")), "## Title\n\\- x"],
364 [el("BODY", "- item"), "\\- item"],
365 [
366 el("DIV", el("DL", el("DT", "Term"), el("DD", "\n", el("UL", el("LI", "item"))))),
367 "Term\n- item",
368 ],
369 [el("DIV", el("P", el("SPAN", el("CODE", "# c\n- d")))), "# c\n- d"],
370 [el("DIV", el("P", el("CODE", "a\nb"), "- x")), "a\nb- x"],
371 [el("DIV", el("P", el("CODE", "a\nb\n"), "- x")), "a\nb\n\\- x"],
372 [el("DIV", el("P", "a", el("BR"), "\u0003- x")), "a\n\u0003- x"],
373 [el("DIV", rawCopy), "- raw"],
374 [el("P", "See ", renderedFormula("a\n- b"), " - end"), "See \\(a\n- b\\) - end"],
375 [el("DIV", displayMath, "- after"), "\\[\n- x\n\\]\n\n\\- after"],
376 [el("P", "See ", el("CODE", "x"), " - not a list"), "See `x` - not a list"],
377 [el("P", "intro", el("BR"), el("BR"), " - literal"), "intro\n\n - literal"],
378 ...["#123", "-flag", "1.5", "1234567890. ten", "= foo"].map((s) => [el("DIV", s), s]),
379 [el("DIV", table), expectedTable],
380 ] as Array<[FakeElement, string]>) {
381 expect(copy(node)).toBe(expected);
382 }
383 expect(serializeTableElementToMarkdown(table as unknown as Element)).toBe(expectedTable);
384 });
385​
386 it.each([
387 ["*", "EM", "word"],
388 ["\\", "CODE", "value"],
389 ])("keeps a text edge %j beside %s", (edge, tag, value) => {
390 const container = new FakeElement("DIV").append(
391 new FakeText(edge),
392 new FakeElement(tag).append(new FakeText(value)),
393 );
394 const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container)));
395 expect(paragraph.children.map(inline)).toEqual([
396 ["text", edge],
397 [tag.toLowerCase(), value],
398 ]);
399 });
400​
401 it("copies email links with their address and drops in-app destinations", () => {
402 const container = new FakeElement("DIV").append(
403 new FakeElement("P").append(
404 new FakeText("Write to "),
405 new FakeElement("A", [], { href: "mailto:support@example.com" }).append(
406 new FakeText("support@example.com"),
407 ),
408 new FakeText(", "),
409 new FakeElement("A", [], { href: "mailto:support@example.com?subject=Help" }).append(
410 new FakeText("Support"),
411 ),
412 new FakeText(", "),
413 new FakeElement("A", [], { href: "mailto:support@example.com?subject=Help)" }).append(
414 new FakeText("Support"),
415 ),
416 new FakeText(" or "),
417 new FakeElement("A", [], { href: "/environment-one/thread-one" }).append(
418 new FakeText("the thread"),
419 ),
420 new FakeText("."),
421 ),
422 );
423 const copied = serializeRenderedMarkdownFragment(asNode(container));
424 expect(copied).toBe(
425 "Write to support@example.com, [Support](mailto:support@example.com?subject=Help), [Support](mailto:support@example.com?subject=Help\\)) or the thread.",
426 );
427 expect(
428 elementsOf(readBack(copied))
429 .filter((child) => child.tagName === "a")
430 .map((link) => link.properties.href),
431 ).toEqual([
432 "mailto:support@example.com",
433 "mailto:support@example.com?subject=Help",
434 "mailto:support@example.com?subject=Help)",
435 ]);
436 });
437​
438 it("copies a bare web address as shown when its destination is the normalized spelling", () => {
439 const container = new FakeElement("DIV").append(
440 new FakeElement("A", [], { href: "https://de.wikipedia.org/wiki/Stra%C3%9Fe" }).append(
441 new FakeText("https://de.wikipedia.org/wiki/Straße"),
442 ),
443 );
444 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
445 "https://de.wikipedia.org/wiki/Straße",
446 );
447 });
448​
449 it.each([
450 ["array[index]", "https://example.com"] as const,
451 ["C:\\repo\\file[1].ts", "https://example.com"] as const,
452 ["https://T3.CODES/docs.", "https://t3.codes/docs."] as const,
453 ["https://T3.CODES/docs)", "https://t3.codes/docs)"] as const,
454 ...[
455 "support@example.com?subject=Help",
456 "foo",
457 "support@example.internal1",
458 "support@example.com_",
459 "support@example.com-",
460 "first_last@example.com",
461 ].map((label) => [label, `mailto:${label}`] as const),
462 ])("keeps the link label and destination: %s", (label, href) => {
463 const anchor = new FakeElement("A", [], { href }).append(new FakeText(label));
464 const container = new FakeElement("DIV").append(anchor);
465 const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container)));
466 expect(
467 paragraph.children.map((child) =>
468 child.type === "element"
469 ? [child.tagName, decodeURI(String(child.properties.href)), textOf(child)]
470 : [child.type, textOf(child)],
471 ),
472 ).toEqual([["a", href, label]]);
473 });
474​
475 it("copies alert and insight callouts as their Markdown instead of the rendered label", () => {
476 // The shape ChatMarkdown renders for `> [!WARNING]\n> Back up first.`.
477 const callout = new FakeElement("DIV", [], {
478 role: "note",
479 "data-markdown-alert": "warning",
480 }).append(
481 new FakeElement("P", [], {
482 "data-thread-find-ignore": "true",
483 "data-markdown-alert-label": "",
484 }).append(new FakeElement("SVG", [], { "aria-hidden": "true" }), new FakeText("Warning")),
485 new FakeElement("P").append(new FakeText("Back up first.")),
486 );
487 const container = new FakeElement("DIV").append(callout);
488​
489 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
490 "> [!WARNING]\n> Back up first.",
491 );
492 const insight = new FakeElement("DIV", [], {
493 role: "note",
494 "data-markdown-alert": "insight",
495 }).append(
496 new FakeElement("P", [], {
497 "data-thread-find-ignore": "true",
498 "data-markdown-alert-label": "",
499 }).append(new FakeText("Insight")),
500 new FakeElement("P").append(new FakeText("Caches are warm.")),
501 );
502 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(insight)))).toBe(
503 `★ Insight ${"─".repeat(37)}\nCaches are warm.\n${"─".repeat(49)}`,
504 );
505 });
506​
507 it("preserves explicit ordered-list values and continues from resets when copying", () => {
508 const list = new FakeElement("OL", [], { start: "0" }).append(
509 new FakeElement("LI").append(new FakeText("A")),
510 new FakeElement("LI", [], { value: "5" }).append(new FakeText("B")),
511 new FakeElement("LI").append(new FakeText("C")),
512 new FakeElement("LI", [], { value: "0" }).append(new FakeText("D")),
513 );
514 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
515 "0. A\n5. B\n6. C\n0. D",
516 );
517 });
518​
519 it("keeps both items when copying a list that starts at the nine-digit marker limit", () => {
520 const rendered = readBack("999999999. first\n1. second");
521 expect(rendered.properties.start).toBe("999999999");
522 expect(elementsOf(rendered).map(textOf)).toEqual(["first", "second"]);
523 const list = new FakeElement("OL", [], { start: "999999999" }).append(
524 new FakeElement("LI").append(new FakeText("first")),
525 new FakeElement("LI").append(new FakeText("second")),
526 );
527 const copied = serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)));
528 const reread = readBack(copied);
529 expect(reread.tagName).toBe("ol");
530 expect(reread.properties.start).toBe("999999999");
531 expect(elementsOf(reread).map(textOf)).toEqual(["first", "second"]);
532 });
533​
534 it("keeps the shown numbers when copying items past the nine-digit marker limit", () => {
535 const list = new FakeElement("OL", [], { start: "1000000000" }).append(
536 new FakeElement("LI").append(new FakeText("second")),
537 new FakeElement("LI").append(new FakeText("third")),
538 );
539 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
540 "1000000000. second\n1000000001. third",
541 );
542 });
543​
544 it("keeps a bare list item that sits alongside the code block", () => {
545 const container = new FakeElement("DIV").append(
546 new FakeElement("UL").append(new FakeElement("LI")),
547 renderedCodeBlock(["pnpm test"]),
548 );
549​
550 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\npnpm test");
551 });
552​
553 it("copies a command and the prose after it as shown, without code fences", () => {
554 const container = new FakeElement("DIV").append(
555 renderedCodeBlock(["printf 'hello\\n'"]),
556 new FakeElement("P").append(new FakeText("T")),
557 );
558​
559 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("printf 'hello\\n'\n\nT");
560 });
561​
562 it("keeps a diagram's source exactly as written when copied with prose", () => {
563 const source = 'flowchart TD\n A["first \n\n\nlast"]';
564 const container = new FakeElement("DIV").append(
565 new FakeElement("DIV", [], {
566 "data-markdown-mermaid": "",
567 "data-markdown-copy": serializeCodeBlockToMarkdown(source, "mermaid"),
568 }),
569 new FakeElement("P").append(new FakeText("After")),
570 );
571​
572 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
573 `\`\`\`mermaid\n${source}\n\`\`\`\n\nAfter`,
574 );
575 });
576​
577 it("keeps blank lines inside a code block in a list item, quote, or longer fence", () => {
578 const code = ["import os", "", "", "def main():"];
579 const list = new FakeElement("OL").append(
580 new FakeElement("LI").append(new FakeText("Create it:\n"), renderedCodeBlock(code)),
581 );
582 const quote = new FakeElement("BLOCKQUOTE").append(
583 new FakeElement("P").append(new FakeText("Note:")),
584 renderedCodeBlock(code),
585 );
586 const nestedFence = new FakeElement("DIV").append(
587 new FakeElement("P").append(new FakeText("Example:")),
588 renderedCodeBlock(["```js", "a()", "", "", "b() ", "```"]),
589 );
590​
591 expect(serializeRenderedMarkdownFragment(asNode(nestedFence))).toBe(
592 "Example:\n\n```js\na()\n\n\nb() \n```",
593 );
594​
595 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
596 "1. Create it:\n import os\n\n\n def main():",
597 );
598 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(quote)))).toBe(
599 "> Note:\n>\n> import os\n>\n>\n> def main():",
600 );
601 });
602​
603 it("omits fences when a selection past the last line drags in the whole code block", () => {
604 const container = new FakeElement("DIV").append(
605 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
606 new FakeText("\n"),
607 new FakeElement("P").append(new FakeText("")),
608 );
609​
610 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
611 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
612 );
613 });
614});
615​
616function renderedFormula(tex: string): FakeElement {
617 // MarkdownMath's wrapper; its children stand in for KaTeX's glyphs.
618 return new FakeElement("SPAN", [], {
619 "data-markdown-math": "inline",
620 "data-markdown-copy": `\\(${tex}\\)`,
621 }).append(new FakeText(tex));
623​
624function renderedTable(...rows: Array<Array<FakeElement | FakeText>>): FakeElement {
625 const row = (tag: string, cells: Array<FakeElement | FakeText>) =>
626 new FakeElement("TR").append(...cells.map((cell) => new FakeElement(tag).append(cell)));
627 const [head = [], ...body] = rows;
628 return new FakeElement("TABLE").append(
629 new FakeElement("THEAD").append(row("TH", head)),
630 new FakeElement("TBODY").append(...body.map((cells) => row("TD", cells))),
631 );
633​
634describe("copying rendered Markdown tables", () => {
635 beforeEach(() => {
636 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
637 });
638​
639 afterEach(() => {
640 vi.unstubAllGlobals();
641 });
642​
643 it("keeps formula pipes as authored while escaping prose pipes", () => {
644 const table = renderedTable(
645 [new FakeText("Formula"), new FakeText("Note")],
646 [renderedFormula("|x|"), new FakeText("*a* | ~~b~~")],
647 [renderedFormula("\\|x\\|"), new FakeElement("CODE").append(new FakeText("\\(c|d\\)"))],
648 [
649 new FakeElement("A", [], { href: "https://example.com/?q=a|b" }).append(
650 new FakeText("norm "),
651 renderedFormula("|y|"),
652 ),
653 new FakeText("e"),
654 ],
655 [
656 new FakeElement("UL").append(
657 new FakeElement("LI").append(renderedFormula("|z|"), new FakeText(" a | b")),
658 ),
659 new FakeElement("BLOCKQUOTE").append(new FakeElement("P").append(new FakeText("c | d"))),
660 ],
661 );
662 const markdown = serializeTableElementToMarkdown(table as unknown as Element);
663​
664 const parsed = readBack(markdown, { math: true });
665 expect(parsed.tagName).toBe("table");
666 const rows = elementsOf(parsed).flatMap((section) => elementsOf(section));
667 const cells = rows.map((row) => elementsOf(row));
668 expect(cells.map((row) => row.length)).toEqual([2, 2, 2, 2, 2]);
669 const formulas: string[] = [];
670 const visit = (node: HastElement) => {
671 if (node.tagName === "svg") formulas.push(String(node.properties.ariaLabel));
672 else elementsOf(node).forEach(visit);
673 };
674 visit(parsed);
675 expect(formulas).toEqual(["|x|", "\\|x\\|", "|y|", "|z|"]);
676 expect(textOf(cells[1]![1]!)).toBe("*a* | ~~b~~");
677 expect(textOf(cells[4]![1]!).trim()).toBe("> c | d");
678 expect(inline(cells[2]![1]!.children[0]!)).toEqual(["code", "\\(c|d\\)"]);
679 const link = cells[3]![0]!.children[0]!;
680 expect(link.type === "element" && decodeURI(String(link.properties.href))).toBe(
681 "https://example.com/?q=a|b",
682 );
683 });
684​
685 it("copies code and diagrams in cells without markers or unescaped pipes", () => {
686 const code = new FakeElement("PRE").append(
687 new FakeElement("CODE").append(new FakeText("a b")),
688 );
689 const diagram = new FakeElement("DIV", [], {
690 "data-markdown-mermaid": "",
691 "data-markdown-copy": serializeCodeBlockToMarkdown("A -->|hi| B", "mermaid"),
692 });
693 expect(
694 serializeTableElementToMarkdown(
695 asNode(
696 renderedTable([new FakeText("Command"), new FakeText("Diagram")], [code, diagram]),
697 ) as Element,
698 ),
699 ).toBe("| Command | Diagram |\n| --- | --- |\n| a b | ```mermaid A -->\\|hi\\| B ``` |");
700 });
701});
702​
703describe("copying a table as HTML", () => {
704 const cell = (
705 tag: "TH" | "TD",
706 text: string,
707 attributes: Record<string, string> = {},
708 style?: { textAlign: string },
709 ) => {
710 const element = new FakeElement(tag, [], attributes).append(new FakeText(text));
711 return style ? Object.assign(element, { style }) : element;
712 };
713 const row = (...cells: FakeElement[]) => new FakeElement("TR").append(...cells);
714 const html = (table: FakeElement) => serializeTableElementToHtml(table as unknown as Element);
715​
716 beforeEach(() => {
717 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
718 });
719​
720 afterEach(() => {
721 vi.unstubAllGlobals();
722 });
723​
724 /** Structure only: every style attribute is reduced to its text alignment. */
725 const structure = (table: FakeElement) =>
726 html(table).replace(/ style="([^"]*)"/g, (_, style: string) => {
727 const align = /text-align:(\w+)/.exec(style)?.[1];
728 return align ? ` align="${align}"` : "";
729 });
730​
731 it("escapes text and keeps column alignment from the style or the align attribute", () => {
732 const table = new FakeElement("TABLE").append(
733 new FakeElement("THEAD").append(
734 row(cell("TH", "Name"), cell("TH", "Amount", {}, { textAlign: "right" })),
735 ),
736 new FakeElement("TBODY").append(
737 row(cell("TD", 'A & B <"Ltd">'), cell("TD", "1,200", {}, { textAlign: "right" })),
738 // An absent inline style reads as "": the align attribute still applies.
739 row(cell("TD", " Bob\n Smith "), cell("TD", "3", { align: "center" }, { textAlign: "" })),
740 row(cell("TD", "text", { align: "justify" }), cell("TD", "4", {}, { textAlign: "end" })),
741 ),
742 );
743​
744 expect(structure(table)).toBe(
745 [
746 '<table dir="ltr">',
747 " <thead>",
748 ' <tr><th align="left">Name</th><th align="right">Amount</th></tr>',
749 " </thead>",
750 " <tbody>",
751 ' <tr><td>A &amp; B &lt;&quot;Ltd&quot;&gt;</td><td align="right">1,200</td></tr>',
752 ' <tr><td>Bob Smith</td><td align="center">3</td></tr>',
753 ' <tr><td align="justify">text</td><td align="right">4</td></tr>',
754 " </tbody>",
755 "</table>",
756 ].join("\n"),
757 );
758 });
759​
760 it("keeps every header row, body header cells, footers, and merged cells", () => {
761 const table = new FakeElement("TABLE").append(
762 new FakeElement("THEAD").append(
763 row(cell("TH", "Region", { rowspan: "2" }), cell("TH", "Sales", { colspan: "2" })),
764 row(cell("TH", "Q1"), cell("TH", "Q2", { colspan: "1" })),
765 ),
766 new FakeElement("TBODY").append(
767 row(
768 cell("TH", "EU"),
769 cell("TD", "1", { rowspan: "0" }),
770 cell("TD", "2", { rowspan: "-1" }),
771 ),
772 row(),
773 ),
774 new FakeElement("TFOOT").append(
775 row(cell("TD", "Total"), cell("TD", "3", { colspan: "2garbage" })),
776 ),
777 );
778​
779 expect(structure(table)).toBe(
780 [
781 '<table dir="ltr">',
782 " <thead>",
783 ' <tr><th align="left" rowspan="2">Region</th><th align="left" colspan="2">Sales</th></tr>',
784 ' <tr><th align="left">Q1</th><th align="left">Q2</th></tr>',
785 " </thead>",
786 " <tbody>",
787 // rowspan="0" runs to the end of its section; a negative span is invalid.
788 ' <tr><th align="left">EU</th><td rowspan="0">1</td><td>2</td></tr>',
789 " <tr></tr>",
790 " </tbody>",
791 " <tfoot>",
792 // HTML reads a span's leading digits, as the DOM does.
793 ' <tr><td>Total</td><td colspan="2">3</td></tr>',
794 " </tfoot>",
795 "</table>",
796 ].join("\n"),
797 );
798 });
799​
800 it("keeps line breaks, block edges, nested cells, and formulas as TeX", () => {
801 const nested = new FakeElement("TABLE").append(
802 new FakeElement("TBODY").append(row(cell("TD", "a"), cell("TD", "b"))),
803 );
804 const table = new FakeElement("TABLE").append(
805 new FakeElement("TBODY").append(
806 row(
807 new FakeElement("TD").append(
808 new FakeText("first"),
809 new FakeElement("BR"),
810 new FakeElement("STRONG").append(new FakeText("second")),
811 ),
812 new FakeElement("TD").append(
813 new FakeElement("P").append(new FakeText("one")),
814 new FakeElement("P").append(new FakeText("two")),
815 ),
816 ),
817 row(
818 new FakeElement("TD").append(nested),
819 new FakeElement("TD").append(new FakeText("area "), renderedFormula("\\pi r^2")),
820 ),
821 ),
822 );
823​
824 expect(structure(table)).toBe(
825 [
826 '<table dir="ltr">',
827 " <tbody>",
828 " <tr><td>first<br>second</td><td>one<br>two</td></tr>",
829 " <tr><td>a b</td><td>area \\(\\pi r^2\\)</td></tr>",
830 " </tbody>",
831 "</table>",
832 ].join("\n"),
833 );
834 });
835​
836 it("keeps every explicit break, preformatted spacing, and nonbreaking spaces", () => {
837 const br = () => new FakeElement("BR");
838 const content = (...children: Array<FakeElement | FakeText>) =>
839 structure(
840 new FakeElement("TABLE").append(
841 new FakeElement("TBODY").append(row(new FakeElement("TD").append(...children))),
842 ),
843 ).split("\n")[2];
844 const td = (html: string) => ` <tr><td>${html}</td></tr>`;
845​
846 expect(content(new FakeText("a"), br(), br(), new FakeText("b"))).toBe(td("a<br><br>b"));
847 expect(content(br(), new FakeText(" lead "), br())).toBe(td("<br>lead<br>"));
848 // A break that ends a paragraph already ends the line.
849 expect(
850 content(
851 new FakeElement("P").append(new FakeText("a "), br()),
852 new FakeElement("P").append(new FakeText("b")),
853 ),
854 ).toBe(td("a<br>b"));
855 expect(
856 content(
857 new FakeText("run:"),
858 new FakeElement("DIV", ["select-none"]).append(new FakeText("madeup")),
859 new FakeElement("PRE").append(
860 new FakeElement("CODE").append(new FakeText("if x:\n\ty = 1\n\nend\n")),
861 ),
862 ),
863 ).toBe(
864 td("run:<br>if&nbsp;x:<br>&nbsp;&nbsp;&nbsp;&nbsp;y&nbsp;&nbsp;=&nbsp;&nbsp;1<br><br>end"),
865 );
866 expect(content(new FakeText("1\u00a0000 EUR"))).toBe(td("1&nbsp;000 EUR"));
867 expect(
868 content(
869 new FakeElement("BUTTON", [], {
870 "data-markdown-copy": "[source](https://example.com)",
871 }).append(new FakeText("source")),
872 ),
873 ).toBe(td("source"));
874 });
875​
876 it("keeps a right-to-left table's direction and puts headers on its start side", () => {
877 const table = new FakeElement("TABLE", [], { dir: "rtl" }).append(
878 new FakeElement("THEAD").append(
879 row(cell("TH", "Name"), cell("TH", "End", {}, { textAlign: "end" })),
880 ),
881 );
882​
883 expect(structure(table)).toBe(
884 [
885 '<table dir="rtl">',
886 " <thead>",
887 ' <tr><th align="right">Name</th><th align="left">End</th></tr>',
888 " </thead>",
889 "</table>",
890 ].join("\n"),
891 );
892 });
893​
894 it("wraps rows outside any section in a body", () => {
895 const table = new FakeElement("TABLE").append(row(cell("TD", "only"), cell("TD", "cells")));
896​
897 expect(structure(table)).toBe(
898 '<table dir="ltr">\n <tbody>\n <tr><td>only</td><td>cells</td></tr>\n </tbody>\n</table>',
899 );
900 });
901​
902 it("returns an empty string for a table without cells", () => {
903 expect(html(new FakeElement("TABLE").append(new FakeElement("TBODY").append(row())))).toBe("");
904 });
905});
906​
907describe("copying a table as CSV", () => {
908 const row = (...cells: FakeElement[]) => new FakeElement("TR").append(...cells);
909 const td = (...children: Array<FakeElement | FakeText>) =>
910 new FakeElement("TD").append(...children);
911​
912 beforeEach(() => {
913 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
914 });
915​
916 afterEach(() => {
917 vi.unstubAllGlobals();
918 });
919​
920 it("separates line breaks and block edges, and leaves out hidden elements", () => {
921 const table = new FakeElement("TABLE").append(
922 new FakeElement("THEAD").append(
923 row(
924 new FakeElement("TH").append(new FakeText("Col A")),
925 new FakeElement("TH").append(new FakeText("Col B")),
926 ),
927 ),
928 new FakeElement("TBODY").append(
929 row(
930 td(new FakeText("line 1"), new FakeElement("BR"), new FakeText("line 2")),
931 td(
932 new FakeElement("P").append(new FakeText("para 1")),
933 new FakeElement("P").append(new FakeText("para 2")),
934 ),
935 ),
936 row(
937 td(
938 new FakeElement("SPAN", ["sr-only"]).append(new FakeText("hidden")),
939 new FakeText("visible"),
940 ),
941 td(
942 new FakeElement("SPAN", [], { "aria-hidden": "true" }).append(new FakeText("icon")),
943 new FakeText("a, b"),
944 ),
945 ),
946 ),
947 );
948​
949 expect(serializeTableElementToCsv(table as unknown as Element)).toBe(
950 'Col A,Col B\nline 1 line 2,para 1 para 2\nvisible,"a, b"',
951 );
952 });
953​
954 it("keeps values under their headers across colspans and rowspans", () => {
955 const cell = (tag: string, text: string, attributes: Record<string, string> = {}) =>
956 new FakeElement(tag, [], attributes).append(new FakeText(text));
957 const table = new FakeElement("TABLE").append(
958 new FakeElement("THEAD").append(row(cell("TH", "A"), cell("TH", "B"), cell("TH", "C"))),
959 new FakeElement("TBODY").append(
960 row(cell("TD", "wide", { colspan: "2" }), cell("TD", "c1")),
961 row(cell("TD", "tall", { rowspan: "2" }), cell("TD", "b2"), cell("TD", "c2")),
962 row(cell("TD", "b3"), cell("TD", "c3")),
963 ),
964 );
965​
966 expect(serializeTableElementToCsv(table as unknown as Element)).toBe(
967 "A,B,C\nwide,,c1\ntall,b2,c2\n,b3,c3",
968 );
969 });
970​
971 it("aligns columns with spaces inside a code fence for chat apps", () => {
972 const table = new FakeElement("TABLE").append(
973 new FakeElement("THEAD").append(
974 row(
975 new FakeElement("TH").append(new FakeText("Name")),
976 new FakeElement("TH", [], { align: "right" }).append(new FakeText("Amount")),
977 ),
978 ),
979 new FakeElement("TBODY").append(
980 row(td(new FakeText("Ada")), td(new FakeText("1,200"))),
981 row(td(new FakeText("東京")), td(new FakeText("5"))),
982 row(td(new FakeText("```"))),
983 ),
984 );
985​
986 const { text, html } = serializeTableElementForChat(table as unknown as Element);
987 const aligned = ["Name Amount", "---- ------", "Ada 1,200", "東京 5", "```"].join(
988 "\n",
989 );
990 expect(text).toBe(`\`\`\`\`\n${aligned}\n\`\`\`\``);
991 expect(html).toBe(`<meta charset="utf-8"><pre>${aligned}</pre>`);
992 });
993​
994 it("bounds rowspans by their row group and keeps empty rows while placing spans", () => {
995 const cell = (tag: string, text: string, attributes: Record<string, string> = {}) =>
996 new FakeElement(tag, [], attributes).append(new FakeText(text));
997 const table = new FakeElement("TABLE").append(
998 new FakeElement("THEAD").append(row(cell("TH", "A", { rowspan: "0" }), cell("TH", "B"))),
999 new FakeElement("TBODY").append(
1000 row(cell("TD", "X", { rowspan: "2" }), cell("TD", "P", { rowspan: "2" })),
1001 new FakeElement("TR"),
1002 row(cell("TD", "Y"), cell("TD", "Z")),
1003 ),
1004 );
1005​
1006 const { text } = serializeTableElementForChat(table as unknown as Element);
1007 expect(text).toBe(["```", "A B", "- -", "X P", "Y Z", "```"].join("\n"));
1008 });
1009​
1010 it("orders header, loose and footer rows as the table renders them", () => {
1011 const table = new FakeElement("TABLE").append(
1012 new FakeElement("THEAD").append(
1013 row(
1014 new FakeElement("TH").append(new FakeText("A")),
1015 new FakeElement("TH", [], { align: "right" }).append(new FakeText("B")),
1016 ),
1017 ),
1018 new FakeElement("TFOOT").append(row(td(new FakeText("t")), td(new FakeText("9")))),
1019 row(td(new FakeText("x")), td(new FakeText("yy"))),
1020 );
1021​
1022 const { text } = serializeTableElementForChat(table as unknown as Element);
1023 expect(text).toBe(["```", "A B", "- --", "x yy", "t 9", "```"].join("\n"));
1024 });
1025​
1026 it("counts emoji and CJK as two columns, and digits and combining marks as one", () => {
1027 const table = new FakeElement("TABLE").append(
1028 new FakeElement("THEAD").append(
1029 row(new FakeElement("TH").append(new FakeText("ID")), td(new FakeText("Value"))),
1030 ),
1031 new FakeElement("TBODY").append(
1032 row(td(new FakeText("🇺🇸")), td(new FakeText("x"))),
1033 row(td(new FakeText("1️⃣")), td(new FakeText("y"))),
1034 row(td(new FakeText("1")), td(new FakeText("z"))),
1035 row(td(new FakeText("𠮷")), td(new FakeText("w"))),
1036 row(td(new FakeText("𛀀")), td(new FakeText("v"))),
1037 row(td(new FakeText("A\u3099")), td(new FakeText("u"))),
1038 ),
1039 );
1040​
1041 const { text } = serializeTableElementForChat(table as unknown as Element);
1042 expect(text).toBe(
1044 "```",
1045 "ID Value",
1046 "-- -----",
1047 "🇺🇸 x",
1048 "1️⃣ y",
1049 "1 z",
1050 "𠮷 w",
1051 "𛀀 v",
1052 "A\u3099 u",
1053 "```",
1054 ].join("\n"),
1055 );
1056 });
1057​
1058 it("counts text-style symbols such as ™, © and ↔ as one column unless shown as emoji", () => {
1059 const table = new FakeElement("TABLE").append(
1060 new FakeElement("THEAD").append(
1061 row(new FakeElement("TH").append(new FakeText("Name")), td(new FakeText("Note"))),
1062 ),
1063 new FakeElement("TBODY").append(
1064 row(td(new FakeText("Acme™")), td(new FakeText("a"))),
1065 row(td(new FakeText("©2026")), td(new FakeText("b"))),
1066 row(td(new FakeText("A↔B")), td(new FakeText("c"))),
1067 row(td(new FakeText("❤️")), td(new FakeText("d"))),
1068 ),
1069 );
1070​
1071 const { text } = serializeTableElementForChat(table as unknown as Element);
1072 expect(text).toBe(
1074 "```",
1075 "Name Note",
1076 "----- ----",
1077 "Acme™ a",
1078 "©2026 b",
1079 "A↔B c",
1080 "❤️ d",
1081 "```",
1082 ].join("\n"),
1083 );
1084 });
1085​
1086 it("keeps values under their headers across spans, and copies footer rows", () => {
1087 const span = (attributes: Record<string, string>, text: string) =>
1088 new FakeElement("TD", [], attributes).append(new FakeText(text));
1089 const table = new FakeElement("TABLE").append(
1090 new FakeElement("THEAD").append(
1091 row(
1092 new FakeElement("TH").append(new FakeText("A")),
1093 new FakeElement("TH").append(new FakeText("B")),
1094 new FakeElement("TH").append(new FakeText("C")),
1095 ),
1096 ),
1097 new FakeElement("TBODY").append(
1098 row(span({ rowspan: "2" }, "tall"), span({ colspan: "2" }, "wide")),
1099 row(td(new FakeText("b2")), td(new FakeText("c2"))),
1100 ),
1101 new FakeElement("TFOOT").append(
1102 row(td(new FakeText("total")), td(new FakeText("")), td(new FakeText("9"))),
1103 ),
1104 );
1105​
1106 const { text } = serializeTableElementForChat(table as unknown as Element);
1107 expect(text).toBe(
1109 "```",
1110 "A B C",
1111 "----- ---- --",
1112 "tall wide",
1113 " b2 c2",
1114 "total 9",
1115 "```",
1116 ].join("\n"),
1117 );
1118 });
1119});