@mccaskie-labs/workbench-ui 0.13.3 → 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,17 @@
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
+
9
+ ## 0.14.0
10
+
11
+ ### Minor Changes
12
+
13
+ - Design mode's try-it part (docs/look-studio.md §8, step 7b). `npx workbench-ui styles` also writes `public/scripts/design-mode.generated.js` from the installed tools' layouts. On a page that loads it, a bar across the top tries any look, light or dark, a site layout (its header and footer) and a phone's width, and a badge before each tool lists that tool's layouts, for this one or every one on the site. Everything tried is a page attribute the stylesheets already answer, so nothing redraws or redeploys. A trial sits in the browser's session only, and nobody else sees it. Keep saves to the address the page gives the script (`data-keep`), which workbench-settings' design group provides next. A layout a tool draws differently (not by CSS alone) is shown but can't be tried in place. New `wb-ui-design*` classes, each with its default style and a sample. Also exports `designData`, `designBar`, `designBadge`, `designScript` and `DESIGN_FILE`.
14
+
3
15
  ## 0.13.3
4
16
 
5
17
  ### Patch Changes
package/dist/cli.js CHANGED
@@ -18,16 +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
+ import { DESIGN_FILE, designModeFile } from "./design-mode.js";
27
+ import { capture, compare, installedSamples, visualMarkdown } from "./visual.js";
26
28
  import { libraryProblems, PREVIEW_FILE, previewFamilies, renderLooks, renderSchemes, resolveSiteLayout, renderTheme, resolveAdminTheme, resolveTheme, themeFixes, themeInput, themeProblems } from "./theme.js";
27
29
  import { familiesIn, fontGaps, projectFonts } from "./fonts.js";
28
30
  import { findItem, itemProblems, LIBRARY, withProjectItems } from "./library.js";
29
31
  import { DEFAULT_THEME_CSS, renderStyles, STYLE_FILES, STYLED_SCOPE, starterProjectCss, unknownMarkupNames, unknownNames } from "./styles.js";
30
- 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]";
31
33
  const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
32
34
  /** The styles of each Workbench tool the project at `dir` has installed, and the workbench-ui version. */
