@mccaskie-labs/workbench-ui 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @mccaskie-labs/workbench-ui
2
2
 
3
+ ## 0.15.0
4
+
5
+ ### Minor Changes
6
+
7
+ - The visual change check (docs/look-studio.md §9.7, step 8). `npx workbench-ui visual capture --url <address> --out <folder>` photographs the project running locally: the home page, each public page in `workbench/site.json`, and the style guide (every installed tool's samples) in light and dark, each at a phone's width (390) and a desktop's (1280). `npx workbench-ui visual compare <before> <after> --out <folder> [--kind tool-update|look-change]` compares the pictures in a browser, writes a difference picture for each (changed pixels in red) and `summary.json`, and adds a table to the run's summary. A tool update that moves more than 1% of any picture fails the command, so the project's check fails and Control's merge gate leaves the update for the owner; a look change is never held. Playwright isn't a dependency: the caller installs it and names its folder in `PLAYWRIGHT_DIR`.
8
+
3
9
  ## 0.14.0
4
10
 
5
11
  ### Minor Changes
package/dist/cli.js CHANGED
@@ -18,17 +18,18 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
18
18
  }
19
19
  return path;
20
20
  };
21
- import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
21
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
22
22
  import { createRequire } from "node:module";
23
23
  import { dirname, join, relative, resolve } from "node:path";
24
24
  import { fileURLToPath, pathToFileURL } from "node:url";
25
25
  import { UI_STYLES } from "./ui-styles.js";
26
26
  import { DESIGN_FILE, designModeFile } from "./design-mode.js";
27
+ import { capture, compare, installedSamples, visualMarkdown } from "./visual.js";
27
28
  import { libraryProblems, PREVIEW_FILE, previewFamilies, renderLooks, renderSchemes, resolveSiteLayout, renderTheme, resolveAdminTheme, resolveTheme, themeFixes, themeInput, themeProblems } from "./theme.js";
28
29
  import { familiesIn, fontGaps, projectFonts } from "./fonts.js";
29
30
  import { findItem, itemProblems, LIBRARY, withProjectItems } from "./library.js";
30
31
  import { DEFAULT_THEME_CSS, renderStyles, STYLE_FILES, STYLED_SCOPE, starterProjectCss, unknownMarkupNames, unknownNames } from "./styles.js";
31
- const USAGE = "usage: workbench-ui styles [--check | --fix] [dir]";
32
+ const USAGE = "usage: workbench-ui styles [--check | --fix] [dir]\n workbench-ui visual capture --url <address> --out <folder> [dir]\n workbench-ui visual compare <before> <after> --out <folder> [--kind tool-update|look-change]";
32
33
  const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
33
34
  /** The styles of each Workbench tool the project at `dir` has installed, and the workbench-ui version. */
34
35
  export async function installedStyles(dir) {
@@ -308,8 +309,51 @@ export function planStyles(dir, tools, uiVersion) {
308
309
  }
309
310
  return { files, problems, notes: fontGaps(theme.families) };
310
311
  }
