@seanyeh77/ui-cli 0.46.0 → 0.47.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ npm i -D @seanyeh77/ui-cli
7
7
  npx playwright install chromium # ui check 與 ui shots 用的瀏覽器;或設定 CHROMIUM_PATH
8
8
  ```
9
9
 
10
- - `ui check <檔案或 URL>`:在 390 px 與 1280 px、淺色與深色打開頁面,檢查 console 錯誤、水平溢出、小於 48 px 的觸控目標、1280 px 時小於 24 px 又擠著別的目標的目標(WCAG 2.5.8)、卡片裡的卡片、原生控制項、被截斷又沒有 Tooltip 或 title 的介面文字、跑出卡片外的文字、同一列工具列或表單欄位不同高、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」,不檢查觸控目標。
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」,不檢查觸控目標。 file:// 頁面的字型被 CORS 擋下時不算 console 錯誤,每頁最後寫一行 note,提醒用 http 開頁面。
11
11
  - 它也會點開每個分頁(`[role=tablist]`)、SettingsLayout 的每個分類,以及工具列與頂欄裡 `[aria-haspopup]` 按鈕的選單,檢查打開後的畫面(淺色、兩種寬度,每頁最多 12 個狀態),只回報原本沒有的問題。
12
12
  - 每個寬度與主題那一行的結果算進頁面和打開的狀態;各狀態的問題列在「after opening …」底下。
13
13
  - `--open <selector>` 點開頁面上第一個符合的元素(對話框、側欄)並檢查,可以重複;`--no-interact` 不自動點分頁、分類和選單;`--no-axe` 不跑 axe-core。`--shots <資料夾>` 存每個寬度與主題的整頁截圖,也存每個打開的狀態。
package/dist/cli.js CHANGED
@@ -177,7 +177,7 @@ function measure() {
177
177
  if (!parent || parent.closest("pre, code, script, style, textarea, .ui-cv") || !visible(parent)) continue;
178
178
  if (/`[^`]+`|\*\*[^*]+\*\*|^\s*#{1,6}\s/.test(t)) out.markdown.push(`${describe(parent)}: ${t.trim().slice(0, 40)}`);
179
179
  }
