@seanyeh77/ui-cli 0.44.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 +11 -4
- package/dist/cli.js +793 -106
- package/dist/templates.json +66 -0
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -7,13 +7,20 @@ 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
|
|
11
|
-
- `
|
|
12
|
-
-
|
|
13
|
-
- `
|
|
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
|
+
- 它也會點開每個分頁(`[role=tablist]`)、SettingsLayout 的每個分類,以及工具列與頂欄裡 `[aria-haspopup]` 按鈕的選單,檢查打開後的畫面(淺色、兩種寬度,每頁最多 12 個狀態),只回報原本沒有的問題。
|
|
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`)。網路閒置、字型載入、高度連續兩次相同之後才截圖。
|
|
15
|
+
- 每個指令加 `--help` 印出自己的說明。
|
|
16
|
+
- `ui docs [Name] [--full]`:印出元件的用法區塊或使用規則;不加名稱時先印閱讀順序(guidelines 最先),再列出全部文件。
|
|
17
|
+
- `ui add <dashboard|list-detail|settings|login> [資料夾]`:把頁面範本寫進專案,內容在這個套件裡,不連網路(預設 `src/components/blocks/<範本>`;已有的檔案保留,`--force` 才覆寫)。和文件網站的 shadcn registry 是同一份範本。
|
|
18
|
+
- `ui list`:依閱讀順序列出每份規則,再依分組(和 llms.txt 相同)列出每個元件的一句說明。
|
|
14
19
|
|
|
15
20
|
`npx @seanyeh77/ui-cli` 不加參數會印出完整說明。
|
|
16
21
|
|
|
22
|
+
Playwright 在 `@seanyeh77/ui` 與這個套件固定成同一個確切版本:畫面基準圖是用它的 Chromium 產生的,升級 Playwright 就要重新產生基準圖(Update visual baselines workflow)。
|
|
23
|
+
|
|
17
24
|
## 文件
|
|
18
25
|
|
|
19
26
|
- 文件網站:<https://seanyeh77.github.io/ui-design-system/>
|
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";
|
|
@@ -20,7 +20,14 @@ function measure() {
|
|
|
20
20
|
escaped: [],
|
|
21
21
|
mixed: [],
|
|
22
22
|
raised: [],
|
|
23
|
-
unlayered: []
|
|
23
|
+
unlayered: [],
|
|
24
|
+
viewportMeta: !!document.querySelector("meta[name=\"viewport\" i]"),
|
|
25
|
+
truncated: [],
|
|
26
|
+
outside: [],
|
|
27
|
+
small24: [],
|
|
28
|
+
formMixed: [],
|
|
29
|
+
centered: [],
|
|
30
|
+
docScroll: ""
|
|
24
31
|
};
|
|
25
32
|
const describe = (el) => {
|
|
26
33
|
let s = el.tagName.toLowerCase();
|
|
@@ -35,10 +42,14 @@ function measure() {
|
|
|
35
42
|
const p = el.parentElement;
|
|
36
43
|
return !!p && [...p.childNodes].some((n) => n.nodeType === 3 && !!n.textContent?.trim());
|
|
37
44
|
};
|
|
45
|
+
const srOnly = (el, cs = getComputedStyle(el)) => {
|
|
46
|
+
const r = el.getBoundingClientRect();
|
|
47
|
+
return r.width <= 1 && r.height <= 1 || /rect\(0(px)?,? 0(px)?,? 0(px)?,? 0(px)?\)/.test(cs.clip) || cs.clipPath === "inset(50%)";
|
|
48
|
+
};
|
|
38
49
|
const visible = (el) => {
|
|
39
50
|
const cs = getComputedStyle(el);
|
|
40
51
|
const r = el.getBoundingClientRect();
|
|
41
|
-
return cs.visibility !== "hidden" && cs.display !== "none" && r.width > 0 && r.height > 0;
|
|
52
|
+
return cs.visibility !== "hidden" && cs.display !== "none" && r.width > 0 && r.height > 0 && !srOnly(el, cs);
|
|
42
53
|
};
|
|
43
54
|
const vw = document.documentElement.clientWidth;
|
|
44
55
|
if (document.documentElement.scrollWidth > vw + 1) {
|
|
@@ -54,12 +65,23 @@ function measure() {
|
|
|
54
65
|
}
|
|
55
66
|
const sel = "a[href], button, input:not([type=hidden]), select, textarea, summary, [role=button], [role=tab], [role=switch], [role=checkbox], [role=radio], [role=option], [role=menuitem], [role=link], [tabindex]:not([tabindex=\"-1\"])";
|
|
56
67
|
const control = sel.replace(", [tabindex]:not([tabindex=\"-1\"])", "") + ", [role=slider], [role=separator], [role=combobox], [role=treeitem]";
|
|
68
|
+
const wholeRow = (el) => {
|
|
69
|
+
if (el.matches(".ui-dt-rowlink")) return true;
|
|
70
|
+
if (!el.matches("a[href]")) return false;
|
|
71
|
+
for (let a = el.parentElement; a && a !== document.body; a = a.parentElement) {
|
|
72
|
+
if (getComputedStyle(a).cursor === "pointer" && a.getBoundingClientRect().height >= 47.5) return true;
|
|
73
|
+
if (a.matches("tr, [role=row], li, [role=listitem], .ui-card, article")) break;
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
};
|
|
77
|
+
const targets = [];
|
|
78
|
+
const inText = (el, cs) => isInline(el, cs) || cs.display === "inline" || !!el.closest(".ui-md");
|
|
57
79
|
for (const el of new Set(document.querySelectorAll(sel))) {
|
|
58
80
|
if (el.closest("[aria-hidden=\"true\"], [inert]")) continue;
|
|
59
81
|
const cs = getComputedStyle(el);
|
|
60
82
|
if (cs.visibility === "hidden" || cs.display === "none" || cs.pointerEvents === "none") continue;
|
|
61
83
|
const r = el.getBoundingClientRect();
|
|
62
|
-
if (!r.width || !r.height) continue;
|
|
84
|
+
if (!r.width || !r.height || srOnly(el, cs)) continue;
|
|
63
85
|
if (!el.matches(control) && /auto|scroll/.test(cs.overflowX + " " + cs.overflowY)) continue;
|
|
64
86
|
const input = el;
|
|
65
87
|
if ((input.type === "checkbox" || input.type === "radio") && el.closest("label")) continue;
|
|
@@ -92,13 +114,43 @@ function measure() {
|
|
|
92
114
|
h = Math.max(h, ph);
|
|
93
115
|
}
|
|
94
116
|
}
|
|
117
|
+
targets.push({
|
|
118
|
+
el,
|
|
119
|
+
r,
|
|
120
|
+
w,
|
|
121
|
+
h,
|
|
122
|
+
inline: inText(el, cs)
|
|
123
|
+
});
|
|
95
124
|
if (w >= 47.5 && h >= 47.5) continue;
|
|
125
|
+
if (wholeRow(el)) {
|
|
126
|
+
out.inline.push(`${describe(el)} (its row or card is the target)`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
96
129
|
if (el.matches(".ui-lg-hit")) {
|
|
97
130
|
out.inline.push(`${describe(el)} line`);
|
|
98
131
|
continue;
|
|
99
132
|
}
|
|
100
133
|
(isInline(el, cs) ? out.inline : out.small).push(`${describe(el)} ${Math.round(w)} x ${Math.round(h)} px`);
|
|
101
134
|
}
|
|
135
|
+
for (const t of targets) {
|
|
136
|
+
if (out.small24.length >= 60) break;
|
|
137
|
+
if (t.w >= 23.5 && t.h >= 23.5) continue;
|
|
138
|
+
if (t.inline || t.el.matches(".ui-lg-hit") || wholeRow(t.el)) continue;
|
|
139
|
+
const cx = t.r.left + t.r.width / 2;
|
|
140
|
+
const cy = t.r.top + t.r.height / 2;
|
|
141
|
+
if (cx >= 0 && cy >= 0 && cx < innerWidth && cy < innerHeight) {
|
|
142
|
+
const top = document.elementFromPoint(cx, cy);
|
|
143
|
+
if (top && !t.el.contains(top) && !top.contains(t.el)) continue;
|
|
144
|
+
}
|
|
145
|
+
const near = targets.find((o) => {
|
|
146
|
+
if (o === t || o.el.contains(t.el) || t.el.contains(o.el)) return false;
|
|
147
|
+
const dx = Math.max(o.r.left - cx, 0, cx - o.r.right);
|
|
148
|
+
const dy = Math.max(o.r.top - cy, 0, cy - o.r.bottom);
|
|
149
|
+
if (Math.hypot(dx, dy) < 12) return true;
|
|
150
|
+
return (o.w < 23.5 || o.h < 23.5) && Math.hypot(o.r.left + o.r.width / 2 - cx, o.r.top + o.r.height / 2 - cy) < 24;
|
|
151
|
+
});
|
|
152
|
+
if (near) out.small24.push(`${describe(t.el)} ${Math.round(t.w)} x ${Math.round(t.h)} px, next to ${describe(near.el)}`);
|
|
153
|
+
}
|
|
102
154
|
const cardLike = (el) => {
|
|
103
155
|
const sh = getComputedStyle(el).boxShadow;
|
|
104
156
|
if (!sh || sh === "none") return false;
|
|
@@ -146,8 +198,51 @@ function measure() {
|
|
|
146
198
|
return new Set([...range.getClientRects()].filter((r) => r.width > 1).map((r) => Math.round(r.top / 4))).size > 1;
|
|
147
199
|
}))) out.wrapped.push(describe(el));
|
|
148
200
|
}
|
|
201
|
+
const titled = (n, el) => {
|
|
202
|
+
if (n.closest("[title], [data-ui-tip]")) return true;
|
|
203
|
+
const named = n.closest("[aria-label]");
|
|
204
|
+
return !!named && (named === el || el.contains(named));
|
|
205
|
+
};
|
|
206
|
+
const cut = (el) => {
|
|
207
|
+
const cs = getComputedStyle(el);
|
|
208
|
+
if (cs.overflowX === "visible" && cs.textOverflow !== "ellipsis") return false;
|
|
209
|
+
if (/auto|scroll/.test(cs.overflowX)) return false;
|
|
210
|
+
return el.scrollWidth > el.clientWidth + 1 && !!el.textContent?.trim();
|
|
211
|
+
};
|
|
212
|
+
const labels = ".ui-btn, .ui-tab, [role=tab], [role=columnheader], h1, h2, h3, h4, h5, h6, [class*=\"-title\"]";
|
|
213
|
+
const isLabel = (el) => !el.matches("[class*=\"-title\"]") || el.matches(labels.replace(", [class*=\"-title\"]", "")) || [...el.classList].some((c) => /^ui-[\w-]+-title$/.test(c));
|
|
214
|
+
for (const el of [...document.querySelectorAll(labels)].filter(isLabel)) {
|
|
215
|
+
if (out.truncated.length >= 30) break;
|
|
216
|
+
if (!visible(el) || el.closest(".ui-md, .ui-md-h, [aria-hidden=\"true\"]")) continue;
|
|
217
|
+
const hit = [el, ...el.querySelectorAll("*")].find((n) => visible(n) && cut(n) && !titled(n, el));
|
|
218
|
+
if (hit) out.truncated.push(`${describe(el)}: "${(hit.textContent || "").trim().slice(0, 32)}" is cut off`);
|
|
219
|
+
}
|
|
220
|
+
for (const card of document.querySelectorAll(".ui-card")) {
|
|
221
|
+
if (out.outside.length >= 6) break;
|
|
222
|
+
if (!visible(card)) continue;
|
|
223
|
+
const box = card.getBoundingClientRect();
|
|
224
|
+
const scrolls = (n) => {
|
|
225
|
+
for (let a = n.parentElement; a && a !== card; a = a.parentElement) if (/auto|scroll/.test(getComputedStyle(a).overflowX + getComputedStyle(a).overflowY)) return true;
|
|
226
|
+
return false;
|
|
227
|
+
};
|
|
228
|
+
const past = (r) => r.width > 1 && r.height > 1 && (r.left < box.left - 1 || r.right > box.right + 1 || r.top < box.top - 1 || r.bottom > box.bottom + 1);
|
|
229
|
+
const walkText = document.createTreeWalker(card, NodeFilter.SHOW_TEXT);
|
|
230
|
+
for (let n = walkText.nextNode(); n; n = walkText.nextNode()) {
|
|
231
|
+
const parent = n.parentElement;
|
|
232
|
+
if (!parent || !n.textContent?.trim() || !visible(parent) || scrolls(parent)) continue;
|
|
233
|
+
if (parent.closest("[class*=\"sr-only\"], [class*=\"visually-hidden\"]") || getComputedStyle(parent).position === "fixed") continue;
|
|
234
|
+
const range = document.createRange();
|
|
235
|
+
range.selectNodeContents(n);
|
|
236
|
+
const r = [...range.getClientRects()].find(past);
|
|
237
|
+
if (r) {
|
|
238
|
+
out.outside.push(`${describe(card)}: "${n.textContent.trim().slice(0, 24)}" ${Math.round(Math.max(box.left - r.left, r.right - box.right, box.top - r.top, r.bottom - box.bottom))} px outside`);
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
149
243
|
const bars = ".ui-dt-tools, .ui-dt-actions, .ui-card-actions, [role=toolbar]";
|
|
150
|
-
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;
|
|
151
246
|
for (const bar of document.querySelectorAll(bars)) {
|
|
152
247
|
if (out.mixed.length >= 6) break;
|
|
153
248
|
if (bar.parentElement?.closest(bars) || !visible(bar)) continue;
|
|
@@ -168,6 +263,57 @@ function measure() {
|
|
|
168
263
|
}
|
|
169
264
|
if (hit) out.mixed.push(hit);
|
|
170
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
|
+
}
|
|
171
317
|
for (const el of document.querySelectorAll(".ui-dt-body .ui-badge, .ui-card .ui-badge")) {
|
|
172
318
|
if (out.raised.length >= 6) break;
|
|
173
319
|
const sh = getComputedStyle(el).boxShadow;
|
|
@@ -289,6 +435,68 @@ function summary(md) {
|
|
|
289
435
|
else if (!code && line[i] === "。") return line.slice(0, i + 1);
|
|
290
436
|
return line;
|
|
291
437
|
}
|
|
438
|
+
/** The groups of the component list, in order, with their Chinese names (llms.txt and ui list use the same). A
|
|
439
|
+
component's group is the `group` of the @dsCard line of its preview.html (see groupOf). */
|
|
440
|
+
const GROUPS = {
|
|
441
|
+
Foundations: "基礎",
|
|
442
|
+
Layout: "版面與外框",
|
|
443
|
+
Actions: "按鈕與操作",
|
|
444
|
+
Forms: "表單",
|
|
445
|
+
Data: "數據呈現",
|
|
446
|
+
Monitoring: "監控畫面",
|
|
447
|
+
Code: "程式碼與架構圖",
|
|
448
|
+
Text: "文字標記",
|
|
449
|
+
Status: "狀態",
|
|
450
|
+
Feedback: "回饋",
|
|
451
|
+
Overlays: "浮層",
|
|
452
|
+
Navigation: "導覽",
|
|
453
|
+
Appearance: "外觀",
|
|
454
|
+
Pages: "整頁元件"
|
|
455
|
+
};
|
|
456
|
+
/** The reading order for an agent: the core rules every page needs, then a topic file only when the page has that topic. */
|
|
457
|
+
const GUIDES = [
|
|
458
|
+
["guidelines", "Core rules every page needs (read first): look, type, controls, layout, formats, copy, status, accessibility, checks"],
|
|
459
|
+
["layout", "Page frames, navigation, search and first-use tours: when you lay out a frame yourself"],
|
|
460
|
+
["forms", "Which input component to use and how to arrange a form"],
|
|
461
|
+
["data", "Tables, result lists, file trees, KPIs and charts"],
|
|
462
|
+
["monitoring", "Full-screen always-on monitoring screens (ConsoleLayout and its parts)"],
|
|
463
|
+
["code", "Code-reading tools: code views, architecture graphs, project docs"],
|
|
464
|
+
["theme", "Every token, theme and accent settings, the accent derivation, the Slidev teaching preset"],
|
|
465
|
+
["motion", "Animation durations and effects, when you animate something yourself"]
|
|
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
|
+
}
|
|
292
500
|
// src/compare.ts
|
|
293
501
|
/** Anti-aliasing noise passes; a moved border, a changed color or a new line of text does not. */
|
|
294
502
|
const DEFAULT_TOLERANCE = {
|
|
@@ -336,17 +544,103 @@ function samePixels(x, y) {
|
|
|
336
544
|
const b = PNG.sync.read(y);
|
|
337
545
|
return a.width === b.width && a.height === b.height && Buffer.compare(a.data, b.data) === 0;
|
|
338
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
|
+
}
|
|
339
600
|
// src/shots.ts
|
|
340
601
|
const WIDTHS = [390, 1280];
|
|
341
602
|
const THEMES = ["light", "dark"];
|
|
342
603
|
/** The time every shot sees (Date, timers, relative times): 2026/11/20(五)17:00 in Taipei. */
|
|
343
604
|
const FIXED_TIME = "2026-11-20T17:00:00+08:00";
|
|
344
|
-
/**
|
|
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
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* The name a page's screenshots are filed under. A file: its name without the extension (Button.html → Button). A
|
|
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.
|
|
614
|
+
*/
|
|
615
|
+
function stemFor(url) {
|
|
616
|
+
let u;
|
|
617
|
+
try {
|
|
618
|
+
u = new URL(url);
|
|
619
|
+
} catch {
|
|
620
|
+
return cleanName(url) || "page";
|
|
621
|
+
}
|
|
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";
|
|
637
|
+
}
|
|
638
|
+
/** Turns paths and URLs into jobs, named by stemFor; a second target with the same name gets -2, -3, … */
|
|
345
639
|
function jobsFor(targets, toUrl) {
|
|
346
640
|
const stems = /* @__PURE__ */ new Map();
|
|
347
641
|
return targets.map((target) => {
|
|
348
642
|
const url = toUrl(target);
|
|
349
|
-
const base =
|
|
643
|
+
const base = stemFor(url);
|
|
350
644
|
const n = (stems.get(base) ?? 0) + 1;
|
|
351
645
|
stems.set(base, n);
|
|
352
646
|
return {
|
|
@@ -373,6 +667,75 @@ function applyTheme(t) {
|
|
|
373
667
|
function shotLaunchOptions() {
|
|
374
668
|
return process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : { channel: "chromium" };
|
|
375
669
|
}
|
|
670
|
+
/**
|
|
671
|
+
* Makes a full-page screenshot hold what scrolls inside the page's own scroll container. A frame such as AppShell
|
|
672
|
+
* keeps the document at the window's height and scrolls its main area (.ui-shell-main), so a full-page shot would
|
|
673
|
+
* stop at the window's bottom edge. When the document does not scroll but one large element (at least 60 % of the
|
|
674
|
+
* window's height) does, the viewport grows by what that element hides, up to 12000 px, until nothing is hidden.
|
|
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.
|
|
677
|
+
*/
|
|
678
|
+
async function growToScrollContainer(page, viewport, settle) {
|
|
679
|
+
let size = viewport;
|
|
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
|
+
};
|
|
688
|
+
let most = 0;
|
|
689
|
+
let key = "none";
|
|
690
|
+
for (const el of document.body.querySelectorAll("*")) {
|
|
691
|
+
if (el.clientHeight < innerHeight * .6) continue;
|
|
692
|
+
const cs = getComputedStyle(el);
|
|
693
|
+
if (!/auto|scroll/.test(cs.overflowY) || cs.display === "none") continue;
|
|
694
|
+
const hidden = el.scrollHeight - el.clientHeight;
|
|
695
|
+
if (hidden >= most) {
|
|
696
|
+
most = hidden;
|
|
697
|
+
key = `box ${el.scrollHeight}`;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
return {
|
|
701
|
+
hidden: most,
|
|
702
|
+
key: `${key} ${innerHeight}`
|
|
703
|
+
};
|
|
704
|
+
});
|
|
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;
|
|
713
|
+
await settle();
|
|
714
|
+
}
|
|
715
|
+
return size;
|
|
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
|
+
}
|
|
376
739
|
/** File name of one screenshot. */
|
|
377
740
|
const shotName = (stem, width, theme) => `${stem}-${width}-${theme}.png`;
|
|
378
741
|
/**
|
|
@@ -404,6 +767,7 @@ async function shootPage(browser, job, settle) {
|
|
|
404
767
|
await page.clock.pauseAt(Date.parse(FIXED_TIME));
|
|
405
768
|
const resp = await page.goto(job.url, { waitUntil: "load" });
|
|
406
769
|
if (resp && !resp.ok()) throw new Error(`HTTP ${resp.status()}`);
|
|
770
|
+
await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => void 0);
|
|
407
771
|
const fonts = () => page.evaluate(() => document.fonts.ready.then(() => void 0));
|
|
408
772
|
await fonts();
|
|
409
773
|
await page.evaluate(applyTheme, theme);
|
|
@@ -424,6 +788,13 @@ async function shootPage(browser, job, settle) {
|
|
|
424
788
|
}
|
|
425
789
|
});
|
|
426
790
|
await page.waitForTimeout(100);
|
|
791
|
+
await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => void 0);
|
|
792
|
+
await fonts();
|
|
793
|
+
await growToScrollContainer(page, viewport, async () => {
|
|
794
|
+
await page.waitForTimeout(100);
|
|
795
|
+
await page.clock.runFor(100);
|
|
796
|
+
await fonts();
|
|
797
|
+
});
|
|
427
798
|
await page.waitForTimeout(200);
|
|
428
799
|
const shoot = () => page.screenshot({
|
|
429
800
|
fullPage: true,
|
|
@@ -551,21 +922,39 @@ function summaryMarkdown(results, orphans, baseDir) {
|
|
|
551
922
|
return lines.join("\n");
|
|
552
923
|
}
|
|
553
924
|
// src/cli.ts
|
|
554
|
-
const
|
|
925
|
+
const HELP_CHECK = `ui check <file or URL>... [--shots DIR] [--strict] [--wait MS] [--open SELECTOR]... [--no-interact] [--no-axe]
|
|
555
926
|
Opens each page at 390 px and 1280 px, light and dark, and fails (exit 1) on:
|
|
556
|
-
console errors, horizontal overflow at 390 px, touch targets under 48 px
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
927
|
+
console errors, horizontal overflow at 390 px, touch targets under 48 px at 390 px and targets under 24 px that
|
|
928
|
+
crowd another target at 1280 px (WCAG 2.5.8), touch areas that spill past their control, a card inside a card, raw
|
|
929
|
+
Markdown, native controls the design system replaces, wrapped buttons, tabs, table headers or interface headings
|
|
930
|
+
(headings in Markdown content may wrap), interface text cut off with no tooltip or title, text outside its card,
|
|
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.
|
|
938
|
+
A page without <meta name="viewport"> gets one report at 390 px (缺 viewport meta) and no touch-target check there.
|
|
939
|
+
It also opens what the page hides behind clicks, in light at both widths: each tab of a [role=tablist], each
|
|
940
|
+
SettingsLayout category, and each menu or popover of an [aria-haspopup] button in a toolbar or top bar (up to 12
|
|
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.
|
|
943
|
+
--open SELECTOR clicks the first match and checks the state it opens (a dialog, a drawer); repeat for more.
|
|
944
|
+
--no-interact skips the automatic tabs, categories and toolbar menus (--open still runs).
|
|
945
|
+
--no-axe skips the axe-core pass.
|
|
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).
|
|
948
|
+
--strict also fails on inline text links under 48 px.
|
|
949
|
+
--wait MS waits this long after load before measuring (default 800).
|
|
950
|
+
Exits 2 when a page cannot be checked at all: it does not load, or the check itself crashes.`;
|
|
951
|
+
const HELP_SHOTS = `ui shots <file or URL>... (--out DIR [--prune] | --compare DIR --diff DIR) [--settle MS] [--threshold N] [--max-diff PERCENT]
|
|
567
952
|
Deterministic screenshots at 390 px and 1280 px, light and dark (DIR/<name>-<width>-<theme>.png): fixed clock
|
|
568
|
-
(${FIXED_TIME}, fake timers), reduced motion, animations stopped, caret hidden, fonts loaded, scale 1, full page
|
|
953
|
+
(${FIXED_TIME}, fake timers), reduced motion, animations stopped, caret hidden, fonts loaded, scale 1, full page,
|
|
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).
|
|
569
958
|
--out DIR writes the shots (baselines); a file with the same pixels is left as it is. New files are
|
|
570
959
|
optimised losslessly with oxipng when it is on PATH. --prune also deletes the PNGs in DIR
|
|
571
960
|
that no page of this run produced (a removed or renamed page).
|
|
@@ -576,39 +965,96 @@ ui shots <file or URL>... (--out DIR [--prune] | --compare DIR --diff DIR) [--se
|
|
|
576
965
|
shot, and summary.md.
|
|
577
966
|
--settle MS fake time the page runs before the shot (default 1000).
|
|
578
967
|
A changed shot is taken once more; it passes when the second shot matches.
|
|
579
|
-
Exits 2 when a page cannot be opened. Uses CHROMIUM_PATH, else Playwright's full Chromium (channel chromium)
|
|
580
|
-
|
|
968
|
+
Exits 2 when a page cannot be opened. Uses CHROMIUM_PATH, else Playwright's full Chromium (channel chromium).`;
|
|
969
|
+
const HELP_DOCS = `ui docs [Name] [--full]
|
|
970
|
+
Prints the 用法 block of a component (Button, DataTable…): what it is, a minimal example and the rules most often
|
|
971
|
+
gotten wrong. --full prints the whole README. Guides print whole: guidelines (the core rules every page needs),
|
|
972
|
+
layout, forms, data, monitoring, code, theme, motion. ui docs icons prints every built-in icon name on one line;
|
|
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.`;
|
|
978
|
+
const HELP = `${HELP_CHECK}
|
|
979
|
+
${HELP_ADD}
|
|
980
|
+
${HELP_DOCS}
|
|
981
|
+
${HELP_SHOTS}
|
|
982
|
+
ui list lists every guide (in reading order) and every component by group, with its one-line description`;
|
|
581
983
|
function docsDir() {
|
|
582
984
|
const require = createRequire(import.meta.url);
|
|
583
985
|
return join(dirname(require.resolve("@seanyeh77/ui/package.json")), "docs");
|
|
584
986
|
}
|
|
585
|
-
/**
|
|
987
|
+
/** Each component's group, from docs/components.json (written at build time); empty for an older package. */
|
|
988
|
+
function componentIndex(dir) {
|
|
989
|
+
try {
|
|
990
|
+
return JSON.parse(readFileSync(join(dir, "components.json"), "utf8"));
|
|
991
|
+
} catch {
|
|
992
|
+
return [];
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
/** A guide is any doc that is not a component's README (guidelines, the topic files, icons, agents). */
|
|
996
|
+
function isGuide(dir) {
|
|
997
|
+
const names = new Set(componentIndex(dir).map((c) => c.name));
|
|
998
|
+
return (f) => names.size ? !names.has(f.slice(0, -3)) : /^[a-z]/.test(f);
|
|
999
|
+
}
|
|
1000
|
+
/** Guides first, then the components. */
|
|
586
1001
|
function docFiles(dir) {
|
|
587
1002
|
const files = readdirSync(dir).filter((f) => f.endsWith(".md"));
|
|
588
|
-
const
|
|
1003
|
+
const guideFile = isGuide(dir);
|
|
1004
|
+
const guide = (f) => guideFile(f) ? 0 : 1;
|
|
589
1005
|
return files.sort((a, b) => guide(a) - guide(b) || (a === "guidelines.md" ? -1 : b === "guidelines.md" ? 1 : a.localeCompare(b)));
|
|
590
1006
|
}
|
|
1007
|
+
function readingOrder() {
|
|
1008
|
+
return [
|
|
1009
|
+
"Reading order: guidelines first, then a topic guide only when the page has that topic, then the 用法 block of each component you use.",
|
|
1010
|
+
...GUIDES.map(([g, what], i) => ` ${String(i + 1).padStart(2)}. ${g.padEnd(12)} ${what}`),
|
|
1011
|
+
""
|
|
1012
|
+
];
|
|
1013
|
+
}
|
|
591
1014
|
function docs(name, full) {
|
|
592
1015
|
const dir = docsDir();
|
|
593
1016
|
const files = docFiles(dir);
|
|
594
|
-
if (!name) return console.log(
|
|
1017
|
+
if (!name) return console.log([
|
|
1018
|
+
...readingOrder(),
|
|
1019
|
+
"Every doc:",
|
|
1020
|
+
...files.map((f) => " " + f.slice(0, -3))
|
|
1021
|
+
].join("\n"));
|
|
595
1022
|
const hit = files.find((f) => f.slice(0, -3).toLowerCase() === name.toLowerCase());
|
|
596
1023
|
if (!hit) {
|
|
597
1024
|
console.error(`No docs for "${name}". Run "ui docs" for the list.`);
|
|
598
1025
|
process.exit(1);
|
|
599
1026
|
}
|
|
600
|
-
const md = readFileSync(join(dir, hit), "utf8");
|
|
1027
|
+
const md = stripComments(readFileSync(join(dir, hit), "utf8"));
|
|
601
1028
|
const usage = full ? null : usageBlock(md);
|
|
602
1029
|
if (!usage) return console.log(md);
|
|
603
|
-
|
|
1030
|
+
const more = md.trim().length > usage.trim().length;
|
|
1031
|
+
console.log(more ? usage + `\n(用法 only. The whole README: ui docs ${hit.slice(0, -3)} --full)` : usage);
|
|
604
1032
|
}
|
|
605
1033
|
function list() {
|
|
606
1034
|
const dir = docsDir();
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
1035
|
+
const files = docFiles(dir);
|
|
1036
|
+
const lines = ["Guides, in reading order:"];
|
|
1037
|
+
const guideFile = isGuide(dir);
|
|
1038
|
+
const guides = files.filter(guideFile).map((f) => f.slice(0, -3));
|
|
1039
|
+
const ordered = [...GUIDES.map(([g]) => g).filter((g) => guides.includes(g)), ...guides.filter((g) => !GUIDES.some(([n]) => n === g))];
|
|
1040
|
+
for (const g of ordered) {
|
|
1041
|
+
const md = readFileSync(join(dir, `${g}.md`), "utf8");
|
|
1042
|
+
lines.push(` ${g.padEnd(18)} ${/^# (.+)$/m.exec(md)?.[1] ?? ""}`);
|
|
1043
|
+
}
|
|
1044
|
+
const groupOf = new Map(componentIndex(dir).map((c) => [c.name, c.group]));
|
|
1045
|
+
const components = files.filter((f) => !guideFile(f)).map((f) => f.slice(0, -3));
|
|
1046
|
+
const order = [...Object.keys(GROUPS), "Other"];
|
|
1047
|
+
const byGroup = /* @__PURE__ */ new Map();
|
|
1048
|
+
for (const c of components) {
|
|
1049
|
+
const g = groupOf.get(c) ?? "Other";
|
|
1050
|
+
byGroup.set(g, [...byGroup.get(g) ?? [], c]);
|
|
611
1051
|
}
|
|
1052
|
+
const groups = [...byGroup.keys()].sort((a, b) => (order.indexOf(a) + 1 || 99) - (order.indexOf(b) + 1 || 99));
|
|
1053
|
+
for (const g of groups) {
|
|
1054
|
+
lines.push("", `${GROUPS[g] ?? (g === "Other" ? "其他" : g)} (${g}):`);
|
|
1055
|
+
for (const c of byGroup.get(g) ?? []) lines.push(` ${c.padEnd(18)} ${summary(readFileSync(join(dir, `${c}.md`), "utf8"))}`);
|
|
1056
|
+
}
|
|
1057
|
+
console.log(lines.join("\n"));
|
|
612
1058
|
}
|
|
613
1059
|
const toUrl = (t) => t.includes("://") ? new URL(t).href : pathToFileURL(resolve(t)).href;
|
|
614
1060
|
/** The page itself could not be opened: a wrong path, no server, or an HTTP error. */
|
|
@@ -700,9 +1146,127 @@ async function shots(targets, opts) {
|
|
|
700
1146
|
console.log(`${all.length} screenshots in ${opts.out}: ${written} written${optimized ? " (oxipng)" : " (oxipng not found: PNGs as Playwright wrote them)"}, ${all.length - written} kept (same pixels).`);
|
|
701
1147
|
process.exit(unshot ? 2 : 0);
|
|
702
1148
|
}
|
|
1149
|
+
/** The WCAG levels the axe-core pass checks: 2.0, 2.1 and 2.2, A and AA. */
|
|
1150
|
+
const AXE_TAGS = [
|
|
1151
|
+
"wcag2a",
|
|
1152
|
+
"wcag2aa",
|
|
1153
|
+
"wcag21aa",
|
|
1154
|
+
"wcag22aa"
|
|
1155
|
+
];
|
|
1156
|
+
let axeSource;
|
|
1157
|
+
const axeScript = () => axeSource ??= readFileSync(createRequire(import.meta.url).resolve("axe-core/axe.min.js"), "utf8");
|
|
1158
|
+
/**
|
|
1159
|
+
* Runs axe-core in the page and returns one line per rule it reports. contrastOnly: only color-contrast (the dark
|
|
1160
|
+
* pass: every other rule gives the same result as in light). preload off: axe would fetch the stylesheets again,
|
|
1161
|
+
* which fails on file:// pages and shows up as console errors.
|
|
1162
|
+
*/
|
|
1163
|
+
async function axeRun(page, contrastOnly = false, skip = []) {
|
|
1164
|
+
if (!await page.evaluate(() => "axe" in window)) await page.addScriptTag({ content: axeScript() });
|
|
1165
|
+
return (await page.evaluate(async ({ tags, contrastOnly, skip }) => {
|
|
1166
|
+
const axe = window.axe;
|
|
1167
|
+
const runOnly = contrastOnly ? {
|
|
1168
|
+
type: "rule",
|
|
1169
|
+
values: ["color-contrast"]
|
|
1170
|
+
} : {
|
|
1171
|
+
type: "tag",
|
|
1172
|
+
values: tags
|
|
1173
|
+
};
|
|
1174
|
+
const rules = Object.fromEntries(["target-size", ...skip].map((id) => [id, { enabled: false }]));
|
|
1175
|
+
const run = async (tries) => {
|
|
1176
|
+
try {
|
|
1177
|
+
return await axe.run(document, {
|
|
1178
|
+
runOnly,
|
|
1179
|
+
resultTypes: ["violations"],
|
|
1180
|
+
preload: false,
|
|
1181
|
+
rules
|
|
1182
|
+
});
|
|
1183
|
+
} catch (e) {
|
|
1184
|
+
if (tries <= 0 || !String(e).includes("already running")) throw e;
|
|
1185
|
+
await new Promise((ok) => setTimeout(ok, 200));
|
|
1186
|
+
return run(tries - 1);
|
|
1187
|
+
}
|
|
1188
|
+
};
|
|
1189
|
+
return (await run(50)).violations.map((v) => ({
|
|
1190
|
+
id: v.id,
|
|
1191
|
+
impact: v.impact ?? "",
|
|
1192
|
+
help: v.help,
|
|
1193
|
+
count: v.nodes.length,
|
|
1194
|
+
target: String(v.nodes[0]?.target?.[0] ?? "")
|
|
1195
|
+
}));
|
|
1196
|
+
}, {
|
|
1197
|
+
tags: AXE_TAGS,
|
|
1198
|
+
contrastOnly,
|
|
1199
|
+
skip
|
|
1200
|
+
})).map((v) => `${v.id} (${v.impact}): ${v.help}; ${v.count} element${v.count === 1 ? "" : "s"}, e.g. ${v.target}`);
|
|
1201
|
+
}
|
|
1202
|
+
/** The problems in one measurement. noViewport: the 390 px pass of a page without a viewport meta (no touch checks). */
|
|
1203
|
+
function problemsOf(res, phone, strict) {
|
|
1204
|
+
const problems = [];
|
|
1205
|
+
const list = (items, n = 12) => `${items.slice(0, n).join("; ")}${items.length > n ? ` (+${items.length - n} more)` : ""}`;
|
|
1206
|
+
if (res.nested.length) problems.push("card inside a card (two shadows): " + res.nested.join("; "));
|
|
1207
|
+
if (res.markdown.length) problems.push("raw Markdown shown: " + res.markdown.join("; "));
|
|
1208
|
+
if (res.native.length) problems.push("native controls: " + [...new Set(res.native)].join("; "));
|
|
1209
|
+
if (res.wrapped.length) problems.push("text that must stay on one line wraps: " + res.wrapped.join("; "));
|
|
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.");
|
|
1211
|
+
if (res.outside.length) problems.push("text outside its card: " + res.outside.join("; ") + ". Leave room inside the card (chart axis labels, long words).");
|
|
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.`);
|
|
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.");
|
|
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.");
|
|
1217
|
+
if (phone && res.viewportMeta) {
|
|
1218
|
+
if (res.overflow.length) problems.push("horizontal overflow: " + res.overflow.join("; "));
|
|
1219
|
+
if (res.escaped.length) problems.push("touch area larger than its control (covers other controls): " + res.escaped.join("; "));
|
|
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).");
|
|
1222
|
+
if (res.inline.length && strict) problems.push("inline targets under 48 px: " + list(res.inline));
|
|
1223
|
+
}
|
|
1224
|
+
if (!phone && res.small24.length) problems.push(`targets under 24 px next to another target (WCAG 2.5.8): ${list(res.small24, 8)}`);
|
|
1225
|
+
return problems;
|
|
1226
|
+
}
|
|
1227
|
+
const NO_VIEWPORT = "缺 viewport meta: add <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">. Without it a phone lays the page out 980 px wide and shrinks it, so overflow and touch targets at 390 px were not checked.";
|
|
1228
|
+
/** Buttons that open a menu or popover in a toolbar or the top bar; their open state is checked by itself. */
|
|
1229
|
+
const TOOLBAR_POPUPS = [
|
|
1230
|
+
".ui-dt-tools",
|
|
1231
|
+
".ui-dt-actions",
|
|
1232
|
+
".ui-card-actions",
|
|
1233
|
+
"[role=toolbar]",
|
|
1234
|
+
".ui-topbar",
|
|
1235
|
+
".ui-actionbar"
|
|
1236
|
+
].map((t) => `${t} [aria-haspopup]:not([aria-haspopup="false"])`).join(", ");
|
|
1237
|
+
const MAX_STATES = 12;
|
|
1238
|
+
/** Marks the elements to click for the automatic states (data-ui-check-state) and names them. Runs inside the page. */
|
|
1239
|
+
function findStates({ popups, max }) {
|
|
1240
|
+
const out = [];
|
|
1241
|
+
const shown = (el) => {
|
|
1242
|
+
const r = el.getBoundingClientRect();
|
|
1243
|
+
const cs = getComputedStyle(el);
|
|
1244
|
+
return r.width > 0 && r.height > 0 && cs.visibility !== "hidden" && !el.closest("[inert], [aria-hidden=\"true\"]");
|
|
1245
|
+
};
|
|
1246
|
+
const name = (el) => {
|
|
1247
|
+
const by = el.getAttribute("aria-labelledby");
|
|
1248
|
+
const labelled = by ? by.split(/\s+/).map((id) => document.getElementById(id)?.textContent ?? "").join(" ") : "";
|
|
1249
|
+
const label = el.labels?.[0]?.textContent ?? "";
|
|
1250
|
+
return (el.getAttribute("aria-label") || labelled || label || el.textContent || el.getAttribute("placeholder") || el.tagName.toLowerCase()).trim().replace(/\s+/g, " ").slice(0, 24);
|
|
1251
|
+
};
|
|
1252
|
+
const add = (el, label, kind) => {
|
|
1253
|
+
if (out.length >= max || !shown(el) || el.matches(":disabled, [aria-disabled=\"true\"]")) return;
|
|
1254
|
+
const id = String(out.length);
|
|
1255
|
+
el.setAttribute("data-ui-check-state", id);
|
|
1256
|
+
out.push({
|
|
1257
|
+
id,
|
|
1258
|
+
label,
|
|
1259
|
+
kind
|
|
1260
|
+
});
|
|
1261
|
+
};
|
|
1262
|
+
for (const el of document.querySelectorAll(popups)) add(el, `the menu of "${name(el)}"`, "popup");
|
|
1263
|
+
for (const list of [...document.querySelectorAll("[role=tablist]")].slice(0, 3)) for (const tab of list.querySelectorAll("[role=tab]")) if (tab.getAttribute("aria-selected") !== "true") add(tab, `tab "${name(tab)}"`, "view");
|
|
1264
|
+
for (const cat of document.querySelectorAll(".ui-settings-cat")) if (cat.getAttribute("aria-current") !== "page") add(cat, `category "${name(cat)}"`, "view");
|
|
1265
|
+
return out;
|
|
1266
|
+
}
|
|
703
1267
|
async function check(targets, opts) {
|
|
704
1268
|
const { chromium } = await import("playwright");
|
|
705
|
-
const browser = await chromium.launch(
|
|
1269
|
+
const browser = await chromium.launch(shotLaunchOptions()).catch((e) => {
|
|
706
1270
|
console.error(String(e).split("\n")[0]);
|
|
707
1271
|
console.error("No Chromium for ui check. Run `npx playwright install chromium`, or set CHROMIUM_PATH to an installed Chrome or Chromium.");
|
|
708
1272
|
process.exit(2);
|
|
@@ -711,13 +1275,15 @@ async function check(targets, opts) {
|
|
|
711
1275
|
const checkOne = async ({ url, stem }) => {
|
|
712
1276
|
const out = [url];
|
|
713
1277
|
let bad = false;
|
|
1278
|
+
let viewportReported = false;
|
|
714
1279
|
for (const width of [390, 1280]) for (const theme of ["light", "dark"]) {
|
|
715
1280
|
const phone = width === 390;
|
|
1281
|
+
const viewport = {
|
|
1282
|
+
width,
|
|
1283
|
+
height: phone ? 844 : 900
|
|
1284
|
+
};
|
|
716
1285
|
const ctx = await browser.newContext({
|
|
717
|
-
viewport
|
|
718
|
-
width,
|
|
719
|
-
height: phone ? 844 : 900
|
|
720
|
-
},
|
|
1286
|
+
viewport,
|
|
721
1287
|
colorScheme: theme,
|
|
722
1288
|
hasTouch: phone,
|
|
723
1289
|
isMobile: phone,
|
|
@@ -748,31 +1314,117 @@ async function check(targets, opts) {
|
|
|
748
1314
|
await run(() => page.evaluate(applyTheme, theme));
|
|
749
1315
|
await page.waitForTimeout(opts.wait);
|
|
750
1316
|
await page.waitForLoadState("load");
|
|
1317
|
+
await run(() => waitForAnimations(page));
|
|
751
1318
|
const res = await run(() => page.evaluate(measure));
|
|
752
1319
|
if (page.url() !== url && width === 390 && theme === "light") out.push(` (redirected to ${page.url()})`);
|
|
753
1320
|
const problems = [];
|
|
754
1321
|
if (errors.length) problems.push("console errors: " + errors.slice(0, 5).join(" | "));
|
|
755
|
-
if (res.
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
if (res.wrapped.length) problems.push("text that must stay on one line wraps: " + res.wrapped.join("; "));
|
|
759
|
-
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.");
|
|
760
|
-
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.");
|
|
761
|
-
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.");
|
|
762
|
-
if (phone) {
|
|
763
|
-
if (res.overflow.length) problems.push("horizontal overflow: " + res.overflow.join("; "));
|
|
764
|
-
if (res.escaped.length) problems.push("touch area larger than its control (covers other controls): " + res.escaped.join("; "));
|
|
765
|
-
if (res.small.length) problems.push(`touch targets under 48 px: ${res.small.slice(0, 12).join("; ")}${res.small.length > 12 ? ` (+${res.small.length - 12} more)` : ""}`);
|
|
766
|
-
if (res.inline.length && opts.strict) problems.push("inline targets under 48 px: " + res.inline.slice(0, 12).join("; "));
|
|
1322
|
+
if (phone && !res.viewportMeta && !viewportReported) {
|
|
1323
|
+
problems.push(NO_VIEWPORT);
|
|
1324
|
+
viewportReported = true;
|
|
767
1325
|
}
|
|
768
|
-
|
|
1326
|
+
problems.push(...problemsOf(res, phone, opts.strict));
|
|
1327
|
+
const axe = opts.axe ? await run(() => axeRun(page, theme === "dark")).catch((e) => [`axe-core could not run: ${String(e).split("\n")[0]}`]) : [];
|
|
1328
|
+
if (axe.length) problems.push("accessibility (axe-core): " + axe.join(" | "));
|
|
1329
|
+
const shoot = async (suffix) => {
|
|
1330
|
+
if (!opts.shots) return;
|
|
1331
|
+
await growToScrollContainer(page, viewport, () => page.waitForTimeout(150));
|
|
1332
|
+
await page.screenshot({
|
|
1333
|
+
path: join(opts.shots, `${shotName(stem, width, theme).slice(0, -4)}${suffix}.png`),
|
|
1334
|
+
fullPage: true
|
|
1335
|
+
});
|
|
1336
|
+
await page.setViewportSize(viewport);
|
|
1337
|
+
};
|
|
1338
|
+
await shoot("");
|
|
1339
|
+
const states = [];
|
|
1340
|
+
if (theme === "light" && (opts.open.length || opts.interact)) {
|
|
1341
|
+
const itemKey = (item) => item.split(", next to ")[0].replace(/ \d+ x \d+ px$/, "");
|
|
1342
|
+
const axeKey = (line) => line.split(" ")[0];
|
|
1343
|
+
const knownAxe = new Set(axe.map(axeKey));
|
|
1344
|
+
const newOnly = (now) => {
|
|
1345
|
+
const out = { ...now };
|
|
1346
|
+
for (const k of Object.keys(now)) {
|
|
1347
|
+
const was = res[k];
|
|
1348
|
+
const is = now[k];
|
|
1349
|
+
if (Array.isArray(was) && Array.isArray(is)) {
|
|
1350
|
+
const seen = new Set(was.map(itemKey));
|
|
1351
|
+
out[k] = is.filter((x) => !seen.has(itemKey(x)));
|
|
1352
|
+
} else if (typeof was === "string" && was) out[k] = "";
|
|
1353
|
+
}
|
|
1354
|
+
return out;
|
|
1355
|
+
};
|
|
1356
|
+
const checkState = async (label, target, trigger) => {
|
|
1357
|
+
const before = errors.length;
|
|
1358
|
+
try {
|
|
1359
|
+
await target.click({ timeout: 3e3 });
|
|
1360
|
+
} catch {
|
|
1361
|
+
return null;
|
|
1362
|
+
}
|
|
1363
|
+
await page.waitForTimeout(150);
|
|
1364
|
+
await run(() => waitForAnimations(page));
|
|
1365
|
+
const after = await run(() => page.evaluate(measure));
|
|
1366
|
+
const found = problemsOf(newOnly(after), phone, opts.strict);
|
|
1367
|
+
if (errors.length > before) found.unshift("console errors: " + errors.slice(before, before + 5).join(" | "));
|
|
1368
|
+
if (opts.axe) {
|
|
1369
|
+
const skip = trigger ? ["aria-hidden-focus"] : [];
|
|
1370
|
+
const more = (await run(() => axeRun(page, false, skip)).catch(() => [])).filter((v) => !knownAxe.has(axeKey(v)));
|
|
1371
|
+
if (more.length) found.push("accessibility (axe-core): " + more.join(" | "));
|
|
1372
|
+
}
|
|
1373
|
+
await shoot(`-${cleanName(label)}`);
|
|
1374
|
+
if (trigger) {
|
|
1375
|
+
await page.keyboard.press("Escape");
|
|
1376
|
+
await page.waitForTimeout(150);
|
|
1377
|
+
if (await target.getAttribute("aria-expanded").catch(() => null) === "true") {
|
|
1378
|
+
await target.click({ timeout: 3e3 }).catch(() => void 0);
|
|
1379
|
+
await page.waitForTimeout(150);
|
|
1380
|
+
}
|
|
1381
|
+
await run(() => waitForAnimations(page));
|
|
1382
|
+
}
|
|
1383
|
+
return found;
|
|
1384
|
+
};
|
|
1385
|
+
for (const sel of opts.open) {
|
|
1386
|
+
const target = page.locator(sel).first();
|
|
1387
|
+
const label = `--open ${sel}`;
|
|
1388
|
+
if (!await target.count()) {
|
|
1389
|
+
states.push({
|
|
1390
|
+
label,
|
|
1391
|
+
problems: ["nothing on the page matches"]
|
|
1392
|
+
});
|
|
1393
|
+
continue;
|
|
1394
|
+
}
|
|
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
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
if (opts.interact) {
|
|
1406
|
+
const auto = await run(() => page.evaluate(findStates, {
|
|
1407
|
+
popups: TOOLBAR_POPUPS,
|
|
1408
|
+
max: MAX_STATES
|
|
1409
|
+
}));
|
|
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
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
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"}`);
|
|
769
1421
|
for (const p of problems) out.push(" - " + p);
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
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;
|
|
776
1428
|
} finally {
|
|
777
1429
|
await ctx.close();
|
|
778
1430
|
}
|
|
@@ -809,25 +1461,51 @@ async function check(targets, opts) {
|
|
|
809
1461
|
await browser.close();
|
|
810
1462
|
process.exit(unchecked ? 2 : failed ? 1 : 0);
|
|
811
1463
|
}
|
|
1464
|
+
/** Parses the options of one command; --help prints that command's help, an unknown option its help and exit 2. */
|
|
1465
|
+
function parse(args, options, help) {
|
|
1466
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
1467
|
+
console.log(help);
|
|
1468
|
+
process.exit(0);
|
|
1469
|
+
}
|
|
1470
|
+
try {
|
|
1471
|
+
return parseArgs({
|
|
1472
|
+
args,
|
|
1473
|
+
allowPositionals: true,
|
|
1474
|
+
options
|
|
1475
|
+
});
|
|
1476
|
+
} catch (e) {
|
|
1477
|
+
console.error(`${e.message}\n\n${help}`);
|
|
1478
|
+
process.exit(2);
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
812
1481
|
const [cmd, ...rest] = process.argv.slice(2);
|
|
813
1482
|
if (cmd === "check") {
|
|
814
|
-
const { values, positionals } =
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
1483
|
+
const { values, positionals } = parse(rest, {
|
|
1484
|
+
shots: { type: "string" },
|
|
1485
|
+
strict: {
|
|
1486
|
+
type: "boolean",
|
|
1487
|
+
default: false
|
|
1488
|
+
},
|
|
1489
|
+
wait: {
|
|
1490
|
+
type: "string",
|
|
1491
|
+
default: "800"
|
|
1492
|
+
},
|
|
1493
|
+
open: {
|
|
1494
|
+
type: "string",
|
|
1495
|
+
multiple: true,
|
|
1496
|
+
default: []
|
|
1497
|
+
},
|
|
1498
|
+
"no-interact": {
|
|
1499
|
+
type: "boolean",
|
|
1500
|
+
default: false
|
|
1501
|
+
},
|
|
1502
|
+
"no-axe": {
|
|
1503
|
+
type: "boolean",
|
|
1504
|
+
default: false
|
|
827
1505
|
}
|
|
828
|
-
});
|
|
1506
|
+
}, HELP_CHECK);
|
|
829
1507
|
if (!positionals.length) {
|
|
830
|
-
console.error(
|
|
1508
|
+
console.error(HELP_CHECK);
|
|
831
1509
|
process.exit(2);
|
|
832
1510
|
}
|
|
833
1511
|
for (const t of positionals) if (!t.includes("://") && !existsSync(t)) {
|
|
@@ -845,39 +1523,38 @@ if (cmd === "check") {
|
|
|
845
1523
|
await check(positionals, {
|
|
846
1524
|
shots: values.shots,
|
|
847
1525
|
strict: !!values.strict,
|
|
848
|
-
wait
|
|
1526
|
+
wait,
|
|
1527
|
+
open: values.open ?? [],
|
|
1528
|
+
interact: !values["no-interact"],
|
|
1529
|
+
axe: !values["no-axe"]
|
|
849
1530
|
});
|
|
850
1531
|
} else if (cmd === "shots") {
|
|
851
|
-
const { values, positionals } =
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
"max-diff": {
|
|
871
|
-
type: "string",
|
|
872
|
-
default: String(DEFAULT_TOLERANCE.maxDiffPercent)
|
|
873
|
-
}
|
|
1532
|
+
const { values, positionals } = parse(rest, {
|
|
1533
|
+
out: { type: "string" },
|
|
1534
|
+
compare: { type: "string" },
|
|
1535
|
+
diff: { type: "string" },
|
|
1536
|
+
prune: {
|
|
1537
|
+
type: "boolean",
|
|
1538
|
+
default: false
|
|
1539
|
+
},
|
|
1540
|
+
settle: {
|
|
1541
|
+
type: "string",
|
|
1542
|
+
default: "1000"
|
|
1543
|
+
},
|
|
1544
|
+
threshold: {
|
|
1545
|
+
type: "string",
|
|
1546
|
+
default: String(DEFAULT_TOLERANCE.threshold)
|
|
1547
|
+
},
|
|
1548
|
+
"max-diff": {
|
|
1549
|
+
type: "string",
|
|
1550
|
+
default: String(DEFAULT_TOLERANCE.maxDiffPercent)
|
|
874
1551
|
}
|
|
875
|
-
});
|
|
1552
|
+
}, HELP_SHOTS);
|
|
876
1553
|
const fail = (msg) => {
|
|
877
1554
|
console.error(msg);
|
|
878
1555
|
process.exit(2);
|
|
879
1556
|
};
|
|
880
|
-
if (!positionals.length || !values.out && !values.compare) fail(
|
|
1557
|
+
if (!positionals.length || !values.out && !values.compare) fail(HELP_SHOTS);
|
|
881
1558
|
if (values.out && values.compare) fail("Give --out DIR (write baselines) or --compare DIR (check against them), not both.");
|
|
882
1559
|
if (values.prune && !values.out) fail("--prune goes with --out: it deletes the baselines in that folder that no page produced.");
|
|
883
1560
|
if (values.compare && !values.diff) fail("--compare needs --diff DIR: where the diff images and new shots go.");
|
|
@@ -901,18 +1578,28 @@ if (cmd === "check") {
|
|
|
901
1578
|
}
|
|
902
1579
|
});
|
|
903
1580
|
} else if (cmd === "docs") {
|
|
904
|
-
const { values, positionals } =
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
type: "boolean",
|
|
909
|
-
default: false
|
|
910
|
-
} }
|
|
911
|
-
});
|
|
1581
|
+
const { values, positionals } = parse(rest, { full: {
|
|
1582
|
+
type: "boolean",
|
|
1583
|
+
default: false
|
|
1584
|
+
} }, HELP_DOCS);
|
|
912
1585
|
docs(positionals[0], !!values.full);
|
|
913
1586
|
} else if (cmd === "list") list();
|
|
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);
|
|
914
1601
|
else {
|
|
915
|
-
console.
|
|
916
|
-
process.exit(
|
|
1602
|
+
console.error(`Unknown command "${cmd}".\n\n${HELP}`);
|
|
1603
|
+
process.exit(2);
|
|
917
1604
|
}
|
|
918
1605
|
export {};
|
|
@@ -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",
|
|
@@ -17,10 +17,11 @@
|
|
|
17
17
|
"dist"
|
|
18
18
|
],
|
|
19
19
|
"dependencies": {
|
|
20
|
+
"axe-core": "4.14.1",
|
|
20
21
|
"pixelmatch": "^8.0.0",
|
|
21
|
-
"playwright": "
|
|
22
|
+
"playwright": "1.65.0",
|
|
22
23
|
"pngjs": "^7.0.0",
|
|
23
|
-
"@seanyeh77/ui": "^0.
|
|
24
|
+
"@seanyeh77/ui": "^0.46.0"
|
|
24
25
|
},
|
|
25
26
|
"engines": {
|
|
26
27
|
"node": ">=22"
|
|
@@ -29,7 +30,7 @@
|
|
|
29
30
|
"@types/pngjs": "^6.0.5"
|
|
30
31
|
},
|
|
31
32
|
"scripts": {
|
|
32
|
-
"build": "tsdown",
|
|
33
|
+
"build": "tsdown && node scripts/templates.ts",
|
|
33
34
|
"typecheck": "tsc -p .",
|
|
34
35
|
"test": "node --test src/*.test.ts"
|
|
35
36
|
}
|