33
35
  export async function installedStyles(dir) {
@@ -275,6 +277,7 @@ export function planStyles(dir, tools, uiVersion) {
275
277
  [SAMPLE_FILES.guide]: theme.guide,
276
278
  [PREVIEW_FILE.path]: renderLooks(theme.library, preview.css),
277
279
  [SITE_LAYOUT_FILE]: siteLayoutModule(theme.layout),
280
+ [DESIGN_FILE.path]: designModeFile(tools, theme.library),
278
281
  };
279
282
  for (const [path, text] of Object.entries(derived)) {
280
283
  if (existsSync(join(dir, path)) && read(join(dir, path)) === text)
@@ -306,8 +309,51 @@ export function planStyles(dir, tools, uiVersion) {
306
309
  }
307
310
  return { files, problems, notes: fontGaps(theme.families) };
308
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
+ }
309
353
  async function main(argv) {
310
354
  const [command, ...rest] = argv;
355
+ if (command === "visual")
356
+ return visualCommand(rest);
311
357
  if (command !== "styles") {
312
358
  console.error(USAGE);
313
359
  return 2;
@@ -352,7 +398,7 @@ async function main(argv) {
352
398
  }
353
399
  // Writing fixes workbench.css; project.css and the project's own pages are fixed by hand.
354
400
  // brand.json's problems are fixed by hand too.
355
- const left = plan.problems.filter((p) => !p.startsWith(STYLE_FILES.generated) && !Object.values(SAMPLE_FILES).some((f) => p.startsWith(f)) && !p.startsWith(PREVIEW_FILE.path) && !p.startsWith(SITE_LAYOUT_FILE) && !p.startsWith("public/fonts/") && !(p.startsWith(STYLE_FILES.project) && plan.files[STYLE_FILES.project]));
401
+ const left = plan.problems.filter((p) => !p.startsWith(STYLE_FILES.generated) && !Object.values(SAMPLE_FILES).some((f) => p.startsWith(f)) && !p.startsWith(PREVIEW_FILE.path) && !p.startsWith(SITE_LAYOUT_FILE) && !p.startsWith(DESIGN_FILE.path) && !p.startsWith("public/fonts/") && !(p.startsWith(STYLE_FILES.project) && plan.files[STYLE_FILES.project]));
356
402
  for (const p of left)
357
403
  console.error(p);
358
404
  return left.length ? 1 : 0;
@@ -0,0 +1,80 @@
1
+ import { type Library } from "./library.ts";
2
+ import type { InstalledStyles } from "./styles.ts";
3
+ /** Where the generated script sits and is served. */
4
+ export declare const DESIGN_FILE: {
5
+ readonly path: "public/scripts/design-mode.generated.js";
6
+ readonly url: "/scripts/design-mode.generated.js";
7
+ };
8
+ /** One tool design mode can lay out: the data-tool its outer element carries, and its layouts. */
9
+ export interface DesignTool {
10
+ tool: string;
11
+ /** Its name in the badge, such as "Form". */
12
+ title: string;
13
+ default: string;
14
+ layouts: {
15
+ id: string;
16
+ title: string;
17
+ bestFor: string;
18
+ needs?: readonly string[];
19
+ render?: boolean;
20
+ }[];
21
+ }
22
+ /** What the script knows: every choice it can offer. */
23
+ export interface DesignData {
24
+ looks: {
25
+ id: string;
26
+ title: string;
27
+ feel: string;
28
+ }[];
29
+ siteLayouts: {
30
+ id: string;
31
+ title: string;
32
+ bestFor: string;
33
+ header: string;
34
+ footer: string;
35
+ }[];
36
+ tools: DesignTool[];
37
+ /** The words, in the site's language. */
38
+ words: DesignWords;
39
+ }
40
+ export interface DesignWords {
41
+ bar: string;
42
+ look: string;
43
+ scheme: string;
44
+ light: string;
45
+ dark: string;
46
+ siteLayout: string;
47
+ asNow: string;
48
+ width: string;
49
+ phone: string;
50
+ desktop: string;
51
+ keep: string;
52
+ keepNone: string;
53
+ putBack: string;
54
+ leave: string;
55
+ layout: string;
56
+ thisOne: string;
57
+ everyOne: string;
58
+ needs: string;
59
+ afterKeep: string;
60
+ tried: string;
61
+ }
62
+ export declare const DESIGN_WORDS: DesignWords;
63
+ /** The choices design mode offers in this project: the library's looks and site layouts, and each installed tool's layouts. */
64
+ export declare function designData(tools: readonly InstalledStyles[], lib?: Library, words?: Partial<DesignWords>): DesignData;
65
+ /** The bar across the top of every page in design mode. The script fills in what is chosen and counts the changes. */
66
+ export declare function designBar(d: DesignData): string;
67
+ /** The page at a phone's width, over the page, while Width is Phone. */
68
+ export declare function designPhone(src: string, w: DesignWords): string;
69
+ /** A tool's badge and the list of its layouts it opens: the script puts one before each tool on the page. */
70
+ export declare function designBadge(d: DesignData, t: DesignTool, current: string): string;
71
+ /**
72
+ * The script itself: the bar, a badge on each tool, and the trial kept in
73
+ * sessionStorage. A tool's layout key is its tool id for the whole site, or
74
+ * tool@/path for this page only, as workbench-settings' design.layouts keys
75
+ * them. `keep` (the site's address for saving) is read from the script tag's
76
+ * data-keep; without one the Keep button stays off.
77
+ */
78
+ export declare function designScript(d: DesignData): string;
79
+ /** The script for a project's installed tools, as `styles` writes it. */
80
+ export declare function designModeFile(tools: readonly InstalledStyles[], lib?: Library): string;
@@ -0,0 +1,209 @@
1
+ // Design mode's trial part (docs/look-studio.md §8): on the test site, a
2
+ // signed-in admin tries a look, light or dark, a site layout and each tool's
3
+ // layouts in place, on the real pages. Every choice here is a page attribute
4
+ // the stylesheets already answer (looks.css's [data-wb-look], the frame's
5
+ // data-header and data-footer, each tool's [data-layout]), so trying needs no
6
+ // redraw and no redeploy. Trials sit in the browser's session only: nothing is
7
+ // saved, and nobody else's view changes. Keeping goes through the settings
8
+ // tool (workbench-settings' "design" group) at the address the site gives.
9
+ //
10
+ // `npx workbench-ui styles` writes public/scripts/design-mode.generated.js from the
11
+ // installed tools' layouts, and the site frame loads it only in design mode.
12
+ import { LIBRARY, usable } from "./library.js";
13
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
14
+ /** Where the generated script sits and is served. */
15
+ export const DESIGN_FILE = { path: "public/scripts/design-mode.generated.js", url: "/scripts/design-mode.generated.js" };
16
+ export const DESIGN_WORDS = {
17
+ bar: "Design mode",
18
+ look: "Look",
19
+ scheme: "Show",
20
+ light: "Light",
21
+ dark: "Dark",
22
+ siteLayout: "Site layout",
23
+ asNow: "As it is now",
24
+ width: "Width",
25
+ phone: "Phone",
26
+ desktop: "Desktop",
27
+ keep: "Keep these {n} changes",
28
+ keepNone: "Nothing tried yet",
29
+ putBack: "Put back",
30
+ leave: "Leave design mode",
31
+ layout: "layout",
32
+ thisOne: "This one",
33
+ everyOne: "Every one on the site",
34
+ needs: "Needs {what}",
35
+ afterKeep: "Shows once kept",
36
+ tried: "Only you see these until you keep them.",
37
+ };
38
+ /** A tool's own name for its badge, from its tool id. */
39
+ const TOOL_TITLES = { forms: "Form", booking: "Booking", orders: "Order list", review: "Reviews", tickets: "Tickets" };
40
+ /** The choices design mode offers in this project: the library's looks and site layouts, and each installed tool's layouts. */
41
+ export function designData(tools, lib = LIBRARY, words = {}) {
42
+ return {
43
+ looks: usable(lib.looks).map((l) => ({ id: l.id, title: l.title, feel: l.feel })),
44
+ siteLayouts: usable(lib.layouts).map((l) => ({ id: l.id, title: l.title, bestFor: l.bestFor, header: l.header, footer: l.footer })),
45
+ tools: tools
46
+ .flatMap(({ styles: s }) => (s.layouts && s.layouts.layouts.length > 1 ? [{ tool: s.tool, layouts: s.layouts }] : []))
47
+ .map(({ tool, layouts }) => ({
48
+ tool,
49
+ title: TOOL_TITLES[tool] ?? tool,
50
+ default: layouts.default,
51
+ layouts: layouts.layouts.map((l) => ({ id: l.id, title: l.title, bestFor: l.bestFor, ...(l.needs?.length ? { needs: l.needs } : {}), ...(l.render ? { render: true } : {}) })),
52
+ }))
53
+ .sort((a, b) => (a.tool < b.tool ? -1 : 1)),
54
+ words: { ...DESIGN_WORDS, ...words },
55
+ };
56
+ }
57
+ const option = (value, label) => `<option class="wb-ui-design-option" value="${esc(value)}">${esc(label)}</option>`;
58
+ /** The bar across the top of every page in design mode. The script fills in what is chosen and counts the changes. */
59
+ export function designBar(d) {
60
+ const w = d.words;
61
+ const select = (name, label, options) => `<label class="wb-ui-design-field"><span class="wb-ui-design-label">${esc(label)}</span><select class="wb-ui-design-select" name="${name}">${options}</select></label>`;
62
+ const pair = (name, label, a, b) => `<fieldset class="wb-ui-design-pair"><legend class="wb-ui-design-label">${esc(label)}</legend>${[a, b].map(([v, t]) => `<label class="wb-ui-design-choice"><input class="wb-ui-design-radio" type="radio" name="${name}" value="${esc(v)}"> ${esc(t)}</label>`).join("")}</fieldset>`;
63
+ return (`<div class="wb-ui-design" role="region" aria-label="${esc(w.bar)}" data-wb-design-bar>` +
64
+ `<strong class="wb-ui-design-name">${esc(w.bar)}</strong>` +
65
+ select("look", w.look, option("", w.asNow) + d.looks.map((l) => option(l.id, l.title)).join("")) +
66
+ pair("scheme", w.scheme, ["light", w.light], ["dark", w.dark]) +
67
+ select("site-layout", w.siteLayout, option("", w.asNow) + d.siteLayouts.map((l) => option(l.id, l.title)).join("")) +
68
+ pair("width", w.width, ["phone", w.phone], ["desktop", w.desktop]) +
69
+ `<span class="wb-ui-design-actions"><button class="wb-ui-design-keep" type="button" data-wb-design="keep" disabled>${esc(w.keepNone)}</button>` +
70
+ `<button class="wb-ui-design-button" type="button" data-wb-design="put-back">${esc(w.putBack)}</button>` +
71
+ `<button class="wb-ui-design-button" type="button" data-wb-design="leave">${esc(w.leave)}</button></span>` +
72
+ `<p class="wb-ui-design-note">${esc(w.tried)}</p>` +
73
+ `</div>`);
74
+ }
75
+ /** The page at a phone's width, over the page, while Width is Phone. */
76
+ export function designPhone(src, w) {
77
+ return `<div class="wb-ui-design-phone" data-wb-design-phone><iframe class="wb-ui-design-frame" src="${esc(src)}" title="${esc(w.phone)}"></iframe></div>`;
78
+ }
79
+ /** A tool's badge and the list of its layouts it opens: the script puts one before each tool on the page. */
80
+ export function designBadge(d, t, current) {
81
+ const w = d.words;
82
+ const now = t.layouts.find((l) => l.id === current) ?? t.layouts.find((l) => l.id === t.default);
83
+ const items = t.layouts
84
+ .map((l) => {
85
+ const why = l.render ? w.afterKeep : l.needs?.length ? w.needs.replace("{what}", l.needs.join(", ")) : "";
86
+ return `<li class="wb-ui-design-item"><button class="wb-ui-design-pick" type="button" data-wb-layout="${esc(l.id)}"${l.id === now.id ? ' aria-pressed="true"' : ""}${l.render ? " disabled" : ""}><span class="wb-ui-design-pick-title">${esc(l.title)}</span><span class="wb-ui-design-pick-about">${esc(l.bestFor)}</span>${why ? `<span class="wb-ui-design-pick-why">${esc(why)}</span>` : ""}</button></li>`;
87
+ })
88
+ .join("");
89
+ return (`<details class="wb-ui-design-badge" data-wb-design-tool="${esc(t.tool)}"><summary class="wb-ui-design-badge-name">${esc(t.title)} ${esc(w.layout)}: ${esc(now.title)}</summary>` +
90
+ `<div class="wb-ui-design-menu"><fieldset class="wb-ui-design-pair"><legend class="wb-ui-design-label">${esc(t.title)}</legend>` +
91
+ `<label class="wb-ui-design-choice"><input class="wb-ui-design-radio" type="radio" name="scope-${esc(t.tool)}" value="page" checked> ${esc(w.thisOne)}</label>` +
92
+ `<label class="wb-ui-design-choice"><input class="wb-ui-design-radio" type="radio" name="scope-${esc(t.tool)}" value="site"> ${esc(w.everyOne)}</label></fieldset>` +
93
+ `<ul class="wb-ui-design-list">${items}</ul></div></details>`);
94
+ }
95
+ /**
96
+ * The script itself: the bar, a badge on each tool, and the trial kept in
97
+ * sessionStorage. A tool's layout key is its tool id for the whole site, or
98
+ * tool@/path for this page only, as workbench-settings' design.layouts keys
99
+ * them. `keep` (the site's address for saving) is read from the script tag's
100
+ * data-keep; without one the Keep button stays off.
101
+ */
102
+ export function designScript(d) {
103
+ const badges = Object.fromEntries(d.tools.flatMap((t) => t.layouts.map((l) => [`${t.tool}:${l.id}`, designBadge(d, t, l.id)])));
104
+ return `// Generated by @mccaskie-labs/workbench-ui (\`npx workbench-ui styles\`): design mode (docs/look-studio.md §8). Do not edit.
105
+ (() => {
106
+ "use strict";
107
+ const DATA = ${JSON.stringify({ looks: d.looks, siteLayouts: d.siteLayouts, tools: d.tools.map((t) => ({ tool: t.tool, layouts: t.layouts.map((l) => ({ id: l.id, render: !!l.render })) })), words: { keep: d.words.keep, keepNone: d.words.keepNone } })};
108
+ const BAR = ${JSON.stringify(designBar(d))};
109
+ const BADGES = ${JSON.stringify(badges)};
110
+ const PHONE = ${JSON.stringify(designPhone("{src}", d.words))};
111
+ const KEY = "wb-design-trial";
112
+ // Inside the phone frame: the page only, in the same trial, without a bar of its own.
113
+ const framed = window.top !== window.self;
114
+ const me = document.currentScript;
115
+ const keepAt = me && me.dataset.keep;
116
+ const html = document.documentElement;
117
+ const path = location.pathname;
118
+ const read = () => { try { return JSON.parse(sessionStorage.getItem(KEY) || "{}") || {}; } catch { return {}; } };
119
+ const write = (t) => { try { sessionStorage.setItem(KEY, JSON.stringify(t)); } catch {} };
120
+ const own = { look: html.getAttribute("data-wb-look"), scheme: html.getAttribute("data-wb-scheme") };
121
+ const header = document.querySelector(".wb-site-header[data-header]");
122
+ const footer = document.querySelector(".wb-site-footer[data-footer]");
123
+ const frame = { header: header && header.getAttribute("data-header"), footer: footer && footer.getAttribute("data-footer") };
124
+ const tools = [...document.querySelectorAll("[data-tool][data-layout]")].filter((el) => DATA.tools.some((t) => t.tool === el.dataset.tool));
125
+ tools.forEach((el) => { el.dataset.wbOwnLayout = el.dataset.layout; });
126
+ const count = (t) => ["look", "scheme", "siteLayout"].filter((k) => t[k]).length + Object.keys(t.layouts || {}).length;
127
+ let apply = function (t) {
128
+ const look = t.look || own.look;
129
+ if (look) html.setAttribute("data-wb-look", look); else html.removeAttribute("data-wb-look");
130
+ const scheme = t.scheme || own.scheme;
131
+ if (scheme) html.setAttribute("data-wb-scheme", scheme); else html.removeAttribute("data-wb-scheme");
132
+ const site = DATA.siteLayouts.find((l) => l.id === t.siteLayout);
133
+ if (header) header.setAttribute("data-header", site ? site.header : frame.header);
134
+ if (footer) footer.setAttribute("data-footer", site ? site.footer : frame.footer);
135
+ // A phone's width: the page itself in a frame that wide, so each tool's own phone rules apply.
136
+ const shown = document.querySelector("[data-wb-design-phone]");
137
+ if (t.width === "phone" && !shown) document.body.insertAdjacentHTML("beforeend", PHONE.replace("{src}", location.href.replace(/"/g, "%22")));
138
+ else if (t.width !== "phone" && shown) shown.remove();
139
+ const layouts = t.layouts || {};
140
+ for (const el of tools) {
141
+ const id = layouts[el.dataset.tool + "@" + path] || layouts[el.dataset.tool] || el.dataset.wbOwnLayout;
142
+ const known = DATA.tools.find((x) => x.tool === el.dataset.tool).layouts.find((l) => l.id === id && !l.render);
143
+ el.dataset.layout = known ? id : el.dataset.wbOwnLayout;
144
+ const badge = el.previousElementSibling && el.previousElementSibling.matches("[data-wb-design-tool]") ? el.previousElementSibling : null;
145
+ const fresh = document.createRange().createContextualFragment(BADGES[el.dataset.tool + ":" + el.dataset.layout] || "");
146
+ if (badge) badge.replaceWith(fresh); else el.before(fresh);
147
+ }
148
+ const keep = bar.querySelector("[data-wb-design=keep]");
149
+ const n = count(t);
150
+ keep.textContent = n ? DATA.words.keep.replace("{n}", String(n)) : DATA.words.keepNone;
151
+ keep.disabled = !n || !keepAt;
152
+ for (const s of bar.querySelectorAll("select")) s.value = (s.name === "site-layout" ? t.siteLayout : t[s.name]) || "";
153
+ for (const r of bar.querySelectorAll("input[type=radio]")) r.checked = r.name === "scheme" ? r.value === (t.scheme || own.scheme || "light") : r.value === (t.width || "desktop");
154
+ const phone = document.querySelector("[data-wb-design-phone] iframe");
155
+ if (phone && phone.contentWindow && phone.contentWindow.wbDesignApply) phone.contentWindow.wbDesignApply();
156
+ };
157
+ window.wbDesignApply = () => apply(read());
158
+ if (framed) {
159
+ apply = ((inner) => (t) => inner({ ...t, width: undefined }))(apply);
160
+ addEventListener("storage", () => apply(read()));
161
+ }
162
+ document.body.insertAdjacentHTML("afterbegin", BAR);
163
+ const bar = document.body.firstElementChild;
164
+ if (framed) bar.hidden = true;
165
+ bar.addEventListener("change", (e) => {
166
+ const t = read();
167
+ const el = e.target;
168
+ if (el.name === "look") t.look = el.value || undefined;
169
+ else if (el.name === "site-layout") t.siteLayout = el.value || undefined;
170
+ else if (el.name === "scheme") t.scheme = el.value === (own.scheme || "light") ? undefined : el.value;
171
+ else if (el.name === "width") t.width = el.value === "phone" ? "phone" : undefined;
172
+ write(t);
173
+ apply(t);
174
+ });
175
+ bar.addEventListener("click", async (e) => {
176
+ const act = e.target.closest("[data-wb-design]");
177
+ if (!act) return;
178
+ const what = act.dataset.wbDesign;
179
+ if (what === "put-back") { write({}); apply({}); }
180
+ else if (what === "leave") { write({}); document.cookie = "wb-design=; Path=/; Max-Age=0; SameSite=Lax; Secure"; location.reload(); }
181
+ else if (what === "keep" && keepAt) {
182
+ const t = read();
183
+ act.disabled = true;
184
+ const res = await fetch(keepAt, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ look: t.look, scheme: t.scheme, layout: t.siteLayout, layouts: t.layouts || {} }), credentials: "same-origin" }).catch(() => null);
185
+ if (res && res.ok) { write({}); location.reload(); } else { act.disabled = false; act.textContent = (res && (await res.text().catch(() => ""))) || act.textContent; }
186
+ }
187
+ });
188
+ document.addEventListener("click", (e) => {
189
+ const pick = e.target.closest("[data-wb-layout]");
190
+ const badge = pick && pick.closest("[data-wb-design-tool]");
191
+ if (!badge) return;
192
+ const tool = badge.dataset.wbDesignTool;
193
+ const site = badge.querySelector("input[value=site]").checked;
194
+ const t = read();
195
+ t.layouts = t.layouts || {};
196
+ delete t.layouts[tool + "@" + path];
197
+ if (site) delete t.layouts[tool];
198
+ t.layouts[site ? tool : tool + "@" + path] = pick.dataset.wbLayout;
199
+ write(t);
200
+ apply(t);
201
+ });
202
+ apply(read());
203
+ })();
204
+ `;
205
+ }
206
+ /** The script for a project's installed tools, as `styles` writes it. */
207
+ export function designModeFile(tools, lib = LIBRARY) {
208
+ return designScript(designData(tools, lib));
209
+ }
package/dist/index.d.ts CHANGED
@@ -199,3 +199,4 @@ export interface ShellOptions {
199
199
  }
200
200
  /** A whole page: the shared look, the top bar, the heading, then `body`. */
201
201
  export declare function shell(opts: ShellOptions): string;
202
+ export { DESIGN_FILE, DESIGN_WORDS, designBadge, designBar, designData, designModeFile, designPhone, designScript, type DesignData, type DesignTool, type DesignWords } from "./design-mode.ts";
package/dist/index.js CHANGED
@@ -306,3 +306,4 @@ export function shell(opts) {
306
306
  ${opts.top}
307
307
  <main class="wb-ui-main"><h1 class="wb-ui-title">${escape(opts.title)}</h1>${opts.body}</main>${opts.tail ?? ""}</html>`;
308
308
  }
309
+ export { DESIGN_FILE, DESIGN_WORDS, designBadge, designBar, designData, designModeFile, designPhone, designScript } from "./design-mode.js";
@@ -3,6 +3,7 @@
3
3
  // words. Exported at ./samples beside ./styles.
4
4
  import { actions, body, button, card, check, chip, code, confirm, facts, field, input, jumpNav, message, more, note, pill, select, small, table, textarea, topBar } from "./index.js";
5
5
  import { lookPreview } from "./look-preview.js";
6
+ import { designBadge, designBar, designData, designPhone } from "./design-mode.js";
6
7
  import { styleGuide } from "./style-guide.js";
7
8
  export const UI_SAMPLES = {
8
9
  format: 1,
@@ -68,6 +69,15 @@ export const UI_SAMPLES = {
68
69
  html: () => styleGuide([{ format: 1, package: "@mccaskie-labs/workbench-ui", title: "Page parts", prefix: "wb-ui-", samples: [{ id: "note", title: "A note", layout: "stacked", html: () => note("<p>A note.</p>") }] }]) +
69
70
  styleGuide([], { view: "dark" }),
70
71
  },
72
+ {
73
+ id: "design-mode",
74
+ title: "Design mode: the bar, and a tool's badge opened",
75
+ html: () => {
76
+ const tool = { tool: "forms", title: "Form", default: "stacked", layouts: [{ id: "stacked", title: "Stacked", bestFor: "Most forms" }, { id: "two-columns", title: "Two columns", bestFor: "Long forms on a wide screen" }, { id: "steps", title: "One question at a time", bestFor: "Long forms on a phone", render: true }, { id: "beside-picture", title: "Beside a picture", bestFor: "A short form with a photo", needs: ["pictures"] }] };
77
+ const d = { ...designData([]), tools: [tool] };
78
+ return designBar(d) + designBadge(d, tool, "two-columns").replace("<details", "<details open") + designPhone("about:blank", d.words).replace('class="wb-ui-design-phone"', 'class="wb-ui-design-phone" style="position:static;height:14rem"');
79
+ },
80
+ },
71
81
  {
72
82
  id: "look-preview",
73
83
  title: "The look previewer, with its pages left blank, then as the live site shows it",
package/dist/ui-styles.js CHANGED
@@ -343,6 +343,30 @@ export const UI_STYLES = {
343
343
  css: `padding:.3rem .8rem;border:1px solid ${v("line")};border-radius:999px;color:${v("text")};text-decoration:none`,
344
344
  states: [{ selector: "[aria-current=page]", about: "The choice shown now", css: `background:${v("accent")};border-color:${v("accent")};color:${v("accent-text")}` }, { selector: ":focus-visible", about: "Has focus", css: FOCUS }],
345
345
  },
346
+ { name: "wb-ui-design", element: "div", about: "Design mode's bar across the top of the page", css: `position:sticky;top:0;z-index:50;display:flex;flex-wrap:wrap;gap:.5rem 1rem;align-items:end;padding:.6rem 1rem;background:${v("surface")};color:${v("text")};border-bottom:2px solid ${v("accent")};font-size:.9rem` },
347
+ { name: "wb-ui-design-name", element: "strong", about: "Design mode's name", css: "align-self:center" },
348
+ { name: "wb-ui-design-field", element: "label", about: "One choice on the bar, with its name", css: "display:grid;gap:.15rem" },
349
+ { name: "wb-ui-design-label", element: "span", about: "A choice's name", css: `font-size:.75rem;color:${v("muted")};padding:0` },
350
+ { name: "wb-ui-design-select", element: "select", about: "A list of choices", css: `font:inherit;padding:.25rem .5rem;border:1px solid ${v("line")};border-radius:6px;background:${v("surface")};color:${v("text")}`, states: [{ selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
351
+ { name: "wb-ui-design-pair", element: "fieldset", about: "Two choices side by side, such as light or dark", css: "display:flex;gap:.6rem;align-items:center;margin:0;padding:0;border:0" },
352
+ { name: "wb-ui-design-choice", element: "label", about: "One of a pair", css: "display:inline-flex;gap:.25rem;align-items:center" },
353
+ { name: "wb-ui-design-radio", element: "input", about: "A round choice", css: `margin:0;accent-color:${v("accent")}`, states: [{ selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
354
+ { name: "wb-ui-design-option", element: "option", about: "One choice in a list", css: "font:inherit" },
355
+ { name: "wb-ui-design-actions", element: "span", about: "Keep, Put back and Leave", css: "display:flex;flex-wrap:wrap;gap:.5rem;margin-left:auto" },
356
+ { name: "wb-ui-design-keep", element: "button", about: "Keeps what was tried", css: `font:inherit;padding:.35rem .9rem;border:0;border-radius:6px;background:${v("accent")};color:${v("accent-text")};cursor:pointer`, states: [{ selector: ":disabled", about: "Nothing to keep", css: "opacity:.55;cursor:default" }, { selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
357
+ { name: "wb-ui-design-button", element: "button", about: "Put back or Leave design mode", css: `font:inherit;padding:.35rem .9rem;border:1px solid ${v("line")};border-radius:6px;background:${v("surface")};color:${v("text")};cursor:pointer`, states: [{ selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
358
+ { name: "wb-ui-design-note", element: "p", about: "Says only the admin sees what they try", css: `flex-basis:100%;margin:0;font-size:.8rem;color:${v("muted")}` },
359
+ { name: "wb-ui-design-badge", element: "details", about: "The badge on a tool: its layout now, and the others to try", css: `position:relative;z-index:40;margin:0 0 .5rem;font-size:.85rem;color:${v("text")}` },
360
+ { name: "wb-ui-design-badge-name", element: "summary", about: "The tool and its layout now", css: `display:inline-block;padding:.2rem .7rem;border:1px dashed ${v("accent")};border-radius:999px;background:${v("surface")};cursor:pointer`, states: [{ selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
361
+ { name: "wb-ui-design-menu", element: "div", about: "The tool's layouts and where a choice applies", css: `position:absolute;top:100%;left:0;width:min(22rem,90vw);display:grid;gap:.5rem;margin-top:.3rem;padding:.6rem;background:${v("surface")};border:1px solid ${v("line")};border-radius:8px;box-shadow:0 6px 24px rgb(0 0 0 / .15)` },
362
+ { name: "wb-ui-design-list", element: "ul", about: "The tool's layouts", css: "display:grid;gap:.3rem;margin:0;padding:0;list-style:none" },
363
+ { name: "wb-ui-design-item", element: "li", about: "One layout", css: "margin:0" },
364
+ { name: "wb-ui-design-pick", element: "button", about: "Tries the layout", css: `display:grid;gap:.1rem;width:100%;text-align:left;font:inherit;padding:.4rem .6rem;border:1px solid ${v("line")};border-radius:6px;background:${v("surface")};color:${v("text")};cursor:pointer`, states: [{ selector: "[aria-pressed=true]", about: "The layout shown now", css: `border-color:${v("accent")};box-shadow:inset 3px 0 0 ${v("accent")}` }, { selector: ":disabled", about: "Can't be tried in place", css: "opacity:.6;cursor:default" }, { selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
365
+ { name: "wb-ui-design-pick-title", element: "span", about: "The layout's name", css: "font-weight:700" },
366
+ { name: "wb-ui-design-pick-about", element: "span", about: "What the layout is good for", css: `font-size:.8rem;color:${v("muted")}` },
367
+ { name: "wb-ui-design-pick-why", element: "span", about: "Why it can't be tried here", css: `font-size:.8rem;color:${v("muted")};font-style:italic` },
368
+ { name: "wb-ui-design-phone", element: "div", about: "The page at a phone's width, over the page", css: `position:fixed;inset:4.5rem 0 0;z-index:45;display:grid;justify-items:center;padding:1rem;background:rgb(0 0 0 / .45)` },
369
+ { name: "wb-ui-design-frame", element: "iframe", about: "The page itself, 390 pixels wide", css: "width:390px;max-width:100%;height:100%;border:0;border-radius:12px;background:#fff" },
346
370
  { name: "wb-ui-look-live", element: "p", about: "On the live site: where the other looks show", css: `margin:0;color:${v("muted")}` },
347
371
  { name: "wb-ui-look-grid", element: "div", about: "The looks side by side, as many as fit", css: "display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,22rem),1fr));gap:1rem" },
348
372
  { name: "wb-ui-look", element: "figure", about: "One look: its name and the page drawn in it", css: `margin:0;display:grid;border:1px solid ${v("line")};border-radius:${v("corner")};overflow:hidden` },
@@ -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.13.3",
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",