@seanyeh77/ui-cli 0.40.0 → 0.42.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.
Files changed (3) hide show
  1. package/README.md +20 -0
  2. package/dist/cli.js +605 -28
  3. package/package.json +10 -4
package/README.md ADDED
@@ -0,0 +1,20 @@
1
+ # @seanyeh77/ui-cli
2
+
3
+ SeanYeh 設計系統的命令列工具。用 `npx @seanyeh77/ui-cli …` 執行(單打 `npx ui` 會跑到另一個無關的 npm 套件)。
4
+
5
+ ```bash
6
+ npm i -D @seanyeh77/ui-cli
7
+ npx playwright install chromium # ui check 與 ui shots 用的瀏覽器;或設定 CHROMIUM_PATH
8
+ ```
9
+
10
+ - `ui check <檔案或 URL>`:在 390 px 與 1280 px、淺色與深色打開頁面,檢查 console 錯誤、水平溢出、小於 48 px 的觸控目標、卡片裡的卡片、原生控制項、沒放進 layer 又蓋過元件的重設 CSS 等,有問題時 exit 1。
11
+ - `ui shots <檔案或 URL>`:固定時間、停止動畫的截圖,寫成基準圖(`--out`)或和基準圖比對(`--compare`)。
12
+ - `ui docs [Name] [--full]`:印出元件的用法區塊或使用規則。
13
+ - `ui list`:列出每份規則與每個元件的一句說明。
14
+
15
+ `npx @seanyeh77/ui-cli` 不加參數會印出完整說明。
16
+
17
+ ## 文件
18
+
19
+ - 文件網站:<https://seanyeh77.github.io/ui-design-system/>
20
+ - 給 AI agent 的使用說明:[AGENTS.md](https://github.com/seanyeh77/ui-design-system/blob/main/AGENTS.md)
package/dist/cli.js CHANGED
@@ -1,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
3
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { parseArgs } from "node:util";
7
+ import pixelmatch from "pixelmatch";
8
+ import { PNG } from "pngjs";
9
+ import { execFileSync } from "node:child_process";
7
10
  // src/measure.ts
8
11
  function measure() {
9
12
  const out = {
@@ -14,7 +17,10 @@ function measure() {
14
17
  markdown: [],
15
18
  native: [],
16
19
  wrapped: [],
17
- escaped: []
20
+ escaped: [],
21
+ mixed: [],
22
+ raised: [],
23
+ unlayered: []
18
24
  };
19
25
  const describe = (el) => {
20
26
  let s = el.tagName.toLowerCase();
@@ -137,40 +143,559 @@ function measure() {
137
143
  return new Set([...range.getClientRects()].filter((r) => r.width > 1).map((r) => Math.round(r.top / 4))).size > 1;
138
144
  }))) out.wrapped.push(describe(el));
139
145
  }
