| @@ -0,0 +1,231 @@ |
| 1 | +/** |
| 2 | + * Headless-Chromium smoke for the shipped timeline bundle: serves a page that |
| 3 | + * loads dist/timeline.js (no compiler, the consumer's path) and checks what |
| 4 | + * happy-dom cannot, the geometry: segments sit on their gridlines, shown labels |
| 5 | + * fit their segments, the tooltip stays inside its lane, the narrow layout puts |
| 6 | + * each track's label above its lane, and nothing overflows the page, at a |
| 7 | + * phone's width and a desktop's. |
| 8 | + * |
| 9 | + * Run: `bun examples/timeline-smoke.ts`. Exits non-zero on failure. Bun's |
| 10 | + * WebSocket speaks CDP to the playwright-pinned Chromium (tablet-smoke.ts's pattern). |
| 11 | + */ |
| 12 | +import { existsSync, readdirSync } from "node:fs"; |
| 13 | +import { spawn, spawnSync, type ChildProcess } from "node:child_process"; |
| 14 | + |
| 15 | +function chrome(): string { |
| 16 | + const cache = `${process.env.HOME}/.cache/ms-playwright`; |
| 17 | + const newest = readdirSync(cache).filter(dir => /^chromium-\d+$/.test(dir)).sort().pop(); |
| 18 | + if (newest === undefined) throw new Error(`no playwright chromium under ${cache}`); |
| 19 | + return `${cache}/${newest}/chrome-linux64/chrome`; |
| 20 | +} |
| 21 | + |
| 22 | +function bundle(): string { |
| 23 | + const path = `${import.meta.dir}/../dist/timeline.js`; |
| 24 | + if (!existsSync(path)) { |
| 25 | + const built = spawnSync("bun", ["run", "build"], { cwd: `${import.meta.dir}/..` }); |
| 26 | + if (built.status !== 0) throw new Error(`build failed:\n${built.stderr.toString()}`); |
| 27 | + } |
| 28 | + return path; |
| 29 | +} |
| 30 | + |
| 31 | +const PAGE = `<!doctype html> |
| 32 | +<html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1"></head> |
| 33 | +<body style="margin: 0; padding: 16px; font-family: system-ui"> |
| 34 | +<pebble-timeline min="-14" max="105" step="14" per="7" unit="wk" axis="Weeks from taking the cutting"> |
| 35 | + <table> |
| 36 | + <caption>Two schedules</caption> |
| 37 | + <thead><tr><th>Method</th><th>Phase</th><th>Starts (day)</th><th>Days</th><th>Source</th></tr></thead> |
| 38 | + <tbody> |
| 39 | + <tr><th>Standard topping</th><td>Rooting</td><td>0</td><td>10</td><td>Fig. 2</td></tr> |
| 40 | + <tr data-series="2"><th>Standard topping</th><td>Vegetative growth</td><td>10</td><td>14</td><td>Fig. 2</td></tr> |
| 41 | + <tr data-series="2" data-texture="hatch"><th>Standard topping</th><td>Recovery (extra vegetative growth)</td><td>24</td><td>14</td><td>Fig. 2</td></tr> |
| 42 | + <tr data-series="3"><th>Standard topping</th><td>Flowering</td><td>38</td><td>56</td><td>Fig. 2</td></tr> |
| 43 | + <tr data-series="muted"><th>Early topping</th><td>Mother-plant wait</td><td>−14</td><td>14</td><td>Fig. 2</td></tr> |
| 44 | + <tr><th>Early topping</th><td>Rooting</td><td>0</td><td>10</td><td>Fig. 2</td></tr> |
| 45 | + <tr data-series="2"><th>Early topping</th><td>Vegetative growth</td><td>10</td><td>14</td><td>Fig. 2</td></tr> |
| 46 | + <tr data-series="3"><th>Early topping</th><td>Flowering</td><td>24</td><td>56</td><td>Fig. 2</td></tr> |
| 47 | + </tbody> |
| 48 | + </table> |
| 49 | +</pebble-timeline> |
| 50 | +<script type="module" src="/timeline.js"></script> |
| 51 | +</body></html>`; |
| 52 | + |
| 53 | +/** Everything the checks need, measured in the page in one go. */ |
| 54 | +const MEASURE = `(() => { |
| 55 | + const el = document.querySelector("pebble-timeline"); |
| 56 | + const r = n => { const b = n.getBoundingClientRect(); return { left: b.left, right: b.right, top: b.top, bottom: b.bottom, width: b.width }; }; |
| 57 | + const lanes = [...el.querySelectorAll(".lane")].map(r); |
| 58 | + return { |
| 59 | + enhanced: el.hasAttribute("data-enhanced"), |
| 60 | + table: r(el.querySelector("table")), |
| 61 | + lanes, |
| 62 | + labels: [...el.querySelectorAll(".track-label")].map(r), |
| 63 | + baseline: r(el.querySelector(".gridline[data-baseline]") ?? el), |
| 64 | + gridShown: getComputedStyle(el.querySelector(".grid")).display !== "none", |
| 65 | + segments: [...el.querySelectorAll(".segment")].map(s => ({ |
| 66 | + ...r(s), |
| 67 | + start: Number(s.style.getPropertyValue("--start")), |
| 68 | + size: Number(s.style.getPropertyValue("--size")), |
| 69 | + last: s.hasAttribute("data-last"), |
| 70 | + unlabelled: s.hasAttribute("data-unlabelled"), |
| 71 | + labelFits: s.querySelector(".segment-label").scrollWidth <= s.querySelector(".segment-label").clientWidth + 0.5, |
| 72 | + })), |
| 73 | + overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth, |
| 74 | + }; |
| 75 | +})()`; |
| 76 | + |
| 77 | +class Cdp { |
| 78 | + private next = 0; |
| 79 | + private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: unknown) => void }>(); |
| 80 | + private session = ""; |
| 81 | + private constructor(private ws: WebSocket) { |
| 82 | + ws.onmessage = message => { |
| 83 | + const data = JSON.parse(String(message.data)); |
| 84 | + const entry = data.id === undefined ? undefined : this.pending.get(data.id); |
| 85 | + if (entry) { |
| 86 | + this.pending.delete(data.id); |
| 87 | + data.error ? entry.reject(new Error(data.error.message)) : entry.resolve(data.result); |
| 88 | + } |
| 89 | + }; |
| 90 | + } |
| 91 | + static async connect(process: ChildProcess): Promise<Cdp> { |
| 92 | + const endpoint = await new Promise<string>((resolve, reject) => { |
| 93 | + let buffer = ""; |
| 94 | + process.stderr!.on("data", (chunk: Buffer) => { |
| 95 | + buffer += chunk.toString(); |
| 96 | + const match = buffer.match(/DevTools listening on (ws:\/\/\S+)/); |
| 97 | + if (match) resolve(match[1]!); |
| 98 | + }); |
| 99 | + setTimeout(() => reject(new Error(`chromium never printed its DevTools endpoint: ${buffer}`)), 15000); |
| 100 | + }); |
| 101 | + const ws = new WebSocket(endpoint); |
| 102 | + await new Promise<void>((resolve, reject) => { |
| 103 | + ws.onopen = () => resolve(); |
| 104 | + ws.onerror = event => reject(new Error(`CDP websocket failed: ${event}`)); |
| 105 | + }); |
| 106 | + return new Cdp(ws); |
| 107 | + } |
| 108 | + private raw<T>(method: string, params: Record<string, unknown>, sessionId?: string): Promise<T> { |
| 109 | + const id = (this.next += 1); |
| 110 | + return new Promise<T>((resolve, reject) => { |
| 111 | + this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject }); |
| 112 | + this.ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })); |
| 113 | + }); |
| 114 | + } |
| 115 | + call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> { |
| 116 | + return this.raw<T>(method, params, this.session); |
| 117 | + } |
| 118 | + async attach(url: string): Promise<void> { |
| 119 | + const { targetId } = await this.raw<{ targetId: string }>("Target.createTarget", { url }); |
| 120 | + const { sessionId } = await this.raw<{ sessionId: string }>("Target.attachToTarget", { targetId, flatten: true }); |
| 121 | + this.session = sessionId; |
| 122 | + await this.call("Runtime.enable"); |
| 123 | + } |
| 124 | + async eval<T = unknown>(expression: string): Promise<T> { |
| 125 | + const result = await this.call<{ result: { value: T }; exceptionDetails?: { text: string } }>("Runtime.evaluate", { |
| 126 | + expression, |
| 127 | + returnByValue: true, |
| 128 | + awaitPromise: true, |
| 129 | + }); |
| 130 | + if (result.exceptionDetails) throw new Error(`page threw: ${result.exceptionDetails.text}`); |
| 131 | + return result.result.value; |
| 132 | + } |
| 133 | + close(): void { |
| 134 | + this.ws.close(); |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +type Rect = { left: number; right: number; top: number; bottom: number; width: number }; |
| 139 | +type Measure = { |
| 140 | + enhanced: boolean; |
| 141 | + table: Rect; |
| 142 | + lanes: Rect[]; |
| 143 | + labels: Rect[]; |
| 144 | + baseline: Rect; |
| 145 | + gridShown: boolean; |
| 146 | + segments: Array<Rect & { start: number; size: number; last: boolean; unlabelled: boolean; labelFits: boolean }>; |
| 147 | + overflow: number; |
| 148 | +}; |
| 149 | + |
| 150 | +const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); |
| 151 | +const checks: Array<[string, boolean, string?]> = []; |
| 152 | +const check = (name: string, ok: boolean, extra?: string) => checks.push([name, ok, extra]); |
| 153 | +const near = (a: number, b: number, tolerance = 1) => Math.abs(a - b) <= tolerance; |
| 154 | + |
| 155 | +const server = Bun.serve({ |
| 156 | + port: 0, |
| 157 | + fetch(request) { |
| 158 | + if (new URL(request.url).pathname === "/timeline.js") return new Response(Bun.file(bundle()), { headers: { "content-type": "text/javascript" } }); |
| 159 | + return new Response(PAGE, { headers: { "content-type": "text/html" } }); |
| 160 | + }, |
| 161 | +}); |
| 162 | +const chromium = spawn(chrome(), ["--headless=new", "--disable-gpu", "--no-sandbox", "--remote-debugging-port=0", "about:blank"], { |
| 163 | + stdio: ["ignore", "ignore", "pipe"], |
| 164 | +}); |
| 165 | + |
| 166 | +try { |
| 167 | + const cdp = await Cdp.connect(chromium); |
| 168 | + await cdp.attach("about:blank"); |
| 169 | + for (const width of [390, 1280]) { |
| 170 | + await cdp.call("Emulation.setDeviceMetricsOverride", { width, height: 800, deviceScaleFactor: 1, mobile: width < 600 }); |
| 171 | + await cdp.call("Page.navigate", { url: `http://localhost:${server.port}/` }); |
| 172 | + let ready = false; |
| 173 | + for (let attempt = 0; attempt < 50 && !ready; attempt++) { |
| 174 | + try { |
| 175 | + ready = (await cdp.eval(`customElements.whenDefined("pebble-timeline").then(() => !!document.querySelector("pebble-timeline .segment"))`)) === true; |
| 176 | + } catch { |
| 177 | + await sleep(100); // the navigation replaced the execution context |
| 178 | + } |
| 179 | + } |
| 180 | + if (!ready) throw new Error(`${width}px: the timeline never drew`); |
| 181 | + await sleep(100); // the label fit runs on the next animation frame |
| 182 | + |
| 183 | + const m = await cdp.eval<Measure>(MEASURE); |
| 184 | + const at = `${width}px`; |
| 185 | + // Visually hidden: the scaled table is a few pixels, clipped to nothing (timeline.css). |
| 186 | + check(`${at} enhanced, table visually hidden`, m.enhanced && m.table.width < 8, `table ${m.table.width}px`); |
| 187 | + check(`${at} no horizontal overflow`, m.overflow <= 0, `${m.overflow}px`); |
| 188 | + |
| 189 | + // Each segment starts where its fraction of the lane says, and the gap is 2px. |
| 190 | + const lane = m.lanes[0]!; |
| 191 | + const misplaced = m.segments.filter(s => !near(s.left, lane.left + s.start * lane.width)); |
| 192 | + check(`${at} segments start on their place`, misplaced.length === 0, JSON.stringify(misplaced.map(s => s.left))); |
| 193 | + const wrongWidth = m.segments.filter(s => !near(s.width, s.size * lane.width - (s.last ? 0 : 2))); |
| 194 | + check(`${at} segments end 2px short of the next`, wrongWidth.length === 0, JSON.stringify(wrongWidth.map(s => s.width))); |
| 195 | + // Rooting starts at day 0: on the baseline gridline, where gridlines show. |
| 196 | + if (m.gridShown) check(`${at} day 0 sits on the baseline gridline`, near(m.segments[0]!.left, m.baseline.left), `${m.segments[0]!.left} vs ${m.baseline.left}`); |
| 197 | + else check(`${at} narrow: track labels sit above their lanes`, m.labels.every((label, i) => label.bottom <= m.lanes[i]!.top + 0.5)); |
| 198 | + |
| 199 | + check(`${at} every shown label fits its segment`, m.segments.every(s => s.unlabelled || s.labelFits)); |
| 200 | + check(`${at} some labels show`, m.segments.some(s => !s.unlabelled)); |
| 201 | + |
| 202 | + // The tooltip of the first and the last segment stays inside the lane. |
| 203 | + for (const key of ["Home", "End"]) { |
| 204 | + await cdp.eval(`(() => { const plot = document.querySelector(".plot"); plot.focus(); |
| 205 | + plot.dispatchEvent(new KeyboardEvent("keydown", { key: "${key}", bubbles: true, cancelable: true })); })()`); |
| 206 | + await sleep(30); |
| 207 | + const tip = await cdp.eval<Rect & { open: boolean }>(`(() => { const t = document.querySelector(".tooltip"); |
| 208 | + const b = t.getBoundingClientRect(); return { left: b.left, right: b.right, top: b.top, bottom: b.bottom, width: b.width, open: t.hasAttribute("data-open") }; })()`); |
| 209 | + const laneOfTip = key === "Home" ? m.lanes[0]! : m.lanes[m.lanes.length - 1]!; |
| 210 | + check( |
| 211 | + `${at} ${key}: tooltip open, inside its lane, above it`, |
| 212 | + tip.open && tip.left >= laneOfTip.left - 1 && tip.right <= laneOfTip.right + 1 && tip.bottom <= laneOfTip.top + 1, |
| 213 | + JSON.stringify({ tip, lane: laneOfTip }), |
| 214 | + ); |
| 215 | + } |
| 216 | + } |
| 217 | + cdp.close(); |
| 218 | +} finally { |
| 219 | + chromium.kill(); |
| 220 | + server.stop(true); |
| 221 | +} |
| 222 | + |
| 223 | +let failed = 0; |
| 224 | +for (const [name, ok, extra] of checks) { |
| 225 | + console.log(`${ok ? "ok " : "FAIL"} ${name}${!ok && extra ? ` ${extra}` : ""}`); |
| 226 | + if (!ok) failed++; |
| 227 | +} |
| 228 | +if (failed > 0) { |
| 229 | + console.log(`\n${failed} check(s) failed`); |
| 230 | + process.exit(1); |
| 231 | +} |