|
| 1 | +import { describe, expect, it } from "vite-plus/test"; |
| 2 | + |
| 3 | +import { serializeTableElementToDelimited } from "./markdown-clipboard"; |
| 4 | + |
| 5 | +function renderTable(html: string): HTMLTableElement { |
| 6 | + const container = document.createElement("div"); |
| 7 | + container.innerHTML = html; |
| 8 | + return container.querySelector("table")!; |
| 9 | +} |
| 10 | + |
| 11 | +function exampleTable() { |
| 12 | + return renderTable(` |
| 13 | + <table> |
| 14 | + <thead><tr><th>Question</th><th>Owner, team</th></tr></thead> |
| 15 | + <tbody> |
| 16 | + <tr><td></td><td>Platform</td></tr> |
| 17 | + <tr><td>first<br>second\tthird</td><td></td></tr> |
| 18 | + <tr><td><img alt="Build badge" src="b.svg"></td><td>say "ok"</td></tr> |
| 19 | + </tbody> |
| 20 | + </table>`); |
| 21 | +} |
| 22 | + |
| 23 | +describe("serializeTableElementToDelimited", () => { |
| 24 | + it("keeps every cell in its column as tab-separated rows", () => { |
| 25 | + expect(serializeTableElementToDelimited(exampleTable(), "tsv")).toBe( |
| 26 | + 'Question\tOwner, team\n\tPlatform\nfirst second third\t\nBuild badge\tsay "ok"', |
| 27 | + ); |
| 28 | + }); |
| 29 | + |
| 30 | + it.each(["tsv", "csv"] as const)("copies formula-leading text literally in %s", (format) => { |
| 31 | + const table = renderTable( |
| 32 | + "<table><tr><td>=1+1</td><td>+SUM(A1)</td><td>-cmd</td><td>@cmd</td><td>-42</td><td>+1.5e2</td></tr></table>", |
| 33 | + ); |
| 34 | + const separator = format === "tsv" ? "\t" : ","; |
| 35 | + expect(serializeTableElementToDelimited(table, format)).toBe( |
| 36 | + ["'=1+1", "'+SUM(A1)", "'-cmd", "'@cmd", "-42", "+1.5e2"].join(separator), |
| 37 | + ); |
| 38 | + }); |
| 39 | + |
| 40 | + it("escapes quote-leading TSV cells", () => { |
| 41 | + const table = renderTable('<table><tr><td>"hello"</td><td>"open</td></tr></table>'); |
| 42 | + expect(serializeTableElementToDelimited(table, "tsv")).toBe('"""hello"""\t"""open"'); |
| 43 | + }); |
| 44 | + |
| 45 | + it("keeps math as TeX", () => { |
| 46 | + const table = renderTable( |
| 47 | + '<table><tr><td><span data-markdown-math="inline" data-markdown-copy="x^2">rendered math</span></td></tr></table>', |
| 48 | + ); |
| 49 | + expect(serializeTableElementToDelimited(table, "tsv")).toBe("x^2"); |
| 50 | + }); |
| 51 | + |
| 52 | + it("quotes CSV cells that contain commas or quotes", () => { |
| 53 | + expect(serializeTableElementToDelimited(exampleTable(), "csv")).toBe( |
| 54 | + 'Question,"Owner, team"\n,Platform\nfirst second third,\nBuild badge,"say ""ok"""', |
| 55 | + ); |
| 56 | + }); |
| 57 | +}); |
0 commit comments