@seanyeh77/ui-cli 0.45.0 → 0.47.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/README.md CHANGED
@@ -7,12 +7,14 @@ npm i -D @seanyeh77/ui-cli
7
7
  npx playwright install chromium # ui check 與 ui shots 用的瀏覽器;或設定 CHROMIUM_PATH
8
8
  ```
9
9
 
10
- - `ui check <檔案或 URL>`:在 390 px 與 1280 px、淺色與深色打開頁面,檢查 console 錯誤、水平溢出、小於 48 px 的觸控目標、1280 px 時小於 24 px 又擠著別的目標的目標(WCAG 2.5.8)、卡片裡的卡片、原生控制項、被截斷又沒有 Tooltip 或 title 的介面文字、跑出卡片外的文字、沒放進 layer 又蓋過元件的重設 CSS,以及 axe-core 的 WCAG 2.0、2.1、2.2 A 與 AA 規則,有問題時 exit 1。頁面沒有 viewport meta 時,390 px 只回報一次「缺 viewport meta」,不檢查觸控目標。
10
+ - `ui check <檔案或 URL>`:在 390 px 與 1280 px、淺色與深色打開頁面,檢查 console 錯誤、水平溢出、小於 48 px 的觸控目標、1280 px 時小於 24 px 又擠著別的目標的目標(WCAG 2.5.8)、卡片裡的卡片、原生控制項、被截斷又沒有 Tooltip 或 title 的介面文字、跑出卡片外的文字、同一列工具列或表單欄位不同高、390 px 時置中的兩行以上段落、AppShell 頁面的文件本身也在捲動、沒放進 layer 又蓋過元件的重設 CSS,以及 axe-core 的 WCAG 2.0、2.1、2.2 A 與 AA 規則,有問題時 exit 1。每次量測前等動畫和轉場結束(最多 1.5 s)。頁面沒有 viewport meta 時,390 px 只回報一次「缺 viewport meta」,不檢查觸控目標。
11
11
  - 它也會點開每個分頁(`[role=tablist]`)、SettingsLayout 的每個分類,以及工具列與頂欄裡 `[aria-haspopup]` 按鈕的選單,檢查打開後的畫面(淺色、兩種寬度,每頁最多 12 個狀態),只回報原本沒有的問題。
12
- - `--open <selector>` 點開頁面上第一個符合的元素(對話框、側欄)並檢查,可以重複;`--no-interact` 不自動點分頁、分類和選單;`--no-axe` 不跑 axe-core。
13
- - `ui shots <檔案或 URL>`:固定時間、停止動畫的截圖,寫成基準圖(`--out`)或和基準圖比對(`--compare`)。整頁截圖包含頁面自己的捲動區(AppShell 的主內容)裡捲到下面的內容。檔名來自檔案名稱,網址則用路徑加 hash(`http://localhost:5173/settings#billing` 是 `settings-billing`)。
12
+ - 每個寬度與主題那一行的結果算進頁面和打開的狀態;各狀態的問題列在「after opening …」底下。
13
+ - `--open <selector>` 點開頁面上第一個符合的元素(對話框、側欄)並檢查,可以重複;`--no-interact` 不自動點分頁、分類和選單;`--no-axe` 不跑 axe-core。`--shots <資料夾>` 存每個寬度與主題的整頁截圖,也存每個打開的狀態。
14
+ - `ui shots <檔案或 URL>`:固定時間、停止動畫的截圖,寫成基準圖(`--out`)或和基準圖比對(`--compare`)。整頁截圖包含頁面自己的捲動區(AppShell 的主內容)裡捲到下面的內容。檔名來自檔案名稱或網址的路徑,再接查詢字串和 hash(`http://localhost:5173/settings#billing` 是 `settings-billing`,`iframe.html?id=button--primary` 是 `iframe-id-button-primary`)。網路閒置、字型載入、高度連續兩次相同之後才截圖。
14
15
  - 每個指令加 `--help` 印出自己的說明。
15
16
  - `ui docs [Name] [--full]`:印出元件的用法區塊或使用規則;不加名稱時先印閱讀順序(guidelines 最先),再列出全部文件。
17
+ - `ui add <dashboard|list-detail|settings|login> [資料夾]`:把頁面範本寫進專案,內容在這個套件裡,不連網路(預設 `src/components/blocks/<範本>`;已有的檔案保留,`--force` 才覆寫)。和文件網站的 shadcn registry 是同一份範本。
16
18
  - `ui list`:依閱讀順序列出每份規則,再依分組(和 llms.txt 相同)列出每個元件的一句說明。
17
19
 
18
20
  `npx @seanyeh77/ui-cli` 不加參數會印出完整說明。
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
3
  import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
