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

markdown-clipboard.test.ts

734 lines26.5 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 { markdownMathRanges, parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
15​
16import { unified } from "unified";
17import remarkParse from "remark-parse";
18import {
19 CHAT_MARKDOWN_REMARK_PLUGINS,
20 CHAT_USER_MARKDOWN_REMARK_PLUGINS,
21} from "@t3tools/shared/markdownPipeline";
22​
23const userMarkdown = unified()
24 .use(remarkParse)
25 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
26 .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS);
27​
28const TEXT_NODE = 3;
29const ELEMENT_NODE = 1;
30​
31class FakeText {
32 readonly nodeType = TEXT_NODE;
33 readonly childNodes: ReadonlyArray<never> = [];
34​
35 constructor(readonly textContent: string) {}
37​
38class FakeElement {
39 readonly nodeType = ELEMENT_NODE;
40 checked = false;
41 readonly childNodes: Array<FakeElement | FakeText> = [];
42 readonly classList = {
43 contains: (name: string) => this.classNames.includes(name),
44 };
45​
46 constructor(
47 readonly tagName: string,
48 private readonly classNames: ReadonlyArray<string> = [],
49 private readonly attributes: Readonly<Record<string, string>> = {},
50 ) {}
51​
52 get localName(): string {
53 return this.tagName.toLowerCase();
54 }
55​
56 get textContent(): string {
57 return this.childNodes.map((child) => child.textContent).join("");
58 }
59​
60 get children(): ReadonlyArray<FakeElement> {
61 return this.childNodes.filter((child): child is FakeElement => child instanceof FakeElement);
62 }
63​
64 append(...children: Array<FakeElement | FakeText>): this {
65 this.childNodes.push(...children);
66 return this;
67 }
68​
69 getAttribute(name: string): string | null {
70 return this.attributes[name] ?? null;
71 }
72​
73 hasAttribute(name: string): boolean {
74 return Object.hasOwn(this.attributes, name);
75 }
76​
77 closest(): FakeElement | null {
78 return null;
79 }
80​
81 querySelector(selector: string): FakeElement | null {
82 if (selector.includes(", ")) {
83 for (const part of selector.split(", ")) {
84 const match = this.querySelector(part);
85 if (match) return match;
86 }
87 return null;
88 }
89 const childOnly = selector.startsWith(":scope > ");
90 const [target, ...rest] = (childOnly ? selector.slice(":scope > ".length) : selector).split(
91 " > ",
92 );
93 const matches = (element: FakeElement): boolean => {
94 if (target === 'input[type="checkbox"]') {
95 return element.tagName === "INPUT" && element.getAttribute("type") === "checkbox";
96 }
97 return element.tagName === target?.toUpperCase();
98 };
99 const search = (parent: FakeElement): FakeElement | null => {
100 for (const child of parent.childNodes) {
101 if (!(child instanceof FakeElement)) continue;
102 if (matches(child)) {
103 if (rest.length === 0) return child;
104 const nested = child.querySelector(`:scope > ${rest.join(" > ")}`);
105 if (nested) return nested;
106 }
107 if (!childOnly) {
108 const nested = search(child);
109 if (nested) return nested;
110 }
111 }
112 return null;
113 };
114 return search(this);
115 }
116​
117 /** Supports the `:scope > a > b` child paths the table serializer queries. */
118 querySelectorAll(selector: string): FakeElement[] {
119 return selector.split(", ").flatMap((part) =>
120 part
121 .replace(/^:scope > /, "")
122 .split(" > ")
123 .reduce<FakeElement[]>(
124 (level, tag) =>
125 level.flatMap((element) =>
126 element.children.filter((child) => child.tagName === tag.toUpperCase()),
127 ),
128 [this],
129 ),
130 );
131 }
133​
134function asNode(element: FakeElement): Node {
135 return element as unknown as Node;
137​
138function shikiCodeLine(text: string): FakeElement {
139 const token = new FakeElement("SPAN").append(new FakeText(text));
140 return new FakeElement("SPAN", ["line"]).append(token);
142​
143function renderedCodeBlock(lines: ReadonlyArray<string>): FakeElement {
144 const code = new FakeElement("CODE");
145 lines.forEach((line, index) => {
146 if (index > 0) code.append(new FakeText("\n"));
147 code.append(shikiCodeLine(line));
148 });
149 return new FakeElement("DIV", ["chat-markdown-codeblock"]).append(
150 new FakeElement("DIV", ["chat-markdown-codeblock-header", "select-none"]).append(
151 new FakeText("sh"),
152 ),
153 new FakeElement("DIV", ["chat-markdown-shiki"]).append(new FakeElement("PRE").append(code)),
154 );
156​
157describe("serializeRenderedMarkdownFragment", () => {
158 it("copies a popover context reference once, without its details or nested label", () => {
159 const reference = "[Review comment](t3-context://v1/review-comment/review-1)";
160 const container = new FakeElement("DIV").append(
161 new FakeText("Fix "),
162 new FakeElement("BUTTON", [], { "data-markdown-copy": reference }).append(
163 new FakeElement("SPAN", [], { "data-markdown-copy": reference }).append(
164 new FakeText("Review comment"),
165 ),
166 ),
167 new FakeText(" please"),
168 );
169​
170 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(`Fix ${reference} please`);
171 });
172​
173 beforeEach(() => {
174 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
175 });
176​
177 afterEach(() => {
178 vi.unstubAllGlobals();
179 });
180​
181 it("copies the complete quote, source, and comment instead of the comment-only chip label", () => {
182 const citation = {
183 version: 1 as const,
184 environmentId: EnvironmentId.make("environment-one"),
185 threadId: ThreadId.make("thread-one"),
186 messageId: MessageId.make("assistant-one"),
187 text: "A complete quote, including the part hidden by the chip preview.",
188 comment: "What does this mean?\nPlease expand on the hidden part.",
189 start: 0,
190 end: 66,
191 prefix: "",
192 suffix: "",
193 };
194 const anchor = new FakeElement("A", [], {
195 "data-markdown-copy": serializeAssistantCitation(citation),
196 href: "/environment-one/thread-one#citation",
197 }).append(new FakeText("What does this mean?…"));
198 const chip = new FakeElement("SPAN", [], {
199 "data-markdown-copy": serializeAssistantCitation(citation),
200 }).append(anchor, new FakeElement("BUTTON").append(new FakeText("Edit comment")));
201 const container = new FakeElement("DIV").append(new FakeText("Explain "), chip);
202 const copied = serializeRenderedMarkdownFragment(asNode(container));
203 expect(copied).toBe(`Explain ${serializeAssistantCitation(citation)}`);
204 expect(collectAssistantCitations(copied).map((entry) => entry.citation)).toEqual([citation]);
205 });
206​
207 it("keeps a multi-line code selection plain instead of inline-wrapping it", () => {
208 const code = new FakeElement("CODE").append(new FakeText("first line\nsecond line"));
209 const container = new FakeElement("DIV").append(code);
210​
211 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line");
212 });
213​
214 it.each([
215 ["backtick edges", "`value`"],
216 ["space edges", " value "],
217 ["only spaces", " "],
218 ])("copies inline code that parses back unchanged: %s", (_, value) => {
219 const container = new FakeElement("DIV").append(
220 new FakeElement("P").append(
221 new FakeText("Use "),
222 new FakeElement("CODE").append(new FakeText(value)),
223 new FakeText(" here."),
224 ),
225 );
226 const paragraph = parseMarkdownWithMath(serializeRenderedMarkdownFragment(asNode(container)))
227 .children[0];
228 if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph");
229 expect(paragraph.children.find((child) => child.type === "inlineCode")?.value).toBe(value);
230 });
231​
232 it.each([
233 String.raw`see C:\me\.t3\shot.png`,
234 String.raw`C:\work\_build`,
235 "C:/work/_build/out.txt",
236 String.raw`C:\work\a-_b.txt`,
237 "a*word*b and a_word_b; ~~literal~~ and ~single~",
238 String.raw`before\ after\ end`,
239 ])("copies prose that parses back unchanged: %s", (value) => {
240 const container = new FakeElement("DIV").append(new FakeText(value));
241 const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container)))
242 .children[0];
243 expect(paragraph).toMatchObject({ type: "paragraph", children: [{ type: "text", value }] });
244 });
245​
246 it.each([
247 ["*", "EM", "word", "emphasis"],
248 ["\\", "CODE", "value", "inlineCode"],
249 ])("keeps a text edge %j beside %s", (edge, tag, value, type) => {
250 const container = new FakeElement("DIV").append(
251 new FakeText(edge),
252 new FakeElement(tag).append(new FakeText(value)),
253 );
254 const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container)))
255 .children[0];
256 expect(paragraph).toMatchObject({
257 type: "paragraph",
258 children: [
259 { type: "text", value: edge },
260 type === "inlineCode" ? { type, value } : { type, children: [{ type: "text", value }] },
261 ],
262 });
263 });
264​
265 it("copies email links with their address and drops in-app destinations", () => {
266 const container = new FakeElement("DIV").append(
267 new FakeElement("P").append(
268 new FakeText("Write to "),
269 new FakeElement("A", [], { href: "mailto:support@example.com" }).append(
270 new FakeText("support@example.com"),
271 ),
272 new FakeText(", "),
273 new FakeElement("A", [], { href: "mailto:support@example.com?subject=Help" }).append(
274 new FakeText("Support"),
275 ),
276 new FakeText(", "),
277 new FakeElement("A", [], { href: "mailto:support@example.com?subject=Help)" }).append(
278 new FakeText("Support"),
279 ),
280 new FakeText(" or "),
281 new FakeElement("A", [], { href: "/environment-one/thread-one" }).append(
282 new FakeText("the thread"),
283 ),
284 new FakeText("."),
285 ),
286 );
287 const copied = serializeRenderedMarkdownFragment(asNode(container));
288 expect(copied).toBe(
289 "Write to support@example.com, [Support](mailto:support@example.com?subject=Help), [Support](mailto:support@example.com?subject=Help\\)) or the thread.",
290 );
291 const paragraph = parseMarkdownWithMath(copied).children[0];
292 if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph");
293 expect(
294 paragraph.children.filter((child) => child.type === "link").map((link) => link.url),
295 ).toEqual([
296 "mailto:support@example.com",
297 "mailto:support@example.com?subject=Help",
298 "mailto:support@example.com?subject=Help)",
299 ]);
300 });
301​
302 it.each([
303 ["array[index]", "https://example.com"] as const,
304 ...[
305 "support@example.com?subject=Help",
306 "foo",
307 "support@example.internal1",
308 "support@example.com_",
309 "support@example.com-",
310 "first_last@example.com",
311 ].map((label) => [label, `mailto:${label}`] as const),
312 ])("keeps the link label and destination: %s", (label, href) => {
313 const anchor = new FakeElement("A", [], { href }).append(new FakeText(label));
314 const container = new FakeElement("DIV").append(anchor);
315 const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container)))
316 .children[0];
317 if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph");
318 expect(paragraph.children).toMatchObject([
319 { type: "link", url: href, children: [{ type: "text", value: label }] },
320 ]);
321 });
322​
323 it("copies alert and insight callouts as their Markdown instead of the rendered label", () => {
324 // The shape ChatMarkdown renders for `> [!WARNING]\n> Back up first.`.
325 const callout = new FakeElement("DIV", [], {
326 role: "note",
327 "data-markdown-alert": "warning",
328 }).append(
329 new FakeElement("P", [], {
330 "data-thread-find-ignore": "true",
331 "data-markdown-alert-label": "",
332 }).append(new FakeElement("SVG", [], { "aria-hidden": "true" }), new FakeText("Warning")),
333 new FakeElement("P").append(new FakeText("Back up first.")),
334 );
335 const container = new FakeElement("DIV").append(callout);
336​
337 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
338 "> [!WARNING]\n> Back up first.",
339 );
340 const insight = new FakeElement("DIV", [], {
341 role: "note",
342 "data-markdown-alert": "insight",
343 }).append(
344 new FakeElement("P", [], {
345 "data-thread-find-ignore": "true",
346 "data-markdown-alert-label": "",
347 }).append(new FakeText("Insight")),
348 new FakeElement("P").append(new FakeText("Caches are warm.")),
349 );
350 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(insight)))).toBe(
351 `★ Insight ${"─".repeat(37)}\nCaches are warm.\n${"─".repeat(49)}`,
352 );
353 });
354​
355 it("preserves explicit ordered-list values and continues from resets when copying", () => {
356 const list = new FakeElement("OL", [], { start: "0" }).append(
357 new FakeElement("LI").append(new FakeText("A")),
358 new FakeElement("LI", [], { value: "5" }).append(new FakeText("B")),
359 new FakeElement("LI").append(new FakeText("C")),
360 new FakeElement("LI", [], { value: "0" }).append(new FakeText("D")),
361 );
362 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
363 "0. A\n5. B\n6. C\n0. D",
364 );
365 });
366​
367 it("keeps a bare list item that sits alongside the code block", () => {
368 const container = new FakeElement("DIV").append(
369 new FakeElement("UL").append(new FakeElement("LI")),
370 renderedCodeBlock(["pnpm test"]),
371 );
372​
373 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\npnpm test");
374 });
375​
376 it("copies a command and the prose after it as shown, without code fences", () => {
377 const container = new FakeElement("DIV").append(
378 renderedCodeBlock(["printf 'hello\\n'"]),
379 new FakeElement("P").append(new FakeText("T")),
380 );
381​
382 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("printf 'hello\\n'\n\nT");
383 });
384​
385 it("keeps a diagram's source exactly as written when copied with prose", () => {
386 const source = 'flowchart TD\n A["first \n\n\nlast"]';
387 const container = new FakeElement("DIV").append(
388 new FakeElement("DIV", [], {
389 "data-markdown-mermaid": "",
390 "data-markdown-copy": serializeCodeBlockToMarkdown(source, "mermaid"),
391 }),
392 new FakeElement("P").append(new FakeText("After")),
393 );
394​
395 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
396 `\`\`\`mermaid\n${source}\n\`\`\`\n\nAfter`,
397 );
398 });
399​
400 it("keeps blank lines inside a code block in a list item, quote, or longer fence", () => {
401 const code = ["import os", "", "", "def main():"];
402 const list = new FakeElement("OL").append(
403 new FakeElement("LI").append(new FakeText("Create it:\n"), renderedCodeBlock(code)),
404 );
405 const quote = new FakeElement("BLOCKQUOTE").append(
406 new FakeElement("P").append(new FakeText("Note:")),
407 renderedCodeBlock(code),
408 );
409 const nestedFence = new FakeElement("DIV").append(
410 new FakeElement("P").append(new FakeText("Example:")),
411 renderedCodeBlock(["```js", "a()", "", "", "b() ", "```"]),
412 );
413​
414 expect(serializeRenderedMarkdownFragment(asNode(nestedFence))).toBe(
415 "Example:\n\n```js\na()\n\n\nb() \n```",
416 );
417​
418 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
419 "1. Create it:\n import os\n\n\n def main():",
420 );
421 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(quote)))).toBe(
422 "> Note:\n>\n> import os\n>\n>\n> def main():",
423 );
424 });
425​
426 it("omits fences when a selection past the last line drags in the whole code block", () => {
427 const container = new FakeElement("DIV").append(
428 renderedCodeBlock(["printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN"]),
429 new FakeText("\n"),
430 new FakeElement("P").append(new FakeText("")),
431 );
432​
433 expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
434 "printf '%s' 'TOKEN' | gh secret set CLOUDFLARE_API_TOKEN",
435 );
436 });
437});
438​
439function renderedFormula(tex: string): FakeElement {
440 // MarkdownMath's wrapper; its children stand in for KaTeX's glyphs.
441 return new FakeElement("SPAN", [], {
442 "data-markdown-math": "inline",
443 "data-markdown-copy": `\\(${tex}\\)`,
444 }).append(new FakeText(tex));
446​
447function renderedTable(...rows: Array<Array<FakeElement | FakeText>>): FakeElement {
448 const row = (tag: string, cells: Array<FakeElement | FakeText>) =>
449 new FakeElement("TR").append(...cells.map((cell) => new FakeElement(tag).append(cell)));
450 const [head = [], ...body] = rows;
451 return new FakeElement("TABLE").append(
452 new FakeElement("THEAD").append(row("TH", head)),
453 new FakeElement("TBODY").append(...body.map((cells) => row("TD", cells))),
454 );
456​
457describe("copying rendered Markdown tables", () => {
458 beforeEach(() => {
459 vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
460 });
461​
462 afterEach(() => {
463 vi.unstubAllGlobals();
464 });
465​
466 it("keeps formula pipes as authored while escaping prose pipes", () => {
467 const table = renderedTable(
468 [new FakeText("Formula"), new FakeText("Note")],
469 [renderedFormula("|x|"), new FakeText("*a* | ~~b~~")],
470 [renderedFormula("\\|x\\|"), new FakeElement("CODE").append(new FakeText("\\(c|d\\)"))],
471 [
472 new FakeElement("A", [], { href: "https://example.com/?q=a|b" }).append(
473 new FakeText("norm "),
474 renderedFormula("|y|"),
475 ),
476 new FakeText("e"),
477 ],
478 [
479 new FakeElement("UL").append(
480 new FakeElement("LI").append(renderedFormula("|z|"), new FakeText(" a | b")),
481 ),
482 new FakeElement("BLOCKQUOTE").append(new FakeElement("P").append(new FakeText("c | d"))),
483 ],
484 );
485 const markdown = serializeTableElementToMarkdown(table as unknown as Element);
486​
487 const tree = parseMarkdownWithMath(markdown);
488 const parsed = tree.children[0];
489 if (parsed?.type !== "table") throw new Error("Expected a table");
490 expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]);
491 expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([
492 "|x|",
493 "\\|x\\|",
494 "|y|",
495 "|z|",
496 ]);
497 expect(parsed.children[1]?.children[1]?.children).toMatchObject([
498 { type: "text", value: "*a* | ~~b~~" },
499 ]);
500 expect(parsed.children[4]?.children[1]?.children).toMatchObject([
501 { type: "text", value: "> c | d" },
502 ]);
503 const [, , codeRow, linkRow] = parsed.children;
504 expect(codeRow?.children[1]?.children[0]).toMatchObject({
505 type: "inlineCode",
506 value: "\\(c|d\\)",
507 });
508 expect(linkRow?.children[0]?.children[0]).toMatchObject({
509 type: "link",
510 url: "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});