180
- for (const [q, use] of Object.entries({
180
+ const replacements = {
181
181
  select: "Select",
182
182
  table: "DataTable",
183
183
  dialog: "Dialog",
@@ -188,7 +188,13 @@ function measure() {
188
188
  "input[type=search]": "SearchField",
189
189
  "input[type=file]": "FileUpload",
190
190
  "input[type=color]": "AccentPicker"
191
- })) for (const el of document.querySelectorAll(q)) if (visible(el) && !el.matches("[class^=\"ui-\"], [class*=\" ui-\"]")) out.native.push(`<${q}> → use ${use}`);
191
+ };
192
+ const UI_CLASS = "[class^=\"ui-\"], [class*=\" ui-\"]";
193
+ replacements.button = "Button or IconButton";
194
+ replacements["a[href]"] = "Link";
195
+ replacements["input:is(:not([type]), [type=text], [type=email], [type=password], [type=number], [type=tel], [type=url])"] = "TextField";
196
+ replacements.textarea = "TextArea";
197
+ for (const [q, use] of Object.entries(replacements)) for (const el of document.querySelectorAll(q)) if (visible(el) && !el.matches(UI_CLASS) && !el.closest(".ui-md")) out.native.push(`${describe(el)} → use ${use}`);
192
198
  for (const el of document.querySelectorAll(".ui-btn, .ui-tab, [role=columnheader], .ui-field-label, h1, h2, h3, h4")) {
193
199
  if (out.wrapped.length >= 8 || !visible(el) || el.matches(".ui-md-h")) continue;
194
200
  if ([...el.querySelectorAll("*"), el].some((node) => [...node.childNodes].some((t) => {
@@ -241,7 +247,7 @@ function measure() {
241
247
  }
242
248
  }
243
249
  const bars = ".ui-dt-tools, .ui-dt-actions, .ui-card-actions, [role=toolbar]";
244
- const boxes = ".ui-searchfield, .ui-pwfield, .ui-datefield, .ui-ms, .ui-select, [role=tablist]";
250
+ const boxes = ".ui-searchfield, .ui-pwfield, .ui-datefield, .ui-field-box, .ui-ms, .ui-select, [role=tablist]";
245
251
  const controls = "button, a[href], input:not([type=hidden]), [role=button], [role=combobox], " + boxes;
246
252
  for (const bar of document.querySelectorAll(bars)) {
247
253
  if (out.mixed.length >= 6) break;
@@ -585,14 +591,20 @@ function addReport(t, dir, r, cwd) {
585
591
  const lines = [`${t.title} (${t.name}) → ${rel(dir)}/`];
586
592
  for (const p of r.written) lines.push(` wrote ${rel(p)}`);
587
593
  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`);
594
+ let listed = {};
595
+ try {
596
+ const pkg = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
597
+ listed = {
598
+ ...pkg.devDependencies,
599
+ ...pkg.dependencies
600
+ };
601
+ } catch {}
602
+ const deps = [.../* @__PURE__ */ new Set([
603
+ ...t.dependencies,
604
+ "react",
605
+ "react-dom"
606
+ ])].filter((d) => !listed[d]);
607
+ if (deps.length) lines.push(`Missing packages: npm i ${deps.join(" ")}`);
596
608
  const sample = t.files.find((f) => /(^|\/)sample\.ts$/.test(f.target));
597
609
  lines.push(`Use: render <${main} … /> from ${rel(join(dir, basename(t.files[0]?.target ?? "")))} with your data (its props are typed there${sample ? `; ${basename(sample.target)} has example data in their shape` : ""}).`);
598
610
  return lines;
@@ -737,6 +749,15 @@ async function waitForAnimations(page, cap = 1500) {
737
749
  }, cap);
738
750
  }
739
751
  /** File name of one screenshot. */
752
+ /**
753
+ * A font a file:// page loads from a server, blocked by CORS (the page's origin is null): Chromium logs the CORS
754
+ * error and a failed load of the font file. Not a problem of the page itself; ui check reports it once as a note.
755
+ */
756
+ function isFileFontCors(pageUrl, text, src) {
757
+ if (!pageUrl.startsWith("file:")) return false;
758
+ if (/^Access to font at .* has been blocked by CORS policy/.test(text)) return true;
759
+ return /^Failed to load resource/.test(text) && /\.(?:woff2?|ttf|otf)(?:[?#]|$)/i.test(src);
760
+ }
740
761
  const shotName = (stem, width, theme) => `${stem}-${width}-${theme}.png`;
741
762
  /**
742
763
  * Takes the 4 screenshots of one page (2 widths x 2 themes), each in a fresh context, and returns them by file name.
@@ -944,7 +965,7 @@ const HELP_CHECK = `ui check <file or URL>... [--shots DIR] [--strict] [--wait M
944
965
  --no-interact skips the automatic tabs, categories and toolbar menus (--open still runs).
945
966
  --no-axe skips the axe-core pass.
946
967
  --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).
968
+ in ui shots), and one of each opened state (<name>-<width>-light-<state>.png; an open dialog, drawer or menu at the viewport size).
948
969
  --strict also fails on inline text links under 48 px.
949
970
  --wait MS waits this long after load before measuring (default 800).
950
971
  Exits 2 when a page cannot be checked at all: it does not load, or the check itself crashes.`;
@@ -1276,6 +1297,7 @@ async function check(targets, opts) {
1276
1297
  const out = [url];
1277
1298
  let bad = false;
1278
1299
  let viewportReported = false;
1300
+ let fontCors = false;
1279
1301
  for (const width of [390, 1280]) for (const theme of ["light", "dark"]) {
1280
1302
  const phone = width === 390;
1281
1303
  const viewport = {
@@ -1297,6 +1319,7 @@ async function check(targets, opts) {
1297
1319
  if (m.type() !== "error") return;
1298
1320
  const src = m.location().url;
1299
1321
  if (/\/favicon\.ico$/.test(src)) return;
1322
+ if (isFileFontCors(url, m.text(), src)) return void (fontCors = true);
1300
1323
  errors.push(src && src !== url ? `${m.text()} (${src})` : m.text());
1301
1324
  });
1302
1325
  const resp = await page.goto(url, { waitUntil: "load" }).catch((e) => {
@@ -1326,11 +1349,13 @@ async function check(targets, opts) {
1326
1349
  problems.push(...problemsOf(res, phone, opts.strict));
1327
1350
  const axe = opts.axe ? await run(() => axeRun(page, theme === "dark")).catch((e) => [`axe-core could not run: ${String(e).split("\n")[0]}`]) : [];
1328
1351
  if (axe.length) problems.push("accessibility (axe-core): " + axe.join(" | "));
1329
- const shoot = async (suffix) => {
1352
+ const shoot = async (suffix, overlay = false) => {
1330
1353
  if (!opts.shots) return;
1354
+ const path = join(opts.shots, `${shotName(stem, width, theme).slice(0, -4)}${suffix}.png`);
1355
+ if (overlay) return void await page.screenshot({ path });
1331
1356
  await growToScrollContainer(page, viewport, () => page.waitForTimeout(150));
1332
1357
  await page.screenshot({
1333
- path: join(opts.shots, `${shotName(stem, width, theme).slice(0, -4)}${suffix}.png`),
1358
+ path,
1334
1359
  fullPage: true
1335
1360
  });
1336
1361
  await page.setViewportSize(viewport);
@@ -1370,7 +1395,7 @@ async function check(targets, opts) {
1370
1395
  const more = (await run(() => axeRun(page, false, skip)).catch(() => [])).filter((v) => !knownAxe.has(axeKey(v)));
1371
1396
  if (more.length) found.push("accessibility (axe-core): " + more.join(" | "));
1372
1397
  }
1373
- await shoot(`-${cleanName(label)}`);
1398
+ await shoot(`-${cleanName(label)}`, trigger);
1374
1399
  if (trigger) {
1375
1400
  await page.keyboard.press("Escape");
1376
1401
  await page.waitForTimeout(150);
@@ -1429,6 +1454,7 @@ async function check(targets, opts) {
1429
1454
  await ctx.close();
1430
1455
  }
1431
1456
  }
1457
+ if (fontCors) out.push(" note: fonts were blocked by CORS because the page is a file:// URL; serve the page over http to load fonts");
1432
1458
  return {
1433
1459
  out,
1434
1460
  bad
@@ -9,11 +9,11 @@
9
9
  "files": [
10
10
  {
11
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"
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
13
  },
14
14
  {
15
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"
16
+ "content": "import type { DashboardProps, ProjectRow } from './Dashboard';\n\nconst NAMES = ['網站改版', '叢集監控', '課程平台', '帳務整合', '資料備份', '權限管理', '告警通知', '成本報表'];\nconst OWNERS = ['王小明', '李小華', '陳大同', '林美玲'];\nconst STATUS: ProjectRow['status'][] = ['doing', 'review', 'done', 'fail', 'draft'];\n// Relative to today, so the figures cover the dashboard's default period (the last 30 days, today included).\nconst now = new Date();\nconst DAYS = Array.from({ length: 30 }, (_, i) => new Date(now.getFullYear(), now.getMonth(), now.getDate() - 29 + i));\nconst DONE = [3, 2, 4, 3, 5, 1, 2, 4, 3, 4, 6, 2, 1, 3, 5, 4, 3, 5, 2, 2, 4, 6, 5, 3, 4, 5, 3, 2, 4, 6];\n\nexport const sample: DashboardProps = {\n kpis: [\n { label: '營收', value: 12840000, format: 'money', delta: 8.2, spark: [8, 9, 9.5, 10, 11, 12.8] },\n { label: '預算使用率', value: 74.5, format: 'percent', unit: '%', delta: 3.1, deltaUnit: 'pt', direction: 'down', spark: [58, 61, 63, 66, 71.4, 74.5] },\n { label: '準時完成率', value: 92.4, format: 'percent', unit: '%', delta: 1.8, deltaUnit: 'pt', spark: [88, 89.5, 90.1, 89.8, 90.6, 92.4] },\n { label: '平均回應時間', value: 184, unit: 'ms', delta: -12.5, direction: 'down', spark: [230, 221, 214, 206, 210, 184] },\n ],\n trend: { labels: DAYS.map((d) => `${d.getMonth() + 1}/${d.getDate()}`), series: [{ name: '完成', values: DONE }] },\n rows: NAMES.map((name, i) => ({\n id: String(i + 1),\n name,\n owner: OWNERS[i % OWNERS.length],\n status: STATUS[i % STATUS.length],\n progress: [64, 88, 100, 40, 12, 72, 55, 100][i],\n budget: (i + 2) * 85000,\n updated: new Date(now.getTime() - (i + 1) * 5 * 3600 * 1000),\n })),\n notifications: [\n { id: 1, title: '叢集監控 部署失敗', body: 'node-3 超過 5 分鐘沒有回應', time: '10 分鐘前', group: '今天' },\n { id: 2, title: '李小華 提到了你', body: '「預算表請幫忙看一下」', time: '1 小時前', group: '今天', read: true },\n ],\n};\n"
17
17
  }
18
18
  ]
19
19
  },
@@ -27,7 +27,7 @@
27
27
  "files": [
28
28
  {
29
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"
30
+ "content": "import * as React from 'react';\nimport {\n AppShell,\n Badge,\n Button,\n Card,\n DataTable,\n Drawer,\n FormGrid,\n IconButton,\n Page,\n Select,\n TextArea,\n TextField,\n toast,\n type DataTableColumn,\n useFormErrors,\n type NavSection,\n} from '@seanyeh77/ui';\n\n/* A list page: the title once (top bar), the list in one Card, the page's one primary action (新增) at the end of the\n summary row (DataTable's action), the count in the table's toolbar. Hover a row (or tab to it) and click its pencil to\n edit it in a drawer; closing with unsaved changes asks first. Replace Item and the fields with yours. */\n\nexport interface Item {\n id: string;\n name: string;\n owner: string;\n status: 'draft' | 'doing' | 'review' | 'done' | 'fail';\n note: string;\n /** Last change; shown as relative time within a week. */\n updated: Date;\n}\n\nexport interface ListDetailProps {\n items: Item[];\n owners: string[];\n /** A new item has id ''; give it an id when you store it. */\n onSave: (item: Item) => void;\n}\n\nconst NAV: NavSection[] = [\n {\n items: [\n { id: 'items', label: '項目', icon: 'list-bullets' },\n { id: 'settings', label: '設定', icon: 'gear' },\n ],\n },\n];\nconst STATUS_OPTIONS: { value: Item['status']; label: string }[] = [\n { value: 'draft', label: '草稿' },\n { value: 'doing', label: '進行中' },\n { value: 'review', label: '審核中' },\n { value: 'done', label: '完成' },\n { value: 'fail', label: '失敗' },\n];\n\n// The summary: 「全部」, then the state that needs attention, then the rest.\nconst statusLabel = (s: Item['status']) => STATUS_OPTIONS.find((o) => o.value === s)?.label ?? s;\nconst SUMMARY = (['fail', 'review', 'doing', 'done', 'draft'] as const).map((v) => ({ value: v, label: statusLabel(v) }));\n// Outside the component: one array for every render, so the table does not sort and filter again on each one.\nconst COLUMNS: DataTableColumn<Item>[] = [\n { key: 'name', label: '名稱' },\n { key: 'owner', label: '負責人' },\n { key: 'status', label: '狀態', render: (r) => <Badge status={r.status} />, searchText: (r) => statusLabel(r.status), mobile: 'status' },\n { key: 'note', label: '備註', long: true },\n { key: 'updated', label: '更新', format: 'relative' },\n];\n\nexport function ListDetail({ items, owners, onSave }: ListDetailProps) {\n const [editing, setEditing] = React.useState<Item | null>(null);\n const [draft, setDraft] = React.useState<Item | null>(null);\n // Errors show once a field is left (blur) or on 儲存, not on every key; 儲存 with an error moves focus to the field.\n const form = useFormErrors({ name: draft?.name ?? '' }, (v) => ({\n name: v.name.trim() ? undefined : '名稱不能空白,請輸入專案名稱。',\n }));\n const dirty = !!editing && JSON.stringify(editing) !== JSON.stringify(draft);\n const open = (it: Item) => {\n setEditing(it);\n setDraft(it);\n };\n const close = () => {\n setEditing(null);\n setDraft(null);\n form.reset();\n };\n const create = () => open({ id: '', name: '', owner: owners[0] ?? '', status: 'draft', note: '', updated: new Date() });\n const set = <K extends keyof Item>(k: K, v: Item[K]) => setDraft((d) => (d ? { ...d, [k]: v } : d));\n return (\n <AppShell nav={NAV} value=\"items\" onNavigate={() => {}} brand=\"專案中心\" title=\"項目\">\n <Page>\n <Card padding={false}>\n <DataTable\n label=\"項目\"\n columns={COLUMNS}\n rows={items}\n summary={{ key: 'status', items: SUMMARY }}\n action={\n <Button variant=\"primary\" icon=\"plus\" onClick={create}>\n 新增\n </Button>\n }\n rowActions={(r) => <IconButton variant=\"quiet\" icon=\"pencil-simple\" label={`編輯 ${r.name}`} onClick={() => open(r)} />}\n urlKey=\"items\"\n />\n </Card>\n </Page>\n <Drawer\n open={!!editing}\n onOpenChange={(o) => !o && close()}\n dirty={dirty}\n title={!editing ? '' : editing.id ? `編輯 ${editing.name}` : '新增項目'}\n actions={(requestClose) => (\n <>\n <Button onClick={requestClose}>取消</Button>\n <Button\n variant=\"primary\"\n // Not disabled for an error: 儲存 says what is wrong and goes to the field.\n disabled={!dirty}\n onClick={form.submit(() => {\n if (!draft) return;\n onSave({ ...draft, updated: new Date() });\n close();\n toast(draft.id ? '已儲存' : '已新增');\n })}\n >\n 儲存\n </Button>\n </>\n )}\n >\n {draft ? (\n <FormGrid>\n <TextField\n label=\"名稱\"\n name=\"name\"\n required\n value={draft.name}\n onChange={(v) => set('name', v)}\n onBlur={() => form.onBlur('name')}\n error={form.errors.name}\n />\n <Select label=\"負責人\" value={draft.owner} options={owners.map((o) => ({ value: o, label: o }))} onChange={(v) => set('owner', v)} />\n <Select label=\"狀態\" value={draft.status} options={STATUS_OPTIONS} onChange={(v) => set('status', v)} />\n <TextArea label=\"備註\" value={draft.note} onChange={(v) => set('note', v)} />\n </FormGrid>\n ) : null}\n </Drawer>\n </AppShell>\n );\n}\n"
31
31
  },
32
32
  {
33
33
  "target": "components/blocks/list-detail/sample.ts",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seanyeh77/ui-cli",
3
- "version": "0.46.0",
3
+ "version": "0.47.1",
4
4
  "description": "Checks a page against SeanYeh's design system, compares its screenshots with baselines and prints component docs: ui check, ui shots, ui docs, ui list.",
5
5
  "license": "MIT",
6
6
  "author": "Hsiu-An Yeh",
@@ -21,7 +21,7 @@
21
21
  "pixelmatch": "^8.0.0",
22
22
  "playwright": "1.65.0",
23
23
  "pngjs": "^7.0.0",
24
- "@seanyeh77/ui": "^0.46.0"
24
+ "@seanyeh77/ui": "^0.47.1"
25
25
  },
26
26
  "engines": {
27
27
  "node": ">=22"