4
- import { dirname, join, resolve } from "node:path";
4
+ import { basename, dirname, join, relative, resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { parseArgs } from "node:util";
7
7
  import pixelmatch from "pixelmatch";
@@ -24,7 +24,10 @@ function measure() {
24
24
  viewportMeta: !!document.querySelector("meta[name=\"viewport\" i]"),
25
25
  truncated: [],
26
26
  outside: [],
27
- small24: []
27
+ small24: [],
28
+ formMixed: [],
29
+ centered: [],
30
+ docScroll: ""
28
31
  };
29
32
  const describe = (el) => {
30
33
  let s = el.tagName.toLowerCase();
@@ -174,7 +177,7 @@ function measure() {
174
177
  if (!parent || parent.closest("pre, code, script, style, textarea, .ui-cv") || !visible(parent)) continue;
175
178
  if (/`[^`]+`|\*\*[^*]+\*\*|^\s*#{1,6}\s/.test(t)) out.markdown.push(`${describe(parent)}: ${t.trim().slice(0, 40)}`);
176
179
  }
177
- for (const [q, use] of Object.entries({
180
+ const replacements = {
178
181
  select: "Select",
179
182
  table: "DataTable",
180
183
  dialog: "Dialog",
@@ -185,7 +188,13 @@ function measure() {
185
188
  "input[type=search]": "SearchField",
186
189
  "input[type=file]": "FileUpload",
187
190
  "input[type=color]": "AccentPicker"
188
- })) for (const el of document.querySelectorAll(q)) if (visible(el) && !el.matches("[class^=\"ui-\"], [class*=\" ui-\"]")) out.native.push(`<${q}> → use ${use}`);
191
+ };
192
+ const UI_CLASS = "[class^=\"ui-\"], [class*=\" ui-\"]";
193
+ replacements.button = "Button or IconButton";
194
+ replacements["a[href]"] = "Link";
195
+ replacements["input:is(:not([type]), [type=text], [type=email], [type=password], [type=number], [type=tel], [type=url])"] = "TextField";
196
+ replacements.textarea = "TextArea";
197
+ for (const [q, use] of Object.entries(replacements)) for (const el of document.querySelectorAll(q)) if (visible(el) && !el.matches(UI_CLASS) && !el.closest(".ui-md")) out.native.push(`${describe(el)} → use ${use}`);
189
198
  for (const el of document.querySelectorAll(".ui-btn, .ui-tab, [role=columnheader], .ui-field-label, h1, h2, h3, h4")) {
190
199
  if (out.wrapped.length >= 8 || !visible(el) || el.matches(".ui-md-h")) continue;
191
200
  if ([...el.querySelectorAll("*"), el].some((node) => [...node.childNodes].some((t) => {
@@ -238,7 +247,8 @@ function measure() {
238
247
  }
239
248
  }
240
249
  const bars = ".ui-dt-tools, .ui-dt-actions, .ui-card-actions, [role=toolbar]";
241
- const controls = "button, a[href], input:not([type=hidden]), [role=button], [role=combobox], .ui-searchfield, .ui-pwfield, .ui-datefield, .ui-ms, .ui-select, [role=tablist]";
250
+ const boxes = ".ui-searchfield, .ui-pwfield, .ui-datefield, .ui-field-box, .ui-ms, .ui-select, [role=tablist]";
251
+ const controls = "button, a[href], input:not([type=hidden]), [role=button], [role=combobox], " + boxes;
242
252
  for (const bar of document.querySelectorAll(bars)) {
243
253
  if (out.mixed.length >= 6) break;
244
254
  if (bar.parentElement?.closest(bars) || !visible(bar)) continue;
@@ -259,6 +269,57 @@ function measure() {
259
269
  }
260
270
  if (hit) out.mixed.push(hit);
261
271
  }
272
+ const fieldControls = "input:not([type=hidden]):not([type=checkbox]):not([type=radio]):not([type=range]), [role=combobox], " + boxes + ", .ui-input";
273
+ const rows = /* @__PURE__ */ new Map();
274
+ for (const field of document.querySelectorAll(".ui-field")) {
275
+ if (field.parentElement?.closest(".ui-field") || field.closest(bars) || !visible(field)) continue;
276
+ const el = [...field.querySelectorAll(fieldControls)].find((c) => {
277
+ const own = c.parentElement?.closest(fieldControls);
278
+ return !(own && field.contains(own)) && visible(c) && !c.closest("[aria-hidden=\"true\"], [role=listbox], [role=dialog]");
279
+ });
280
+ if (!el || el.matches("textarea") || el.querySelector("textarea")) continue;
281
+ let row = field.parentElement;
282
+ for (; row && row !== document.body; row = row.parentElement) {
283
+ const cs = getComputedStyle(row);
284
+ if (/grid/.test(cs.display) || /flex/.test(cs.display) && !cs.flexDirection.startsWith("column")) break;
285
+ }
286
+ if (!row || row === document.body) continue;
287
+ rows.set(row, [...rows.get(row) ?? [], {
288
+ field,
289
+ el,
290
+ r: el.getBoundingClientRect()
291
+ }]);
292
+ }
293
+ for (const [row, items] of rows) {
294
+ if (out.formMixed.length >= 6) break;
295
+ let hit = "";
296
+ for (let i = 0; i < items.length && !hit; i++) for (let j = i + 1; j < items.length && !hit; j++) {
297
+ const a = items[i].r;
298
+ const b = items[j].r;
299
+ if (Math.min(a.bottom, b.bottom) > Math.max(a.top, b.top) && Math.abs(a.height - b.height) > 1) {
300
+ const name = (f) => f.querySelector(".ui-field-label, label")?.textContent?.trim().slice(0, 16) || describe(f);
301
+ hit = `${describe(row)}: "${name(items[i].field)}" ${Math.round(a.height)} px, "${name(items[j].field)}" ${Math.round(b.height)} px`;
302
+ }
303
+ }
304
+ if (hit) out.formMixed.push(hit);
305
+ }
306
+ for (const el of document.body.querySelectorAll("*")) {
307
+ if (out.centered.length >= 6) break;
308
+ const cs = getComputedStyle(el);
309
+ if (!/center/.test(cs.textAlign) || cs.display.startsWith("inline") || /flex|grid/.test(cs.display)) continue;
310
+ if (![...el.childNodes].some((n) => n.nodeType === 3 && !!n.textContent?.trim())) continue;
311
+ if ([...el.children].some((c) => !getComputedStyle(c).display.startsWith("inline") && getComputedStyle(c).display !== "none")) continue;
312
+ if (el.closest(".ui-empty, .ui-errorpage, button, [role=button], td, th, [role=cell], [role=gridcell], [role=columnheader], svg, .ui-md table, [aria-hidden=\"true\"]")) continue;
313
+ if (!visible(el) || el.getBoundingClientRect().width < 160) continue;
314
+ const range = document.createRange();
315
+ range.selectNodeContents(el);
316
+ const lines = new Set([...range.getClientRects()].filter((r) => r.width > 1).map((r) => Math.round(r.top / 4))).size;
317
+ if (lines >= 2) out.centered.push(`${describe(el)} (${lines} lines)`);
318
+ }
319
+ if (document.querySelector(".ui-shell")) {
320
+ const doc = document.scrollingElement ?? document.documentElement;
321
+ if (doc.scrollHeight > innerHeight + 1) out.docScroll = `document ${doc.scrollHeight} px tall in a ${innerHeight} px window`;
322
+ }
262
323
  for (const el of document.querySelectorAll(".ui-dt-body .ui-badge, .ui-card .ui-badge")) {
263
324
  if (out.raised.length >= 6) break;
264
325
  const sh = getComputedStyle(el).boxShadow;
@@ -409,6 +470,39 @@ const GUIDES = [
409
470
  ["theme", "Every token, theme and accent settings, the accent derivation, the Slidev teaching preset"],
410
471
  ["motion", "Animation durations and effects, when you animate something yourself"]
411
472
  ];
473
+ /** The Markdown without its HTML comments (the @dsCard line of a hook's README, notes to maintainers); comments inside
474
+ fenced code stay, they are part of an example. Blank lines left behind are collapsed. */
475
+ function stripComments(md) {
476
+ let fenced = false;
477
+ const kept = [];
478
+ let open = false;
479
+ for (const line of md.split("\n")) {
480
+ if (!open && /^\s*(```|~~~)/.test(line)) fenced = !fenced;
481
+ if (fenced) {
482
+ kept.push(line);
483
+ continue;
484
+ }
485
+ let rest = line;
486
+ let text = "";
487
+ while (rest) if (open) {
488
+ const close = rest.indexOf("-->");
489
+ if (close < 0) break;
490
+ rest = rest.slice(close + 3);
491
+ open = false;
492
+ } else {
493
+ const start = rest.indexOf("<!--");
494
+ if (start < 0) {
495
+ text += rest;
496
+ break;
497
+ }
498
+ text += rest.slice(0, start);
499
+ rest = rest.slice(start + 4);
500
+ open = true;
501
+ }
502
+ if (text.trim() || line.trim() === "") kept.push(text.trimEnd());
503
+ }
504
+ return kept.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd().concat("\n");
505
+ }
412
506
  // src/compare.ts
413
507
  /** Anti-aliasing noise passes; a moved border, a changed color or a new line of text does not. */
