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

MarkdownCopy.browser.test.tsx

247 lines8.7 KB

1import { describe, expect, it, vi } from "vite-plus/test";
2import { page, userEvent } from "vite-plus/test/browser";
3​
4import "~/index.css";
5import { render } from "../../../test/render";
6import { MarkdownCodeBlock } from "./MarkdownCodeBlock";
7import { MarkdownTable } from "./MarkdownTable";
8​
9// Insecure origins (a LAN or tailnet address over plain http) have no async clipboard.
10function withoutAsyncClipboard() {
11 const original = Object.getOwnPropertyDescriptor(Navigator.prototype, "clipboard");
12 Object.defineProperty(navigator, "clipboard", { configurable: true, value: undefined });
13 const execCommand = vi.spyOn(document, "execCommand").mockReturnValue(true);
14 return {
15 execCommand,
16 [Symbol.dispose]() {
17 execCommand.mockRestore();
18 Reflect.deleteProperty(navigator, "clipboard");
19 if (original) Object.defineProperty(Navigator.prototype, "clipboard", original);
20 },
21 };
23​
24describe("markdown copy without the async clipboard", () => {
25 it("copies a code block through the execCommand fallback", async () => {
26 await using screen = await render(
27 <MarkdownCodeBlock
28 code="echo hi"
29 language="sh"
30 fenceTitle={null}
31 theme="light"
32 isStreaming={false}
33 >
34 <pre>
35 <code>echo hi</code>
36 </pre>
37 </MarkdownCodeBlock>,
38 // The block renders no links and reads no route.
39 { router: false },
40 );
41 using clipboard = withoutAsyncClipboard();
42​
43 await userEvent.click(screen.getByRole("button", { name: "Copy code" }));
44 await expect.element(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument();
45 expect(clipboard.execCommand).toHaveBeenCalledWith("copy");
46 });
47​
48 it("copies a table through the execCommand fallback", async () => {
49 await using screen = await render(
50 <MarkdownTable>
51 <thead>
52 <tr>
53 <th>Name</th>
54 </tr>
55 </thead>
56 <tbody>
57 <tr>
58 <td>Ada</td>
59 </tr>
60 </tbody>
61 </MarkdownTable>,
62 // The table renders no links and reads no route.
63 { router: false },
64 );
65 using clipboard = withoutAsyncClipboard();
66​
67 await userEvent.click(screen.getByRole("button", { name: "Copy table" }));
68 await userEvent.click(page.getByRole("menuitem", { name: "Copy as Markdown" }));
69 await expect.element(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument();
70 expect(clipboard.execCommand).toHaveBeenCalledWith("copy");
71 });
72});
73​
74describe("copying a table as HTML", () => {
75 it("writes the markup as plain text and as the rich HTML flavor", async () => {
76 await using screen = await render(
77 <div dir="rtl">
78 <MarkdownTable>
79 <thead>
80 <tr>
81 <th>Name</th>
82 <th style={{ textAlign: "right" }}>Amount</th>
83 </tr>
84 </thead>
85 <tbody>
86 <tr>
87 <td>Ada &amp; co</td>
88 <td style={{ textAlign: "right" }}>1,200</td>
89 </tr>
90 <tr>
91 <td>
92 first
93 <br />
94 second
95 </td>
96 <td>
97 {/* The wrapper MarkdownMath renders around a formula. */}
98 <span data-markdown-math="inline" data-markdown-copy="\(x^2\)">
99 x²
100 </span>
101 </td>
102 </tr>
103 <tr>
104 <td>zero</td>
105 <td>garbage</td>
106 </tr>
107 </tbody>
108 </MarkdownTable>
109 </div>,
110 // The table renders no links and reads no route.
111 { router: false },
112 );
113 // Raw span values, so the copy reads the DOM's own rowSpan/colSpan normalization.
114 const sourceCell = (text: string) =>
115 [...document.querySelectorAll("td")].find((cell) => cell.textContent === text);
116 sourceCell("zero")?.setAttribute("rowspan", "0");
117 sourceCell("garbage")?.setAttribute("colspan", "2garbage");
118 sourceCell("Ada & co")?.setAttribute("rowspan", "-1");
119 const items: ClipboardItem[] = [];
120 const write = vi.spyOn(navigator.clipboard, "write").mockImplementation(async (data) => {
121 items.push(...data);
122 });
123​
124 try {
125 await userEvent.click(screen.getByRole("button", { name: "Copy table" }));
126 await userEvent.click(page.getByRole("menuitem", { name: "Copy as HTML" }));
127 await expect.element(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument();
128​
129 const [item] = items;
130 expect(item?.types).toEqual(["text/plain", "text/html"]);
131 const markup = await (await item!.getType("text/plain")).text();
132 expect(markup).toMatch(/^<table[\s>]/);
133 expect(await (await item!.getType("text/html")).text()).toBe(
134 `<meta charset="utf-8">${markup}`,
135 );
136​
137 const pasted = new DOMParser().parseFromString(markup, "text/html").querySelector("table");
138 expect(pasted?.getAttribute("dir")).toBe("rtl");
139 const cells = [...(pasted?.querySelectorAll("th, td") ?? [])] as HTMLElement[];
140 expect(cells[0]?.style.textAlign).toBe("right");
141 const span = (cell: HTMLElement | undefined) => [
142 cell?.getAttribute("rowspan") ?? null,
143 cell?.getAttribute("colspan") ?? null,
144 ];
145 // rowspan="0" runs to the section end, "2garbage" reads as 2, a negative span is dropped.
146 expect([span(cells[6]), span(cells[7]), span(cells[2])]).toEqual([
147 ["0", null],
148 [null, "2"],
149 [null, null],
150 ]);
151 } finally {
152 write.mockRestore();
153 }
154 });
155});
156​
157describe("copying a table for chat apps", () => {
158 it("writes aligned columns in a code fence, with a pre block for rich targets", async () => {
159 await using screen = await render(
160 <MarkdownTable>
161 <thead>
162 <tr>
163 <th>Name</th>
164 <th style={{ textAlign: "right" }}>Amount</th>
165 </tr>
166 </thead>
167 <tbody>
168 <tr>
169 <td>Ada &amp; co</td>
170 <td style={{ textAlign: "right" }}>1,200</td>
171 </tr>
172 </tbody>
173 </MarkdownTable>,
174 // The table renders no links and reads no route.
175 { router: false },
176 );
177 const items: ClipboardItem[] = [];
178 const write = vi.spyOn(navigator.clipboard, "write").mockImplementation(async (data) => {
179 items.push(...data);
180 });
181​
182 try {
183 await userEvent.click(screen.getByRole("button", { name: "Copy table" }));
184 await userEvent.click(page.getByRole("menuitem", { name: "Copy for chat apps" }));
185 await expect.element(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument();
186​
187 const [item] = items;
188 expect(item?.types).toEqual(["text/plain", "text/html"]);
189 expect(await (await item!.getType("text/plain")).text()).toBe(
190 "```\nName Amount\n-------- ------\nAda & co 1,200\n```",
191 );
192 expect(await (await item!.getType("text/html")).text()).toBe(
193 '<meta charset="utf-8"><pre>Name Amount\n-------- ------\nAda &amp; co 1,200</pre>',
194 );
195 } finally {
196 write.mockRestore();
197 }
198 });
199});
200​
201describe("copying a table as PNG", () => {
202 it("writes the drawn table as one image/png clipboard item", async () => {
203 await using screen = await render(
204 <MarkdownTable>
205 <thead>
206 <tr>
207 <th>Name</th>
208 <th>Date</th>
209 </tr>
210 </thead>
211 <tbody>
212 <tr>
213 <td>Ada</td>
214 <td>11 Oct</td>
215 </tr>
216 </tbody>
217 </MarkdownTable>,
218 // The table renders no links and reads no route.
219 { router: false },
220 );
221 const items: ClipboardItem[] = [];
222 const write = vi.spyOn(navigator.clipboard, "write").mockImplementation(async (data) => {
223 items.push(...data);
224 // Settle the promised image as the browser would before the write resolves.
225 await Promise.all(data.flatMap((item) => item.types.map((type) => item.getType(type))));
226 });
227​
228 try {
229 await userEvent.click(screen.getByRole("button", { name: "Copy table" }));
230 await userEvent.click(page.getByRole("menuitem", { name: "Copy as PNG" }));
231 await expect.element(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument();
232​
233 expect(items).toHaveLength(1);
234 const [item] = items;
235 expect(item?.types).toEqual(["image/png"]);
236 const png = await item!.getType("image/png");
237 expect(png.type).toBe("image/png");
238 const table = screen.container.querySelector("table")!.getBoundingClientRect();
239 const bitmap = await createImageBitmap(png);
240 // The table plus a 16px margin on each side, at the screen's pixel density.
241 expect(bitmap.width).toBe(Math.floor((table.width + 32) * devicePixelRatio));
242 expect(bitmap.height).toBe(Math.floor((table.height + 32) * devicePixelRatio));
243 } finally {
244 write.mockRestore();
245 }
246 });
247});