Files
loki/scripts/preview/render-harness.mjs
CatoandClaude d88cab3923 feat(notifications): turn this phone's push on, prove it, turn it off (#1212)
Production held ZERO subscribed push devices (the messaging doctor,
2026-10-15): the server could send a push, the VAPID keys and the service
worker were in place, and no screen anywhere offered a phone the choice —
usePushSubscription was imported by nothing. A new report on a site
reached no device, and said so only in a log line.

- Settings → Notifications gets an "On this phone" card: Turn on, Send a
  test, Turn off, with a plain sentence for every state (not asked,
  working, on, blocked by the browser, unsupported — with the iPhone
  Add-to-Home-Screen fix — error with retry, server has no key).
  Pure view logic (lib/push-card.ts) is pinned by scripts/test/push-card.ts;
  copy is SSOT in config/comms.ts.
- GET /api/push/public-key hands out the server's own VAPID_PUBLIC_KEY, so
  a phone no longer subscribes against a key inlined at build time that a
  build can lose or leave stale; POST /api/push/test sends one test push
  and names the failed precondition instead of a bare zero.
- The page-render harness is now a shared core (render-harness.mjs) with a
  thin script per page; the push card has one, and rendering it is how a
  filled button 8px shorter than its neighbour, and under 44px, was caught
  and fixed.


Claude-Session: https://claude.ai/code/session_01NJJp6XiUkeEVzjDaBmWjL3

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-15 05:21:22 -07:00

117 lines
5.2 KiB
JavaScript

// The shared core of the page-render harnesses (REVIEW.md → "Definition of done
// for a page"): bundle a real component with esbuild, compile globals.css
// through @tailwindcss/postcss, load it in headless Chromium at phone and
// desktop widths in dark and light, and FAIL on horizontal overflow or a
// console error. Screenshots land in .tmp/<name>/ for a person to look at —
// this tool can see broken, never ugly.
//
// Each page has a thin script that calls renderPreview() with its entry file
// and the variants (URL queries) worth looking at. No database, no session, no
// dev server: the entry mocks `fetch` itself.
import { build } from "esbuild";
import { createRequire } from "node:module";
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { chromium } from "playwright";
const require = createRequire(import.meta.url);
const postcss = require(
require.resolve("postcss", { paths: [require.resolve("@tailwindcss/postcss")] }),
);
import tailwind from "@tailwindcss/postcss";
const here = dirname(fileURLToPath(import.meta.url));
const root = resolve(here, "../..");
const FONT_VARS =
':root{--font-geist-sans:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;--font-geist-mono:ui-monospace,SFMono-Regular,Menlo,monospace}';
/**
* @param {{ entry: string, name: string, queries?: string[], outDir?: string,
* pageClass?: string }} opts
* entry — path of the preview entry (relative to scripts/preview or absolute)
* name — output folder under .tmp/ and the label in the log
* queries — URL queries to visit, "" for none
*/
export async function renderPreview({ entry, name, queries = [""], outDir }) {
const out = resolve(outDir ?? resolve(root, ".tmp", name));
mkdirSync(out, { recursive: true });
await build({
entryPoints: [resolve(here, entry)],
bundle: true,
format: "iife",
outfile: resolve(out, "preview.js"),
jsx: "automatic",
tsconfig: resolve(root, "tsconfig.json"),
alias: {
"next/link": resolve(here, "shims/next-link.tsx"),
"next/navigation": resolve(here, "shims/next-navigation.ts"),
},
define: { "process.env.NODE_ENV": '"development"' },
// Shared config modules read process.env at import time; the browser has no
// `process`, so give the bundle an empty one rather than patch app code.
banner: { js: "window.process = window.process || { env: { NODE_ENV: 'development' } };" },
logLevel: "warning",
});
const cssIn = resolve(root, "src/app/globals.css");
// A package's stylesheet that is not installed here (a git dependency this
// sandbox cannot fetch) must not stop a LAYOUT check of this repo's own
// components: skip that one @import, loudly, and render with the rest.
let cssText = readFileSync(cssIn, "utf8");
cssText = cssText.replace(/^@import\s+["']([^"'.][^"']*)["'][^;]*;\s*$/gm, (line, spec) => {
const parts = spec.split("/");
const pkg = spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
if (existsSync(resolve(root, "node_modules", pkg))) return line;
console.warn(`harness: skipping @import "${spec}" (not installed here); its styles are absent`);
return "";
});
const css = await postcss([tailwind({ base: root })]).process(cssText, {
from: cssIn,
to: resolve(out, "app.css"),
});
writeFileSync(resolve(out, "app.css"), css.css);
for (const theme of ["dark", "light"]) {
writeFileSync(
resolve(out, `index-${theme}.html`),
`<!doctype html><html lang="en" class="${theme}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="app.css"><style>${FONT_VARS}</style></head><body><div id="root"></div><script src="preview.js"></script></body></html>`,
);
}
const browser = await chromium.launch();
const problems = [];
for (const theme of ["dark", "light"]) {
for (const [vp, width, height] of [
["phone", 390, 844],
["desktop", 1280, 900],
]) {
for (const query of queries) {
const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 2 });
const errors = [];
page.on("console", (m) => m.type() === "error" && errors.push(m.text()));
page.on("pageerror", (e) => errors.push(String(e)));
await page.goto(pathToFileURL(resolve(out, `index-${theme}.html`)).href + query);
await page.waitForTimeout(1200);
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - window.innerWidth,
);
const tag = `${theme}-${vp}${query ? "-" + query.replace(/[^a-z0-9]+/gi, "_") : ""}`;
await page.screenshot({ path: resolve(out, `${tag}.png`), fullPage: true });
if (overflow > 0) problems.push(`${tag}: horizontal overflow ${overflow}px`);
for (const e of errors) problems.push(`${tag}: console error: ${e.slice(0, 200)}`);
console.log(`${tag}: overflow=${overflow}px errors=${errors.length}`);
await page.close();
}
}
}
await browser.close();
if (problems.length) {
console.error(problems.join("\n"));
process.exit(1);
}
console.log(`ok → ${out}`);
}