414
508
  const DEFAULT_TOLERANCE = {
@@ -456,28 +550,102 @@ function samePixels(x, y) {
456
550
  const b = PNG.sync.read(y);
457
551
  return a.width === b.width && a.height === b.height && Buffer.compare(a.data, b.data) === 0;
458
552
  }
553
+ // src/add.ts
554
+ /** The templates shipped with this CLI. */
555
+ function loadTemplates(url = new URL("./templates.json", import.meta.url)) {
556
+ return JSON.parse(readFileSync(url, "utf8"));
557
+ }
558
+ /**
559
+ * Where a template goes when no folder is given: src/components/blocks/<name> in a project with a src folder (Vite,
560
+ * Next.js with src), else components/blocks/<name> (the shadcn registry's target).
561
+ */
562
+ function defaultDir(name, cwd) {
563
+ return join(existsSync(join(cwd, "src")) ? "src" : "", "components", "blocks", name);
564
+ }
565
+ /**
566
+ * Writes the template's files into dir, each under its file name (the files import each other by relative path).
567
+ * Existing files are left alone unless force is set; returns what was written and what was skipped.
568
+ */
569
+ function writeTemplate(t, dir, force) {
570
+ const written = [];
571
+ const skipped = [];
572
+ mkdirSync(dir, { recursive: true });
573
+ for (const f of t.files) {
574
+ const path = join(dir, basename(f.target));
575
+ if (existsSync(path) && !force) {
576
+ skipped.push(path);
577
+ continue;
578
+ }
579
+ writeFileSync(path, f.content);
580
+ written.push(path);
581
+ }
582
+ return {
583
+ written,
584
+ skipped
585
+ };
586
+ }
587
+ /** The lines printed after ui add: what was written and how to use it. */
588
+ function addReport(t, dir, r, cwd) {
589
+ const rel = (p) => relative(cwd, p) || ".";
590
+ const main = basename(t.files[0]?.target ?? "").replace(/\.tsx?$/, "");
591
+ const lines = [`${t.title} (${t.name}) → ${rel(dir)}/`];
592
+ for (const p of r.written) lines.push(` wrote ${rel(p)}`);
593
+ for (const p of r.skipped) lines.push(` kept ${rel(p)} (exists; --force overwrites it)`);
594
+ let listed = {};
595
+ try {
596
+ const pkg = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
597
+ listed = {
598
+ ...pkg.devDependencies,
599
+ ...pkg.dependencies
600
+ };
601
+ } catch {}
602
+ const deps = [.../* @__PURE__ */ new Set([
603
+ ...t.dependencies,
604
+ "react",
605
+ "react-dom"
606
+ ])].filter((d) => !listed[d]);
607
+ if (deps.length) lines.push(`Missing packages: npm i ${deps.join(" ")}`);
608
+ const sample = t.files.find((f) => /(^|\/)sample\.ts$/.test(f.target));
609
+ lines.push(`Use: render <${main} … /> from ${rel(join(dir, basename(t.files[0]?.target ?? "")))} with your data (its props are typed there${sample ? `; ${basename(sample.target)} has example data in their shape` : ""}).`);
610
+ return lines;
611
+ }
459
612
  // src/shots.ts
460
613
  const WIDTHS = [390, 1280];
461
614
  const THEMES = ["light", "dark"];
462
615
  /** The time every shot sees (Date, timers, relative times): 2026/11/20(五)17:00 in Taipei. */
463
616
  const FIXED_TIME = "2026-11-20T17:00:00+08:00";
617
+ /** A name part made safe for a file name: only letters, digits, dot, dash and underscore remain (no colon or slash). */
618
+ function cleanName(s) {
619
+ return s.replace(/[^\p{L}\p{N}._-]+/gu, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|-+$/g, "");
620
+ }
464
621
  /**
465
622
  * The name a page's screenshots are filed under. A file: its name without the extension (Button.html → Button). A
466
- * page on a server: its path and hash (http://localhost:5173/settings#billing → settings-billing, / → index), so the
467
- * pages of one site do not overwrite each other. Only letters, digits, dot, dash and underscore remain (no colon).
623
+ * page on a server: its path (http://localhost:5173/projects/42 → projects-42, / → index), so the pages of one site do
624
+ * not overwrite each other. Then the query and the hash of either, sanitised (iframe.html?id=button--primary →
625
+ * iframe-id-button-primary; settings#billing → settings-billing), so variants of one page get their own files.
468
626
  */
469
627
  function stemFor(url) {
470
- const clean = (s) => s.replace(/[^\p{L}\p{N}._-]+/gu, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|-+$/g, "");
471
628
  let u;
472
629
  try {
473
630
  u = new URL(url);
474
631
  } catch {
475
- return clean(url) || "page";
632
+ return cleanName(url) || "page";
476
633
  }
477
- const hash = decodeURIComponent(u.hash.slice(1));
478
- const path = decodeURIComponent(u.pathname).replace(/\/+$/, "");
479
- const base = u.protocol === "file:" ? (path.split("/").pop() ?? "").replace(/\.[^.]*$/, "") : path.replace(/\.html?$/i, "").split("/").filter(Boolean).join("-") || "index";
480
- return clean(hash ? `${base}-${hash}` : base) || "page";
634
+ const decode = (s) => {
635
+ try {
636
+ return decodeURIComponent(s.replace(/\+/g, " "));
637
+ } catch {
638
+ return s;
639
+ }
640
+ };
641
+ const query = [...u.searchParams].map(([k, v]) => v ? `${k}-${v}` : k).join("-");
642
+ const hash = decode(u.hash.slice(1));
643
+ const path = decode(u.pathname).replace(/\/+$/, "");
644
+ return cleanName([
645
+ u.protocol === "file:" ? (path.split("/").pop() ?? "").replace(/\.[^.]*$/, "") : path.replace(/\.html?$/i, "").split("/").filter(Boolean).join("-") || "index",
646
+ query,
647
+ hash
648
+ ].filter(Boolean).join("-")) || "page";
481
649
  }
482
650
  /** Turns paths and URLs into jobs, named by stemFor; a second target with the same name gets -2, -3, … */
483
651
  function jobsFor(targets, toUrl) {
@@ -516,33 +684,70 @@ function shotLaunchOptions() {
516
684
  * keeps the document at the window's height and scrolls its main area (.ui-shell-main), so a full-page shot would
517
685
  * stop at the window's bottom edge. When the document does not scroll but one large element (at least 60 % of the
518
686
  * window's height) does, the viewport grows by what that element hides, up to 12000 px, until nothing is hidden.
519
- * Returns the viewport to restore. Runs the given settle step after each resize.
687
+ * Content that renders late (data after a fetch, a list after fonts) changes the scroll height: the height is measured
688
+ * again after each settle step until two measurements in a row agree. Returns the viewport to restore.
520
689
  */
521
690
  async function growToScrollContainer(page, viewport, settle) {
522
691
  let size = viewport;
523
- for (let i = 0; i < 4; i++) {
524
- const hidden = await page.evaluate(() => {
525
- if ((document.scrollingElement ?? document.documentElement).scrollHeight > innerHeight + 1) return 0;
692
+ let last = "";
693
+ for (let i = 0; i < 10; i++) {
694
+ const m = await page.evaluate(() => {
695
+ const doc = document.scrollingElement ?? document.documentElement;
696
+ if (doc.scrollHeight > innerHeight + 1) return {
697
+ hidden: 0,
698
+ key: `doc ${doc.scrollHeight}`
699
+ };
526
700
  let most = 0;
701
+ let key = "none";
527
702
  for (const el of document.body.querySelectorAll("*")) {
528
703
  if (el.clientHeight < innerHeight * .6) continue;
529
704
  const cs = getComputedStyle(el);
530
705
  if (!/auto|scroll/.test(cs.overflowY) || cs.display === "none") continue;
531
- most = Math.max(most, el.scrollHeight - el.clientHeight);
706
+ const hidden = el.scrollHeight - el.clientHeight;
707
+ if (hidden >= most) {
708
+ most = hidden;
709
+ key = `box ${el.scrollHeight}`;
710
+ }
532
711
  }
533
- return most;
712
+ return {
713
+ hidden: most,
714
+ key: `${key} ${innerHeight}`
715
+ };
534
716
  });
535
- if (hidden <= 1) break;
536
- size = {
537
- width: size.width,
538
- height: Math.min(12e3, size.height + Math.ceil(hidden))
539
- };
540
- await page.setViewportSize(size);
717
+ if (m.hidden > 1 && size.height < 12e3) {
718
+ size = {
719
+ width: size.width,
720
+ height: Math.min(12e3, size.height + Math.ceil(m.hidden))
721
+ };
722
+ await page.setViewportSize(size);
723
+ } else if (m.key === last) break;
724
+ last = m.key;
541
725
  await settle();
542
- if (size.height >= 12e3) break;
543
726
  }
544
727
  return size;
545
728
  }
729
+ /**
730
+ * Waits until the page's animations and transitions have finished, up to `cap` ms. Endless ones (a spinner, a
731
+ * skeleton's shimmer) and paused ones are not waited for. Animations that start while waiting are waited for too.
732
+ * For ui check, on the real clock (ui shots stops animations instead).
733
+ */
734
+ async function waitForAnimations(page, cap = 1500) {
735
+ await page.evaluate(async (cap) => {
736
+ const end = performance.now() + cap;
737
+ const moving = () => document.getAnimations().filter((a) => {
738
+ if (a.playState !== "running" && !a.pending) return false;
739
+ const t = a.effect?.getComputedTiming();
740
+ return !!t && Number.isFinite(t.endTime);
741
+ });
742
+ const frame = () => new Promise((ok) => requestAnimationFrame(() => ok(void 0)));
743
+ for (let list = moving(); list.length && performance.now() < end; list = moving()) {
744
+ const left = end - performance.now();
745
+ await Promise.race([Promise.all(list.map((a) => a.finished.catch(() => void 0))), new Promise((ok) => setTimeout(ok, left))]);
746
+ await frame();
747
+ }
748
+ await frame();
749
+ }, cap);
750
+ }
546
751
  /** File name of one screenshot. */
547
752
  const shotName = (stem, width, theme) => `${stem}-${width}-${theme}.png`;
548
753
  /**
@@ -574,6 +779,7 @@ async function shootPage(browser, job, settle) {
574
779
  await page.clock.pauseAt(Date.parse(FIXED_TIME));
575
780
  const resp = await page.goto(job.url, { waitUntil: "load" });
576
781
  if (resp && !resp.ok()) throw new Error(`HTTP ${resp.status()}`);
782
+ await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => void 0);
577
783
  const fonts = () => page.evaluate(() => document.fonts.ready.then(() => void 0));
578
784
  await fonts();
579
785
  await page.evaluate(applyTheme, theme);
@@ -594,9 +800,12 @@ async function shootPage(browser, job, settle) {
594
800
  }
595
801
  });
596
802
  await page.waitForTimeout(100);
803
+ await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => void 0);
804
+ await fonts();
597
805
  await growToScrollContainer(page, viewport, async () => {
598
806
  await page.waitForTimeout(100);
599
807
  await page.clock.runFor(100);
808
+ await fonts();
600
809
  });
601
810
  await page.waitForTimeout(200);
602
811
  const shoot = () => page.screenshot({
@@ -731,25 +940,33 @@ const HELP_CHECK = `ui check <file or URL>... [--shots DIR] [--strict] [--wait M
731
940
  crowd another target at 1280 px (WCAG 2.5.8), touch areas that spill past their control, a card inside a card, raw
732
941
  Markdown, native controls the design system replaces, wrapped buttons, tabs, table headers or interface headings
733
942
  (headings in Markdown content may wrap), interface text cut off with no tooltip or title, text outside its card,
734
- controls of different heights in one toolbar row, a status badge with a shadow in a table or card, page CSS outside
735
- a cascade layer on element selectors (a reset, normalize or starter CSS: button, *, h1) that overrides a component,
736
- and the axe-core rules of WCAG 2.0, 2.1 and 2.2 A and AA.
943
+ controls of different heights in one toolbar row or one form row (a FormGrid row, fields side by side), paragraphs
944
+ of two or more lines centered at 390 px (EmptyState and ErrorPage excepted), a document that scrolls around
945
+ AppShell, a status badge with a shadow in a table or card, page CSS outside a cascade layer on element selectors (a
946
+ reset, normalize or starter CSS: button, *, h1) that overrides a component, and the axe-core rules of WCAG 2.0, 2.1
947
+ and 2.2 A and AA.
948
+ Each measurement waits until the page's animations and transitions end (up to 1.5 s), so a fade is not measured
949
+ half way.
737
950
  A page without <meta name="viewport"> gets one report at 390 px (缺 viewport meta) and no touch-target check there.
738
951
  It also opens what the page hides behind clicks, in light at both widths: each tab of a [role=tablist], each
739
952
  SettingsLayout category, and each menu or popover of an [aria-haspopup] button in a toolbar or top bar (up to 12
740
- states a page), and checks every state for the problems the page did not already have.
953
+ states a page), and checks every state for the problems the page did not already have. The line of each width and
954
+ theme counts the problems of the page and of its opened states; each state's problems follow under its name.
741
955
  --open SELECTOR clicks the first match and checks the state it opens (a dialog, a drawer); repeat for more.
742
956
  --no-interact skips the automatic tabs, categories and toolbar menus (--open still runs).
743
957
  --no-axe skips the axe-core pass.
744
- --shots DIR saves a full-page screenshot of each width and theme in DIR.
958
+ --shots DIR saves a full-page screenshot of each width and theme in DIR (<name>-<width>-<theme>.png, <name> as
959
+ in ui shots), and one of each opened state (<name>-<width>-light-<state>.png; an open dialog, drawer or menu at the viewport size).
745
960
  --strict also fails on inline text links under 48 px.
746
961
  --wait MS waits this long after load before measuring (default 800).
747
962
  Exits 2 when a page cannot be checked at all: it does not load, or the check itself crashes.`;
748
963
  const HELP_SHOTS = `ui shots <file or URL>... (--out DIR [--prune] | --compare DIR --diff DIR) [--settle MS] [--threshold N] [--max-diff PERCENT]
749
964
  Deterministic screenshots at 390 px and 1280 px, light and dark (DIR/<name>-<width>-<theme>.png): fixed clock
750
965
  (${FIXED_TIME}, fake timers), reduced motion, animations stopped, caret hidden, fonts loaded, scale 1, full page,
751
- including what scrolls inside the page's own scroll container (AppShell's main area). <name> is a file's name, or a
752
- URL's path and hash (http://host/settings#billing → settings-billing).
966
+ including what scrolls inside the page's own scroll container (AppShell's main area), measured once the network is
967
+ idle and the fonts are loaded, and again until the height stays the same. <name> is a file's name or a URL's path,
968
+ then its query and hash (http://host/settings#billing → settings-billing, iframe.html?id=button--primary →
969
+ iframe-id-button-primary).
753
970
  --out DIR writes the shots (baselines); a file with the same pixels is left as it is. New files are
754
971
  optimised losslessly with oxipng when it is on PATH. --prune also deletes the PNGs in DIR
755
972
  that no page of this run produced (a removed or renamed page).
@@ -766,7 +983,12 @@ const HELP_DOCS = `ui docs [Name] [--full]
766
983
  gotten wrong. --full prints the whole README. Guides print whole: guidelines (the core rules every page needs),
767
984
  layout, forms, data, monitoring, code, theme, motion. ui docs icons prints every built-in icon name on one line;
768
985
  ui docs agents prints the package's AGENTS.md. Without a name, prints the reading order and lists every doc.`;
986
+ const HELP_ADD = `ui add <template> [dir] [--force]
987
+ Writes a page template into the project, from the copy inside this package (no network): dashboard, list-detail,
988
+ settings, login. dir defaults to src/components/blocks/<template> (components/blocks/<template> without a src
989
+ folder). Existing files are kept unless --force. The same templates as the shadcn registry on the docs site.`;
769
990
  const HELP = `${HELP_CHECK}
991
+ ${HELP_ADD}
770
992
  ${HELP_DOCS}
771
993
  ${HELP_SHOTS}
772
994
  ui list lists every guide (in reading order) and every component by group, with its one-line description`;
@@ -814,7 +1036,7 @@ function docs(name, full) {
814
1036
  console.error(`No docs for "${name}". Run "ui docs" for the list.`);
815
1037
  process.exit(1);
816
1038
  }
817
- const md = readFileSync(join(dir, hit), "utf8");
1039
+ const md = stripComments(readFileSync(join(dir, hit), "utf8"));
818
1040
  const usage = full ? null : usageBlock(md);
819
1041
  if (!usage) return console.log(md);
820
1042
  const more = md.trim().length > usage.trim().length;
@@ -1000,12 +1222,15 @@ function problemsOf(res, phone, strict) {
1000
1222
  if (res.truncated.length) problems.push("interface text cut off: " + list(res.truncated, 8) + ". Give it room, or put the full text in a Tooltip or a title.");
1001
1223
  if (res.outside.length) problems.push("text outside its card: " + res.outside.join("; ") + ". Leave room inside the card (chart axis labels, long words).");
1002
1224
  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.");
1225
+ if (res.formMixed.length) problems.push("fields of different heights in one form row: " + res.formMixed.join("; ") + ". Use the system fields (TextField, Select, MultiSelect, DatePicker: 40 px) without your own height or padding.");
1226
+ if (res.docScroll) problems.push(`the document scrolls around AppShell (${res.docScroll}): AppShell scrolls its own main area. Remove page margin or padding around the frame and keep content inside it.`);
1003
1227
  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.");
1004
1228
  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.");
1005
1229
  if (phone && res.viewportMeta) {
1006
1230
  if (res.overflow.length) problems.push("horizontal overflow: " + res.overflow.join("; "));
1007
1231
  if (res.escaped.length) problems.push("touch area larger than its control (covers other controls): " + res.escaped.join("; "));
1008
1232
  if (res.small.length) problems.push(`touch targets under 48 px: ${list(res.small)}`);
1233
+ if (res.centered.length) problems.push("long text centered on a phone: " + res.centered.join("; ") + ". Align paragraphs of two or more lines to the start (text-align: start).");
1009
1234
  if (res.inline.length && strict) problems.push("inline targets under 48 px: " + list(res.inline));
1010
1235
  }
1011
1236
  if (!phone && res.small24.length) problems.push(`targets under 24 px next to another target (WCAG 2.5.8): ${list(res.small24, 8)}`);
@@ -1101,6 +1326,7 @@ async function check(targets, opts) {
1101
1326
  await run(() => page.evaluate(applyTheme, theme));
1102
1327
  await page.waitForTimeout(opts.wait);
1103
1328
  await page.waitForLoadState("load");
1329
+ await run(() => waitForAnimations(page));
1104
1330
  const res = await run(() => page.evaluate(measure));
1105
1331
  if (page.url() !== url && width === 390 && theme === "light") out.push(` (redirected to ${page.url()})`);
1106
1332
  const problems = [];
@@ -1112,18 +1338,19 @@ async function check(targets, opts) {
1112
1338
  problems.push(...problemsOf(res, phone, opts.strict));
1113
1339
  const axe = opts.axe ? await run(() => axeRun(page, theme === "dark")).catch((e) => [`axe-core could not run: ${String(e).split("\n")[0]}`]) : [];
1114
1340
  if (axe.length) problems.push("accessibility (axe-core): " + axe.join(" | "));
1115
- out.push(` ${width} px ${theme}: ${problems.length ? "" : "ok"}`);
1116
- for (const p of problems) out.push(" - " + p);
1117
- if (phone && theme === "light" && res.viewportMeta && res.inline.length && !opts.strict) out.push(` (inline text targets and links whose row is the target, exempt: ${res.inline.length})`);
1118
- bad ||= problems.length > 0;
1119
- if (opts.shots) {
1341
+ const shoot = async (suffix, overlay = false) => {
1342
+ if (!opts.shots) return;
1343
+ const path = join(opts.shots, `${shotName(stem, width, theme).slice(0, -4)}${suffix}.png`);
1344
+ if (overlay) return void await page.screenshot({ path });
1120
1345
  await growToScrollContainer(page, viewport, () => page.waitForTimeout(150));
1121
1346
  await page.screenshot({
1122
- path: join(opts.shots, `${stem}-${width}-${theme}.png`),
1347
+ path,
1123
1348
  fullPage: true
1124
1349
  });
1125
1350
  await page.setViewportSize(viewport);
1126
- }
1351
+ };
1352
+ await shoot("");
1353
+ const states = [];
1127
1354
  if (theme === "light" && (opts.open.length || opts.interact)) {
1128
1355
  const itemKey = (item) => item.split(", next to ")[0].replace(/ \d+ x \d+ px$/, "");
1129
1356
  const axeKey = (line) => line.split(" ")[0];
@@ -1136,7 +1363,7 @@ async function check(targets, opts) {
1136
1363
  if (Array.isArray(was) && Array.isArray(is)) {
1137
1364
  const seen = new Set(was.map(itemKey));
1138
1365
  out[k] = is.filter((x) => !seen.has(itemKey(x)));
1139
- }
1366
+ } else if (typeof was === "string" && was) out[k] = "";
1140
1367
  }
1141
1368
  return out;
1142
1369
  };
@@ -1144,10 +1371,11 @@ async function check(targets, opts) {
1144
1371
  const before = errors.length;
1145
1372
  try {
1146
1373
  await target.click({ timeout: 3e3 });
1147
- } catch (e) {
1148
- return `could not click ${label}: ${String(e).split("\n")[0]}`;
1374
+ } catch {
1375
+ return null;
1149
1376
  }
1150
- await page.waitForTimeout(350);
1377
+ await page.waitForTimeout(150);
1378
+ await run(() => waitForAnimations(page));
1151
1379
  const after = await run(() => page.evaluate(measure));
1152
1380
  const found = problemsOf(newOnly(after), phone, opts.strict);
1153
1381
  if (errors.length > before) found.unshift("console errors: " + errors.slice(before, before + 5).join(" | "));
@@ -1156,6 +1384,7 @@ async function check(targets, opts) {
1156
1384
  const more = (await run(() => axeRun(page, false, skip)).catch(() => [])).filter((v) => !knownAxe.has(axeKey(v)));
1157
1385
  if (more.length) found.push("accessibility (axe-core): " + more.join(" | "));
1158
1386
  }
1387
+ await shoot(`-${cleanName(label)}`, trigger);
1159
1388
  if (trigger) {
1160
1389
  await page.keyboard.press("Escape");
1161
1390
  await page.waitForTimeout(150);
@@ -1163,32 +1392,53 @@ async function check(targets, opts) {
1163
1392
  await target.click({ timeout: 3e3 }).catch(() => void 0);
1164
1393
  await page.waitForTimeout(150);
1165
1394
  }
1395
+ await run(() => waitForAnimations(page));
1166
1396
  }
1167
- return found.length ? `after opening ${label}: ${found.join(" / ")}` : "";
1397
+ return found;
1168
1398
  };
1169
- const stateProblems = [];
1170
1399
  for (const sel of opts.open) {
1171
1400
  const target = page.locator(sel).first();
1401
+ const label = `--open ${sel}`;
1172
1402
  if (!await target.count()) {
1173
- stateProblems.push(`--open ${sel}: nothing on the page matches`);
1403
+ states.push({
1404
+ label,
1405
+ problems: ["nothing on the page matches"]
1406
+ });
1174
1407
  continue;
1175
1408
  }
1176
- const r = await checkState(`--open ${sel}`, target, true);
1177
- if (r) stateProblems.push(r);
1409
+ const found = await checkState(label, target, true);
1410
+ if (!found) states.push({
1411
+ label,
1412
+ problems: ["could not click it"]
1413
+ });
1414
+ else if (found.length) states.push({
1415
+ label,
1416
+ problems: found
1417
+ });
1178
1418
  }
1179
1419
  if (opts.interact) {
1180
- const states = await run(() => page.evaluate(findStates, {
1420
+ const auto = await run(() => page.evaluate(findStates, {
1181
1421
  popups: TOOLBAR_POPUPS,
1182
1422
  max: MAX_STATES
1183
1423
  }));
1184
- for (const st of states) {
1185
- const r = await checkState(st.label, page.locator(`[data-ui-check-state="${st.id}"]`), st.kind === "popup");
1186
- if (r && !r.startsWith("could not click")) stateProblems.push(r);
1424
+ for (const st of auto) {
1425
+ const found = await checkState(st.label, page.locator(`[data-ui-check-state="${st.id}"]`), st.kind === "popup");
1426
+ if (found?.length) states.push({
1427
+ label: st.label,
1428
+ problems: found
1429
+ });
1187
1430
  }
1188
1431
  }
1189
- for (const p of stateProblems) out.push(` - ${p}`);
1190
- bad ||= stateProblems.length > 0;
1191
1432
  }
1433
+ const count = problems.length + states.reduce((n, st) => n + st.problems.length, 0);
1434
+ out.push(` ${width} px ${theme}: ${count ? `${count} problem${count === 1 ? "" : "s"}` : "ok"}`);
1435
+ for (const p of problems) out.push(" - " + p);
1436
+ for (const st of states) {
1437
+ out.push(` after opening ${st.label}:`);
1438
+ for (const p of st.problems) out.push(" - " + p);
1439
+ }
1440
+ if (phone && theme === "light" && res.viewportMeta && res.inline.length && !opts.strict) out.push(` (inline text targets and links whose row is the target, exempt: ${res.inline.length})`);
1441
+ bad ||= count > 0;
1192
1442
  } finally {
1193
1443
  await ctx.close();
1194
1444
  }
@@ -1348,7 +1598,20 @@ if (cmd === "check") {
1348
1598
  } }, HELP_DOCS);
1349
1599
  docs(positionals[0], !!values.full);
1350
1600
  } else if (cmd === "list") list();
1351
- else if (cmd === "--help" || cmd === "-h" || cmd === "help" || !cmd) console.log(HELP);
1601
+ else if (cmd === "add") {
1602
+ const { values, positionals } = parse(rest, { force: {
1603
+ type: "boolean",
1604
+ default: false
1605
+ } }, HELP_ADD);
1606
+ const templates = loadTemplates();
1607
+ const t = templates.find((x) => x.name === positionals[0]);
1608
+ if (!t) {
1609
+ console.error(`${positionals[0] ? `No template "${positionals[0]}". ` : ""}Templates:\n${templates.map((x) => ` ${x.name.padEnd(12)} ${x.description}`).join("\n")}\n\n${HELP_ADD}`);
1610
+ process.exit(2);
1611
+ }
1612
+ const dir = resolve(positionals[1] ?? defaultDir(t.name, process.cwd()));
1613
+ console.log(addReport(t, dir, writeTemplate(t, dir, !!values.force), process.cwd()).join("\n"));
1614
+ } else if (cmd === "--help" || cmd === "-h" || cmd === "help" || !cmd) console.log(HELP);
1352
1615
  else {
1353
1616
  console.error(`Unknown command "${cmd}".\n\n${HELP}`);
1354
1617
  process.exit(2);
@@ -0,0 +1,66 @@
1
+ [
2
+ {
3
+ "name": "dashboard",
4
+ "title": "Dashboard",
5
+ "description": "Dashboard page in the app frame: a period picker, KPI cards, a trend chart and a table of records, marked 示範資料. Replace the sample data with yours and drop the mark.",
6
+ "dependencies": [
7
+ "@seanyeh77/ui"
8
+ ],
9
+ "files": [
10
+ {
11
+ "target": "components/blocks/dashboard/Dashboard.tsx",
12
+ "content": "import * as React from 'react';\nimport {\n AppShell,\n Badge,\n Card,\n DataTable,\n DateRangePicker,\n Grid,\n KpiCard,\n LineChart,\n NotificationBell,\n Page,\n Tag,\n type DataTableColumn,\n type KpiCardProps,\n type NavSection,\n type NotificationItem,\n} from '@seanyeh77/ui';\n\n/* Dashboard: KPI cards, one trend chart and the table of records, inside the app frame.\n Replace the sample data with yours and drop the 「示範資料」 tag once the figures are real; keep the order (period,\n figures, trend, records). KPIs show only\n figures the table cannot: its summary already counts the projects per status. Give every KPI a sparkline (spark)\n or none, so the cards line up. */\n\nexport interface ProjectRow {\n id: string;\n name: string;\n owner: string;\n status: 'draft' | 'doing' | 'review' | 'done' | 'fail';\n progress: number;\n budget: number;\n updated: Date;\n}\n\nexport interface DashboardProps {\n kpis: KpiCardProps[];\n trend: { labels: string[]; series: { name: string; values: number[] }[] };\n rows: ProjectRow[];\n notifications: NotificationItem[];\n}\n\nconst NAV: NavSection[] = [\n {\n items: [\n { id: 'overview', label: '總覽', icon: 'house' },\n { id: 'projects', label: '專案', icon: 'folder' },\n { id: 'reports', label: '報表', icon: 'chart-bar' },\n ],\n },\n { items: [{ id: 'settings', label: '設定', icon: 'gear' }] },\n];\n\nconst STATUS_LABEL: Record<ProjectRow['status'], string> = { draft: '草稿', doing: '進行中', review: '審核中', done: '完成', fail: '失敗' };\n\nconst COLUMNS: DataTableColumn<ProjectRow>[] = [\n { key: 'name', label: '名稱' },\n { key: 'owner', label: '負責人' },\n { key: 'status', label: '狀態', render: (r) => <Badge status={r.status} />, searchText: (r) => STATUS_LABEL[r.status], mobile: 'status' },\n { key: 'progress', label: '進度', numeric: true, unit: '%' },\n { key: 'budget', label: '預算', format: 'money' },\n { key: 'updated', label: '更新', format: 'relative' },\n];\n\n// The last 30 days, today included.\nfunction last30(): [Date, Date] {\n const end = new Date();\n end.setHours(0, 0, 0, 0);\n return [new Date(end.getFullYear(), end.getMonth(), end.getDate() - 29), end];\n}\n\nexport function Dashboard({ kpis, trend, rows, notifications }: DashboardProps) {\n const [page, setPage] = React.useState('overview');\n // The period every figure below covers: at the top of the content, before the first row of cards.\n const [range, setRange] = React.useState<[Date | null, Date | null]>(last30);\n return (\n <AppShell\n nav={NAV}\n value={page}\n onNavigate={setPage}\n brand=\"專案中心\"\n title=\"總覽\"\n tags={<Tag icon=\"info\">示範資料</Tag>}\n actions={<NotificationBell items={notifications} />}\n >\n <Page>\n <DateRangePicker label=\"期間\" hideLabel value={range} onChange={setRange} />\n <Grid columns={4}>\n {kpis.map((k) => (\n <KpiCard key={k.label} {...k} />\n ))}\n </Grid>\n <Card title=\"每日完成的任務\">\n <LineChart label=\"每日完成的任務\" labels={trend.labels} series={trend.series} unit=\"個\" />\n </Card>\n {/* A short table on an overview: the summary tabs only, no search, filter or sort row (headings still sort). */}\n <Card title=\"專案\" padding={false}>\n <DataTable\n label=\"專案\"\n toolbar={false}\n columns={COLUMNS}\n rows={rows}\n summary={{\n key: 'status',\n items: [\n { value: 'fail', label: '失敗' },\n { value: 'review', label: '審核中' },\n { value: 'doing', label: '進行中' },\n { value: 'done', label: '完成' },\n { value: 'draft', label: '草稿' },\n ],\n unit: '個',\n }}\n urlKey=\"projects\"\n />\n </Card>\n </Page>\n </AppShell>\n );\n}\n"
13
+ },
14
+ {
15
+ "target": "components/blocks/dashboard/sample.ts",
16
+ "content": "import type { DashboardProps, ProjectRow } from './Dashboard';\n\nconst NAMES = ['網站改版', '叢集監控', '課程平台', '帳務整合', '資料備份', '權限管理', '告警通知', '成本報表'];\nconst OWNERS = ['王小明', '李小華', '陳大同', '林美玲'];\nconst STATUS: ProjectRow['status'][] = ['doing', 'review', 'done', 'fail', 'draft'];\n// Relative to today, so the figures cover the dashboard's default period (the last 30 days, today included).\nconst now = new Date();\nconst DAYS = Array.from({ length: 30 }, (_, i) => new Date(now.getFullYear(), now.getMonth(), now.getDate() - 29 + i));\nconst DONE = [3, 2, 4, 3, 5, 1, 2, 4, 3, 4, 6, 2, 1, 3, 5, 4, 3, 5, 2, 2, 4, 6, 5, 3, 4, 5, 3, 2, 4, 6];\n\nexport const sample: DashboardProps = {\n kpis: [\n { label: '營收', value: 12840000, format: 'money', delta: 8.2, spark: [8, 9, 9.5, 10, 11, 12.8] },\n { label: '預算使用率', value: 74.5, format: 'percent', unit: '%', delta: 3.1, deltaUnit: 'pt', direction: 'down', spark: [58, 61, 63, 66, 71.4, 74.5] },\n { label: '準時完成率', value: 92.4, format: 'percent', unit: '%', delta: 1.8, deltaUnit: 'pt', spark: [88, 89.5, 90.1, 89.8, 90.6, 92.4] },\n { label: '平均回應時間', value: 184, unit: 'ms', delta: -12.5, direction: 'down', spark: [230, 221, 214, 206, 210, 184] },\n ],\n trend: { labels: DAYS.map((d) => `${d.getMonth() + 1}/${d.getDate()}`), series: [{ name: '完成', values: DONE }] },\n rows: NAMES.map((name, i) => ({\n id: String(i + 1),\n name,\n owner: OWNERS[i % OWNERS.length],\n status: STATUS[i % STATUS.length],\n progress: [64, 88, 100, 40, 12, 72, 55, 100][i],\n budget: (i + 2) * 85000,\n updated: new Date(now.getTime() - (i + 1) * 5 * 3600 * 1000),\n })),\n notifications: [\n { id: 1, title: '叢集監控 部署失敗', body: 'node-3 超過 5 分鐘沒有回應', time: '10 分鐘前', group: '今天' },\n { id: 2, title: '李小華 提到了你', body: '「預算表請幫忙看一下」', time: '1 小時前', group: '今天', read: true },\n ],\n};\n"
17
+ }
18
+ ]
19
+ },
20
+ {
21
+ "name": "list-detail",
22
+ "title": "List and edit drawer",
23
+ "description": "A table of records with an edit drawer that asks before discarding unsaved changes.",
24
+ "dependencies": [
25
+ "@seanyeh77/ui"
26
+ ],
27
+ "files": [
28
+ {
29
+ "target": "components/blocks/list-detail/ListDetail.tsx",
30
+ "content": "import * as React from 'react';\nimport {\n AppShell,\n Badge,\n Button,\n Card,\n DataTable,\n Drawer,\n FormGrid,\n IconButton,\n Page,\n Select,\n TextArea,\n TextField,\n toast,\n type DataTableColumn,\n useFormErrors,\n type NavSection,\n} from '@seanyeh77/ui';\n\n/* A list page: the title once (top bar), the list in one Card, the page's one primary action (新增) at the end of the\n summary row (DataTable's action), the count in the table's toolbar. Hover a row (or tab to it) and click its pencil to\n edit it in a drawer; closing with unsaved changes asks first. Replace Item and the fields with yours. */\n\nexport interface Item {\n id: string;\n name: string;\n owner: string;\n status: 'draft' | 'doing' | 'review' | 'done' | 'fail';\n note: string;\n /** Last change; shown as relative time within a week. */\n updated: Date;\n}\n\nexport interface ListDetailProps {\n items: Item[];\n owners: string[];\n /** A new item has id ''; give it an id when you store it. */\n onSave: (item: Item) => void;\n}\n\nconst NAV: NavSection[] = [\n {\n items: [\n { id: 'items', label: '項目', icon: 'list-bullets' },\n { id: 'settings', label: '設定', icon: 'gear' },\n ],\n },\n];\nconst STATUS_OPTIONS: { value: Item['status']; label: string }[] = [\n { value: 'draft', label: '草稿' },\n { value: 'doing', label: '進行中' },\n { value: 'review', label: '審核中' },\n { value: 'done', label: '完成' },\n { value: 'fail', label: '失敗' },\n];\n\n// The summary: 「全部」, then the state that needs attention, then the rest.\nconst statusLabel = (s: Item['status']) => STATUS_OPTIONS.find((o) => o.value === s)?.label ?? s;\nconst SUMMARY = (['fail', 'review', 'doing', 'done', 'draft'] as const).map((v) => ({ value: v, label: statusLabel(v) }));\n// Outside the component: one array for every render, so the table does not sort and filter again on each one.\nconst COLUMNS: DataTableColumn<Item>[] = [\n { key: 'name', label: '名稱' },\n { key: 'owner', label: '負責人' },\n { key: 'status', label: '狀態', render: (r) => <Badge status={r.status} />, searchText: (r) => statusLabel(r.status), mobile: 'status' },\n { key: 'note', label: '備註', long: true },\n { key: 'updated', label: '更新', format: 'relative' },\n];\n\nexport function ListDetail({ items, owners, onSave }: ListDetailProps) {\n const [editing, setEditing] = React.useState<Item | null>(null);\n const [draft, setDraft] = React.useState<Item | null>(null);\n // Errors show once a field is left (blur) or on 儲存, not on every key; 儲存 with an error moves focus to the field.\n const form = useFormErrors({ name: draft?.name ?? '' }, (v) => ({\n name: v.name.trim() ? undefined : '名稱不能空白,請輸入專案名稱。',\n }));\n const dirty = !!editing && JSON.stringify(editing) !== JSON.stringify(draft);\n const open = (it: Item) => {\n setEditing(it);\n setDraft(it);\n };\n const close = () => {\n setEditing(null);\n setDraft(null);\n form.reset();\n };\n const create = () => open({ id: '', name: '', owner: owners[0] ?? '', status: 'draft', note: '', updated: new Date() });\n const set = <K extends keyof Item>(k: K, v: Item[K]) => setDraft((d) => (d ? { ...d, [k]: v } : d));\n return (\n <AppShell nav={NAV} value=\"items\" onNavigate={() => {}} brand=\"專案中心\" title=\"項目\">\n <Page>\n <Card padding={false}>\n <DataTable\n label=\"項目\"\n columns={COLUMNS}\n rows={items}\n summary={{ key: 'status', items: SUMMARY }}\n action={\n <Button variant=\"primary\" icon=\"plus\" onClick={create}>\n 新增\n </Button>\n }\n rowActions={(r) => <IconButton variant=\"quiet\" icon=\"pencil-simple\" label={`編輯 ${r.name}`} onClick={() => open(r)} />}\n urlKey=\"items\"\n />\n </Card>\n </Page>\n <Drawer\n open={!!editing}\n onOpenChange={(o) => !o && close()}\n dirty={dirty}\n title={!editing ? '' : editing.id ? `編輯 ${editing.name}` : '新增項目'}\n actions={(requestClose) => (\n <>\n <Button onClick={requestClose}>取消</Button>\n <Button\n variant=\"primary\"\n // Not disabled for an error: 儲存 says what is wrong and goes to the field.\n disabled={!dirty}\n onClick={form.submit(() => {\n if (!draft) return;\n onSave({ ...draft, updated: new Date() });\n close();\n toast(draft.id ? '已儲存' : '已新增');\n })}\n >\n 儲存\n </Button>\n </>\n )}\n >\n {draft ? (\n <FormGrid>\n <TextField\n label=\"名稱\"\n name=\"name\"\n required\n value={draft.name}\n onChange={(v) => set('name', v)}\n onBlur={() => form.onBlur('name')}\n error={form.errors.name}\n />\n <Select label=\"負責人\" value={draft.owner} options={owners.map((o) => ({ value: o, label: o }))} onChange={(v) => set('owner', v)} />\n <Select label=\"狀態\" value={draft.status} options={STATUS_OPTIONS} onChange={(v) => set('status', v)} />\n <TextArea label=\"備註\" value={draft.note} onChange={(v) => set('note', v)} />\n </FormGrid>\n ) : null}\n </Drawer>\n </AppShell>\n );\n}\n"
31
+ },
32
+ {
33
+ "target": "components/blocks/list-detail/sample.ts",
34
+ "content": "import type { ListDetailProps } from './ListDetail';\n\nconst now = new Date(2026, 10, 4, 15, 0);\n\nexport const sample: Omit<ListDetailProps, 'onSave'> = {\n owners: ['王小明', '李小華', '陳大同'],\n items: [\n {\n id: '1',\n name: '網站改版',\n owner: '王小明',\n status: 'doing',\n note: '首頁與定價頁先上線,其餘頁面下個月。',\n updated: new Date(now.getTime() - 2 * 3600 * 1000),\n },\n {\n id: '2',\n name: '叢集監控',\n owner: '李小華',\n status: 'fail',\n note: 'node-3 的代理程式版本太舊,需要更新後重新部署。',\n updated: new Date(now.getTime() - 26 * 3600 * 1000),\n },\n { id: '3', name: '課程平台', owner: '陳大同', status: 'review', note: '', updated: new Date(now.getTime() - 72 * 3600 * 1000) },\n { id: '4', name: '帳務整合', owner: '王小明', status: 'done', note: '已和會計系統對帳完成。', updated: new Date(now.getTime() - 216 * 3600 * 1000) },\n ],\n};\n"
35
+ }
36
+ ]
37
+ },
38
+ {
39
+ "name": "settings",
40
+ "title": "Settings page",
41
+ "description": "Settings in the app frame: categories in the URL hash, switch rows, fields that save on blur, 「已儲存」, theme and accent pickers, and a danger zone last.",
42
+ "dependencies": [
43
+ "@seanyeh77/ui"
44
+ ],
45
+ "files": [
46
+ {
47
+ "target": "components/blocks/settings/Settings.tsx",
48
+ "content": "import * as React from 'react';\nimport {\n AccentPicker,\n AppShell,\n DangerZone,\n SettingsLayout,\n SettingsRow,\n SettingsSection,\n Switch,\n TextField,\n ThemePicker,\n toast,\n useFormErrors,\n type NavSection,\n} from '@seanyeh77/ui';\n\n/* Settings page: categories on the left, sections on the right, the open category in the URL hash. Changes save on\n their own and show 「已儲存」; there is no save button. Switches save when they change; a text field saves when it is\n left (blur) and valid, not on every key. Delete-type actions go last, in a DangerZone at the bottom of the last\n category. The title shows once: AppShell's title=\"設定\", none on SettingsLayout. */\n\nexport interface SettingsValues {\n name: string;\n email: string;\n notifyEmail: boolean;\n notifyWeekly: boolean;\n}\n\nexport interface SettingsProps {\n values: SettingsValues;\n /** Store the new values; called once per saved change. */\n onChange: (values: SettingsValues) => void;\n onDeleteAccount: () => void;\n}\n\nconst NAV: NavSection[] = [\n {\n items: [\n { id: 'overview', label: '總覽', icon: 'house' },\n { id: 'projects', label: '專案', icon: 'folder' },\n ],\n },\n { items: [{ id: 'settings', label: '設定', icon: 'gear' }] },\n];\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nexport function Settings({ values, onChange, onDeleteAccount }: SettingsProps) {\n const save = (next: Partial<SettingsValues>) => {\n onChange({ ...values, ...next });\n // One 「已儲存」 that restarts its 3 s on every change, not a new one per key.\n toast('已儲存', { id: 'saved' });\n };\n\n // Text fields: a draft while typing; saved when the field is left and the value is valid and changed.\n const [name, setName] = React.useState(values.name);\n const [email, setEmail] = React.useState(values.email);\n // Errors show once a field is left; onBlur returns whether the field is valid, so it saves only then.\n const form = useFormErrors({ name, email }, (v) => ({\n name: v.name.trim() ? undefined : '名稱不能空白,請輸入顯示名稱。',\n email: EMAIL.test(v.email) ? undefined : 'Email 格式不正確,例如 name@example.com',\n }));\n\n return (\n <AppShell nav={NAV} value=\"settings\" onNavigate={() => {}} brand=\"專案中心\" title=\"設定\">\n <SettingsLayout\n categories={[\n {\n id: 'profile',\n label: '個人資料',\n content: (\n <SettingsSection title=\"個人資料\">\n <TextField\n label=\"名稱\"\n value={name}\n onChange={(v) => setName(v)}\n onBlur={() => {\n if (form.onBlur('name') && name.trim() !== values.name) save({ name: name.trim() });\n }}\n error={form.errors.name}\n />\n <TextField\n label=\"Email\"\n type=\"email\"\n value={email}\n onChange={(v) => setEmail(v)}\n onBlur={() => {\n if (form.onBlur('email') && email !== values.email) save({ email });\n }}\n error={form.errors.email}\n />\n </SettingsSection>\n ),\n },\n {\n id: 'notifications',\n label: '通知',\n content: (\n <SettingsSection title=\"通知\">\n <SettingsRow label=\"部署失敗時寄 Email\" description=\"寄到個人資料裡的 Email。\">\n <Switch label=\"部署失敗時寄 Email\" checked={values.notifyEmail} onChange={(v) => save({ notifyEmail: v })} />\n </SettingsRow>\n <SettingsRow label=\"每週摘要\" description=\"每週一早上寄出上週的進度。\">\n <Switch label=\"每週摘要\" checked={values.notifyWeekly} onChange={(v) => save({ notifyWeekly: v })} />\n </SettingsRow>\n </SettingsSection>\n ),\n },\n {\n id: 'appearance',\n label: '外觀',\n content: (\n <SettingsSection title=\"外觀\" description=\"只影響這個瀏覽器。\">\n <ThemePicker />\n <AccentPicker />\n </SettingsSection>\n ),\n },\n {\n id: 'account',\n label: '帳號',\n content: (\n <DangerZone\n title=\"刪除帳號\"\n description=\"刪除後,所有專案和資料都無法復原。\"\n actionLabel=\"刪除帳號\"\n confirm={{ title: '刪除帳號?', body: '所有專案和資料會一起刪除,無法復原。' }}\n onAction={onDeleteAccount}\n />\n ),\n },\n ]}\n />\n </AppShell>\n );\n}\n"
49
+ }
50
+ ]
51
+ },
52
+ {
53
+ "name": "login",
54
+ "title": "Sign-in page",
55
+ "description": "A centered sign-in card with per-field errors from your sign-in check.",
56
+ "dependencies": [
57
+ "@seanyeh77/ui"
58
+ ],
59
+ "files": [
60
+ {
61
+ "target": "components/blocks/login/Login.tsx",
62
+ "content": "import * as React from 'react';\nimport { LoginCard, type LoginCardProps } from '@seanyeh77/ui';\n\n/* Sign-in page. Pass the result of your sign-in check back as error: the cause and the fix, per field. */\n\nexport interface LoginProps {\n brand?: React.ReactNode;\n /** Resolves to null, or to the field errors (cause and fix). Throw only when the server cannot be reached. */\n signIn: (account: string, password: string) => Promise<LoginCardProps['error']>;\n forgotHref?: string;\n}\n\nexport function Login({ brand, signIn, forgotHref }: LoginProps) {\n const [error, setError] = React.useState<LoginCardProps['error']>(null);\n const [loading, setLoading] = React.useState(false);\n return (\n <LoginCard\n brand={brand}\n forgotHref={forgotHref}\n loading={loading}\n error={error}\n onSubmit={async ({ account, password }) => {\n setLoading(true);\n try {\n setError(await signIn(account, password));\n } catch {\n setError({ password: '無法連線,請確認網路後再試一次。' });\n } finally {\n setLoading(false);\n }\n }}\n />\n );\n}\n"
63
+ }
64
+ ]
65
+ }
66
+ ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seanyeh77/ui-cli",
3
- "version": "0.45.0",
3
+ "version": "0.47.0",
4
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",
@@ -21,7 +21,7 @@
21
21
  "pixelmatch": "^8.0.0",
22
22
  "playwright": "1.65.0",
23
23
  "pngjs": "^7.0.0",
24
- "@seanyeh77/ui": "^0.45.0"
24
+ "@seanyeh77/ui": "^0.47.0"
25
25
  },
26
26
  "engines": {
27
27
  "node": ">=22"
@@ -30,7 +30,7 @@
30
30
  "@types/pngjs": "^6.0.5"
31
31
  },
32
32
  "scripts": {
33
- "build": "tsdown",
33
+ "build": "tsdown && node scripts/templates.ts",
34
34
  "typecheck": "tsc -p .",
35
35
  "test": "node --test src/*.test.ts"
36
36
  }