146
+ const bars = ".ui-dt-tools, .ui-dt-actions, .ui-card-actions, [role=toolbar]";
147
+ const controls = "button, a[href], input:not([type=hidden]), [role=button], [role=combobox], .ui-searchfield, .ui-pwfield, .ui-datefield, .ui-ms, .ui-select";
148
+ for (const bar of document.querySelectorAll(bars)) {
149
+ if (out.mixed.length >= 6) break;
150
+ if (bar.parentElement?.closest(bars) || !visible(bar)) continue;
151
+ const items = [];
152
+ for (const el of bar.querySelectorAll(controls)) {
153
+ const own = el.parentElement?.closest(controls);
154
+ if (own && bar.contains(own) || !visible(el) || el.closest("[aria-hidden=\"true\"]")) continue;
155
+ items.push({
156
+ el,
157
+ r: el.getBoundingClientRect()
158
+ });
159
+ }
160
+ let hit = "";
161
+ for (let i = 0; i < items.length && !hit; i++) for (let j = i + 1; j < items.length && !hit; j++) {
162
+ const a = items[i].r;
163
+ const b = items[j].r;
164
+ if (Math.min(a.bottom, b.bottom) > Math.max(a.top, b.top) && Math.abs(a.height - b.height) > 1) hit = `${describe(bar)}: ${describe(items[i].el)} ${Math.round(a.height)} px, ${describe(items[j].el)} ${Math.round(b.height)} px`;
165
+ }
166
+ if (hit) out.mixed.push(hit);
167
+ }
168
+ for (const el of document.querySelectorAll(".ui-dt-body .ui-badge, .ui-card .ui-badge")) {
169
+ if (out.raised.length >= 6) break;
170
+ const sh = getComputedStyle(el).boxShadow;
171
+ if (sh && sh !== "none" && visible(el)) out.raised.push(describe(el));
172
+ }
173
+ const page = [];
174
+ const system = /* @__PURE__ */ new Map();
175
+ const parts = (sel) => sel.split(/,(?![^(]*\))/).map((x) => x.trim());
176
+ const keys = (sel) => {
177
+ const cls = [...(sel.replace(/\([^()]*\)/g, "").split(/[\s>+~]+/).pop() ?? "").matchAll(/\.([\w-]+)/g)].map((m) => m[1]);
178
+ return cls.length ? cls.slice(0, 1) : [""];
179
+ };
180
+ const applies = (rule) => {
181
+ if (rule instanceof CSSMediaRule) return matchMedia(rule.conditionText).matches;
182
+ if (rule instanceof CSSSupportsRule) return CSS.supports(rule.conditionText);
183
+ return true;
184
+ };
185
+ const walk = (rules, sheet, layer) => {
186
+ for (const rule of rules) if (rule instanceof CSSImportRule) {
187
+ const name = rule.layerName === null ? layer : [layer, rule.layerName].filter(Boolean).join(".");
188
+ try {
189
+ if (rule.styleSheet) walk(rule.styleSheet.cssRules, rule.styleSheet.href?.split("/").pop() || sheet, name);
190
+ } catch {}
191
+ } else if (rule instanceof CSSLayerBlockRule) walk(rule.cssRules, sheet, [layer, rule.name].filter(Boolean).join("."));
192
+ else if (rule instanceof CSSStyleRule) {
193
+ if (layer === null) page.push({
194
+ selector: rule.selectorText,
195
+ style: rule.style,
196
+ sheet
197
+ });
198
+ else if (layer === "ui" || layer.startsWith("ui.")) for (const selector of parts(rule.selectorText)) for (const k of keys(selector)) {
199
+ const list = system.get(k) ?? [];
200
+ list.push({
201
+ selector,
202
+ style: rule.style,
203
+ sheet
204
+ });
205
+ system.set(k, list);
206
+ }
207
+ } else if (rule instanceof CSSGroupingRule && applies(rule)) walk(rule.cssRules, sheet, layer);
208
+ };
209
+ for (const sheet of document.styleSheets) try {
210
+ walk(sheet.cssRules, sheet.href?.split("/").pop() || "a <style> element", null);
211
+ } catch {}
212
+ const plain = (sel) => !/[.#[]|:(?!:)/.test(sel.replace(/::?(before|after|marker|placeholder)\b/g, ""));
213
+ const matches = (el, sel) => {
214
+ try {
215
+ return el.matches(sel);
216
+ } catch {
217
+ return false;
218
+ }
219
+ };
220
+ const valueOf = (style, prop) => {
221
+ const names = [prop];
222
+ for (let p = prop; p.includes("-");) names.push(p = p.slice(0, p.lastIndexOf("-")));
223
+ const side = /^border-(?:top|right|bottom|left)-(color|width|style)$/.exec(prop);
224
+ if (side) names.splice(2, 0, `border-${side[1]}`);
225
+ for (const n of names) {
226
+ const v = style.getPropertyValue(n).trim();
227
+ if (v) return v;
228
+ }
229
+ return "";
230
+ };
231
+ const seen = /* @__PURE__ */ new Set();
232
+ for (const rule of page) {
233
+ if (out.unlayered.length >= 6) break;
234
+ const selectors = parts(rule.selector).filter((x) => plain(x) && !/::/.test(x));
235
+ if (!selectors.length) continue;
236
+ const hits = /* @__PURE__ */ new Map();
237
+ for (const el of document.querySelectorAll(selectors.join(", "))) {
238
+ const classes = [...el.classList].filter((c) => c.startsWith("ui-"));
239
+ if (!classes.length) continue;
240
+ const candidates = [...classes, ""].flatMap((c) => system.get(c) ?? []);
241
+ for (const prop of rule.style) {
242
+ if (hits.has(prop)) continue;
243
+ const value = valueOf(rule.style, prop);
244
+ const own = candidates.find((r) => {
245
+ const v = valueOf(r.style, prop);
246
+ return v !== "" && v !== value && !r.style.getPropertyPriority(prop) && matches(el, r.selector);
247
+ });
248
+ if (own) hits.set(prop, own.selector);
249
+ }
250
+ }
251
+ if (!hits.size) continue;
252
+ const key = rule.sheet + rule.selector;
253
+ if (seen.has(key)) continue;
254
+ seen.add(key);
255
+ const props = [...hits.keys()];
256
+ out.unlayered.push(`${rule.selector} { ${props.slice(0, 4).join(", ")}${props.length > 4 ? ", …" : ""} } in ${rule.sheet} overrides ${[...new Set(hits.values())].slice(0, 2).join(", ")}`);
257
+ }
258
+ return out;
259
+ }
260
+ // src/usage.ts
261
+ const USAGE = /^## 用法[ \t]*$/m;
262
+ /** The title and the 用法 section, up to the next level-2 heading; null when the file has no 用法 section. */
263
+ function usageBlock(md) {
264
+ const start = USAGE.exec(md);
265
+ if (!start) return null;
266
+ const after = start.index + start[0].length;
267
+ let fenced = false;
268
+ let end = md.length;
269
+ let pos = after;
270
+ for (const line of md.slice(after).split("\n")) {
271
+ if (/^\s*(```|~~~)/.test(line)) fenced = !fenced;
272
+ else if (!fenced && /^## /.test(line)) {
273
+ end = pos;
274
+ break;
275
+ }
276
+ pos += line.length + 1;
277
+ }
278
+ return md.slice(0, Math.min(end, md.length)).trimEnd() + "\n";
279
+ }
280
+ /** One sentence about the file: the first sentence of the 用法 section, or of the first text line after the title. */
281
+ function summary(md) {
282
+ const start = USAGE.exec(md);
283
+ const line = (start ? md.slice(start.index + start[0].length) : md).split("\n").find((l) => l.trim() && !l.startsWith("#") && !l.startsWith("|"))?.trim() ?? "";
284
+ let code = false;
285
+ for (let i = 0; i < line.length; i++) if (line[i] === "`") code = !code;
286
+ else if (!code && line[i] === "。") return line.slice(0, i + 1);
287
+ return line;
288
+ }
289
+ // src/compare.ts
290
+ /** Anti-aliasing noise passes; a moved border, a changed color or a new line of text does not. */
291
+ const DEFAULT_TOLERANCE = {
292
+ threshold: .1,
293
+ maxDiffPercent: .02
294
+ };
295
+ /** Puts an image on a canvas of width x height; the added area is transparent, so it always differs from an opaque shot. */
296
+ function pad(img, width, height) {
297
+ if (img.width === width && img.height === height) return img.data;
298
+ const out = new Uint8Array(width * height * 4);
299
+ for (let y = 0; y < img.height; y++) out.set(img.data.subarray(y * img.width * 4, (y + 1) * img.width * 4), y * width * 4);
140
300
  return out;
141
301
  }
302
+ /** Compares a new screenshot with its baseline. Both are PNG bytes. */
303
+ function compareShots(expected, actual, tol = DEFAULT_TOLERANCE) {
304
+ const a = PNG.sync.read(expected);
305
+ const b = PNG.sync.read(actual);
306
+ const width = Math.max(a.width, b.width);
307
+ const height = Math.max(a.height, b.height);
308
+ const diff = new PNG({
309
+ width,
310
+ height
311
+ });
312
+ const diffPixels = pixelmatch(pad(a, width, height), pad(b, width, height), diff.data, width, height, {
313
+ threshold: tol.threshold,
314
+ includeAA: false,
315
+ alpha: .2
316
+ });
317
+ const diffPercent = diffPixels / (width * height) * 100;
318
+ const resized = a.width !== b.width || a.height !== b.height;
319
+ return {
320
+ changed: resized || diffPercent > tol.maxDiffPercent,
321
+ diffPixels,
322
+ diffPercent,
323
+ ...resized ? { sizes: {
324
+ expected: [a.width, a.height],
325
+ actual: [b.width, b.height]
326
+ } } : {},
327
+ ...diffPixels > 0 || resized ? { diff: PNG.sync.write(diff) } : {}
328
+ };
329
+ }
330
+ /** True when two PNGs hold exactly the same pixels, whatever their encoding. */
331
+ function samePixels(x, y) {
332
+ const a = PNG.sync.read(x);
333
+ const b = PNG.sync.read(y);
334
+ return a.width === b.width && a.height === b.height && Buffer.compare(a.data, b.data) === 0;
335
+ }
336
+ // src/shots.ts
337
+ const WIDTHS = [390, 1280];
338
+ const THEMES = ["light", "dark"];
339
+ /** The time every shot sees (Date, timers, relative times): 2026/11/20(五)17:00 in Taipei. */
340
+ const FIXED_TIME = "2026-11-20T17:00:00+08:00";
341
+ /** Turns paths and URLs into jobs. Names come from the file name; a second target with the same name gets -2, -3, … */
342
+ function jobsFor(targets, toUrl) {
343
+ const stems = /* @__PURE__ */ new Map();
344
+ return targets.map((target) => {
345
+ const url = toUrl(target);
346
+ const base = decodeURIComponent(url.replace(/[?#].*$/, "").replace(/\/$/, "").split("/").pop() || "page").replace(/\.[^.]*$/, "");
347
+ const n = (stems.get(base) ?? 0) + 1;
348
+ stems.set(base, n);
349
+ return {
350
+ url,
351
+ stem: n > 1 ? `${base}-${n}` : base
352
+ };
353
+ });
354
+ }
355
+ /**
356
+ * Switches a loaded page to a theme. A page on bundle.js: the system's own setTheme, which also moves the accent's
357
+ * derived colors to the theme, so the dark pass is dark whatever the page did at load. Other pages: the attribute,
358
+ * if it uses one. Runs inside the page.
359
+ */
360
+ function applyTheme(t) {
361
+ const r = document.documentElement;
362
+ const ui = window.UI;
363
+ if (typeof ui?.setTheme === "function") ui.setTheme(t);
364
+ else if (r.hasAttribute("data-theme")) r.setAttribute("data-theme", t);
365
+ }
366
+ /**
367
+ * The browser for screenshots. CHROMIUM_PATH when set; otherwise Playwright's full Chromium (channel "chromium",
368
+ * new headless mode) rather than the headless shell, so local runs and CI render through the same kind of build.
369
+ */
370
+ function shotLaunchOptions() {
371
+ return process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : { channel: "chromium" };
372
+ }
373
+ /** File name of one screenshot. */
374
+ const shotName = (stem, width, theme) => `${stem}-${width}-${theme}.png`;
375
+ /**
376
+ * Takes the 4 screenshots of one page (2 widths x 2 themes), each in a fresh context, and returns them by file name.
377
+ * Deterministic: fixed clock (timers only advance by `settle` ms of fake time), reduced motion, animations stopped,
378
+ * caret hidden, fonts loaded, device scale factor 1, full page, fixed locale and time zone. The clock starts at FIXED_TIME and runs `settle` + 100 ms of fake time.
379
+ */
380
+ async function shootPage(browser, job, settle) {
381
+ const shots = /* @__PURE__ */ new Map();
382
+ for (const width of WIDTHS) for (const theme of THEMES) {
383
+ const phone = width === 390;
384
+ const viewport = {
385
+ width,
386
+ height: phone ? 844 : 900
387
+ };
388
+ const ctx = await browser.newContext({
389
+ viewport,
390
+ colorScheme: theme,
391
+ reducedMotion: "reduce",
392
+ hasTouch: phone,
393
+ isMobile: phone,
394
+ deviceScaleFactor: 1,
395
+ locale: "zh-TW",
396
+ timezoneId: "Asia/Taipei"
397
+ });
398
+ try {
399
+ const page = await ctx.newPage();
400
+ await page.clock.install({ time: Date.parse(FIXED_TIME) - 6e4 });
401
+ await page.clock.pauseAt(Date.parse(FIXED_TIME));
402
+ const resp = await page.goto(job.url, { waitUntil: "load" });
403
+ if (resp && !resp.ok()) throw new Error(`HTTP ${resp.status()}`);
404
+ const fonts = () => page.evaluate(() => document.fonts.ready.then(() => void 0));
405
+ await fonts();
406
+ await page.evaluate(applyTheme, theme);
407
+ await page.clock.runFor(settle);
408
+ await fonts();
409
+ for (const size of [{
410
+ ...viewport,
411
+ width: width + 1
412
+ }, viewport]) {
413
+ await page.setViewportSize(size);
414
+ await page.waitForTimeout(100);
415
+ await page.clock.runFor(100);
416
+ }
417
+ await page.evaluate(() => {
418
+ for (const el of document.querySelectorAll("*")) {
419
+ const { overflowX, overflowY } = getComputedStyle(el);
420
+ if (/auto|scroll/.test(overflowX + overflowY)) el.dispatchEvent(new Event("scroll"));
421
+ }
422
+ });
423
+ await page.waitForTimeout(100);
424
+ await page.waitForTimeout(200);
425
+ const shoot = () => page.screenshot({
426
+ fullPage: true,
427
+ animations: "disabled",
428
+ caret: "hide",
429
+ scale: "css"
430
+ });
431
+ let shot = await shoot();
432
+ for (let i = 0; i < 4; i++) {
433
+ await page.waitForTimeout(100);
434
+ const next = await shoot();
435
+ if (next.equals(shot)) break;
436
+ shot = next;
437
+ }
438
+ shots.set(shotName(job.stem, width, theme), shot);
439
+ } finally {
440
+ await ctx.close();
441
+ }
442
+ }
443
+ return shots;
444
+ }
445
+ /**
446
+ * Writes shots as baselines. A baseline with exactly the same pixels is kept as it is, so regenerating
447
+ * leaves no churn in git. New files are Playwright's PNGs, made smaller losslessly by oxipng when it is on PATH.
448
+ */
449
+ function writeShots(shots, dir) {
450
+ mkdirSync(dir, { recursive: true });
451
+ const results = [...shots].map(([name, png]) => {
452
+ const path = join(dir, name);
453
+ if (existsSync(path) && samePixels(readFileSync(path), png)) return {
454
+ name,
455
+ status: "kept"
456
+ };
457
+ writeFileSync(path, png);
458
+ return {
459
+ name,
460
+ status: "written"
461
+ };
462
+ });
463
+ optimizePngs(results.filter((r) => r.status === "written").map((r) => join(dir, r.name)));
464
+ return results;
465
+ }
466
+ let oxipng;
467
+ /** Lossless PNG optimisation with oxipng (about 35 % smaller than Playwright's PNGs); skipped when it is not installed. */
468
+ function optimizePngs(paths) {
469
+ if (oxipng === void 0) try {
470
+ execFileSync("oxipng", ["--version"], { stdio: "ignore" });
471
+ oxipng = true;
472
+ } catch {
473
+ oxipng = false;
474
+ }
475
+ if (oxipng && paths.length) execFileSync("oxipng", [
476
+ "--opt",
477
+ "4",
478
+ "--strip",
479
+ "safe",
480
+ "--quiet",
481
+ ...paths
482
+ ], { stdio: "inherit" });
483
+ return oxipng;
484
+ }
485
+ const pct = (n) => `${n.toFixed(4)} %`;
486
+ /**
487
+ * Compares shots with the baselines in baseDir. For each changed or new shot, diffDir gets <name>-actual.png
488
+ * (the new shot), and for a changed one also <name>-expected.png and <name>-diff.png (differences in red).
489
+ */
490
+ function compareWithBaselines(shots, baseDir, diffDir, tol) {
491
+ return [...shots].map(([name, png]) => {
492
+ const base = join(baseDir, name);
493
+ const stem = name.replace(/\.png$/, "");
494
+ if (!existsSync(base)) {
495
+ mkdirSync(diffDir, { recursive: true });
496
+ writeFileSync(join(diffDir, `${stem}-actual.png`), png);
497
+ return {
498
+ name,
499
+ status: "new",
500
+ detail: "no baseline"
501
+ };
502
+ }
503
+ const c = compareShots(readFileSync(base), png, tol);
504
+ const detail = c.sizes ? `size ${c.sizes.expected.join("x")} px -> ${c.sizes.actual.join("x")} px, ${c.diffPixels} px differ` : `${c.diffPixels} px differ (${pct(c.diffPercent)}, allowed ${pct(tol.maxDiffPercent)})`;
505
+ if (!c.changed) return {
506
+ name,
507
+ status: "same",
508
+ detail: c.diffPixels ? detail : void 0
509
+ };
510
+ mkdirSync(diffDir, { recursive: true });
511
+ writeFileSync(join(diffDir, `${stem}-actual.png`), png);
512
+ copyFileSync(base, join(diffDir, `${stem}-expected.png`));
513
+ if (c.diff) writeFileSync(join(diffDir, `${stem}-diff.png`), c.diff);
514
+ return {
515
+ name,
516
+ status: "changed",
517
+ detail
518
+ };
519
+ });
520
+ }
521
+ /** Names of the shots that differ from their baseline beyond the tolerance, or have none. Writes nothing. */
522
+ function changedShots(shots, baseDir, tol) {
523
+ return [...shots].filter(([name, png]) => {
524
+ const base = join(baseDir, name);
525
+ return !existsSync(base) || compareShots(readFileSync(base), png, tol).changed;
526
+ }).map(([name]) => name);
527
+ }
528
+ /** Baselines in baseDir that no shot of this run produced (a removed or renamed page). */
529
+ function orphanBaselines(baseDir, names) {
530
+ if (!existsSync(baseDir)) return [];
531
+ return readdirSync(baseDir).filter((f) => f.endsWith(".png") && !names.has(f)).sort();
532
+ }
533
+ /** The Markdown summary written next to the diffs (and shown in the CI job summary). */
534
+ function summaryMarkdown(results, orphans, baseDir) {
535
+ const changed = results.filter((r) => r.status === "changed");
536
+ const added = results.filter((r) => r.status === "new");
537
+ const lines = [
538
+ `# 畫面比對`,
539
+ "",
540
+ `${results.length} 張截圖:${changed.length} 張改變、${added.length} 張沒有基準圖。`,
541
+ ""
542
+ ];
543
+ if (changed.length) lines.push("## 改變", "", ...changed.map((r) => `- \`${r.name}\`: ${r.detail}`), "");
544
+ if (added.length) lines.push("## 沒有基準圖", "", ...added.map((r) => `- \`${r.name}\``), "");
545
+ if (orphans.length > 12) lines.push(`${baseDir} 中另有 ${orphans.length} 張基準圖不在這次比對的頁面內。`, "");
546
+ else if (orphans.length) lines.push(`## ${baseDir} 中沒有對應頁面的基準圖`, "", ...orphans.map((f) => `- \`${f}\``), "");
547
+ if (changed.length || added.length) lines.push("若改變符合預期:在 GitHub 上執行 Update visual baselines workflow(Actions → Update visual baselines → Run workflow,選這個分支),它會重新產生基準圖並 commit 到該分支。", "");
548
+ return lines.join("\n");
549
+ }
142
550
  // src/cli.ts
143
551
  const HELP = `ui check <file or URL>... [--shots DIR] [--strict] [--wait MS]
144
552
  Opens each page at 390 px and 1280 px, light and dark, and fails (exit 1) on:
145
553
  console errors, horizontal overflow at 390 px, touch targets under 48 px, touch areas that spill past their control, a card inside a card,
146
- raw Markdown, native controls the design system replaces, and wrapped buttons, tabs, headers or headings.
554
+ raw Markdown, native controls the design system replaces, wrapped buttons, tabs, headers or headings, controls of
555
+ different heights in one toolbar row, a status badge with a shadow in a table or card, and page CSS outside a
556
+ cascade layer on element selectors (a reset, normalize or starter CSS: button, *, h1) that overrides a component.
147
557
  Exits 2 when a page cannot be checked at all: it does not load, or the check itself crashes.
148
- ui docs [Name] prints the README of a component (Button, DataTable…) or a guide (guidelines, layout, motion)
149
- ui list lists every component`;
558
+ ui docs [Name] [--full]
559
+ Prints the 用法 block of a component (Button, DataTable…): what it is, a minimal example and the rules most often
560
+ gotten wrong. --full prints the whole README. Guides print whole: guidelines (the core rules every page needs),
561
+ layout, forms, data, monitoring, code, theme, motion. Without a name, lists every doc.
562
+ ui shots <file or URL>... (--out DIR [--prune] | --compare DIR --diff DIR) [--settle MS] [--threshold N] [--max-diff PERCENT]
563
+ Deterministic screenshots at 390 px and 1280 px, light and dark (DIR/<name>-<width>-<theme>.png): fixed clock
564
+ (${FIXED_TIME}, fake timers), reduced motion, animations stopped, caret hidden, fonts loaded, scale 1, full page.
565
+ --out DIR writes the shots (baselines); a file with the same pixels is left as it is. New files are
566
+ optimised losslessly with oxipng when it is on PATH. --prune also deletes the PNGs in DIR
567
+ that no page of this run produced (a removed or renamed page).
568
+ --compare DIR compares with the baselines in DIR and exits 1 when a shot changed or has no baseline. A pixel
569
+ differs when its color distance is over --threshold (default ${DEFAULT_TOLERANCE.threshold}, 0 to 1); a shot changed when
570
+ over --max-diff percent of its pixels differ (default ${DEFAULT_TOLERANCE.maxDiffPercent} %) or its size changed.
571
+ --diff DIR with --compare: <name>-actual.png, -expected.png and -diff.png (differences in red) for each changed
572
+ shot, and summary.md.
573
+ --settle MS fake time the page runs before the shot (default 1000).
574
+ A changed shot is taken once more; it passes when the second shot matches.
575
+ Exits 2 when a page cannot be opened. Uses CHROMIUM_PATH, else Playwright's full Chromium (channel chromium).
576
+ ui list lists every guide and component with its one-line description`;
150
577
  function docsDir() {
151
578
  const require = createRequire(import.meta.url);
152
579
  return join(dirname(require.resolve("@seanyeh77/ui/package.json")), "docs");
153
580
  }
154
- function docs(name) {
155
- const dir = docsDir();
581
+ /** Guides (lowercase file names) first, then the components. */
582
+ function docFiles(dir) {
156
583
  const files = readdirSync(dir).filter((f) => f.endsWith(".md"));
584
+ const guide = (f) => /^[a-z]/.test(f) ? 0 : 1;
585
+ return files.sort((a, b) => guide(a) - guide(b) || (a === "guidelines.md" ? -1 : b === "guidelines.md" ? 1 : a.localeCompare(b)));
586
+ }
587
+ function docs(name, full) {
588
+ const dir = docsDir();
589
+ const files = docFiles(dir);
157
590
  if (!name) return console.log(files.map((f) => f.slice(0, -3)).join("\n"));
158
591
  const hit = files.find((f) => f.slice(0, -3).toLowerCase() === name.toLowerCase());
159
592
  if (!hit) {
160
593
  console.error(`No docs for "${name}". Run "ui docs" for the list.`);
161
594
  process.exit(1);
162
595
  }
163
- console.log(readFileSync(join(dir, hit), "utf8"));
596
+ const md = readFileSync(join(dir, hit), "utf8");
597
+ const usage = full ? null : usageBlock(md);
598
+ if (!usage) return console.log(md);
599
+ console.log(usage + `\n(用法 only. The whole README: ui docs ${hit.slice(0, -3)} --full)`);
164
600
  }
165
601
  function list() {
166
602
  const dir = docsDir();
167
- for (const f of readdirSync(dir).filter((x) => x.endsWith(".md") && /^[A-Z]/.test(x))) {
168
- const first = readFileSync(join(dir, f), "utf8").split("\n").find((l) => l.trim() && !l.startsWith("#")) ?? "";
169
- console.log(`${f.slice(0, -3).padEnd(18)} ${first.trim()}`);
603
+ for (const f of docFiles(dir)) {
604
+ const md = readFileSync(join(dir, f), "utf8");
605
+ const line = /^[a-z]/.test(f) ? /^# (.+)$/m.exec(md)?.[1] ?? "" : summary(md);
606
+ console.log(`${f.slice(0, -3).padEnd(18)} ${line}`);
170
607
  }
171
608
  }
609
+ const toUrl = (t) => t.includes("://") ? new URL(t).href : pathToFileURL(resolve(t)).href;
172
610
  /** The page itself could not be opened: a wrong path, no server, or an HTTP error. */
173
611
  var Unreachable = class extends Error {};
612
+ async function shots(targets, opts) {
613
+ const out = opts.out ?? "";
614
+ const diff = opts.diff ?? "";
615
+ const { chromium } = await import("playwright");
616
+ const browser = await chromium.launch(shotLaunchOptions()).catch((e) => {
617
+ console.error(String(e).split("\n")[0]);
618
+ console.error("No Chromium for ui shots. Run `npx playwright install chromium`, or set CHROMIUM_PATH to an installed Chrome or Chromium.");
619
+ process.exit(2);
620
+ });
621
+ const jobs = jobsFor(targets, toUrl);
622
+ const lanes = Array(4).fill(Promise.resolve());
623
+ const runs = jobs.map((job, i) => {
624
+ const shoot = async () => {
625
+ const shots = await shootPage(browser, job, opts.settle);
626
+ if (!opts.compare) return {
627
+ shots,
628
+ retried: []
629
+ };
630
+ const changed = changedShots(shots, opts.compare, opts.tolerance);
631
+ if (!changed.length) return {
632
+ shots,
633
+ retried: []
634
+ };
635
+ const again = await shootPage(browser, job, opts.settle);
636
+ for (const n of changed) {
637
+ const next = again.get(n);
638
+ if (next) shots.set(n, next);
639
+ }
640
+ return {
641
+ shots,
642
+ retried: changed
643
+ };
644
+ };
645
+ const r = lanes[i % 4].then(() => shoot().then(({ shots, retried }) => ({
646
+ job,
647
+ shots,
648
+ retried,
649
+ error: void 0
650
+ }), (e) => ({
651
+ job,
652
+ shots: void 0,
653
+ retried: [],
654
+ error: String(e).split("\n")[0]
655
+ })));
656
+ lanes[i % 4] = r;
657
+ return r;
658
+ });
659
+ const all = [];
660
+ const names = /* @__PURE__ */ new Set();
661
+ let unshot = false;
662
+ for (const r of runs) {
663
+ const { job, shots, retried, error } = await r;
664
+ if (!shots) {
665
+ unshot = true;
666
+ console.log(`${job.url}\n could not shoot: ${error}`);
667
+ continue;
668
+ }
669
+ for (const n of shots.keys()) names.add(n);
670
+ const results = opts.compare ? compareWithBaselines(shots, opts.compare, diff, opts.tolerance) : writeShots(shots, out);
671
+ all.push(...results);
672
+ const bad = results.filter((x) => x.status === "changed" || x.status === "new");
673
+ const head = opts.compare ? bad.length ? "" : "same" : results.some((x) => x.status === "written") ? "written" : "unchanged";
674
+ console.log(`${job.url}: ${head}`);
675
+ for (const x of opts.compare ? bad : results) console.log(` ${x.name}: ${x.status}${x.detail ? ` (${x.detail})` : ""}`);
676
+ for (const n of retried) if (!bad.some((x) => x.name === n)) console.log(` ${n}: same on the second shot (the first differed)`);
677
+ }
678
+ await browser.close();
679
+ if (opts.compare) {
680
+ const orphans = orphanBaselines(opts.compare, names);
681
+ const changed = all.filter((x) => x.status === "changed" || x.status === "new").length;
682
+ if (orphans.length) console.log(orphans.length <= 12 ? `baselines with no page in this run (a removed or renamed page?): ${orphans.join(", ")}` : `${orphans.length} baselines have no page in this run (expected when only some pages are passed).`);
683
+ if (changed || orphans.length || unshot) {
684
+ mkdirSync(diff, { recursive: true });
685
+ writeFileSync(join(diff, "summary.md"), summaryMarkdown(all, orphans, opts.compare));
686
+ }
687
+ console.log(changed ? `${changed} of ${all.length} screenshots changed or have no baseline. Diffs and new shots: ${opts.diff}` : `${all.length} screenshots match ${opts.compare}.`);
688
+ process.exit(unshot ? 2 : changed ? 1 : 0);
689
+ }
690
+ const written = all.filter((x) => x.status === "written").length;
691
+ const optimized = optimizePngs([]);
692
+ if (opts.prune && !unshot) for (const f of orphanBaselines(out, names)) {
693
+ unlinkSync(join(out, f));
694
+ console.log(`removed ${f} (no page produced it)`);
695
+ }
696
+ console.log(`${all.length} screenshots in ${opts.out}: ${written} written${optimized ? " (oxipng)" : " (oxipng not found: PNGs as Playwright wrote them)"}, ${all.length - written} kept (same pixels).`);
697
+ process.exit(unshot ? 2 : 0);
698
+ }
174
699
  async function check(targets, opts) {
175
700
  const { chromium } = await import("playwright");
176
701
  const browser = await chromium.launch(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {}).catch((e) => {
@@ -178,17 +703,7 @@ async function check(targets, opts) {
178
703
  console.error("No Chromium for ui check. Run `npx playwright install chromium`, or set CHROMIUM_PATH to an installed Chrome or Chromium.");
179
704
  process.exit(2);
180
705
  });
181
- const stems = /* @__PURE__ */ new Map();
182
- const jobs = targets.map((target) => {
183
- const url = target.includes("://") ? new URL(target).href : pathToFileURL(resolve(target)).href;
184
- const base = decodeURIComponent(url.replace(/[?#].*$/, "").replace(/\/$/, "").split("/").pop() || "page").replace(/\.[^.]*$/, "");
185
- const n = (stems.get(base) ?? 0) + 1;
186
- stems.set(base, n);
187
- return {
188
- url,
189
- stem: n > 1 ? `${base}-${n}` : base
190
- };
191
- });
706
+ const jobs = jobsFor(targets, toUrl);
192
707
  const checkOne = async ({ url, stem }) => {
193
708
  const out = [url];
194
709
  let bad = false;
@@ -226,10 +741,7 @@ async function check(targets, opts) {
226
741
  await page.waitForLoadState("load");
227
742
  }
228
743
  };
229
- await run(() => page.evaluate((t) => {
230
- const r = document.documentElement;
231
- if (r.hasAttribute("data-theme") || "UI" in window) r.setAttribute("data-theme", t);
232
- }, theme));
744
+ await run(() => page.evaluate(applyTheme, theme));
233
745
  await page.waitForTimeout(opts.wait);
234
746
  await page.waitForLoadState("load");
235
747
  const res = await run(() => page.evaluate(measure));
@@ -240,6 +752,9 @@ async function check(targets, opts) {
240
752
  if (res.markdown.length) problems.push("raw Markdown shown: " + res.markdown.join("; "));
241
753
  if (res.native.length) problems.push("native controls: " + [...new Set(res.native)].join("; "));
242
754
  if (res.wrapped.length) problems.push("text that must stay on one line wraps: " + res.wrapped.join("; "));
755
+ if (res.mixed.length) problems.push("controls of different heights in one toolbar row: " + res.mixed.join("; ") + ". Use the system controls (Button, IconButton, SearchField, Select: 40 px) without your own height or padding.");
756
+ if (res.raised.length) problems.push("status badge with a shadow in a table or card: " + res.raised.join("; ") + ". Inside a table or card a Badge is a dot and text: remove your own box-shadow or chip styles.");
757
+ if (res.unlayered.length) problems.push("page CSS outside a layer overrides components: " + res.unlayered.join("; ") + ". Put page resets and normalize CSS in @layer base (or another layer declared before ui), and delete starter CSS such as Vite's index.css.");
243
758
  if (phone) {
244
759
  if (res.overflow.length) problems.push("horizontal overflow: " + res.overflow.join("; "));
245
760
  if (res.escaped.length) problems.push("touch area larger than its control (covers other controls): " + res.escaped.join("; "));
@@ -328,8 +843,70 @@ if (cmd === "check") {
328
843
  strict: !!values.strict,
329
844
  wait
330
845
  });
331
- } else if (cmd === "docs") docs(rest[0]);
332
- else if (cmd === "list") list();
846
+ } else if (cmd === "shots") {
847
+ const { values, positionals } = parseArgs({
848
+ args: rest,
849
+ allowPositionals: true,
850
+ options: {
851
+ out: { type: "string" },
852
+ compare: { type: "string" },
853
+ diff: { type: "string" },
854
+ prune: {
855
+ type: "boolean",
856
+ default: false
857
+ },
858
+ settle: {
859
+ type: "string",
860
+ default: "1000"
861
+ },
862
+ threshold: {
863
+ type: "string",
864
+ default: String(DEFAULT_TOLERANCE.threshold)
865
+ },
866
+ "max-diff": {
867
+ type: "string",
868
+ default: String(DEFAULT_TOLERANCE.maxDiffPercent)
869
+ }
870
+ }
871
+ });
872
+ const fail = (msg) => {
873
+ console.error(msg);
874
+ process.exit(2);
875
+ };
876
+ if (!positionals.length || !values.out && !values.compare) fail(HELP);
877
+ if (values.out && values.compare) fail("Give --out DIR (write baselines) or --compare DIR (check against them), not both.");
878
+ if (values.prune && !values.out) fail("--prune goes with --out: it deletes the baselines in that folder that no page produced.");
879
+ if (values.compare && !values.diff) fail("--compare needs --diff DIR: where the diff images and new shots go.");
880
+ if (values.compare && !existsSync(values.compare)) fail(`${values.compare}: no such baseline folder. Write baselines first with --out.`);
881
+ for (const t of positionals) if (!t.includes("://") && !existsSync(t)) fail(`${t}: no such file. Pass a file path or a URL.`);
882
+ const settle = Number(values.settle);
883
+ const threshold = Number(values.threshold);
884
+ const maxDiff = Number(values["max-diff"]);
885
+ if (!Number.isFinite(settle) || settle < 0) fail(`--settle ${values.settle}: give milliseconds, e.g. --settle 1000.`);
886
+ if (!(threshold >= 0 && threshold <= 1)) fail(`--threshold ${values.threshold}: give a color distance from 0 to 1, e.g. 0.1.`);
887
+ if (!(maxDiff >= 0 && maxDiff <= 100)) fail(`--max-diff ${values["max-diff"]}: give a percentage from 0 to 100, e.g. 0.02.`);
888
+ await shots(positionals, {
889
+ out: values.out,
890
+ compare: values.compare,
891
+ diff: values.diff,
892
+ prune: !!values.prune,
893
+ settle,
894
+ tolerance: {
895
+ threshold,
896
+ maxDiffPercent: maxDiff
897
+ }
898
+ });
899
+ } else if (cmd === "docs") {
900
+ const { values, positionals } = parseArgs({
901
+ args: rest,
902
+ allowPositionals: true,
903
+ options: { full: {
904
+ type: "boolean",
905
+ default: false
906
+ } }
907
+ });
908
+ docs(positionals[0], !!values.full);
909
+ } else if (cmd === "list") list();
333
910
  else {
334
911
  console.log(HELP);
335
912
  process.exit(cmd ? 2 : 0);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@seanyeh77/ui-cli",
3
- "version": "0.40.0",
4
- "description": "Checks a page against SeanYeh's design system and prints component docs: ui check, ui docs, ui list.",
3
+ "version": "0.42.0",
4
+ "description": "Checks a page against SeanYeh's design system, compares its screenshots with baselines and prints component docs: ui check, ui shots, ui docs, ui list.",
5
5
  "license": "MIT",
6
6
  "author": "Hsiu-An Yeh",
7
7
  "repository": {
@@ -17,14 +17,20 @@
17
17
  "dist"
18
18
  ],
19
19
  "dependencies": {
20
+ "pixelmatch": "^8.0.0",
20
21
  "playwright": "^1.65.0",
21
- "@seanyeh77/ui": "^0.40.0"
22
+ "pngjs": "^7.0.0",
23
+ "@seanyeh77/ui": "^0.42.0"
22
24
  },
23
25
  "engines": {
24
26
  "node": ">=22"
25
27
  },
28
+ "devDependencies": {
29
+ "@types/pngjs": "^6.0.5"
30
+ },
26
31
  "scripts": {
27
32
  "build": "tsdown",
28
- "typecheck": "tsc -p ."
33
+ "typecheck": "tsc -p .",
34
+ "test": "node --test src/*.test.ts"
29
35
  }
30
36
  }