@seanyeh77/ui-cli 0.45.0 → 0.46.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 +5 -3
- package/dist/cli.js +304 -55
- package/dist/templates.json +66 -0
- package/package.json +3 -3
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
|
|
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
|
-
-
|
|
13
|
-
-
|
|
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();
|
|
@@ -238,7 +241,8 @@ function measure() {
|
|
|
238
241
|
}
|
|
239
242
|
}
|
|
240
243
|
const bars = ".ui-dt-tools, .ui-dt-actions, .ui-card-actions, [role=toolbar]";
|
|
241
|
-
const
|
|
244
|
+
const boxes = ".ui-searchfield, .ui-pwfield, .ui-datefield, .ui-ms, .ui-select, [role=tablist]";
|
|
245
|
+
const controls = "button, a[href], input:not([type=hidden]), [role=button], [role=combobox], " + boxes;
|
|
242
246
|
for (const bar of document.querySelectorAll(bars)) {
|
|
243
247
|
if (out.mixed.length >= 6) break;
|
|
244
248
|
if (bar.parentElement?.closest(bars) || !visible(bar)) continue;
|
|
@@ -259,6 +263,57 @@ function measure() {
|
|
|
259
263
|
}
|
|
260
264
|
if (hit) out.mixed.push(hit);
|
|
261
265
|
}
|
|
266
|
+
const fieldControls = "input:not([type=hidden]):not([type=checkbox]):not([type=radio]):not([type=range]), [role=combobox], " + boxes + ", .ui-input";
|
|
267
|
+
const rows = /* @__PURE__ */ new Map();
|
|
268
|
+
for (const field of document.querySelectorAll(".ui-field")) {
|
|
269
|
+
if (field.parentElement?.closest(".ui-field") || field.closest(bars) || !visible(field)) continue;
|
|
270
|
+
const el = [...field.querySelectorAll(fieldControls)].find((c) => {
|
|
271
|
+
const own = c.parentElement?.closest(fieldControls);
|
|
272
|
+
return !(own && field.contains(own)) && visible(c) && !c.closest("[aria-hidden=\"true\"], [role=listbox], [role=dialog]");
|
|
273
|
+
});
|
|
274
|
+
if (!el || el.matches("textarea") || el.querySelector("textarea")) continue;
|
|
275
|
+
let row = field.parentElement;
|
|
276
|
+
for (; row && row !== document.body; row = row.parentElement) {
|
|
277
|
+
const cs = getComputedStyle(row);
|
|
278
|
+
if (/grid/.test(cs.display) || /flex/.test(cs.display) && !cs.flexDirection.startsWith("column")) break;
|
|
279
|
+
}
|
|
280
|
+
if (!row || row === document.body) continue;
|
|
281
|
+
rows.set(row, [...rows.get(row) ?? [], {
|
|
282
|
+
field,
|
|
283
|
+
el,
|
|
284
|
+
r: el.getBoundingClientRect()
|
|
285
|
+
}]);
|
|
286
|
+
}
|
|
287
|
+
for (const [row, items] of rows) {
|
|
288
|
+
if (out.formMixed.length >= 6) break;
|
|
289
|
+
let hit = "";
|
|
290
|
+
for (let i = 0; i < items.length && !hit; i++) for (let j = i + 1; j < items.length && !hit; j++) {
|
|
291
|
+
const a = items[i].r;
|
|
292
|
+
const b = items[j].r;
|
|
293
|
+
if (Math.min(a.bottom, b.bottom) > Math.max(a.top, b.top) && Math.abs(a.height - b.height) > 1) {
|
|
294
|
+
const name = (f) => f.querySelector(".ui-field-label, label")?.textContent?.trim().slice(0, 16) || describe(f);
|
|
295
|
+
hit = `${describe(row)}: "${name(items[i].field)}" ${Math.round(a.height)} px, "${name(items[j].field)}" ${Math.round(b.height)} px`;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (hit) out.formMixed.push(hit);
|
|
299
|
+
}
|
|
300
|
+
for (const el of document.body.querySelectorAll("*")) {
|
|
301
|
+
if (out.centered.length >= 6) break;
|
|
302
|
+
const cs = getComputedStyle(el);
|
|
303
|
+
if (!/center/.test(cs.textAlign) || cs.display.startsWith("inline") || /flex|grid/.test(cs.display)) continue;
|
|
304
|
+
if (![...el.childNodes].some((n) => n.nodeType === 3 && !!n.textContent?.trim())) continue;
|
|
305
|
+
if ([...el.children].some((c) => !getComputedStyle(c).display.startsWith("inline") && getComputedStyle(c).display !== "none")) continue;
|
|
306
|
+
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;
|
|
307
|
+
if (!visible(el) || el.getBoundingClientRect().width < 160) continue;
|
|
308
|
+
const range = document.createRange();
|
|
309
|
+
range.selectNodeContents(el);
|
|
310
|
+
const lines = new Set([...range.getClientRects()].filter((r) => r.width > 1).map((r) => Math.round(r.top / 4))).size;
|
|
311
|
+
if (lines >= 2) out.centered.push(`${describe(el)} (${lines} lines)`);
|
|
312
|
+
}
|
|
313
|
+
if (document.querySelector(".ui-shell")) {
|
|
314
|
+
const doc = document.scrollingElement ?? document.documentElement;
|
|
315
|
+
if (doc.scrollHeight > innerHeight + 1) out.docScroll = `document ${doc.scrollHeight} px tall in a ${innerHeight} px window`;
|
|
316
|
+
}
|
|
262
317
|
for (const el of document.querySelectorAll(".ui-dt-body .ui-badge, .ui-card .ui-badge")) {
|
|
263
318
|
if (out.raised.length >= 6) break;
|
|
264
319
|
const sh = getComputedStyle(el).boxShadow;
|
|
@@ -409,6 +464,39 @@ const GUIDES = [
|
|
|
409
464
|
["theme", "Every token, theme and accent settings, the accent derivation, the Slidev teaching preset"],
|
|
410
465
|
["motion", "Animation durations and effects, when you animate something yourself"]
|
|
411
466
|
];
|
|
467
|
+
/** The Markdown without its HTML comments (the @dsCard line of a hook's README, notes to maintainers); comments inside
|
|
468
|
+
fenced code stay, they are part of an example. Blank lines left behind are collapsed. */
|
|
469
|
+
function stripComments(md) {
|
|
470
|
+
let fenced = false;
|
|
471
|
+
const kept = [];
|
|
472
|
+
let open = false;
|
|
473
|
+
for (const line of md.split("\n")) {
|
|
474
|
+
if (!open && /^\s*(```|~~~)/.test(line)) fenced = !fenced;
|
|
475
|
+
if (fenced) {
|
|
476
|
+
kept.push(line);
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
let rest = line;
|
|
480
|
+
let text = "";
|
|
481
|
+
while (rest) if (open) {
|
|
482
|
+
const close = rest.indexOf("-->");
|
|
483
|
+
if (close < 0) break;
|
|
484
|
+
rest = rest.slice(close + 3);
|
|
485
|
+
open = false;
|
|
486
|
+
} else {
|
|
487
|
+
const start = rest.indexOf("<!--");
|
|
488
|
+
if (start < 0) {
|
|
489
|
+
text += rest;
|
|
490
|
+
break;
|
|
491
|
+
}
|
|
492
|
+
text += rest.slice(0, start);
|
|
493
|
+
rest = rest.slice(start + 4);
|
|
494
|
+
open = true;
|
|
495
|
+
}
|
|
496
|
+
if (text.trim() || line.trim() === "") kept.push(text.trimEnd());
|
|
497
|
+
}
|
|
498
|
+
return kept.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd().concat("\n");
|
|
499
|
+
}
|
|
412
500
|
// src/compare.ts
|
|
413
501
|
/** Anti-aliasing noise passes; a moved border, a changed color or a new line of text does not. */
|
|
414
502
|
const DEFAULT_TOLERANCE = {
|
|
@@ -456,28 +544,96 @@ function samePixels(x, y) {
|
|
|
456
544
|
const b = PNG.sync.read(y);
|
|
457
545
|
return a.width === b.width && a.height === b.height && Buffer.compare(a.data, b.data) === 0;
|
|
458
546
|
}
|
|
547
|
+
// src/add.ts
|
|
548
|
+
/** The templates shipped with this CLI. */
|
|
549
|
+
function loadTemplates(url = new URL("./templates.json", import.meta.url)) {
|
|
550
|
+
return JSON.parse(readFileSync(url, "utf8"));
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Where a template goes when no folder is given: src/components/blocks/<name> in a project with a src folder (Vite,
|
|
554
|
+
* Next.js with src), else components/blocks/<name> (the shadcn registry's target).
|
|
555
|
+
*/
|
|
556
|
+
function defaultDir(name, cwd) {
|
|
557
|
+
return join(existsSync(join(cwd, "src")) ? "src" : "", "components", "blocks", name);
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Writes the template's files into dir, each under its file name (the files import each other by relative path).
|
|
561
|
+
* Existing files are left alone unless force is set; returns what was written and what was skipped.
|
|
562
|
+
*/
|
|
563
|
+
function writeTemplate(t, dir, force) {
|
|
564
|
+
const written = [];
|
|
565
|
+
const skipped = [];
|
|
566
|
+
mkdirSync(dir, { recursive: true });
|
|
567
|
+
for (const f of t.files) {
|
|
568
|
+
const path = join(dir, basename(f.target));
|
|
569
|
+
if (existsSync(path) && !force) {
|
|
570
|
+
skipped.push(path);
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
writeFileSync(path, f.content);
|
|
574
|
+
written.push(path);
|
|
575
|
+
}
|
|
576
|
+
return {
|
|
577
|
+
written,
|
|
578
|
+
skipped
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
/** The lines printed after ui add: what was written and how to use it. */
|
|
582
|
+
function addReport(t, dir, r, cwd) {
|
|
583
|
+
const rel = (p) => relative(cwd, p) || ".";
|
|
584
|
+
const main = basename(t.files[0]?.target ?? "").replace(/\.tsx?$/, "");
|
|
585
|
+
const lines = [`${t.title} (${t.name}) → ${rel(dir)}/`];
|
|
586
|
+
for (const p of r.written) lines.push(` wrote ${rel(p)}`);
|
|
587
|
+
for (const p of r.skipped) lines.push(` kept ${rel(p)} (exists; --force overwrites it)`);
|
|
588
|
+
const deps = t.dependencies.filter((d) => {
|
|
589
|
+
try {
|
|
590
|
+
return !JSON.parse(readFileSync(join(cwd, "package.json"), "utf8")).dependencies?.[d];
|
|
591
|
+
} catch {
|
|
592
|
+
return true;
|
|
593
|
+
}
|
|
594
|
+
});
|
|
595
|
+
if (deps.length) lines.push(`Install: npm i ${deps.join(" ")} react react-dom`);
|
|
596
|
+
const sample = t.files.find((f) => /(^|\/)sample\.ts$/.test(f.target));
|
|
597
|
+
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` : ""}).`);
|
|
598
|
+
return lines;
|
|
599
|
+
}
|
|
459
600
|
// src/shots.ts
|
|
460
601
|
const WIDTHS = [390, 1280];
|
|
461
602
|
const THEMES = ["light", "dark"];
|
|
462
603
|
/** The time every shot sees (Date, timers, relative times): 2026/11/20(五)17:00 in Taipei. */
|
|
463
604
|
const FIXED_TIME = "2026-11-20T17:00:00+08:00";
|
|
605
|
+
/** A name part made safe for a file name: only letters, digits, dot, dash and underscore remain (no colon or slash). */
|
|
606
|
+
function cleanName(s) {
|
|
607
|
+
return s.replace(/[^\p{L}\p{N}._-]+/gu, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|-+$/g, "");
|
|
608
|
+
}
|
|
464
609
|
/**
|
|
465
610
|
* 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
|
|
467
|
-
*
|
|
611
|
+
* page on a server: its path (http://localhost:5173/projects/42 → projects-42, / → index), so the pages of one site do
|
|
612
|
+
* not overwrite each other. Then the query and the hash of either, sanitised (iframe.html?id=button--primary →
|
|
613
|
+
* iframe-id-button-primary; settings#billing → settings-billing), so variants of one page get their own files.
|
|
468
614
|
*/
|
|
469
615
|
function stemFor(url) {
|
|
470
|
-
const clean = (s) => s.replace(/[^\p{L}\p{N}._-]+/gu, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|-+$/g, "");
|
|
471
616
|
let u;
|
|
472
617
|
try {
|
|
473
618
|
u = new URL(url);
|
|
474
619
|
} catch {
|
|
475
|
-
return
|
|
620
|
+
return cleanName(url) || "page";
|
|
476
621
|
}
|
|
477
|
-
const
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
622
|
+
const decode = (s) => {
|
|
623
|
+
try {
|
|
624
|
+
return decodeURIComponent(s.replace(/\+/g, " "));
|
|
625
|
+
} catch {
|
|
626
|
+
return s;
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
const query = [...u.searchParams].map(([k, v]) => v ? `${k}-${v}` : k).join("-");
|
|
630
|
+
const hash = decode(u.hash.slice(1));
|
|
631
|
+
const path = decode(u.pathname).replace(/\/+$/, "");
|
|
632
|
+
return cleanName([
|
|
633
|
+
u.protocol === "file:" ? (path.split("/").pop() ?? "").replace(/\.[^.]*$/, "") : path.replace(/\.html?$/i, "").split("/").filter(Boolean).join("-") || "index",
|
|
634
|
+
query,
|
|
635
|
+
hash
|
|
636
|
+
].filter(Boolean).join("-")) || "page";
|
|
481
637
|
}
|
|
482
638
|
/** Turns paths and URLs into jobs, named by stemFor; a second target with the same name gets -2, -3, … */
|
|
483
639
|
function jobsFor(targets, toUrl) {
|
|
@@ -516,33 +672,70 @@ function shotLaunchOptions() {
|
|
|
516
672
|
* keeps the document at the window's height and scrolls its main area (.ui-shell-main), so a full-page shot would
|
|
517
673
|
* stop at the window's bottom edge. When the document does not scroll but one large element (at least 60 % of the
|
|
518
674
|
* window's height) does, the viewport grows by what that element hides, up to 12000 px, until nothing is hidden.
|
|
519
|
-
*
|
|
675
|
+
* Content that renders late (data after a fetch, a list after fonts) changes the scroll height: the height is measured
|
|
676
|
+
* again after each settle step until two measurements in a row agree. Returns the viewport to restore.
|
|
520
677
|
*/
|
|
521
678
|
async function growToScrollContainer(page, viewport, settle) {
|
|
522
679
|
let size = viewport;
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
680
|
+
let last = "";
|
|
681
|
+
for (let i = 0; i < 10; i++) {
|
|
682
|
+
const m = await page.evaluate(() => {
|
|
683
|
+
const doc = document.scrollingElement ?? document.documentElement;
|
|
684
|
+
if (doc.scrollHeight > innerHeight + 1) return {
|
|
685
|
+
hidden: 0,
|
|
686
|
+
key: `doc ${doc.scrollHeight}`
|
|
687
|
+
};
|
|
526
688
|
let most = 0;
|
|
689
|
+
let key = "none";
|
|
527
690
|
for (const el of document.body.querySelectorAll("*")) {
|
|
528
691
|
if (el.clientHeight < innerHeight * .6) continue;
|
|
529
692
|
const cs = getComputedStyle(el);
|
|
530
693
|
if (!/auto|scroll/.test(cs.overflowY) || cs.display === "none") continue;
|
|
531
|
-
|
|
694
|
+
const hidden = el.scrollHeight - el.clientHeight;
|
|
695
|
+
if (hidden >= most) {
|
|
696
|
+
most = hidden;
|
|
697
|
+
key = `box ${el.scrollHeight}`;
|
|
698
|
+
}
|
|
532
699
|
}
|
|
533
|
-
return
|
|
700
|
+
return {
|
|
701
|
+
hidden: most,
|
|
702
|
+
key: `${key} ${innerHeight}`
|
|
703
|
+
};
|
|
534
704
|
});
|
|
535
|
-
if (hidden
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
705
|
+
if (m.hidden > 1 && size.height < 12e3) {
|
|
706
|
+
size = {
|
|
707
|
+
width: size.width,
|
|
708
|
+
height: Math.min(12e3, size.height + Math.ceil(m.hidden))
|
|
709
|
+
};
|
|
710
|
+
await page.setViewportSize(size);
|
|
711
|
+
} else if (m.key === last) break;
|
|
712
|
+
last = m.key;
|
|
541
713
|
await settle();
|
|
542
|
-
if (size.height >= 12e3) break;
|
|
543
714
|
}
|
|
544
715
|
return size;
|
|
545
716
|
}
|
|
717
|
+
/**
|
|
718
|
+
* Waits until the page's animations and transitions have finished, up to `cap` ms. Endless ones (a spinner, a
|
|
719
|
+
* skeleton's shimmer) and paused ones are not waited for. Animations that start while waiting are waited for too.
|
|
720
|
+
* For ui check, on the real clock (ui shots stops animations instead).
|
|
721
|
+
*/
|
|
722
|
+
async function waitForAnimations(page, cap = 1500) {
|
|
723
|
+
await page.evaluate(async (cap) => {
|
|
724
|
+
const end = performance.now() + cap;
|
|
725
|
+
const moving = () => document.getAnimations().filter((a) => {
|
|
726
|
+
if (a.playState !== "running" && !a.pending) return false;
|
|
727
|
+
const t = a.effect?.getComputedTiming();
|
|
728
|
+
return !!t && Number.isFinite(t.endTime);
|
|
729
|
+
});
|
|
730
|
+
const frame = () => new Promise((ok) => requestAnimationFrame(() => ok(void 0)));
|
|
731
|
+
for (let list = moving(); list.length && performance.now() < end; list = moving()) {
|
|
732
|
+
const left = end - performance.now();
|
|
733
|
+
await Promise.race([Promise.all(list.map((a) => a.finished.catch(() => void 0))), new Promise((ok) => setTimeout(ok, left))]);
|
|
734
|
+
await frame();
|
|
735
|
+
}
|
|
736
|
+
await frame();
|
|
737
|
+
}, cap);
|
|
738
|
+
}
|
|
546
739
|
/** File name of one screenshot. */
|
|
547
740
|
const shotName = (stem, width, theme) => `${stem}-${width}-${theme}.png`;
|
|
548
741
|
/**
|
|
@@ -574,6 +767,7 @@ async function shootPage(browser, job, settle) {
|
|
|
574
767
|
await page.clock.pauseAt(Date.parse(FIXED_TIME));
|
|
575
768
|
const resp = await page.goto(job.url, { waitUntil: "load" });
|
|
576
769
|
if (resp && !resp.ok()) throw new Error(`HTTP ${resp.status()}`);
|
|
770
|
+
await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => void 0);
|
|
577
771
|
const fonts = () => page.evaluate(() => document.fonts.ready.then(() => void 0));
|
|
578
772
|
await fonts();
|
|
579
773
|
await page.evaluate(applyTheme, theme);
|
|
@@ -594,9 +788,12 @@ async function shootPage(browser, job, settle) {
|
|
|
594
788
|
}
|
|
595
789
|
});
|
|
596
790
|
await page.waitForTimeout(100);
|
|
791
|
+
await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => void 0);
|
|
792
|
+
await fonts();
|
|
597
793
|
await growToScrollContainer(page, viewport, async () => {
|
|
598
794
|
await page.waitForTimeout(100);
|
|
599
795
|
await page.clock.runFor(100);
|
|
796
|
+
await fonts();
|
|
600
797
|
});
|
|
601
798
|
await page.waitForTimeout(200);
|
|
602
799
|
const shoot = () => page.screenshot({
|
|
@@ -731,25 +928,33 @@ const HELP_CHECK = `ui check <file or URL>... [--shots DIR] [--strict] [--wait M
|
|
|
731
928
|
crowd another target at 1280 px (WCAG 2.5.8), touch areas that spill past their control, a card inside a card, raw
|
|
732
929
|
Markdown, native controls the design system replaces, wrapped buttons, tabs, table headers or interface headings
|
|
733
930
|
(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
|
|
735
|
-
|
|
736
|
-
|
|
931
|
+
controls of different heights in one toolbar row or one form row (a FormGrid row, fields side by side), paragraphs
|
|
932
|
+
of two or more lines centered at 390 px (EmptyState and ErrorPage excepted), a document that scrolls around
|
|
933
|
+
AppShell, a status badge with a shadow in a table or card, page CSS outside a cascade layer on element selectors (a
|
|
934
|
+
reset, normalize or starter CSS: button, *, h1) that overrides a component, and the axe-core rules of WCAG 2.0, 2.1
|
|
935
|
+
and 2.2 A and AA.
|
|
936
|
+
Each measurement waits until the page's animations and transitions end (up to 1.5 s), so a fade is not measured
|
|
937
|
+
half way.
|
|
737
938
|
A page without <meta name="viewport"> gets one report at 390 px (缺 viewport meta) and no touch-target check there.
|
|
738
939
|
It also opens what the page hides behind clicks, in light at both widths: each tab of a [role=tablist], each
|
|
739
940
|
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.
|
|
941
|
+
states a page), and checks every state for the problems the page did not already have. The line of each width and
|
|
942
|
+
theme counts the problems of the page and of its opened states; each state's problems follow under its name.
|
|
741
943
|
--open SELECTOR clicks the first match and checks the state it opens (a dialog, a drawer); repeat for more.
|
|
742
944
|
--no-interact skips the automatic tabs, categories and toolbar menus (--open still runs).
|
|
743
945
|
--no-axe skips the axe-core pass.
|
|
744
|
-
--shots DIR saves a full-page screenshot of each width and theme in DIR
|
|
946
|
+
--shots DIR saves a full-page screenshot of each width and theme in DIR (<name>-<width>-<theme>.png, <name> as
|
|
947
|
+
in ui shots), and one of each opened state (<name>-<width>-light-<state>.png).
|
|
745
948
|
--strict also fails on inline text links under 48 px.
|
|
746
949
|
--wait MS waits this long after load before measuring (default 800).
|
|
747
950
|
Exits 2 when a page cannot be checked at all: it does not load, or the check itself crashes.`;
|
|
748
951
|
const HELP_SHOTS = `ui shots <file or URL>... (--out DIR [--prune] | --compare DIR --diff DIR) [--settle MS] [--threshold N] [--max-diff PERCENT]
|
|
749
952
|
Deterministic screenshots at 390 px and 1280 px, light and dark (DIR/<name>-<width>-<theme>.png): fixed clock
|
|
750
953
|
(${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)
|
|
752
|
-
|
|
954
|
+
including what scrolls inside the page's own scroll container (AppShell's main area), measured once the network is
|
|
955
|
+
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,
|
|
956
|
+
then its query and hash (http://host/settings#billing → settings-billing, iframe.html?id=button--primary →
|
|
957
|
+
iframe-id-button-primary).
|
|
753
958
|
--out DIR writes the shots (baselines); a file with the same pixels is left as it is. New files are
|
|
754
959
|
optimised losslessly with oxipng when it is on PATH. --prune also deletes the PNGs in DIR
|
|
755
960
|
that no page of this run produced (a removed or renamed page).
|
|
@@ -766,7 +971,12 @@ const HELP_DOCS = `ui docs [Name] [--full]
|
|
|
766
971
|
gotten wrong. --full prints the whole README. Guides print whole: guidelines (the core rules every page needs),
|
|
767
972
|
layout, forms, data, monitoring, code, theme, motion. ui docs icons prints every built-in icon name on one line;
|
|
768
973
|
ui docs agents prints the package's AGENTS.md. Without a name, prints the reading order and lists every doc.`;
|
|
974
|
+
const HELP_ADD = `ui add <template> [dir] [--force]
|
|
975
|
+
Writes a page template into the project, from the copy inside this package (no network): dashboard, list-detail,
|
|
976
|
+
settings, login. dir defaults to src/components/blocks/<template> (components/blocks/<template> without a src
|
|
977
|
+
folder). Existing files are kept unless --force. The same templates as the shadcn registry on the docs site.`;
|
|
769
978
|
const HELP = `${HELP_CHECK}
|
|
979
|
+
${HELP_ADD}
|
|
770
980
|
${HELP_DOCS}
|
|
771
981
|
${HELP_SHOTS}
|
|
772
982
|
ui list lists every guide (in reading order) and every component by group, with its one-line description`;
|
|
@@ -814,7 +1024,7 @@ function docs(name, full) {
|
|
|
814
1024
|
console.error(`No docs for "${name}". Run "ui docs" for the list.`);
|
|
815
1025
|
process.exit(1);
|
|
816
1026
|
}
|
|
817
|
-
const md = readFileSync(join(dir, hit), "utf8");
|
|
1027
|
+
const md = stripComments(readFileSync(join(dir, hit), "utf8"));
|
|
818
1028
|
const usage = full ? null : usageBlock(md);
|
|
819
1029
|
if (!usage) return console.log(md);
|
|
820
1030
|
const more = md.trim().length > usage.trim().length;
|
|
@@ -1000,12 +1210,15 @@ function problemsOf(res, phone, strict) {
|
|
|
1000
1210
|
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
1211
|
if (res.outside.length) problems.push("text outside its card: " + res.outside.join("; ") + ". Leave room inside the card (chart axis labels, long words).");
|
|
1002
1212
|
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.");
|
|
1213
|
+
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.");
|
|
1214
|
+
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
1215
|
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
1216
|
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
1217
|
if (phone && res.viewportMeta) {
|
|
1006
1218
|
if (res.overflow.length) problems.push("horizontal overflow: " + res.overflow.join("; "));
|
|
1007
1219
|
if (res.escaped.length) problems.push("touch area larger than its control (covers other controls): " + res.escaped.join("; "));
|
|
1008
1220
|
if (res.small.length) problems.push(`touch targets under 48 px: ${list(res.small)}`);
|
|
1221
|
+
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
1222
|
if (res.inline.length && strict) problems.push("inline targets under 48 px: " + list(res.inline));
|
|
1010
1223
|
}
|
|
1011
1224
|
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 +1314,7 @@ async function check(targets, opts) {
|
|
|
1101
1314
|
await run(() => page.evaluate(applyTheme, theme));
|
|
1102
1315
|
await page.waitForTimeout(opts.wait);
|
|
1103
1316
|
await page.waitForLoadState("load");
|
|
1317
|
+
await run(() => waitForAnimations(page));
|
|
1104
1318
|
const res = await run(() => page.evaluate(measure));
|
|
1105
1319
|
if (page.url() !== url && width === 390 && theme === "light") out.push(` (redirected to ${page.url()})`);
|
|
1106
1320
|
const problems = [];
|
|
@@ -1112,18 +1326,17 @@ async function check(targets, opts) {
|
|
|
1112
1326
|
problems.push(...problemsOf(res, phone, opts.strict));
|
|
1113
1327
|
const axe = opts.axe ? await run(() => axeRun(page, theme === "dark")).catch((e) => [`axe-core could not run: ${String(e).split("\n")[0]}`]) : [];
|
|
1114
1328
|
if (axe.length) problems.push("accessibility (axe-core): " + axe.join(" | "));
|
|
1115
|
-
|
|
1116
|
-
|
|
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) {
|
|
1329
|
+
const shoot = async (suffix) => {
|
|
1330
|
+
if (!opts.shots) return;
|
|
1120
1331
|
await growToScrollContainer(page, viewport, () => page.waitForTimeout(150));
|
|
1121
1332
|
await page.screenshot({
|
|
1122
|
-
path: join(opts.shots, `${stem
|
|
1333
|
+
path: join(opts.shots, `${shotName(stem, width, theme).slice(0, -4)}${suffix}.png`),
|
|
1123
1334
|
fullPage: true
|
|
1124
1335
|
});
|
|
1125
1336
|
await page.setViewportSize(viewport);
|
|
1126
|
-
}
|
|
1337
|
+
};
|
|
1338
|
+
await shoot("");
|
|
1339
|
+
const states = [];
|
|
1127
1340
|
if (theme === "light" && (opts.open.length || opts.interact)) {
|
|
1128
1341
|
const itemKey = (item) => item.split(", next to ")[0].replace(/ \d+ x \d+ px$/, "");
|
|
1129
1342
|
const axeKey = (line) => line.split(" ")[0];
|
|
@@ -1136,7 +1349,7 @@ async function check(targets, opts) {
|
|
|
1136
1349
|
if (Array.isArray(was) && Array.isArray(is)) {
|
|
1137
1350
|
const seen = new Set(was.map(itemKey));
|
|
1138
1351
|
out[k] = is.filter((x) => !seen.has(itemKey(x)));
|
|
1139
|
-
}
|
|
1352
|
+
} else if (typeof was === "string" && was) out[k] = "";
|
|
1140
1353
|
}
|
|
1141
1354
|
return out;
|
|
1142
1355
|
};
|
|
@@ -1144,10 +1357,11 @@ async function check(targets, opts) {
|
|
|
1144
1357
|
const before = errors.length;
|
|
1145
1358
|
try {
|
|
1146
1359
|
await target.click({ timeout: 3e3 });
|
|
1147
|
-
} catch
|
|
1148
|
-
return
|
|
1360
|
+
} catch {
|
|
1361
|
+
return null;
|
|
1149
1362
|
}
|
|
1150
|
-
await page.waitForTimeout(
|
|
1363
|
+
await page.waitForTimeout(150);
|
|
1364
|
+
await run(() => waitForAnimations(page));
|
|
1151
1365
|
const after = await run(() => page.evaluate(measure));
|
|
1152
1366
|
const found = problemsOf(newOnly(after), phone, opts.strict);
|
|
1153
1367
|
if (errors.length > before) found.unshift("console errors: " + errors.slice(before, before + 5).join(" | "));
|
|
@@ -1156,6 +1370,7 @@ async function check(targets, opts) {
|
|
|
1156
1370
|
const more = (await run(() => axeRun(page, false, skip)).catch(() => [])).filter((v) => !knownAxe.has(axeKey(v)));
|
|
1157
1371
|
if (more.length) found.push("accessibility (axe-core): " + more.join(" | "));
|
|
1158
1372
|
}
|
|
1373
|
+
await shoot(`-${cleanName(label)}`);
|
|
1159
1374
|
if (trigger) {
|
|
1160
1375
|
await page.keyboard.press("Escape");
|
|
1161
1376
|
await page.waitForTimeout(150);
|
|
@@ -1163,32 +1378,53 @@ async function check(targets, opts) {
|
|
|
1163
1378
|
await target.click({ timeout: 3e3 }).catch(() => void 0);
|
|
1164
1379
|
await page.waitForTimeout(150);
|
|
1165
1380
|
}
|
|
1381
|
+
await run(() => waitForAnimations(page));
|
|
1166
1382
|
}
|
|
1167
|
-
return found
|
|
1383
|
+
return found;
|
|
1168
1384
|
};
|
|
1169
|
-
const stateProblems = [];
|
|
1170
1385
|
for (const sel of opts.open) {
|
|
1171
1386
|
const target = page.locator(sel).first();
|
|
1387
|
+
const label = `--open ${sel}`;
|
|
1172
1388
|
if (!await target.count()) {
|
|
1173
|
-
|
|
1389
|
+
states.push({
|
|
1390
|
+
label,
|
|
1391
|
+
problems: ["nothing on the page matches"]
|
|
1392
|
+
});
|
|
1174
1393
|
continue;
|
|
1175
1394
|
}
|
|
1176
|
-
const
|
|
1177
|
-
if (
|
|
1395
|
+
const found = await checkState(label, target, true);
|
|
1396
|
+
if (!found) states.push({
|
|
1397
|
+
label,
|
|
1398
|
+
problems: ["could not click it"]
|
|
1399
|
+
});
|
|
1400
|
+
else if (found.length) states.push({
|
|
1401
|
+
label,
|
|
1402
|
+
problems: found
|
|
1403
|
+
});
|
|
1178
1404
|
}
|
|
1179
1405
|
if (opts.interact) {
|
|
1180
|
-
const
|
|
1406
|
+
const auto = await run(() => page.evaluate(findStates, {
|
|
1181
1407
|
popups: TOOLBAR_POPUPS,
|
|
1182
1408
|
max: MAX_STATES
|
|
1183
1409
|
}));
|
|
1184
|
-
for (const st of
|
|
1185
|
-
const
|
|
1186
|
-
if (
|
|
1410
|
+
for (const st of auto) {
|
|
1411
|
+
const found = await checkState(st.label, page.locator(`[data-ui-check-state="${st.id}"]`), st.kind === "popup");
|
|
1412
|
+
if (found?.length) states.push({
|
|
1413
|
+
label: st.label,
|
|
1414
|
+
problems: found
|
|
1415
|
+
});
|
|
1187
1416
|
}
|
|
1188
1417
|
}
|
|
1189
|
-
for (const p of stateProblems) out.push(` - ${p}`);
|
|
1190
|
-
bad ||= stateProblems.length > 0;
|
|
1191
1418
|
}
|
|
1419
|
+
const count = problems.length + states.reduce((n, st) => n + st.problems.length, 0);
|
|
1420
|
+
out.push(` ${width} px ${theme}: ${count ? `${count} problem${count === 1 ? "" : "s"}` : "ok"}`);
|
|
1421
|
+
for (const p of problems) out.push(" - " + p);
|
|
1422
|
+
for (const st of states) {
|
|
1423
|
+
out.push(` after opening ${st.label}:`);
|
|
1424
|
+
for (const p of st.problems) out.push(" - " + p);
|
|
1425
|
+
}
|
|
1426
|
+
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})`);
|
|
1427
|
+
bad ||= count > 0;
|
|
1192
1428
|
} finally {
|
|
1193
1429
|
await ctx.close();
|
|
1194
1430
|
}
|
|
@@ -1348,7 +1584,20 @@ if (cmd === "check") {
|
|
|
1348
1584
|
} }, HELP_DOCS);
|
|
1349
1585
|
docs(positionals[0], !!values.full);
|
|
1350
1586
|
} else if (cmd === "list") list();
|
|
1351
|
-
else if (cmd === "
|
|
1587
|
+
else if (cmd === "add") {
|
|
1588
|
+
const { values, positionals } = parse(rest, { force: {
|
|
1589
|
+
type: "boolean",
|
|
1590
|
+
default: false
|
|
1591
|
+
} }, HELP_ADD);
|
|
1592
|
+
const templates = loadTemplates();
|
|
1593
|
+
const t = templates.find((x) => x.name === positionals[0]);
|
|
1594
|
+
if (!t) {
|
|
1595
|
+
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}`);
|
|
1596
|
+
process.exit(2);
|
|
1597
|
+
}
|
|
1598
|
+
const dir = resolve(positionals[1] ?? defaultDir(t.name, process.cwd()));
|
|
1599
|
+
console.log(addReport(t, dir, writeTemplate(t, dir, !!values.force), process.cwd()).join("\n"));
|
|
1600
|
+
} else if (cmd === "--help" || cmd === "-h" || cmd === "help" || !cmd) console.log(HELP);
|
|
1352
1601
|
else {
|
|
1353
1602
|
console.error(`Unknown command "${cmd}".\n\n${HELP}`);
|
|
1354
1603
|
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'];\nconst now = new Date(2026, 10, 4, 15, 0);\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: ['第 1 週', '第 2 週', '第 3 週', '第 4 週', '第 5 週', '第 6 週'], series: [{ name: '完成', values: [12, 18, 15, 22, 26, 24] }] },\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 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 // The name's error shows once the field is left (blur), not on every key, as the form rules say.\n const [nameLeft, setNameLeft] = React.useState(false);\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 setNameLeft(false);\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 disabled={!dirty || !draft?.name.trim()}\n onClick={() => {\n if (draft) onSave({ ...draft, updated: new Date() });\n close();\n // AppShell shows the toast; no Toaster of its own is needed.\n toast(draft?.id ? '已儲存' : '已新增');\n }}\n >\n 儲存\n </Button>\n </>\n )}\n >\n {draft ? (\n <FormGrid>\n <TextField\n label=\"名稱\"\n required\n value={draft.name}\n onChange={(v) => set('name', v)}\n onBlur={() => setNameLeft(true)}\n error={nameLeft && !draft.name.trim() ? '名稱不能空白,請輸入專案名稱。' : undefined}\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.
|
|
3
|
+
"version": "0.46.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.
|
|
24
|
+
"@seanyeh77/ui": "^0.46.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
|
}
|