312
+ /** `visual capture` and `visual compare` (docs/look-studio.md §9.7): the pictures for the visual change check. */
313
+ async function visualCommand(args) {
314
+ const [sub, ...rest] = args;
315
+ const flag = (name) => {
316
+ const i = rest.indexOf(name);
317
+ if (i < 0)
318
+ return undefined;
319
+ const v = rest[i + 1];
320
+ rest.splice(i, 2);
321
+ return v;
322
+ };
323
+ const out = flag("--out");
324
+ if (sub === "capture") {
325
+ const url = flag("--url");
326
+ if (!out || !url || rest.length > 1 || rest.some((a) => a.startsWith("-"))) {
327
+ console.error(USAGE);
328
+ return 2;
329
+ }
330
+ const dir = resolve(rest[0] ?? ".");
331
+ const samples = await installedSamples(dir, samplePackages(dir));
332
+ const files = await capture(dir, url, resolve(out), samples);
333
+ console.log(`✓ ${files.length} pictures in ${out}`);
334
+ return 0;
335
+ }
336
+ if (sub === "compare") {
337
+ const kind = flag("--kind") ?? "look-change";
338
+ if (!out || rest.length !== 2 || (kind !== "tool-update" && kind !== "look-change")) {
339
+ console.error(USAGE);
340
+ return 2;
341
+ }
342
+ const summary = await compare(resolve(rest[0]), resolve(rest[1]), resolve(out), kind);
343
+ const text = visualMarkdown(summary);
344
+ console.log(text);
345
+ if (process.env.GITHUB_STEP_SUMMARY)
346
+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, text);
347
+ // A held tool update fails the check, which stops Control's merge gate.
348
+ return summary.held ? 1 : 0;
349
+ }
350
+ console.error(USAGE);
351
+ return 2;
352
+ }
311
353
  async function main(argv) {
312
354
  const [command, ...rest] = argv;
355
+ if (command === "visual")
356
+ return visualCommand(rest);
313
357
  if (command !== "styles") {
314
358
  console.error(USAGE);
315
359
  return 2;
@@ -0,0 +1,43 @@
1
+ import type { ToolSamples } from "./samples.ts";
2
+ /** A tool update that moves more than this share of any picture is held for the owner (Proposed: 1%). */
3
+ export declare const HOLD = 0.01;
4
+ /** The widths each page is photographed at: a phone and a desktop. */
5
+ export declare const WIDTHS: {
6
+ readonly phone: 390;
7
+ readonly desktop: 1280;
8
+ };
9
+ /** One picture capture takes: a name for the file, and the address on the project. */
10
+ export interface Shot {
11
+ name: string;
12
+ path: string;
13
+ width: number;
14
+ }
15
+ /** The public pages to photograph: the home page, then each public page in workbench/site.json. */
16
+ export declare function visualPages(dir: string): string[];
17
+ /** Every picture capture takes, in order. */
18
+ export declare function visualShots(pages: readonly string[]): Shot[];
19
+ /** Every installed tool's samples, read from the project's own node_modules. */
20
+ export declare function installedSamples(dir: string, packages: readonly string[]): Promise<ToolSamples[]>;
21
+ /** Photographs each shot of the project running at `url` into `out`. */
22
+ export declare function capture(dir: string, url: string, out: string, samples: readonly ToolSamples[]): Promise<string[]>;
23
+ /** One picture's result. */
24
+ export interface VisualResult {
25
+ name: string;
26
+ /** The share of the picture that changed, 0 to 1; 1 for a picture only one side has. */
27
+ changed: number;
28
+ }
29
+ export interface VisualSummary {
30
+ format: 1;
31
+ kind: "tool-update" | "look-change";
32
+ results: VisualResult[];
33
+ /** The most any one picture changed. */
34
+ most: number;
35
+ /** A tool update that moved more than HOLD of a picture: the check fails, so Control leaves it for the owner. */
36
+ held: boolean;
37
+ }
38
+ /** The summary of a comparison: held only for a tool update. */
39
+ export declare function visualSummary(kind: VisualSummary["kind"], results: readonly VisualResult[]): VisualSummary;
40
+ /** The step summary a person reads on the run: the pictures that changed, most first. */
41
+ export declare function visualMarkdown(s: VisualSummary): string;
42
+ /** Compares each picture in `before` with the same one in `after`, writes the difference pictures and summary.json into `out`. */
43
+ export declare function compare(before: string, after: string, out: string, kind: VisualSummary["kind"]): Promise<VisualSummary>;
package/dist/visual.js ADDED
@@ -0,0 +1,202 @@
1
+ // The visual change check (docs/look-studio.md §9.7): pictures of a project's
2
+ // pages before and after a change, and how much of each moved. Run in the
3
+ // project's own Checks on GitHub's runners (its .github/workflows/visual-check.yml),
4
+ // against the project running locally with no secrets:
5
+ //
6
+ // npx workbench-ui visual capture --url http://127.0.0.1:8787 --out shots/after [dir]
7
+ // npx workbench-ui visual compare shots/before shots/after --out shots/diff [--kind tool-update|look-change]
8
+ //
9
+ // capture photographs the home page, each public page in workbench/site.json
10
+ // and the style guide (every installed tool's samples, light and dark), at a
11
+ // phone's and a desktop's width. compare writes a difference picture for each
12
+ // and summary.json: the share of each picture that changed, and, for a tool
13
+ // update, whether it moved more than HOLD of any page. A held update fails
14
+ // the check, so Control's merge gate leaves it for the owner. A look change is meant to change
15
+ // things, so it is never held. Playwright isn't a dependency: the workflow
16
+ // installs it and names its folder in PLAYWRIGHT_DIR.
17
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
18
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
19
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
20
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
21
+ });
22
+ }
23
+ return path;
24
+ };
25
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
26
+ import { createRequire } from "node:module";
27
+ import { join, resolve } from "node:path";
28
+ import { pathToFileURL } from "node:url";
29
+ import { styleGuide } from "./style-guide.js";
30
+ import { STYLESHEETS } from "./styles.js";
31
+ /** A tool update that moves more than this share of any picture is held for the owner (Proposed: 1%). */
32
+ export const HOLD = 0.01;
33
+ /** The widths each page is photographed at: a phone and a desktop. */
34
+ export const WIDTHS = { phone: 390, desktop: 1280 };
35
+ /** A channel may differ by this much (of 255) before the pixel counts as changed: font smoothing, not a change. */
36
+ const TOLERANCE = 24;
37
+ const GUIDE_SHEET = "/styles/style-guide.css";
38
+ // Where capture shows its own style guide page: answered by capture itself, never by the project.
39
+ const GUIDE_PATH = "/__workbench-visual/style-guide";
40
+ /** The public pages to photograph: the home page, then each public page in workbench/site.json. */
41
+ export function visualPages(dir) {
42
+ const out = ["/"];
43
+ const file = join(dir, "workbench", "site.json");
44
+ if (existsSync(file)) {
45
+ const site = JSON.parse(readFileSync(file, "utf8"));
46
+ for (const p of site.pages ?? [])
47
+ if (p.access === "public" && p.path && /^\/[A-Za-z0-9/_.-]*$/.test(p.path) && !out.includes(p.path))
48
+ out.push(p.path);
49
+ }
50
+ return out;
51
+ }
52
+ /** Every picture capture takes, in order. */
53
+ export function visualShots(pages) {
54
+ const slug = (p) => (p === "/" ? "home" : p.replace(/^\//, "").replace(/[^A-Za-z0-9]+/g, "-").toLowerCase());
55
+ const shots = [];
56
+ for (const [label, width] of Object.entries(WIDTHS)) {
57
+ for (const p of pages)
58
+ shots.push({ name: `${slug(p)}-${label}`, path: p, width });
59
+ for (const view of ["light", "dark"])
60
+ shots.push({ name: `style-guide-${view}-${label}`, path: `${GUIDE_PATH}?view=${view}`, width });
61
+ }
62
+ return shots;
63
+ }
64
+ /** The style guide page capture shows: every installed tool's samples in the project's look, as the site's own page draws them. */
65
+ function visualGuide(samples, view) {
66
+ const sheets = [...STYLESHEETS, GUIDE_SHEET].map((h) => `<link rel="stylesheet" href="${h}">`).join("");
67
+ return `<!doctype html><html lang="en" class="wb-site" data-wb-scheme="${view}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Style guide</title>${sheets}</head><body class="wb-site-body"><main class="wb-site-main" data-frame="column">${styleGuide(samples, { view })}</main></body></html>`;
68
+ }
69
+ /** Every installed tool's samples, read from the project's own node_modules. */
70
+ export async function installedSamples(dir, packages) {
71
+ const req = createRequire(join(dir, "package.json"));
72
+ const out = [];
73
+ for (const name of packages) {
74
+ const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(req.resolve(`${name}/samples`)).href)));
75
+ for (const x of Object.values(mod))
76
+ if (x && typeof x === "object" && x.format === 1 && Array.isArray(x.samples))
77
+ out.push(x);
78
+ }
79
+ return out;
80
+ }
81
+ /** Playwright's Chromium, from the folder the workflow installed it in. */
82
+ async function chromium() {
83
+ const from = process.env.PLAYWRIGHT_DIR ? resolve(process.env.PLAYWRIGHT_DIR, "package.json") : join(process.cwd(), "package.json");
84
+ const at = createRequire(from).resolve("playwright");
85
+ const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(at).href)));
86
+ return mod.chromium ?? mod.default.chromium;
87
+ }
88
+ /** Photographs each shot of the project running at `url` into `out`. */
89
+ export async function capture(dir, url, out, samples) {
90
+ mkdirSync(out, { recursive: true });
91
+ const base = new URL(url);
92
+ const browser = await (await chromium()).launch();
93
+ const written = [];
94
+ try {
95
+ for (const shot of visualShots(visualPages(dir))) {
96
+ const page = await browser.newPage({ viewport: { width: shot.width, height: 900 } });
97
+ await page.route(`${base.origin}${GUIDE_PATH}*`, async (route) => {
98
+ const view = new URL(shot.path, base).searchParams.get("view") === "dark" ? "dark" : "light";
99
+ await route.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: visualGuide(samples, view) });
100
+ });
101
+ await page.goto(new URL(shot.path, base).href, { waitUntil: "networkidle" });
102
+ // Runs in the page: wait for the hosted fonts.
103
+ await page.evaluate("document.fonts.ready.then(() => undefined)");
104
+ const file = join(out, `${shot.name}.png`);
105
+ await page.screenshot({ path: file, fullPage: true, animations: "disabled" });
106
+ written.push(file);
107
+ await page.close();
108
+ }
109
+ }
110
+ finally {
111
+ await browser.close();
112
+ }
113
+ return written;
114
+ }
115
+ /** The summary of a comparison: held only for a tool update. */
116
+ export function visualSummary(kind, results) {
117
+ const most = results.reduce((m, r) => Math.max(m, r.changed), 0);
118
+ return { format: 1, kind, results: [...results].sort((a, b) => (a.name < b.name ? -1 : 1)), most, held: kind === "tool-update" && most > HOLD };
119
+ }
120
+ /** The step summary a person reads on the run: the pictures that changed, most first. */
121
+ export function visualMarkdown(s) {
122
+ const pct = (n) => `${(n * 100).toFixed(2)}%`;
123
+ const moved = s.results.filter((r) => r.changed > 0).sort((a, b) => b.changed - a.changed);
124
+ const head = s.held
125
+ ? `**Held for the owner:** this tool update moves ${pct(s.most)} of a page, more than ${pct(HOLD)}, so this check fails and Workbench Control won't merge it on its own. Look at the pictures, then merge the update or close it.`
126
+ : s.kind === "tool-update"
127
+ ? `This tool update changes no page by more than ${pct(HOLD)}.`
128
+ : "A look change: the pictures are for looking at, and nothing is held.";
129
+ const rows = moved.length ? ["", "| Picture | Changed |", "| --- | --- |", ...moved.map((r) => `| ${r.name} | ${pct(r.changed)} |`)] : ["", "No picture changed."];
130
+ return ["## Before and after", "", head, ...rows, "", "The before, after and difference pictures are in this run's artifacts.", ""].join("\n");
131
+ }
132
+ /** Compares each picture in `before` with the same one in `after`, writes the difference pictures and summary.json into `out`. */
133
+ export async function compare(before, after, out, kind) {
134
+ mkdirSync(out, { recursive: true });
135
+ const names = [...new Set([...readdirSync(before), ...readdirSync(after)].filter((f) => f.endsWith(".png")))].sort();
136
+ const browser = await (await chromium()).launch();
137
+ const results = [];
138
+ try {
139
+ const page = await browser.newPage();
140
+ await page.setContent("<!doctype html><title>compare</title>");
141
+ for (const name of names) {
142
+ const a = existsSync(join(before, name)) ? readFileSync(join(before, name)).toString("base64") : null;
143
+ const b = existsSync(join(after, name)) ? readFileSync(join(after, name)).toString("base64") : null;
144
+ if (!a || !b) {
145
+ results.push({ name: name.replace(/\.png$/, ""), changed: 1 });
146
+ continue;
147
+ }
148
+ const r = (await page.evaluate(`(${DIFF_IN_PAGE})(${JSON.stringify({ a, b, tolerance: TOLERANCE })})`));
149
+ writeFileSync(join(out, name), Buffer.from(r.diff, "base64"));
150
+ results.push({ name: name.replace(/\.png$/, ""), changed: r.changed });
151
+ }
152
+ }
153
+ finally {
154
+ await browser.close();
155
+ }
156
+ const summary = visualSummary(kind, results);
157
+ writeFileSync(join(out, "summary.json"), `${JSON.stringify(summary, null, 2)}\n`);
158
+ return summary;
159
+ }
160
+ // Runs in the browser. Kept as text so a bundler's helpers (tsx adds __name) never reach the page.
161
+ const DIFF_IN_PAGE = `async ({ a, b, tolerance }) => {
162
+ const load = (src) =>
163
+ new Promise((ok, no) => {
164
+ const img = new Image();
165
+ img.onload = () => ok(img);
166
+ img.onerror = () => no(new Error("not a picture"));
167
+ img.src = "data:image/png;base64," + src;
168
+ });
169
+ const [x, y] = await Promise.all([load(a), load(b)]);
170
+ const w = Math.max(x.width, y.width);
171
+ const h = Math.max(x.height, y.height);
172
+ const canvas = () => {
173
+ const c = document.createElement("canvas");
174
+ c.width = w;
175
+ c.height = h;
176
+ return c;
177
+ };
178
+ const pixels = (img) => {
179
+ const g = canvas().getContext("2d");
180
+ g.drawImage(img, 0, 0);
181
+ return g.getImageData(0, 0, w, h).data;
182
+ };
183
+ const p = pixels(x);
184
+ const q = pixels(y);
185
+ const c = canvas();
186
+ const g = c.getContext("2d");
187
+ const out = g.createImageData(w, h);
188
+ let changed = 0;
189
+ for (let i = 0; i < p.length; i += 4) {
190
+ let moved = false;
191
+ for (let k = 0; k < 4; k++) if (Math.abs(p[i + k] - q[i + k]) > tolerance) moved = true;
192
+ if (moved) {
193
+ changed += 1;
194
+ out.data.set([220, 30, 30, 255], i);
195
+ } else {
196
+ const grey = (q[i] + q[i + 1] + q[i + 2]) / 3;
197
+ out.data.set([grey, grey, grey, 60], i);
198
+ }
199
+ }
200
+ g.putImageData(out, 0, 0);
201
+ return { changed: changed / (w * h || 1), diff: c.toDataURL("image/png").replace(/^data:image\\/png;base64,/, "") };
202
+ }`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mccaskie-labs/workbench-ui",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Workbench pages: one dark look, a top bar with the environment tag, cards, outcome pills, and one format for times, money and durations.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",