@seanyeh77/ui-cli 0.44.0 → 0.45.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 +9 -4
- package/dist/cli.js +539 -101
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -7,13 +7,18 @@ 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
|
-
- `ui
|
|
10
|
+
- `ui check <檔案或 URL>`:在 390 px 與 1280 px、淺色與深色打開頁面,檢查 console 錯誤、水平溢出、小於 48 px 的觸控目標、1280 px 時小於 24 px 又擠著別的目標的目標(WCAG 2.5.8)、卡片裡的卡片、原生控制項、被截斷又沒有 Tooltip 或 title 的介面文字、跑出卡片外的文字、沒放進 layer 又蓋過元件的重設 CSS,以及 axe-core 的 WCAG 2.0、2.1、2.2 A 與 AA 規則,有問題時 exit 1。頁面沒有 viewport meta 時,390 px 只回報一次「缺 viewport meta」,不檢查觸控目標。
|
|
11
|
+
- 它也會點開每個分頁(`[role=tablist]`)、SettingsLayout 的每個分類,以及工具列與頂欄裡 `[aria-haspopup]` 按鈕的選單,檢查打開後的畫面(淺色、兩種寬度,每頁最多 12 個狀態),只回報原本沒有的問題。
|
|
12
|
+
- `--open <selector>` 點開頁面上第一個符合的元素(對話框、側欄)並檢查,可以重複;`--no-interact` 不自動點分頁、分類和選單;`--no-axe` 不跑 axe-core。
|
|
13
|
+
- `ui shots <檔案或 URL>`:固定時間、停止動畫的截圖,寫成基準圖(`--out`)或和基準圖比對(`--compare`)。整頁截圖包含頁面自己的捲動區(AppShell 的主內容)裡捲到下面的內容。檔名來自檔案名稱,網址則用路徑加 hash(`http://localhost:5173/settings#billing` 是 `settings-billing`)。
|
|
14
|
+
- 每個指令加 `--help` 印出自己的說明。
|
|
15
|
+
- `ui docs [Name] [--full]`:印出元件的用法區塊或使用規則;不加名稱時先印閱讀順序(guidelines 最先),再列出全部文件。
|
|
16
|
+
- `ui list`:依閱讀順序列出每份規則,再依分組(和 llms.txt 相同)列出每個元件的一句說明。
|
|
14
17
|
|
|
15
18
|
`npx @seanyeh77/ui-cli` 不加參數會印出完整說明。
|
|
16
19
|
|
|
20
|
+
Playwright 在 `@seanyeh77/ui` 與這個套件固定成同一個確切版本:畫面基準圖是用它的 Chromium 產生的,升級 Playwright 就要重新產生基準圖(Update visual baselines workflow)。
|
|
21
|
+
|
|
17
22
|
## 文件
|
|
18
23
|
|
|
19
24
|
- 文件網站:<https://seanyeh77.github.io/ui-design-system/>
|
package/dist/cli.js
CHANGED
|
@@ -20,7 +20,11 @@ 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: []
|
|
24
28
|
};
|
|
25
29
|
const describe = (el) => {
|
|
26
30
|
let s = el.tagName.toLowerCase();
|
|
@@ -35,10 +39,14 @@ function measure() {
|
|
|
35
39
|
const p = el.parentElement;
|
|
36
40
|
return !!p && [...p.childNodes].some((n) => n.nodeType === 3 && !!n.textContent?.trim());
|
|
37
41
|
};
|
|
42
|
+
const srOnly = (el, cs = getComputedStyle(el)) => {
|
|
43
|
+
const r = el.getBoundingClientRect();
|
|
44
|
+
return r.width <= 1 && r.height <= 1 || /rect\(0(px)?,? 0(px)?,? 0(px)?,? 0(px)?\)/.test(cs.clip) || cs.clipPath === "inset(50%)";
|
|
45
|
+
};
|
|
38
46
|
const visible = (el) => {
|
|
39
47
|
const cs = getComputedStyle(el);
|
|
40
48
|
const r = el.getBoundingClientRect();
|
|
41
|
-
return cs.visibility !== "hidden" && cs.display !== "none" && r.width > 0 && r.height > 0;
|
|
49
|
+
return cs.visibility !== "hidden" && cs.display !== "none" && r.width > 0 && r.height > 0 && !srOnly(el, cs);
|
|
42
50
|
};
|
|
43
51
|
const vw = document.documentElement.clientWidth;
|
|
44
52
|
if (document.documentElement.scrollWidth > vw + 1) {
|
|
@@ -54,12 +62,23 @@ function measure() {
|
|
|
54
62
|
}
|
|
55
63
|
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
64
|
const control = sel.replace(", [tabindex]:not([tabindex=\"-1\"])", "") + ", [role=slider], [role=separator], [role=combobox], [role=treeitem]";
|
|
65
|
+
const wholeRow = (el) => {
|
|
66
|
+
if (el.matches(".ui-dt-rowlink")) return true;
|
|
67
|
+
if (!el.matches("a[href]")) return false;
|
|
68
|
+
for (let a = el.parentElement; a && a !== document.body; a = a.parentElement) {
|
|
69
|
+
if (getComputedStyle(a).cursor === "pointer" && a.getBoundingClientRect().height >= 47.5) return true;
|
|
70
|
+
if (a.matches("tr, [role=row], li, [role=listitem], .ui-card, article")) break;
|
|
71
|
+
}
|
|
72
|
+
return false;
|
|
73
|
+
};
|
|
74
|
+
const targets = [];
|
|
75
|
+
const inText = (el, cs) => isInline(el, cs) || cs.display === "inline" || !!el.closest(".ui-md");
|
|
57
76
|
for (const el of new Set(document.querySelectorAll(sel))) {
|
|
58
77
|
if (el.closest("[aria-hidden=\"true\"], [inert]")) continue;
|
|
59
78
|
const cs = getComputedStyle(el);
|
|
60
79
|
if (cs.visibility === "hidden" || cs.display === "none" || cs.pointerEvents === "none") continue;
|
|
61
80
|
const r = el.getBoundingClientRect();
|
|
62
|
-
if (!r.width || !r.height) continue;
|
|
81
|
+
if (!r.width || !r.height || srOnly(el, cs)) continue;
|
|
63
82
|
if (!el.matches(control) && /auto|scroll/.test(cs.overflowX + " " + cs.overflowY)) continue;
|
|
64
83
|
const input = el;
|
|
65
84
|
if ((input.type === "checkbox" || input.type === "radio") && el.closest("label")) continue;
|
|
@@ -92,13 +111,43 @@ function measure() {
|
|
|
92
111
|
h = Math.max(h, ph);
|
|
93
112
|
}
|
|
94
113
|
}
|
|
114
|
+
targets.push({
|
|
115
|
+
el,
|
|
116
|
+
r,
|
|
117
|
+
w,
|
|
118
|
+
h,
|
|
119
|
+
inline: inText(el, cs)
|
|
120
|
+
});
|
|
95
121
|
if (w >= 47.5 && h >= 47.5) continue;
|
|
122
|
+
if (wholeRow(el)) {
|
|
123
|
+
out.inline.push(`${describe(el)} (its row or card is the target)`);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
96
126
|
if (el.matches(".ui-lg-hit")) {
|
|
97
127
|
out.inline.push(`${describe(el)} line`);
|
|
98
128
|
continue;
|
|
99
129
|
}
|
|
100
130
|
(isInline(el, cs) ? out.inline : out.small).push(`${describe(el)} ${Math.round(w)} x ${Math.round(h)} px`);
|
|
101
131
|
}
|
|
132
|
+
for (const t of targets) {
|
|
133
|
+
if (out.small24.length >= 60) break;
|
|
134
|
+
if (t.w >= 23.5 && t.h >= 23.5) continue;
|
|
135
|
+
if (t.inline || t.el.matches(".ui-lg-hit") || wholeRow(t.el)) continue;
|
|
136
|
+
const cx = t.r.left + t.r.width / 2;
|
|
137
|
+
const cy = t.r.top + t.r.height / 2;
|
|
138
|
+
if (cx >= 0 && cy >= 0 && cx < innerWidth && cy < innerHeight) {
|
|
139
|
+
const top = document.elementFromPoint(cx, cy);
|
|
140
|
+
if (top && !t.el.contains(top) && !top.contains(t.el)) continue;
|
|
141
|
+
}
|
|
142
|
+
const near = targets.find((o) => {
|
|
143
|
+
if (o === t || o.el.contains(t.el) || t.el.contains(o.el)) return false;
|
|
144
|
+
const dx = Math.max(o.r.left - cx, 0, cx - o.r.right);
|
|
145
|
+
const dy = Math.max(o.r.top - cy, 0, cy - o.r.bottom);
|
|
146
|
+
if (Math.hypot(dx, dy) < 12) return true;
|
|
147
|
+
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;
|
|
148
|
+
});
|
|
149
|
+
if (near) out.small24.push(`${describe(t.el)} ${Math.round(t.w)} x ${Math.round(t.h)} px, next to ${describe(near.el)}`);
|
|
150
|
+
}
|
|
102
151
|
const cardLike = (el) => {
|
|
103
152
|
const sh = getComputedStyle(el).boxShadow;
|
|
104
153
|
if (!sh || sh === "none") return false;
|
|
@@ -146,6 +195,48 @@ function measure() {
|
|
|
146
195
|
return new Set([...range.getClientRects()].filter((r) => r.width > 1).map((r) => Math.round(r.top / 4))).size > 1;
|
|
147
196
|
}))) out.wrapped.push(describe(el));
|
|
148
197
|
}
|
|
198
|
+
const titled = (n, el) => {
|
|
199
|
+
if (n.closest("[title], [data-ui-tip]")) return true;
|
|
200
|
+
const named = n.closest("[aria-label]");
|
|
201
|
+
return !!named && (named === el || el.contains(named));
|
|
202
|
+
};
|
|
203
|
+
const cut = (el) => {
|
|
204
|
+
const cs = getComputedStyle(el);
|
|
205
|
+
if (cs.overflowX === "visible" && cs.textOverflow !== "ellipsis") return false;
|
|
206
|
+
if (/auto|scroll/.test(cs.overflowX)) return false;
|
|
207
|
+
return el.scrollWidth > el.clientWidth + 1 && !!el.textContent?.trim();
|
|
208
|
+
};
|
|
209
|
+
const labels = ".ui-btn, .ui-tab, [role=tab], [role=columnheader], h1, h2, h3, h4, h5, h6, [class*=\"-title\"]";
|
|
210
|
+
const isLabel = (el) => !el.matches("[class*=\"-title\"]") || el.matches(labels.replace(", [class*=\"-title\"]", "")) || [...el.classList].some((c) => /^ui-[\w-]+-title$/.test(c));
|
|
211
|
+
for (const el of [...document.querySelectorAll(labels)].filter(isLabel)) {
|
|
212
|
+
if (out.truncated.length >= 30) break;
|
|
213
|
+
if (!visible(el) || el.closest(".ui-md, .ui-md-h, [aria-hidden=\"true\"]")) continue;
|
|
214
|
+
const hit = [el, ...el.querySelectorAll("*")].find((n) => visible(n) && cut(n) && !titled(n, el));
|
|
215
|
+
if (hit) out.truncated.push(`${describe(el)}: "${(hit.textContent || "").trim().slice(0, 32)}" is cut off`);
|
|
216
|
+
}
|
|
217
|
+
for (const card of document.querySelectorAll(".ui-card")) {
|
|
218
|
+
if (out.outside.length >= 6) break;
|
|
219
|
+
if (!visible(card)) continue;
|
|
220
|
+
const box = card.getBoundingClientRect();
|
|
221
|
+
const scrolls = (n) => {
|
|
222
|
+
for (let a = n.parentElement; a && a !== card; a = a.parentElement) if (/auto|scroll/.test(getComputedStyle(a).overflowX + getComputedStyle(a).overflowY)) return true;
|
|
223
|
+
return false;
|
|
224
|
+
};
|
|
225
|
+
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);
|
|
226
|
+
const walkText = document.createTreeWalker(card, NodeFilter.SHOW_TEXT);
|
|
227
|
+
for (let n = walkText.nextNode(); n; n = walkText.nextNode()) {
|
|
228
|
+
const parent = n.parentElement;
|
|
229
|
+
if (!parent || !n.textContent?.trim() || !visible(parent) || scrolls(parent)) continue;
|
|
230
|
+
if (parent.closest("[class*=\"sr-only\"], [class*=\"visually-hidden\"]") || getComputedStyle(parent).position === "fixed") continue;
|
|
231
|
+
const range = document.createRange();
|
|
232
|
+
range.selectNodeContents(n);
|
|
233
|
+
const r = [...range.getClientRects()].find(past);
|
|
234
|
+
if (r) {
|
|
235
|
+
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`);
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
149
240
|
const bars = ".ui-dt-tools, .ui-dt-actions, .ui-card-actions, [role=toolbar]";
|
|
150
241
|
const controls = "button, a[href], input:not([type=hidden]), [role=button], [role=combobox], .ui-searchfield, .ui-pwfield, .ui-datefield, .ui-ms, .ui-select, [role=tablist]";
|
|
151
242
|
for (const bar of document.querySelectorAll(bars)) {
|
|
@@ -289,6 +380,35 @@ function summary(md) {
|
|
|
289
380
|
else if (!code && line[i] === "。") return line.slice(0, i + 1);
|
|
290
381
|
return line;
|
|
291
382
|
}
|
|
383
|
+
/** The groups of the component list, in order, with their Chinese names (llms.txt and ui list use the same). A
|
|
384
|
+
component's group is the `group` of the @dsCard line of its preview.html (see groupOf). */
|
|
385
|
+
const GROUPS = {
|
|
386
|
+
Foundations: "基礎",
|
|
387
|
+
Layout: "版面與外框",
|
|
388
|
+
Actions: "按鈕與操作",
|
|
389
|
+
Forms: "表單",
|
|
390
|
+
Data: "數據呈現",
|
|
391
|
+
Monitoring: "監控畫面",
|
|
392
|
+
Code: "程式碼與架構圖",
|
|
393
|
+
Text: "文字標記",
|
|
394
|
+
Status: "狀態",
|
|
395
|
+
Feedback: "回饋",
|
|
396
|
+
Overlays: "浮層",
|
|
397
|
+
Navigation: "導覽",
|
|
398
|
+
Appearance: "外觀",
|
|
399
|
+
Pages: "整頁元件"
|
|
400
|
+
};
|
|
401
|
+
/** The reading order for an agent: the core rules every page needs, then a topic file only when the page has that topic. */
|
|
402
|
+
const GUIDES = [
|
|
403
|
+
["guidelines", "Core rules every page needs (read first): look, type, controls, layout, formats, copy, status, accessibility, checks"],
|
|
404
|
+
["layout", "Page frames, navigation, search and first-use tours: when you lay out a frame yourself"],
|
|
405
|
+
["forms", "Which input component to use and how to arrange a form"],
|
|
406
|
+
["data", "Tables, result lists, file trees, KPIs and charts"],
|
|
407
|
+
["monitoring", "Full-screen always-on monitoring screens (ConsoleLayout and its parts)"],
|
|
408
|
+
["code", "Code-reading tools: code views, architecture graphs, project docs"],
|
|
409
|
+
["theme", "Every token, theme and accent settings, the accent derivation, the Slidev teaching preset"],
|
|
410
|
+
["motion", "Animation durations and effects, when you animate something yourself"]
|
|
411
|
+
];
|
|
292
412
|
// src/compare.ts
|
|
293
413
|
/** Anti-aliasing noise passes; a moved border, a changed color or a new line of text does not. */
|
|
294
414
|
const DEFAULT_TOLERANCE = {
|
|
@@ -341,12 +461,30 @@ const WIDTHS = [390, 1280];
|
|
|
341
461
|
const THEMES = ["light", "dark"];
|
|
342
462
|
/** The time every shot sees (Date, timers, relative times): 2026/11/20(五)17:00 in Taipei. */
|
|
343
463
|
const FIXED_TIME = "2026-11-20T17:00:00+08:00";
|
|
344
|
-
/**
|
|
464
|
+
/**
|
|
465
|
+
* The name a page's screenshots are filed under. A file: its name without the extension (Button.html → Button). A
|
|
466
|
+
* page on a server: its path and hash (http://localhost:5173/settings#billing → settings-billing, / → index), so the
|
|
467
|
+
* pages of one site do not overwrite each other. Only letters, digits, dot, dash and underscore remain (no colon).
|
|
468
|
+
*/
|
|
469
|
+
function stemFor(url) {
|
|
470
|
+
const clean = (s) => s.replace(/[^\p{L}\p{N}._-]+/gu, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|-+$/g, "");
|
|
471
|
+
let u;
|
|
472
|
+
try {
|
|
473
|
+
u = new URL(url);
|
|
474
|
+
} catch {
|
|
475
|
+
return clean(url) || "page";
|
|
476
|
+
}
|
|
477
|
+
const hash = decodeURIComponent(u.hash.slice(1));
|
|
478
|
+
const path = decodeURIComponent(u.pathname).replace(/\/+$/, "");
|
|
479
|
+
const base = u.protocol === "file:" ? (path.split("/").pop() ?? "").replace(/\.[^.]*$/, "") : path.replace(/\.html?$/i, "").split("/").filter(Boolean).join("-") || "index";
|
|
480
|
+
return clean(hash ? `${base}-${hash}` : base) || "page";
|
|
481
|
+
}
|
|
482
|
+
/** Turns paths and URLs into jobs, named by stemFor; a second target with the same name gets -2, -3, … */
|
|
345
483
|
function jobsFor(targets, toUrl) {
|
|
346
484
|
const stems = /* @__PURE__ */ new Map();
|
|
347
485
|
return targets.map((target) => {
|
|
348
486
|
const url = toUrl(target);
|
|
349
|
-
const base =
|
|
487
|
+
const base = stemFor(url);
|
|
350
488
|
const n = (stems.get(base) ?? 0) + 1;
|
|
351
489
|
stems.set(base, n);
|
|
352
490
|
return {
|
|
@@ -373,6 +511,38 @@ function applyTheme(t) {
|
|
|
373
511
|
function shotLaunchOptions() {
|
|
374
512
|
return process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : { channel: "chromium" };
|
|
375
513
|
}
|
|
514
|
+
/**
|
|
515
|
+
* Makes a full-page screenshot hold what scrolls inside the page's own scroll container. A frame such as AppShell
|
|
516
|
+
* keeps the document at the window's height and scrolls its main area (.ui-shell-main), so a full-page shot would
|
|
517
|
+
* stop at the window's bottom edge. When the document does not scroll but one large element (at least 60 % of the
|
|
518
|
+
* window's height) does, the viewport grows by what that element hides, up to 12000 px, until nothing is hidden.
|
|
519
|
+
* Returns the viewport to restore. Runs the given settle step after each resize.
|
|
520
|
+
*/
|
|
521
|
+
async function growToScrollContainer(page, viewport, settle) {
|
|
522
|
+
let size = viewport;
|
|
523
|
+
for (let i = 0; i < 4; i++) {
|
|
524
|
+
const hidden = await page.evaluate(() => {
|
|
525
|
+
if ((document.scrollingElement ?? document.documentElement).scrollHeight > innerHeight + 1) return 0;
|
|
526
|
+
let most = 0;
|
|
527
|
+
for (const el of document.body.querySelectorAll("*")) {
|
|
528
|
+
if (el.clientHeight < innerHeight * .6) continue;
|
|
529
|
+
const cs = getComputedStyle(el);
|
|
530
|
+
if (!/auto|scroll/.test(cs.overflowY) || cs.display === "none") continue;
|
|
531
|
+
most = Math.max(most, el.scrollHeight - el.clientHeight);
|
|
532
|
+
}
|
|
533
|
+
return most;
|
|
534
|
+
});
|
|
535
|
+
if (hidden <= 1) break;
|
|
536
|
+
size = {
|
|
537
|
+
width: size.width,
|
|
538
|
+
height: Math.min(12e3, size.height + Math.ceil(hidden))
|
|
539
|
+
};
|
|
540
|
+
await page.setViewportSize(size);
|
|
541
|
+
await settle();
|
|
542
|
+
if (size.height >= 12e3) break;
|
|
543
|
+
}
|
|
544
|
+
return size;
|
|
545
|
+
}
|
|
376
546
|
/** File name of one screenshot. */
|
|
377
547
|
const shotName = (stem, width, theme) => `${stem}-${width}-${theme}.png`;
|
|
378
548
|
/**
|
|
@@ -424,6 +594,10 @@ async function shootPage(browser, job, settle) {
|
|
|
424
594
|
}
|
|
425
595
|
});
|
|
426
596
|
await page.waitForTimeout(100);
|
|
597
|
+
await growToScrollContainer(page, viewport, async () => {
|
|
598
|
+
await page.waitForTimeout(100);
|
|
599
|
+
await page.clock.runFor(100);
|
|
600
|
+
});
|
|
427
601
|
await page.waitForTimeout(200);
|
|
428
602
|
const shoot = () => page.screenshot({
|
|
429
603
|
fullPage: true,
|
|
@@ -551,21 +725,31 @@ function summaryMarkdown(results, orphans, baseDir) {
|
|
|
551
725
|
return lines.join("\n");
|
|
552
726
|
}
|
|
553
727
|
// src/cli.ts
|
|
554
|
-
const
|
|
728
|
+
const HELP_CHECK = `ui check <file or URL>... [--shots DIR] [--strict] [--wait MS] [--open SELECTOR]... [--no-interact] [--no-axe]
|
|
555
729
|
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
|
-
|
|
730
|
+
console errors, horizontal overflow at 390 px, touch targets under 48 px at 390 px and targets under 24 px that
|
|
731
|
+
crowd another target at 1280 px (WCAG 2.5.8), touch areas that spill past their control, a card inside a card, raw
|
|
732
|
+
Markdown, native controls the design system replaces, wrapped buttons, tabs, table headers or interface headings
|
|
733
|
+
(headings in Markdown content may wrap), interface text cut off with no tooltip or title, text outside its card,
|
|
734
|
+
controls of different heights in one toolbar row, a status badge with a shadow in a table or card, page CSS outside
|
|
735
|
+
a cascade layer on element selectors (a reset, normalize or starter CSS: button, *, h1) that overrides a component,
|
|
736
|
+
and the axe-core rules of WCAG 2.0, 2.1 and 2.2 A and AA.
|
|
737
|
+
A page without <meta name="viewport"> gets one report at 390 px (缺 viewport meta) and no touch-target check there.
|
|
738
|
+
It also opens what the page hides behind clicks, in light at both widths: each tab of a [role=tablist], each
|
|
739
|
+
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.
|
|
741
|
+
--open SELECTOR clicks the first match and checks the state it opens (a dialog, a drawer); repeat for more.
|
|
742
|
+
--no-interact skips the automatic tabs, categories and toolbar menus (--open still runs).
|
|
743
|
+
--no-axe skips the axe-core pass.
|
|
744
|
+
--shots DIR saves a full-page screenshot of each width and theme in DIR.
|
|
745
|
+
--strict also fails on inline text links under 48 px.
|
|
746
|
+
--wait MS waits this long after load before measuring (default 800).
|
|
747
|
+
Exits 2 when a page cannot be checked at all: it does not load, or the check itself crashes.`;
|
|
748
|
+
const HELP_SHOTS = `ui shots <file or URL>... (--out DIR [--prune] | --compare DIR --diff DIR) [--settle MS] [--threshold N] [--max-diff PERCENT]
|
|
567
749
|
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
|
|
750
|
+
(${FIXED_TIME}, fake timers), reduced motion, animations stopped, caret hidden, fonts loaded, scale 1, full page,
|
|
751
|
+
including what scrolls inside the page's own scroll container (AppShell's main area). <name> is a file's name, or a
|
|
752
|
+
URL's path and hash (http://host/settings#billing → settings-billing).
|
|
569
753
|
--out DIR writes the shots (baselines); a file with the same pixels is left as it is. New files are
|
|
570
754
|
optimised losslessly with oxipng when it is on PATH. --prune also deletes the PNGs in DIR
|
|
571
755
|
that no page of this run produced (a removed or renamed page).
|
|
@@ -576,22 +760,55 @@ ui shots <file or URL>... (--out DIR [--prune] | --compare DIR --diff DIR) [--se
|
|
|
576
760
|
shot, and summary.md.
|
|
577
761
|
--settle MS fake time the page runs before the shot (default 1000).
|
|
578
762
|
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
|
-
|
|
763
|
+
Exits 2 when a page cannot be opened. Uses CHROMIUM_PATH, else Playwright's full Chromium (channel chromium).`;
|
|
764
|
+
const HELP_DOCS = `ui docs [Name] [--full]
|
|
765
|
+
Prints the 用法 block of a component (Button, DataTable…): what it is, a minimal example and the rules most often
|
|
766
|
+
gotten wrong. --full prints the whole README. Guides print whole: guidelines (the core rules every page needs),
|
|
767
|
+
layout, forms, data, monitoring, code, theme, motion. ui docs icons prints every built-in icon name on one line;
|
|
768
|
+
ui docs agents prints the package's AGENTS.md. Without a name, prints the reading order and lists every doc.`;
|
|
769
|
+
const HELP = `${HELP_CHECK}
|
|
770
|
+
${HELP_DOCS}
|
|
771
|
+
${HELP_SHOTS}
|
|
772
|
+
ui list lists every guide (in reading order) and every component by group, with its one-line description`;
|
|
581
773
|
function docsDir() {
|
|
582
774
|
const require = createRequire(import.meta.url);
|
|
583
775
|
return join(dirname(require.resolve("@seanyeh77/ui/package.json")), "docs");
|
|
584
776
|
}
|
|
585
|
-
/**
|
|
777
|
+
/** Each component's group, from docs/components.json (written at build time); empty for an older package. */
|
|
778
|
+
function componentIndex(dir) {
|
|
779
|
+
try {
|
|
780
|
+
return JSON.parse(readFileSync(join(dir, "components.json"), "utf8"));
|
|
781
|
+
} catch {
|
|
782
|
+
return [];
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
/** A guide is any doc that is not a component's README (guidelines, the topic files, icons, agents). */
|
|
786
|
+
function isGuide(dir) {
|
|
787
|
+
const names = new Set(componentIndex(dir).map((c) => c.name));
|
|
788
|
+
return (f) => names.size ? !names.has(f.slice(0, -3)) : /^[a-z]/.test(f);
|
|
789
|
+
}
|
|
790
|
+
/** Guides first, then the components. */
|
|
586
791
|
function docFiles(dir) {
|
|
587
792
|
const files = readdirSync(dir).filter((f) => f.endsWith(".md"));
|
|
588
|
-
const
|
|
793
|
+
const guideFile = isGuide(dir);
|
|
794
|
+
const guide = (f) => guideFile(f) ? 0 : 1;
|
|
589
795
|
return files.sort((a, b) => guide(a) - guide(b) || (a === "guidelines.md" ? -1 : b === "guidelines.md" ? 1 : a.localeCompare(b)));
|
|
590
796
|
}
|
|
797
|
+
function readingOrder() {
|
|
798
|
+
return [
|
|
799
|
+
"Reading order: guidelines first, then a topic guide only when the page has that topic, then the 用法 block of each component you use.",
|
|
800
|
+
...GUIDES.map(([g, what], i) => ` ${String(i + 1).padStart(2)}. ${g.padEnd(12)} ${what}`),
|
|
801
|
+
""
|
|
802
|
+
];
|
|
803
|
+
}
|
|
591
804
|
function docs(name, full) {
|
|
592
805
|
const dir = docsDir();
|
|
593
806
|
const files = docFiles(dir);
|
|
594
|
-
if (!name) return console.log(
|
|
807
|
+
if (!name) return console.log([
|
|
808
|
+
...readingOrder(),
|
|
809
|
+
"Every doc:",
|
|
810
|
+
...files.map((f) => " " + f.slice(0, -3))
|
|
811
|
+
].join("\n"));
|
|
595
812
|
const hit = files.find((f) => f.slice(0, -3).toLowerCase() === name.toLowerCase());
|
|
596
813
|
if (!hit) {
|
|
597
814
|
console.error(`No docs for "${name}". Run "ui docs" for the list.`);
|
|
@@ -600,15 +817,34 @@ function docs(name, full) {
|
|
|
600
817
|
const md = readFileSync(join(dir, hit), "utf8");
|
|
601
818
|
const usage = full ? null : usageBlock(md);
|
|
602
819
|
if (!usage) return console.log(md);
|
|
603
|
-
|
|
820
|
+
const more = md.trim().length > usage.trim().length;
|
|
821
|
+
console.log(more ? usage + `\n(用法 only. The whole README: ui docs ${hit.slice(0, -3)} --full)` : usage);
|
|
604
822
|
}
|
|
605
823
|
function list() {
|
|
606
824
|
const dir = docsDir();
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
825
|
+
const files = docFiles(dir);
|
|
826
|
+
const lines = ["Guides, in reading order:"];
|
|
827
|
+
const guideFile = isGuide(dir);
|
|
828
|
+
const guides = files.filter(guideFile).map((f) => f.slice(0, -3));
|
|
829
|
+
const ordered = [...GUIDES.map(([g]) => g).filter((g) => guides.includes(g)), ...guides.filter((g) => !GUIDES.some(([n]) => n === g))];
|
|
830
|
+
for (const g of ordered) {
|
|
831
|
+
const md = readFileSync(join(dir, `${g}.md`), "utf8");
|
|
832
|
+
lines.push(` ${g.padEnd(18)} ${/^# (.+)$/m.exec(md)?.[1] ?? ""}`);
|
|
833
|
+
}
|
|
834
|
+
const groupOf = new Map(componentIndex(dir).map((c) => [c.name, c.group]));
|
|
835
|
+
const components = files.filter((f) => !guideFile(f)).map((f) => f.slice(0, -3));
|
|
836
|
+
const order = [...Object.keys(GROUPS), "Other"];
|
|
837
|
+
const byGroup = /* @__PURE__ */ new Map();
|
|
838
|
+
for (const c of components) {
|
|
839
|
+
const g = groupOf.get(c) ?? "Other";
|
|
840
|
+
byGroup.set(g, [...byGroup.get(g) ?? [], c]);
|
|
841
|
+
}
|
|
842
|
+
const groups = [...byGroup.keys()].sort((a, b) => (order.indexOf(a) + 1 || 99) - (order.indexOf(b) + 1 || 99));
|
|
843
|
+
for (const g of groups) {
|
|
844
|
+
lines.push("", `${GROUPS[g] ?? (g === "Other" ? "其他" : g)} (${g}):`);
|
|
845
|
+
for (const c of byGroup.get(g) ?? []) lines.push(` ${c.padEnd(18)} ${summary(readFileSync(join(dir, `${c}.md`), "utf8"))}`);
|
|
611
846
|
}
|
|
847
|
+
console.log(lines.join("\n"));
|
|
612
848
|
}
|
|
613
849
|
const toUrl = (t) => t.includes("://") ? new URL(t).href : pathToFileURL(resolve(t)).href;
|
|
614
850
|
/** The page itself could not be opened: a wrong path, no server, or an HTTP error. */
|
|
@@ -700,9 +936,124 @@ async function shots(targets, opts) {
|
|
|
700
936
|
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
937
|
process.exit(unshot ? 2 : 0);
|
|
702
938
|
}
|
|
939
|
+
/** The WCAG levels the axe-core pass checks: 2.0, 2.1 and 2.2, A and AA. */
|
|
940
|
+
const AXE_TAGS = [
|
|
941
|
+
"wcag2a",
|
|
942
|
+
"wcag2aa",
|
|
943
|
+
"wcag21aa",
|
|
944
|
+
"wcag22aa"
|
|
945
|
+
];
|
|
946
|
+
let axeSource;
|
|
947
|
+
const axeScript = () => axeSource ??= readFileSync(createRequire(import.meta.url).resolve("axe-core/axe.min.js"), "utf8");
|
|
948
|
+
/**
|
|
949
|
+
* Runs axe-core in the page and returns one line per rule it reports. contrastOnly: only color-contrast (the dark
|
|
950
|
+
* pass: every other rule gives the same result as in light). preload off: axe would fetch the stylesheets again,
|
|
951
|
+
* which fails on file:// pages and shows up as console errors.
|
|
952
|
+
*/
|
|
953
|
+
async function axeRun(page, contrastOnly = false, skip = []) {
|
|
954
|
+
if (!await page.evaluate(() => "axe" in window)) await page.addScriptTag({ content: axeScript() });
|
|
955
|
+
return (await page.evaluate(async ({ tags, contrastOnly, skip }) => {
|
|
956
|
+
const axe = window.axe;
|
|
957
|
+
const runOnly = contrastOnly ? {
|
|
958
|
+
type: "rule",
|
|
959
|
+
values: ["color-contrast"]
|
|
960
|
+
} : {
|
|
961
|
+
type: "tag",
|
|
962
|
+
values: tags
|
|
963
|
+
};
|
|
964
|
+
const rules = Object.fromEntries(["target-size", ...skip].map((id) => [id, { enabled: false }]));
|
|
965
|
+
const run = async (tries) => {
|
|
966
|
+
try {
|
|
967
|
+
return await axe.run(document, {
|
|
968
|
+
runOnly,
|
|
969
|
+
resultTypes: ["violations"],
|
|
970
|
+
preload: false,
|
|
971
|
+
rules
|
|
972
|
+
});
|
|
973
|
+
} catch (e) {
|
|
974
|
+
if (tries <= 0 || !String(e).includes("already running")) throw e;
|
|
975
|
+
await new Promise((ok) => setTimeout(ok, 200));
|
|
976
|
+
return run(tries - 1);
|
|
977
|
+
}
|
|
978
|
+
};
|
|
979
|
+
return (await run(50)).violations.map((v) => ({
|
|
980
|
+
id: v.id,
|
|
981
|
+
impact: v.impact ?? "",
|
|
982
|
+
help: v.help,
|
|
983
|
+
count: v.nodes.length,
|
|
984
|
+
target: String(v.nodes[0]?.target?.[0] ?? "")
|
|
985
|
+
}));
|
|
986
|
+
}, {
|
|
987
|
+
tags: AXE_TAGS,
|
|
988
|
+
contrastOnly,
|
|
989
|
+
skip
|
|
990
|
+
})).map((v) => `${v.id} (${v.impact}): ${v.help}; ${v.count} element${v.count === 1 ? "" : "s"}, e.g. ${v.target}`);
|
|
991
|
+
}
|
|
992
|
+
/** The problems in one measurement. noViewport: the 390 px pass of a page without a viewport meta (no touch checks). */
|
|
993
|
+
function problemsOf(res, phone, strict) {
|
|
994
|
+
const problems = [];
|
|
995
|
+
const list = (items, n = 12) => `${items.slice(0, n).join("; ")}${items.length > n ? ` (+${items.length - n} more)` : ""}`;
|
|
996
|
+
if (res.nested.length) problems.push("card inside a card (two shadows): " + res.nested.join("; "));
|
|
997
|
+
if (res.markdown.length) problems.push("raw Markdown shown: " + res.markdown.join("; "));
|
|
998
|
+
if (res.native.length) problems.push("native controls: " + [...new Set(res.native)].join("; "));
|
|
999
|
+
if (res.wrapped.length) problems.push("text that must stay on one line wraps: " + res.wrapped.join("; "));
|
|
1000
|
+
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
|
+
if (res.outside.length) problems.push("text outside its card: " + res.outside.join("; ") + ". Leave room inside the card (chart axis labels, long words).");
|
|
1002
|
+
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.");
|
|
1003
|
+
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
|
+
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
|
+
if (phone && res.viewportMeta) {
|
|
1006
|
+
if (res.overflow.length) problems.push("horizontal overflow: " + res.overflow.join("; "));
|
|
1007
|
+
if (res.escaped.length) problems.push("touch area larger than its control (covers other controls): " + res.escaped.join("; "));
|
|
1008
|
+
if (res.small.length) problems.push(`touch targets under 48 px: ${list(res.small)}`);
|
|
1009
|
+
if (res.inline.length && strict) problems.push("inline targets under 48 px: " + list(res.inline));
|
|
1010
|
+
}
|
|
1011
|
+
if (!phone && res.small24.length) problems.push(`targets under 24 px next to another target (WCAG 2.5.8): ${list(res.small24, 8)}`);
|
|
1012
|
+
return problems;
|
|
1013
|
+
}
|
|
1014
|
+
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.";
|
|
1015
|
+
/** Buttons that open a menu or popover in a toolbar or the top bar; their open state is checked by itself. */
|
|
1016
|
+
const TOOLBAR_POPUPS = [
|
|
1017
|
+
".ui-dt-tools",
|
|
1018
|
+
".ui-dt-actions",
|
|
1019
|
+
".ui-card-actions",
|
|
1020
|
+
"[role=toolbar]",
|
|
1021
|
+
".ui-topbar",
|
|
1022
|
+
".ui-actionbar"
|
|
1023
|
+
].map((t) => `${t} [aria-haspopup]:not([aria-haspopup="false"])`).join(", ");
|
|
1024
|
+
const MAX_STATES = 12;
|
|
1025
|
+
/** Marks the elements to click for the automatic states (data-ui-check-state) and names them. Runs inside the page. */
|
|
1026
|
+
function findStates({ popups, max }) {
|
|
1027
|
+
const out = [];
|
|
1028
|
+
const shown = (el) => {
|
|
1029
|
+
const r = el.getBoundingClientRect();
|
|
1030
|
+
const cs = getComputedStyle(el);
|
|
1031
|
+
return r.width > 0 && r.height > 0 && cs.visibility !== "hidden" && !el.closest("[inert], [aria-hidden=\"true\"]");
|
|
1032
|
+
};
|
|
1033
|
+
const name = (el) => {
|
|
1034
|
+
const by = el.getAttribute("aria-labelledby");
|
|
1035
|
+
const labelled = by ? by.split(/\s+/).map((id) => document.getElementById(id)?.textContent ?? "").join(" ") : "";
|
|
1036
|
+
const label = el.labels?.[0]?.textContent ?? "";
|
|
1037
|
+
return (el.getAttribute("aria-label") || labelled || label || el.textContent || el.getAttribute("placeholder") || el.tagName.toLowerCase()).trim().replace(/\s+/g, " ").slice(0, 24);
|
|
1038
|
+
};
|
|
1039
|
+
const add = (el, label, kind) => {
|
|
1040
|
+
if (out.length >= max || !shown(el) || el.matches(":disabled, [aria-disabled=\"true\"]")) return;
|
|
1041
|
+
const id = String(out.length);
|
|
1042
|
+
el.setAttribute("data-ui-check-state", id);
|
|
1043
|
+
out.push({
|
|
1044
|
+
id,
|
|
1045
|
+
label,
|
|
1046
|
+
kind
|
|
1047
|
+
});
|
|
1048
|
+
};
|
|
1049
|
+
for (const el of document.querySelectorAll(popups)) add(el, `the menu of "${name(el)}"`, "popup");
|
|
1050
|
+
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");
|
|
1051
|
+
for (const cat of document.querySelectorAll(".ui-settings-cat")) if (cat.getAttribute("aria-current") !== "page") add(cat, `category "${name(cat)}"`, "view");
|
|
1052
|
+
return out;
|
|
1053
|
+
}
|
|
703
1054
|
async function check(targets, opts) {
|
|
704
1055
|
const { chromium } = await import("playwright");
|
|
705
|
-
const browser = await chromium.launch(
|
|
1056
|
+
const browser = await chromium.launch(shotLaunchOptions()).catch((e) => {
|
|
706
1057
|
console.error(String(e).split("\n")[0]);
|
|
707
1058
|
console.error("No Chromium for ui check. Run `npx playwright install chromium`, or set CHROMIUM_PATH to an installed Chrome or Chromium.");
|
|
708
1059
|
process.exit(2);
|
|
@@ -711,13 +1062,15 @@ async function check(targets, opts) {
|
|
|
711
1062
|
const checkOne = async ({ url, stem }) => {
|
|
712
1063
|
const out = [url];
|
|
713
1064
|
let bad = false;
|
|
1065
|
+
let viewportReported = false;
|
|
714
1066
|
for (const width of [390, 1280]) for (const theme of ["light", "dark"]) {
|
|
715
1067
|
const phone = width === 390;
|
|
1068
|
+
const viewport = {
|
|
1069
|
+
width,
|
|
1070
|
+
height: phone ? 844 : 900
|
|
1071
|
+
};
|
|
716
1072
|
const ctx = await browser.newContext({
|
|
717
|
-
viewport
|
|
718
|
-
width,
|
|
719
|
-
height: phone ? 844 : 900
|
|
720
|
-
},
|
|
1073
|
+
viewport,
|
|
721
1074
|
colorScheme: theme,
|
|
722
1075
|
hasTouch: phone,
|
|
723
1076
|
isMobile: phone,
|
|
@@ -752,27 +1105,90 @@ async function check(targets, opts) {
|
|
|
752
1105
|
if (page.url() !== url && width === 390 && theme === "light") out.push(` (redirected to ${page.url()})`);
|
|
753
1106
|
const problems = [];
|
|
754
1107
|
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("; "));
|
|
1108
|
+
if (phone && !res.viewportMeta && !viewportReported) {
|
|
1109
|
+
problems.push(NO_VIEWPORT);
|
|
1110
|
+
viewportReported = true;
|
|
767
1111
|
}
|
|
1112
|
+
problems.push(...problemsOf(res, phone, opts.strict));
|
|
1113
|
+
const axe = opts.axe ? await run(() => axeRun(page, theme === "dark")).catch((e) => [`axe-core could not run: ${String(e).split("\n")[0]}`]) : [];
|
|
1114
|
+
if (axe.length) problems.push("accessibility (axe-core): " + axe.join(" | "));
|
|
768
1115
|
out.push(` ${width} px ${theme}: ${problems.length ? "" : "ok"}`);
|
|
769
1116
|
for (const p of problems) out.push(" - " + p);
|
|
770
|
-
if (phone && theme === "light" && res.inline.length && !opts.strict) out.push(` (inline text targets, exempt: ${res.inline.length})`);
|
|
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})`);
|
|
771
1118
|
bad ||= problems.length > 0;
|
|
772
|
-
if (opts.shots)
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
1119
|
+
if (opts.shots) {
|
|
1120
|
+
await growToScrollContainer(page, viewport, () => page.waitForTimeout(150));
|
|
1121
|
+
await page.screenshot({
|
|
1122
|
+
path: join(opts.shots, `${stem}-${width}-${theme}.png`),
|
|
1123
|
+
fullPage: true
|
|
1124
|
+
});
|
|
1125
|
+
await page.setViewportSize(viewport);
|
|
1126
|
+
}
|
|
1127
|
+
if (theme === "light" && (opts.open.length || opts.interact)) {
|
|
1128
|
+
const itemKey = (item) => item.split(", next to ")[0].replace(/ \d+ x \d+ px$/, "");
|
|
1129
|
+
const axeKey = (line) => line.split(" ")[0];
|
|
1130
|
+
const knownAxe = new Set(axe.map(axeKey));
|
|
1131
|
+
const newOnly = (now) => {
|
|
1132
|
+
const out = { ...now };
|
|
1133
|
+
for (const k of Object.keys(now)) {
|
|
1134
|
+
const was = res[k];
|
|
1135
|
+
const is = now[k];
|
|
1136
|
+
if (Array.isArray(was) && Array.isArray(is)) {
|
|
1137
|
+
const seen = new Set(was.map(itemKey));
|
|
1138
|
+
out[k] = is.filter((x) => !seen.has(itemKey(x)));
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
return out;
|
|
1142
|
+
};
|
|
1143
|
+
const checkState = async (label, target, trigger) => {
|
|
1144
|
+
const before = errors.length;
|
|
1145
|
+
try {
|
|
1146
|
+
await target.click({ timeout: 3e3 });
|
|
1147
|
+
} catch (e) {
|
|
1148
|
+
return `could not click ${label}: ${String(e).split("\n")[0]}`;
|
|
1149
|
+
}
|
|
1150
|
+
await page.waitForTimeout(350);
|
|
1151
|
+
const after = await run(() => page.evaluate(measure));
|
|
1152
|
+
const found = problemsOf(newOnly(after), phone, opts.strict);
|
|
1153
|
+
if (errors.length > before) found.unshift("console errors: " + errors.slice(before, before + 5).join(" | "));
|
|
1154
|
+
if (opts.axe) {
|
|
1155
|
+
const skip = trigger ? ["aria-hidden-focus"] : [];
|
|
1156
|
+
const more = (await run(() => axeRun(page, false, skip)).catch(() => [])).filter((v) => !knownAxe.has(axeKey(v)));
|
|
1157
|
+
if (more.length) found.push("accessibility (axe-core): " + more.join(" | "));
|
|
1158
|
+
}
|
|
1159
|
+
if (trigger) {
|
|
1160
|
+
await page.keyboard.press("Escape");
|
|
1161
|
+
await page.waitForTimeout(150);
|
|
1162
|
+
if (await target.getAttribute("aria-expanded").catch(() => null) === "true") {
|
|
1163
|
+
await target.click({ timeout: 3e3 }).catch(() => void 0);
|
|
1164
|
+
await page.waitForTimeout(150);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
return found.length ? `after opening ${label}: ${found.join(" / ")}` : "";
|
|
1168
|
+
};
|
|
1169
|
+
const stateProblems = [];
|
|
1170
|
+
for (const sel of opts.open) {
|
|
1171
|
+
const target = page.locator(sel).first();
|
|
1172
|
+
if (!await target.count()) {
|
|
1173
|
+
stateProblems.push(`--open ${sel}: nothing on the page matches`);
|
|
1174
|
+
continue;
|
|
1175
|
+
}
|
|
1176
|
+
const r = await checkState(`--open ${sel}`, target, true);
|
|
1177
|
+
if (r) stateProblems.push(r);
|
|
1178
|
+
}
|
|
1179
|
+
if (opts.interact) {
|
|
1180
|
+
const states = await run(() => page.evaluate(findStates, {
|
|
1181
|
+
popups: TOOLBAR_POPUPS,
|
|
1182
|
+
max: MAX_STATES
|
|
1183
|
+
}));
|
|
1184
|
+
for (const st of states) {
|
|
1185
|
+
const r = await checkState(st.label, page.locator(`[data-ui-check-state="${st.id}"]`), st.kind === "popup");
|
|
1186
|
+
if (r && !r.startsWith("could not click")) stateProblems.push(r);
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
for (const p of stateProblems) out.push(` - ${p}`);
|
|
1190
|
+
bad ||= stateProblems.length > 0;
|
|
1191
|
+
}
|
|
776
1192
|
} finally {
|
|
777
1193
|
await ctx.close();
|
|
778
1194
|
}
|
|
@@ -809,25 +1225,51 @@ async function check(targets, opts) {
|
|
|
809
1225
|
await browser.close();
|
|
810
1226
|
process.exit(unchecked ? 2 : failed ? 1 : 0);
|
|
811
1227
|
}
|
|
1228
|
+
/** Parses the options of one command; --help prints that command's help, an unknown option its help and exit 2. */
|
|
1229
|
+
function parse(args, options, help) {
|
|
1230
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
1231
|
+
console.log(help);
|
|
1232
|
+
process.exit(0);
|
|
1233
|
+
}
|
|
1234
|
+
try {
|
|
1235
|
+
return parseArgs({
|
|
1236
|
+
args,
|
|
1237
|
+
allowPositionals: true,
|
|
1238
|
+
options
|
|
1239
|
+
});
|
|
1240
|
+
} catch (e) {
|
|
1241
|
+
console.error(`${e.message}\n\n${help}`);
|
|
1242
|
+
process.exit(2);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
812
1245
|
const [cmd, ...rest] = process.argv.slice(2);
|
|
813
1246
|
if (cmd === "check") {
|
|
814
|
-
const { values, positionals } =
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
1247
|
+
const { values, positionals } = parse(rest, {
|
|
1248
|
+
shots: { type: "string" },
|
|
1249
|
+
strict: {
|
|
1250
|
+
type: "boolean",
|
|
1251
|
+
default: false
|
|
1252
|
+
},
|
|
1253
|
+
wait: {
|
|
1254
|
+
type: "string",
|
|
1255
|
+
default: "800"
|
|
1256
|
+
},
|
|
1257
|
+
open: {
|
|
1258
|
+
type: "string",
|
|
1259
|
+
multiple: true,
|
|
1260
|
+
default: []
|
|
1261
|
+
},
|
|
1262
|
+
"no-interact": {
|
|
1263
|
+
type: "boolean",
|
|
1264
|
+
default: false
|
|
1265
|
+
},
|
|
1266
|
+
"no-axe": {
|
|
1267
|
+
type: "boolean",
|
|
1268
|
+
default: false
|
|
827
1269
|
}
|
|
828
|
-
});
|
|
1270
|
+
}, HELP_CHECK);
|
|
829
1271
|
if (!positionals.length) {
|
|
830
|
-
console.error(
|
|
1272
|
+
console.error(HELP_CHECK);
|
|
831
1273
|
process.exit(2);
|
|
832
1274
|
}
|
|
833
1275
|
for (const t of positionals) if (!t.includes("://") && !existsSync(t)) {
|
|
@@ -845,39 +1287,38 @@ if (cmd === "check") {
|
|
|
845
1287
|
await check(positionals, {
|
|
846
1288
|
shots: values.shots,
|
|
847
1289
|
strict: !!values.strict,
|
|
848
|
-
wait
|
|
1290
|
+
wait,
|
|
1291
|
+
open: values.open ?? [],
|
|
1292
|
+
interact: !values["no-interact"],
|
|
1293
|
+
axe: !values["no-axe"]
|
|
849
1294
|
});
|
|
850
1295
|
} 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
|
-
}
|
|
1296
|
+
const { values, positionals } = parse(rest, {
|
|
1297
|
+
out: { type: "string" },
|
|
1298
|
+
compare: { type: "string" },
|
|
1299
|
+
diff: { type: "string" },
|
|
1300
|
+
prune: {
|
|
1301
|
+
type: "boolean",
|
|
1302
|
+
default: false
|
|
1303
|
+
},
|
|
1304
|
+
settle: {
|
|
1305
|
+
type: "string",
|
|
1306
|
+
default: "1000"
|
|
1307
|
+
},
|
|
1308
|
+
threshold: {
|
|
1309
|
+
type: "string",
|
|
1310
|
+
default: String(DEFAULT_TOLERANCE.threshold)
|
|
1311
|
+
},
|
|
1312
|
+
"max-diff": {
|
|
1313
|
+
type: "string",
|
|
1314
|
+
default: String(DEFAULT_TOLERANCE.maxDiffPercent)
|
|
874
1315
|
}
|
|
875
|
-
});
|
|
1316
|
+
}, HELP_SHOTS);
|
|
876
1317
|
const fail = (msg) => {
|
|
877
1318
|
console.error(msg);
|
|
878
1319
|
process.exit(2);
|
|
879
1320
|
};
|
|
880
|
-
if (!positionals.length || !values.out && !values.compare) fail(
|
|
1321
|
+
if (!positionals.length || !values.out && !values.compare) fail(HELP_SHOTS);
|
|
881
1322
|
if (values.out && values.compare) fail("Give --out DIR (write baselines) or --compare DIR (check against them), not both.");
|
|
882
1323
|
if (values.prune && !values.out) fail("--prune goes with --out: it deletes the baselines in that folder that no page produced.");
|
|
883
1324
|
if (values.compare && !values.diff) fail("--compare needs --diff DIR: where the diff images and new shots go.");
|
|
@@ -901,18 +1342,15 @@ if (cmd === "check") {
|
|
|
901
1342
|
}
|
|
902
1343
|
});
|
|
903
1344
|
} else if (cmd === "docs") {
|
|
904
|
-
const { values, positionals } =
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
type: "boolean",
|
|
909
|
-
default: false
|
|
910
|
-
} }
|
|
911
|
-
});
|
|
1345
|
+
const { values, positionals } = parse(rest, { full: {
|
|
1346
|
+
type: "boolean",
|
|
1347
|
+
default: false
|
|
1348
|
+
} }, HELP_DOCS);
|
|
912
1349
|
docs(positionals[0], !!values.full);
|
|
913
1350
|
} else if (cmd === "list") list();
|
|
1351
|
+
else if (cmd === "--help" || cmd === "-h" || cmd === "help" || !cmd) console.log(HELP);
|
|
914
1352
|
else {
|
|
915
|
-
console.
|
|
916
|
-
process.exit(
|
|
1353
|
+
console.error(`Unknown command "${cmd}".\n\n${HELP}`);
|
|
1354
|
+
process.exit(2);
|
|
917
1355
|
}
|
|
918
1356
|
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seanyeh77/ui-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.45.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.45.0"
|
|
24
25
|
},
|
|
25
26
|
"engines": {
|
|
26
27
|
"node": ">=22"
|