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

markdown-clipboard.test.ts

734 lines26.7 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2​
3import {
4 serializeCodeBlockToMarkdown,
5 serializeRenderedMarkdownFragment,
6 serializeTableElementToHtml,
7 serializeTableElementToMarkdown,
8} from "./markdown-clipboard";
9import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
10import {
11 collectAssistantCitations,
12 serializeAssistantCitation,
13} from "@t3tools/shared/assistantCitations";
14import type { Element as HastElement, ElementContent, Root } from "hast";
15​
16import { markdownTree } from "./markdown/wordsHast";
17​
18// Copied Markdown read back as the chat reads it, to check it says what was copied.
19const elementsOf = (node: Root | HastElement) =>
20 (node.children as ElementContent[]).filter(
21 (child): child is HastElement => child.type === "element",
22 );
23const textOf = (node: ElementContent): string =>
24 node.type === "text"
25 ? node.value
26 : node.type === "element"
27 ? node.children.map(textOf).join("")
28 : "";
29const readBack = (markdown: string, options?: Parameters<typeof markdownTree>[1]) =>
30 elementsOf(markdownTree(markdown, options))[0]!;
31// A user message's reading: a single `~` stays text.
32const readUserBack = (markdown: string) => readBack(markdown, { singleTilde: false });
33const inline = (node: ElementContent) =>
34 node.type === "element" ? [node.tagName, textOf(node)] : [node.type, textOf(node)];
35​
36const TEXT_NODE = 3;
37const ELEMENT_NODE = 1;
38​
39class FakeText {
40 readonly nodeType = TEXT_NODE;
41 readonly childNodes: ReadonlyArray<never> = [];
42​
43 constructor(readonly textContent: string) {}
45​
46class FakeElement {
47 readonly nodeType = ELEMENT_NODE;
48 checked = false;
49 readonly childNodes: Array<FakeElement | FakeText> = [];
50 readonly classList = {
51 contains: (name: string) => this.classNames.includes(name),
52 };
53​
54 constructor(
55 readonly tagName: string,
56 private readonly classNames: ReadonlyArray<string> = [],
57 private readonly attributes: Readonly<Record<string, string>> = {},
58 ) {}
59​
60 get localName(): string {
61 return this.tagName.toLowerCase();
62 }
63​
64 get textContent(): string {
65 return this.childNodes.map((child) => child.textContent).join("");
66 }
67​
68 get children(): ReadonlyArray<FakeElement> {
69 return this.childNodes.filter((child): child is FakeElement => child instanceof FakeElement);
70 }
71​
72 append(...children: Array<FakeElement | FakeText>): this {
73 this.childNodes.push(...children);
74 return this;
75 }
76​
77 getAttribute(name: string): string | null {
78 return this.attributes[name] ?? null;
79 }
80​
81 hasAttribute(name: string): boolean {
82 return Object.hasOwn(this.attributes, name);
83 }
84​
85 closest(): FakeElement | null {
86 return null;
87 }
88​
89 querySelector(selector: string): FakeElement | null {
90 if (selector.includes(", ")) {
91 for (const part of selector.split(", ")) {
92 const match = this.querySelector(part);
93 if (match) return match;
94 }
95 return null;
96 }
97 const childOnly = selector.startsWith(":scope > ");
98 const [target, ...rest] = (childOnly ? selector.slice(":scope > ".length) : selector).split(
99 " > ",
100 );
101 const matches = (element: FakeElement): boolean => {
102 if (target === 'input[type="checkbox"]') {
103 return element.tagName === "INPUT" && element.getAttribute("type") === "checkbox";
104 }
105 return element.tagName === target?.toUpperCase();
106 };
107 const search = (parent: FakeElement): FakeElement | null => {
108 for (const child of parent.childNodes) {
109 if (!(child instanceof FakeElement)) continue;
110 if (matches(child)) {
111 if (rest.length === 0) return child;
112 const nested = child.querySelector(`:scope > ${rest.join(" > ")}`);
113 if (nested) return nested;
114 }
115 if (!childOnly) {
116 const nested = search(child);
117 if (nested) return nested;
118 }
119 }
120 return null;
121 };
122 return search(this);
123 }
124​
125 /** Supports the `:scope > a > b` child paths the table serializer queries. */
126 querySelectorAll(selector: string): FakeElement[] {
127 return selector.split(", ").flatMap((part) =>
128 part
129 .replace(/^:scope > /, "")
130 .split(" > ")
131 .reduce<FakeElement[]>(
132 (level, tag) =>
133 level.flatMap((element) =>
134 element.children.filter((child) => child.tagName === tag.toUpperCase()),
135 ),
136 [this],
137 ),
138 );
139 }
141​
142function asNode(element: FakeElement): Node {
143 return element as unknown as Node;
145​
146function shikiCodeLine(text: string): FakeElement {
147 const token = new FakeElement("SPAN").append(new FakeText(text));
148 return new FakeElement("SPAN", ["line"]).append(token);
150​
151function renderedCodeBlock(lines: ReadonlyArray<string>): FakeElement {
152 const code = new FakeElement("CODE");
153 lines.forEach((line, index) => {
154 if (index > 0) code.append(new FakeText("\n"));
155 code.append(shikiCodeLine(line));
156 });
157 return new FakeElement("DIV", ["chat-markdown-codeblock"]).append(
158 new FakeElement("DIV", ["chat-markdown-codeblock-header", "select-none"]).append(
159 new FakeText("sh"),
160 ),
161 new FakeElement("DIV", ["chat-markdown-shiki"]).append(new FakeElement("PRE").append(code)),
162 );
164​
165describe("serializeRenderedMarkdownFragment", () => {
166 it("copies a popover context reference once, without its details or nested label", () => {
167 const reference = "[Review comment](t3-context://v1/review-comment/review-1)";
168 const container = new FakeElement("DIV").append(
169 new FakeText("Fix "),
170 new FakeElement("BUTTON", [], { "data-markdown-copy": reference }).append(
171 new FakeElement("SPAN", [], { "data-markdown-copy": reference }).append(
172 new FakeText("Review comment"),
173 ),
174 ),
175 new FakeText(" please"),
176 );
177​
178 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(`Fix ${reference} please`);
179 });
180​
181 beforeEach(() => {
182 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
183 });
184​
185 afterEach(() => {
186 vi.unstubAllGlobals();
187 });
188​
189 it("copies the complete quote, source, and comment instead of the comment-only chip label", () => {
190 const citation = {
191 version: 1 as const,
192 environmentId: EnvironmentId.make("environment-one"),
193 threadId: ThreadId.make("thread-one"),
194 messageId: MessageId.make("assistant-one"),
195 text: "A complete quote, including the part hidden by the chip preview.",
196 comment: "What does this mean?\nPlease expand on the hidden part.",
197 start: 0,
198 end: 66,
199 prefix: "",
200 suffix: "",
201 };
202 const anchor = new FakeElement("A", [], {
203 "data-markdown-copy": serializeAssistantCitation(citation),
204 href: "/environment-one/thread-one#citation",
205 }).append(new FakeText("What does this mean?…"));
206 const chip = new FakeElement("SPAN", [], {
207 "data-markdown-copy": serializeAssistantCitation(citation),
208 }).append(anchor, new FakeElement("BUTTON").append(new FakeText("Edit comment")));
209 const container = new FakeElement("DIV").append(new FakeText("Explain "), chip);
210 const copied = serializeRenderedMarkdownFragment(asNode(container));
211 expect(copied).toBe(`Explain ${serializeAssistantCitation(citation)}`);
212 expect(collectAssistantCitations(copied).map((entry) => entry.citation)).toEqual([citation]);
213 });
214​
215 it("keeps a multi-line code selection plain instead of inline-wrapping it", () => {
216 const code = new FakeElement("CODE").append(new FakeText("first line\nsecond line"));
217 const container = new FakeElement("DIV").append(code);
218​
219 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line");
220 });
221​
222 it.each([
223 ["backtick edges", "`value`"],
224 ["space edges", " value "],
225 ["only spaces", " "],
226 ])("copies inline code that parses back unchanged: %s", (_, value) => {
227 const container = new FakeElement("DIV").append(
228 new FakeElement("P").append(
229 new FakeText("Use "),
230 new FakeElement("CODE").append(new FakeText(value)),
231 new FakeText(" here."),
232 ),
233 );
234 const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container)));
235 const code = elementsOf(paragraph).find((child) => child.tagName === "code");
236 expect(paragraph.tagName).toBe("p");
237 expect(code && textOf(code)).toBe(value);
238 });
239​
240 it.each([
241 String.raw`see C:\me\.t3\shot.png`,
242 String.raw`C:\work\_build`,
243 "C:/work/_build/out.txt",
244 String.raw`C:\work\a-_b.txt`,
245 "a*word*b and a_word_b; ~~literal~~ and ~single~",
246 String.raw`before\ after\ end`,
247 ])("copies prose that parses back unchanged: %s", (value) => {
248 const container = new FakeElement("DIV").append(new FakeText(value));
249 const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container)));
250 expect(paragraph.tagName).toBe("p");
251 expect(paragraph.children.map(inline)).toEqual([["text", value]]);
252 });
253​
254 it.each([
255 ["*", "EM", "word"],
256 ["\\", "CODE", "value"],
257 ])("keeps a text edge %j beside %s", (edge, tag, value) => {
258 const container = new FakeElement("DIV").append(
259 new FakeText(edge),
260 new FakeElement(tag).append(new FakeText(value)),
261 );
262 const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container)));
263 expect(paragraph.children.map(inline)).toEqual([
264 ["text", edge],
265 [tag.toLowerCase(), value],
266 ]);
267 });
268​
269 it("copies email links with their address and drops in-app destinations", () => {
270 const container = new FakeElement("DIV").append(
271 new FakeElement("P").append(
272 new FakeText("Write to "),
273 new FakeElement("A", [], { href: "mailto:support@example.com" }).append(
274 new FakeText("support@example.com"),
275 ),
276 new FakeText(", "),
277 new FakeElement("A", [], { href: "mailto:support@example.com?subject=Help" }).append(
278 new FakeText("Support"),
279 ),
280 new FakeText(", "),
281 new FakeElement("A", [], { href: "mailto:support@example.com?subject=Help)" }).append(
282 new FakeText("Support"),
283 ),
284 new FakeText(" or "),
285 new FakeElement("A", [], { href: "/environment-one/thread-one" }).append(
286 new FakeText("the thread"),
287 ),
288 new FakeText("."),
289 ),
290 );
291 const copied = serializeRenderedMarkdownFragment(asNode(container));
292 expect(copied).toBe(
293 "Write to support@example.com, [Support](mailto:support@example.com?subject=Help), [Support](mailto:support@example.com?subject=Help\\)) or the thread.",
294 );
295 expect(
296 elementsOf(readBack(copied))
297 .filter((child) => child.tagName === "a")
298 .map((link) => link.properties.href),
299 ).toEqual([
300 "mailto:support@example.com",
301 "mailto:support@example.com?subject=Help",
302 "mailto:support@example.com?subject=Help)",
303 ]);
304 });
305​
306 it.each([
307 ["array[index]", "https://example.com"] as const,
308 ...[
309 "support@example.com?subject=Help",
310 "foo",
311 "support@example.internal1",
312 "support@example.com_",
313 "support@example.com-",
314 "first_last@example.com",
315 ].map((label) => [label, `mailto:${label}`] as const),
316 ])("keeps the link label and destination: %s", (label, href) => {
317 const anchor = new FakeElement("A", [], { href }).append(new FakeText(label));
318 const container = new FakeElement("DIV").append(anchor);
319 const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container)));
320 expect(
321 paragraph.children.map((child) =>
322 child.type === "element"
323 ? [child.tagName, decodeURI(String(child.properties.href)), textOf(child)]
324 : [child.type, textOf(child)],
325 ),
326 ).toEqual([["a", href, label]]);
327 });
328​
329 it("copies alert and insight callouts as their Markdown instead of the rendered label", () => {
330 // The shape ChatMarkdown renders for `> [!WARNING]\n> Back up first.`.
331 const callout = new FakeElement("DIV", [], {
332 role: "note",
333 "data-markdown-alert": "warning",
334 }).append(
335 new FakeElement("P", [], {
336 "data-thread-find-ignore": "true",
337 "data-markdown-alert-label": "",
338 }).append(new FakeElement("SVG", [], { "aria-hidden": "true" }), new FakeText("Warning")),
339 new FakeElement("P").append(new FakeText("Back up first.")),
340 );
341 const container = new FakeElement("DIV").append(callout);
342​
343 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
344 "> [!WARNING]\n> Back up first.",
345 );
346 const insight = new FakeElement("DIV", [], {
347 role: "note",
348 "data-markdown-alert": "insight",
349 }).append(
350 new FakeElement("P", [], {
351 "data-thread-find-ignore": "true",
352 "data-markdown-alert-label": "",
353 }).append(new FakeText("Insight")),
354 new FakeElement("P").append(new FakeText("Caches are warm.")),
355 );
356 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(insight)))).toBe(
357 `★ Insight ${"─".repeat(37)}\nCaches are warm.\n${"─".repeat(49)}`,
358 );
359 });
360​
361 it("preserves explicit ordered-list values and continues from resets when copying", () => {
362 const list = new FakeElement("OL", [], { start: "0" }).append(
363 new FakeElement("LI").append(new FakeText("A")),
364 new FakeElement("LI", [], { value: "5" }).append(new FakeText("B")),
365 new FakeElement("LI").append(new FakeText("C")),
366 new FakeElement("LI", [], { value: "0" }).append(new FakeText("D")),
367 );
368 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
369 "0. A\n5. B\n6. C\n0. D",
370 );
371 });
372​
373 it("keeps a bare list item that sits alongside the code block", () => {
374 const container = new FakeElement("DIV").append(
375 new FakeElement("UL").append(new FakeElement("LI")),
376 renderedCodeBlock(["pnpm test"]),
377 );
378​
379 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\npnpm test");
380 });
381​
382 it("copies a command and the prose after it as shown, without code fences", () => {
383 const container = new FakeElement("DIV").append(
384 renderedCodeBlock(["printf 'hello\\n'"]),
385 new FakeElement("P").append(new FakeText("T")),
386 );
387​
388 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("printf 'hello\\n'\n\nT");
389 });
390​
391 it("keeps a diagram's source exactly as written when copied with prose", () => {
392 const source = 'flowchart TD\n A["first \n\n\nlast"]';
393 const container = new FakeElement("DIV").append(
394 new FakeElement("DIV", [], {
395 "data-markdown-mermaid": "",
396 "data-markdown-copy": serializeCodeBlockToMarkdown(source, "mermaid"),
397 }),
398 new FakeElement("P").append(new FakeText("After")),
399 );
400​
401 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
402 `\`\`\`mermaid\n${source}\n\`\`\`\n\nAfter`,
403 );
404 });
405​
406 it("keeps blank lines inside a code block in a list item, quote, or longer fence", () => {
407 const code = ["import os", "", "", "def main():"];
408 const list = new FakeElement("OL").append(
409 new FakeElement("LI").append(new FakeText("Create it:\n"), renderedCodeBlock(code)),
410 );
411 const quote = new FakeElement("BLOCKQUOTE").append(
412 new FakeElement("P").append(new FakeText("Note:")),
413 renderedCodeBlock(code),
414 );
415 const nestedFence = new FakeElement("DIV").append(
416 new FakeElement("P").append(new FakeText("Example:")),
417 renderedCodeBlock(["```js", "a()", "", "", "b() ", "```"]),
418 );
419​
420 expect(serializeRenderedMarkdownFragment(asNode(nestedFence))).toBe(
421 "Example:\n\n```js\na()\n\n\nb() \n```",
422 );
423​
424 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
425 "1. Create it:\n import os\n\n\n def main():",
426 );
427 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(quote)))).toBe(
428 "> Note:\n>\n> import os\n>\n>\n> def main():",
429 );
430 });
431​
432 it("omits fences when a selection past the last line drags in the whole code block", () => {
433 const container = new FakeElement("DIV").append(
434 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
435 new FakeText("\n"),
436 new FakeElement("P").append(new FakeText("")),
437 );
438​
439 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
440 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
441 );
442 });
443});
444​
445function renderedFormula(tex: string): FakeElement {
446 // MarkdownMath's wrapper; its children stand in for KaTeX's glyphs.
447 return new FakeElement("SPAN", [], {
448 "data-markdown-math": "inline",
449 "data-markdown-copy": `\\(${tex}\\)`,
450 }).append(new FakeText(tex));
452​
453function renderedTable(...rows: Array<Array<FakeElement | FakeText>>): FakeElement {
454 const row = (tag: string, cells: Array<FakeElement | FakeText>) =>
455 new FakeElement("TR").append(...cells.map((cell) => new FakeElement(tag).append(cell)));
456 const [head = [], ...body] = rows;
457 return new FakeElement("TABLE").append(
458 new FakeElement("THEAD").append(row("TH", head)),
459 new FakeElement("TBODY").append(...body.map((cells) => row("TD", cells))),
460 );
462​
463describe("copying rendered Markdown tables", () => {
464 beforeEach(() => {
465 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
466 });
467​
468 afterEach(() => {
469 vi.unstubAllGlobals();
470 });
471​
472 it("keeps formula pipes as authored while escaping prose pipes", () => {
473 const table = renderedTable(
474 [new FakeText("Formula"), new FakeText("Note")],
475 [renderedFormula("|x|"), new FakeText("*a* | ~~b~~")],
476 [renderedFormula("\\|x\\|"), new FakeElement("CODE").append(new FakeText("\\(c|d\\)"))],
477 [
478 new FakeElement("A", [], { href: "https://example.com/?q=a|b" }).append(
479 new FakeText("norm "),
480 renderedFormula("|y|"),
481 ),
482 new FakeText("e"),
483 ],
484 [
485 new FakeElement("UL").append(
486 new FakeElement("LI").append(renderedFormula("|z|"), new FakeText(" a | b")),
487 ),
488 new FakeElement("BLOCKQUOTE").append(new FakeElement("P").append(new FakeText("c | d"))),
489 ],
490 );
491 const markdown = serializeTableElementToMarkdown(table as unknown as Element);
492​
493 const parsed = readBack(markdown, { math: true });
494 expect(parsed.tagName).toBe("table");
495 const rows = elementsOf(parsed).flatMap((section) => elementsOf(section));
496 const cells = rows.map((row) => elementsOf(row));
497 expect(cells.map((row) => row.length)).toEqual([2, 2, 2, 2, 2]);
498 const formulas: string[] = [];
499 const visit = (node: HastElement) => {
500 if (node.tagName === "svg") formulas.push(String(node.properties.ariaLabel));
501 else elementsOf(node).forEach(visit);
502 };
503 visit(parsed);
504 expect(formulas).toEqual(["|x|", "\\|x\\|", "|y|", "|z|"]);
505 expect(textOf(cells[1]![1]!)).toBe("*a* | ~~b~~");
506 expect(textOf(cells[4]![1]!).trim()).toBe("> c | d");
507 expect(inline(cells[2]![1]!.children[0]!)).toEqual(["code", "\\(c|d\\)"]);
508 const link = cells[3]![0]!.children[0]!;
509 expect(link.type === "element" && decodeURI(String(link.properties.href))).toBe(
510 "https://example.com/?q=a|b",
511 );
512 });
513​
514 it("copies code and diagrams in cells without markers or unescaped pipes", () => {
515 const code = new FakeElement("PRE").append(
516 new FakeElement("CODE").append(new FakeText("a b")),
517 );
518 const diagram = new FakeElement("DIV", [], {
519 "data-markdown-mermaid": "",
520 "data-markdown-copy": serializeCodeBlockToMarkdown("A -->|hi| B", "mermaid"),
521 });
522 expect(
523 serializeTableElementToMarkdown(
524 asNode(
525 renderedTable([new FakeText("Command"), new FakeText("Diagram")], [code, diagram]),
526 ) as Element,
527 ),
528 ).toBe("| Command | Diagram |\n| --- | --- |\n| a b | ```mermaid A -->\\|hi\\| B ``` |");
529 });
530});
531​
532describe("copying a table as HTML", () => {
533 const cell = (
534 tag: "TH" | "TD",
535 text: string,
536 attributes: Record<string, string> = {},
537 style?: { textAlign: string },
538 ) => {
539 const element = new FakeElement(tag, [], attributes).append(new FakeText(text));
540 return style ? Object.assign(element, { style }) : element;
541 };
542 const row = (...cells: FakeElement[]) => new FakeElement("TR").append(...cells);
543 const html = (table: FakeElement) => serializeTableElementToHtml(table as unknown as Element);
544​
545 beforeEach(() => {
546 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
547 });
548​
549 afterEach(() => {
550 vi.unstubAllGlobals();
551 });
552​
553 /** Structure only: every style attribute is reduced to its text alignment. */
554 const structure = (table: FakeElement) =>
555 html(table).replace(/ style="([^"]*)"/g, (_, style: string) => {
556 const align = /text-align:(\w+)/.exec(style)?.[1];
557 return align ? ` align="${align}"` : "";
558 });
559​
560 it("escapes text and keeps column alignment from the style or the align attribute", () => {
561 const table = new FakeElement("TABLE").append(
562 new FakeElement("THEAD").append(
563 row(cell("TH", "Name"), cell("TH", "Amount", {}, { textAlign: "right" })),
564 ),
565 new FakeElement("TBODY").append(
566 row(cell("TD", 'A & B <"Ltd">'), cell("TD", "1,200", {}, { textAlign: "right" })),
567 // An absent inline style reads as "": the align attribute still applies.
568 row(cell("TD", " Bob\n Smith "), cell("TD", "3", { align: "center" }, { textAlign: "" })),
569 row(cell("TD", "text", { align: "justify" }), cell("TD", "4", {}, { textAlign: "end" })),
570 ),
571 );
572​
573 expect(structure(table)).toBe(
574 [
575 '<table dir="ltr">',
576 " <thead>",
577 ' <tr><th align="left">Name</th><th align="right">Amount</th></tr>',
578 " </thead>",
579 " <tbody>",
580 ' <tr><td>A &amp; B &lt;&quot;Ltd&quot;&gt;</td><td align="right">1,200</td></tr>',
581 ' <tr><td>Bob Smith</td><td align="center">3</td></tr>',
582 ' <tr><td align="justify">text</td><td align="right">4</td></tr>',
583 " </tbody>",
584 "</table>",
585 ].join("\n"),
586 );
587 });
588​
589 it("keeps every header row, body header cells, footers, and merged cells", () => {
590 const table = new FakeElement("TABLE").append(
591 new FakeElement("THEAD").append(
592 row(cell("TH", "Region", { rowspan: "2" }), cell("TH", "Sales", { colspan: "2" })),
593 row(cell("TH", "Q1"), cell("TH", "Q2", { colspan: "1" })),
594 ),
595 new FakeElement("TBODY").append(
596 row(
597 cell("TH", "EU"),
598 cell("TD", "1", { rowspan: "0" }),
599 cell("TD", "2", { rowspan: "-1" }),
600 ),
601 row(),
602 ),
603 new FakeElement("TFOOT").append(
604 row(cell("TD", "Total"), cell("TD", "3", { colspan: "2garbage" })),
605 ),
606 );
607​
608 expect(structure(table)).toBe(
609 [
610 '<table dir="ltr">',
611 " <thead>",
612 ' <tr><th align="left" rowspan="2">Region</th><th align="left" colspan="2">Sales</th></tr>',
613 ' <tr><th align="left">Q1</th><th align="left">Q2</th></tr>',
614 " </thead>",
615 " <tbody>",
616 // rowspan="0" runs to the end of its section; a negative span is invalid.
617 ' <tr><th align="left">EU</th><td rowspan="0">1</td><td>2</td></tr>',
618 " <tr></tr>",
619 " </tbody>",
620 " <tfoot>",
621 // HTML reads a span's leading digits, as the DOM does.
622 ' <tr><td>Total</td><td colspan="2">3</td></tr>',
623 " </tfoot>",
624 "</table>",
625 ].join("\n"),
626 );
627 });
628​
629 it("keeps line breaks, block edges, nested cells, and formulas as TeX", () => {
630 const nested = new FakeElement("TABLE").append(
631 new FakeElement("TBODY").append(row(cell("TD", "a"), cell("TD", "b"))),
632 );
633 const table = new FakeElement("TABLE").append(
634 new FakeElement("TBODY").append(
635 row(
636 new FakeElement("TD").append(
637 new FakeText("first"),
638 new FakeElement("BR"),
639 new FakeElement("STRONG").append(new FakeText("second")),
640 ),
641 new FakeElement("TD").append(
642 new FakeElement("P").append(new FakeText("one")),
643 new FakeElement("P").append(new FakeText("two")),
644 ),
645 ),
646 row(
647 new FakeElement("TD").append(nested),
648 new FakeElement("TD").append(new FakeText("area "), renderedFormula("\\pi r^2")),
649 ),
650 ),
651 );
652​
653 expect(structure(table)).toBe(
654 [
655 '<table dir="ltr">',
656 " <tbody>",
657 " <tr><td>first<br>second</td><td>one<br>two</td></tr>",
658 " <tr><td>a b</td><td>area \\(\\pi r^2\\)</td></tr>",
659 " </tbody>",
660 "</table>",
661 ].join("\n"),
662 );
663 });
664​
665 it("keeps every explicit break, preformatted spacing, and nonbreaking spaces", () => {
666 const br = () => new FakeElement("BR");
667 const content = (...children: Array<FakeElement | FakeText>) =>
668 structure(
669 new FakeElement("TABLE").append(
670 new FakeElement("TBODY").append(row(new FakeElement("TD").append(...children))),
671 ),
672 ).split("\n")[2];
673 const td = (html: string) => ` <tr><td>${html}</td></tr>`;
674​
675 expect(content(new FakeText("a"), br(), br(), new FakeText("b"))).toBe(td("a<br><br>b"));
676 expect(content(br(), new FakeText(" lead "), br())).toBe(td("<br>lead<br>"));
677 // A break that ends a paragraph already ends the line.
678 expect(
679 content(
680 new FakeElement("P").append(new FakeText("a "), br()),
681 new FakeElement("P").append(new FakeText("b")),
682 ),
683 ).toBe(td("a<br>b"));
684 expect(
685 content(
686 new FakeText("run:"),
687 new FakeElement("DIV", ["select-none"]).append(new FakeText("madeup")),
688 new FakeElement("PRE").append(
689 new FakeElement("CODE").append(new FakeText("if x:\n\ty = 1\n\nend\n")),
690 ),
691 ),
692 ).toBe(
693 td("run:<br>if&nbsp;x:<br>&nbsp;&nbsp;&nbsp;&nbsp;y&nbsp;&nbsp;=&nbsp;&nbsp;1<br><br>end"),
694 );
695 expect(content(new FakeText("1\u00a0000 EUR"))).toBe(td("1&nbsp;000 EUR"));
696 expect(
697 content(
698 new FakeElement("BUTTON", [], {
699 "data-markdown-copy": "[source](https://example.com)",
700 }).append(new FakeText("source")),
701 ),
702 ).toBe(td("source"));
703 });
704​
705 it("keeps a right-to-left table's direction and puts headers on its start side", () => {
706 const table = new FakeElement("TABLE", [], { dir: "rtl" }).append(
707 new FakeElement("THEAD").append(
708 row(cell("TH", "Name"), cell("TH", "End", {}, { textAlign: "end" })),
709 ),
710 );
711​
712 expect(structure(table)).toBe(
713 [
714 '<table dir="rtl">',
715 " <thead>",
716 ' <tr><th align="right">Name</th><th align="left">End</th></tr>',
717 " </thead>",
718 "</table>",
719 ].join("\n"),
720 );
721 });
722​
723 it("wraps rows outside any section in a body", () => {
724 const table = new FakeElement("TABLE").append(row(cell("TD", "only"), cell("TD", "cells")));
725​
726 expect(structure(table)).toBe(
727 '<table dir="ltr">\n <tbody>\n <tr><td>only</td><td>cells</td></tr>\n </tbody>\n</table>',
728 );
729 });
730​
731 it("returns an empty string for a table without cells", () => {
732 expect(html(new FakeElement("TABLE").append(new FakeElement("TBODY").append(row())))).toBe("");
733 });
734});