Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2
3import { renderTablePng } from "./tablePng";
4
5const MARGIN = 16;
6const BACKDROP = [12, 34, 56] as const;
7
8interface Pixels {
9 readonly width: number;
10 readonly height: number;
11 readonly origin: DOMRect;
12 /** Whether any pixel inside a viewport rect differs from the backdrop. */
13 readonly hasInk: (rect: DOMRect) => boolean;
14 readonly at: (x: number, y: number) => readonly number[];
15 /** Alpha of the image's last pixel. */
16 readonly cornerAlpha: number;
17}
18
19async function readPng(blob: Blob, table: HTMLTableElement): Promise<Pixels> {
20 expect(blob.type).toBe("image/png");
21 const bitmap = await createImageBitmap(blob);
22 const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
23 const context = canvas.getContext("2d")!;
24 context.drawImage(bitmap, 0, 0);
25 const { data } = context.getImageData(0, 0, bitmap.width, bitmap.height);
26 const origin = table.getBoundingClientRect();
27 const scale = bitmap.width / (origin.width + MARGIN * 2);
28 const index = (x: number, y: number) =>
29 (Math.round((y - origin.top + MARGIN) * scale) * bitmap.width +
30 Math.round((x - origin.left + MARGIN) * scale)) *
31 4;
32 const at = (x: number, y: number) => Array.from(data.subarray(index(x, y), index(x, y) + 3));
33 const hasInk = (rect: DOMRect) => {
34 for (let y = rect.top; y < rect.bottom; y += 1 / scale) {
35 for (let x = rect.left; x < rect.right; x += 1 / scale) {
36 const pixel = at(x, y);
37 if (pixel.some((channel, i) => Math.abs(channel - BACKDROP[i]!) > 24)) return true;
38 }
39 }
40 return false;
41 };
42 return {
43 width: bitmap.width,
44 height: bitmap.height,
45 origin,
46 hasInk,
47 at,
48 cornerAlpha: data[data.length - 1]!,
49 };
50}
51
52/** Mounts a table over a known backdrop; disposing removes it. */
53function mountTable(cells: string, style = "") {
54 const host = document.createElement("div");
55 host.style.cssText = `background: rgb(${BACKDROP.join(",")}); color: white; padding: 40px; font: 14px/20px sans-serif;`;
56 host.innerHTML = `<table style="border-collapse: collapse; ${style}"><tbody>${cells}</tbody></table>`;
57 document.body.append(host);
58 return {
59 table: host.querySelector("table")!,
60 [Symbol.dispose]: () => host.remove(),
61 };
62}
63
64function textRects(element: Element): DOMRect[] {
65 const range = document.createRange();
66 range.selectNodeContents(element);
67 return [...range.getClientRects()];
68}
69
70describe("renderTablePng", () => {
71 it("draws the table at its layout size over the backdrop behind it", async () => {
72 using mounted = mountTable(
73 `<tr><td style="border-bottom: 2px solid rgb(255, 0, 0); padding: 8px">Name</td><td style="padding: 8px"></td></tr>`,
74 // A fractional height, so the canvas size is rounded.
75 "width: 300px; height: 40.6px",
76 );
77 const { table } = mounted;
78 const pixels = await readPng(await renderTablePng(table), table);
79 expect(pixels.width).toBe(Math.floor((pixels.origin.width + MARGIN * 2) * devicePixelRatio));
80 expect(pixels.height).toBe(Math.floor((pixels.origin.height + MARGIN * 2) * devicePixelRatio));
81 expect(pixels.cornerAlpha).toBe(255);
82
83 // The margin shows the backdrop, the rule keeps its color, and the empty cell stays empty.
84 expect(pixels.at(pixels.origin.left - MARGIN / 2, pixels.origin.top)).toEqual([...BACKDROP]);
85 const [nameCell, emptyCell] = table.querySelectorAll("td");
86 const name = nameCell!.getBoundingClientRect();
87 expect(pixels.at(name.left + name.width / 2, name.bottom - 1)).toEqual([255, 0, 0]);
88 expect(pixels.hasInk(textRects(nameCell!)[0]!)).toBe(true);
89 const empty = emptyCell!.getBoundingClientRect();
90 expect(pixels.hasInk(new DOMRect(empty.left, empty.top, empty.width, empty.height - 2))).toBe(
91 false,
92 );
93 });
94
95 it("draws every line of wrapped text where layout put it", async () => {
96 using mounted = mountTable(
97 `<tr><td style="width: 100px">alpha beta gamma delta epsilon zeta eta theta iota kappa</td><td style="padding-left: 24px">done</td></tr>`,
98 );
99 const { table } = mounted;
100 const pixels = await readPng(await renderTablePng(table), table);
101 const lines = textRects(table.querySelector("td")!);
102 expect(lines.length).toBeGreaterThan(2);
103 for (const line of lines) expect(pixels.hasInk(line)).toBe(true);
104 // Nothing spills into the gap after the wrapped column.
105 const done = table.querySelectorAll("td")[1]!.getBoundingClientRect();
106 expect(pixels.hasInk(new DOMRect(done.left, done.top, 20, done.height))).toBe(false);
107 });
108
109 it("cuts an overflowing chip with an ellipsis inside the chip", async () => {
110 using mounted = mountTable(
111 `<tr><td><span id="chip" style="display: inline-block; max-width: 80px; overflow-x: clip; text-overflow: ellipsis; white-space: nowrap">a-very-long-file-name.tsx</span></td><td style="padding-left: 60px">x</td></tr>`,
112 );
113 const { table } = mounted;
114 const pixels = await readPng(await renderTablePng(table), table);
115 const chipElement = document.getElementById("chip")!;
116 const chip = chipElement.getBoundingClientRect();
117 // Chromium reports the visible part of the cut text as its own, shorter rect.
118 const visibleRight = Math.min(...textRects(chipElement).map((rect) => rect.right));
119 expect(visibleRight).toBeLessThan(chip.right - 4);
120 const tail = (top: number, bottom: number) =>
121 new DOMRect(visibleRight + 1, top, chip.right - visibleRight - 1, bottom - top);
122 // After the last whole glyph only the ellipsis's dots remain: low on the line, not letters.
123 expect(pixels.hasInk(tail(chip.top, chip.top + chip.height * 0.45))).toBe(false);
124 expect(pixels.hasInk(tail(chip.top + chip.height * 0.45, chip.bottom))).toBe(true);
125 expect(pixels.hasInk(new DOMRect(chip.right, chip.top, 50, chip.height))).toBe(false);
126 });
127
128 it("clips a block's background to the box that hides its overflow", async () => {
129 using mounted = mountTable(
130 `<tr><td><div id="clip" style="width: 60px; overflow: hidden"><div style="width: 120px; height: 20px; background: rgb(255, 0, 0)"></div></div></td><td style="padding-left: 80px">x</td></tr>`,
131 );
132 const { table } = mounted;
133 const pixels = await readPng(await renderTablePng(table), table);
134 const clip = document.getElementById("clip")!.getBoundingClientRect();
135 expect(pixels.at(clip.left + 30, clip.top + 10)).toEqual([255, 0, 0]);
136 expect(pixels.hasInk(new DOMRect(clip.right + 1, clip.top, 50, clip.height))).toBe(false);
137 });
138
139 it("draws a sprite icon from the shared symbol it points at", async () => {
140 const sprite = document.createElementNS("http://www.w3.org/2000/svg", "svg");
141 sprite.style.display = "none";
142 sprite.innerHTML = `<symbol id="test-icon" viewBox="0 0 10 10"><rect width="10" height="10" fill="currentColor"/></symbol>`;
143 document.body.append(sprite);
144 using _sprite = { [Symbol.dispose]: () => sprite.remove() };
145 using mounted = mountTable(
146 `<tr><td><svg id="icon" width="20" height="20" style="color: rgb(0, 255, 0)"><use href="#test-icon"/></svg></td></tr>`,
147 );
148 const { table } = mounted;
149 const pixels = await readPng(await renderTablePng(table), table);
150 const icon = document.getElementById("icon")!.getBoundingClientRect();
151 expect(pixels.at(icon.left + 10, icon.top + 10)).toEqual([0, 255, 0]);
152 });
153
154 it("draws an image the page loaded from another origin without CORS", async () => {
155 // Another loopback name for the same server is another origin, as desktop's asset URLs are.
156 // The server listens on one of the two loopback addresses, depending on the machine.
157 const sources = ["127.0.0.1", "[::1]"].map((hostname) => {
158 const url = new URL("/favicon-32x32.png", location.href);
159 url.hostname = hostname;
160 return url.href;
161 });
162 using mounted = mountTable(`<tr><td><img id="image" width="32" height="32"></td></tr>`);
163 const { table } = mounted;
164 const image = document.getElementById("image") as HTMLImageElement;
165 for (const source of sources) {
166 image.src = source;
167 if (
168 await image.decode().then(
169 () => true,
170 () => false,
171 )
172 )
173 break;
174 }
175 const probe = new OffscreenCanvas(1, 1).getContext("2d")!;
176 probe.drawImage(image, 0, 0);
177 expect(() => probe.getImageData(0, 0, 1, 1)).toThrow();
178 const pixels = await readPng(await renderTablePng(table), table);
179 expect(pixels.hasInk(image.getBoundingClientRect())).toBe(true);
180 });
181
182 it("leaves visually hidden text out", async () => {
183 using mounted = mountTable(
184 `<tr><td id="cell" style="position: relative; width: 80px; height: 20px"><span style="position: absolute; inset: 0; clip-path: inset(50%)">hidden label</span></td></tr>`,
185 );
186 const { table } = mounted;
187 const pixels = await readPng(await renderTablePng(table), table);
188 expect(pixels.hasInk(document.getElementById("cell")!.getBoundingClientRect())).toBe(false);
189 });
190
191 it("draws checked, unchecked, fieldset-disabled, and light-accent checkboxes", async () => {
192 using mounted = mountTable(
193 `<tr><td><input id="done" type="checkbox" checked disabled></td><td><input id="todo" type="checkbox" disabled></td><td><fieldset disabled style="border: 0; padding: 0; margin: 0"><input id="grouped" type="checkbox" checked></fieldset></td><td><input id="light" type="checkbox" checked style="accent-color: white"></td></tr>`,
194 );
195 const { table } = mounted;
196 const pixels = await readPng(await renderTablePng(table), table);
197 const rect = (id: string) => document.getElementById(id)!.getBoundingClientRect();
198 const fill = (box: DOMRect) =>
199 pixels.at(box.left + box.width * 0.5, box.top + box.height * 0.25);
200 const done = rect("done");
201 const todo = rect("todo");
202 const light = rect("light");
203 expect(pixels.hasInk(done)).toBe(true);
204 expect(pixels.hasInk(todo)).toBe(true);
205 expect(fill(done)).not.toEqual(fill(todo));
206 expect(fill(rect("grouped"))).toEqual(fill(done));
207 expect(fill(light)).toEqual([255, 255, 255]);
208 const mark = [0.3, 0.4, 0.5, 0.6, 0.7].map(
209 (u) => pixels.at(light.left + light.width * u, light.top + light.height * 0.5)[0]!,
210 );
211 expect(Math.min(...mark)).toBeLessThan(128);
212 });
213});