@zhin.js/console-ui 0.0.0-stage → 1.1.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.
Files changed (129) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +21 -0
  3. package/README.md +195 -2
  4. package/audit/index.mjs +21 -0
  5. package/audit/layout-audit.mjs +492 -0
  6. package/audit/mount-page.jsx +90 -0
  7. package/audit/plugin-pages.mjs +186 -0
  8. package/dist/cn.d.ts +4 -0
  9. package/dist/cn.js +6 -0
  10. package/dist/components/BrandMark.d.ts +16 -0
  11. package/dist/components/BrandMark.js +21 -0
  12. package/dist/components/InfoHint.d.ts +12 -0
  13. package/dist/components/InfoHint.js +13 -0
  14. package/dist/components/PageHeader.d.ts +18 -0
  15. package/dist/components/PageHeader.js +11 -0
  16. package/dist/components/PageShell.d.ts +26 -0
  17. package/dist/components/PageShell.js +10 -0
  18. package/dist/components/RefreshControl.d.ts +28 -0
  19. package/dist/components/RefreshControl.js +68 -0
  20. package/dist/components/StatCard.d.ts +41 -0
  21. package/dist/components/StatCard.js +53 -0
  22. package/dist/components/StatusBadge.d.ts +14 -0
  23. package/dist/components/StatusBadge.js +19 -0
  24. package/dist/components/actions.d.ts +53 -0
  25. package/dist/components/actions.js +50 -0
  26. package/dist/components/code.d.ts +11 -0
  27. package/dist/components/code.js +10 -0
  28. package/dist/components/confirm-dialog-model.d.ts +9 -0
  29. package/dist/components/confirm-dialog-model.js +20 -0
  30. package/dist/components/confirm-dialog.d.ts +32 -0
  31. package/dist/components/confirm-dialog.js +72 -0
  32. package/dist/components/content-blocks.d.ts +141 -0
  33. package/dist/components/content-blocks.js +77 -0
  34. package/dist/components/empty-illustrations.d.ts +15 -0
  35. package/dist/components/empty-illustrations.js +36 -0
  36. package/dist/components/empty-state.d.ts +35 -0
  37. package/dist/components/empty-state.js +43 -0
  38. package/dist/components/error-alert.d.ts +15 -0
  39. package/dist/components/error-alert.js +23 -0
  40. package/dist/components/icon.d.ts +11 -0
  41. package/dist/components/icon.js +8 -0
  42. package/dist/components/layout.d.ts +38 -0
  43. package/dist/components/layout.js +28 -0
  44. package/dist/components/page-chrome.d.ts +53 -0
  45. package/dist/components/page-chrome.js +66 -0
  46. package/dist/components/refresh-control-model.d.ts +9 -0
  47. package/dist/components/refresh-control-model.js +26 -0
  48. package/dist/components/ui/accordion.d.ts +7 -0
  49. package/dist/components/ui/accordion.js +15 -0
  50. package/dist/components/ui/alert.d.ts +8 -0
  51. package/dist/components/ui/alert.js +24 -0
  52. package/dist/components/ui/badge.d.ts +9 -0
  53. package/dist/components/ui/badge.js +30 -0
  54. package/dist/components/ui/button.d.ts +20 -0
  55. package/dist/components/ui/button.js +52 -0
  56. package/dist/components/ui/card.d.ts +17 -0
  57. package/dist/components/ui/card.js +17 -0
  58. package/dist/components/ui/checkbox.d.ts +4 -0
  59. package/dist/components/ui/checkbox.js +10 -0
  60. package/dist/components/ui/control-variant.d.ts +10 -0
  61. package/dist/components/ui/control-variant.js +6 -0
  62. package/dist/components/ui/date-field-model.d.ts +39 -0
  63. package/dist/components/ui/date-field-model.js +105 -0
  64. package/dist/components/ui/date-field.d.ts +33 -0
  65. package/dist/components/ui/date-field.js +161 -0
  66. package/dist/components/ui/dialog.d.ts +24 -0
  67. package/dist/components/ui/dialog.js +27 -0
  68. package/dist/components/ui/dropdown-menu.d.ts +19 -0
  69. package/dist/components/ui/dropdown-menu.js +26 -0
  70. package/dist/components/ui/input.d.ts +8 -0
  71. package/dist/components/ui/input.js +9 -0
  72. package/dist/components/ui/list-item-button.d.ts +10 -0
  73. package/dist/components/ui/list-item-button.js +6 -0
  74. package/dist/components/ui/popover.d.ts +6 -0
  75. package/dist/components/ui/popover.js +9 -0
  76. package/dist/components/ui/radio-group.d.ts +5 -0
  77. package/dist/components/ui/radio-group.js +10 -0
  78. package/dist/components/ui/scroll-area.d.ts +5 -0
  79. package/dist/components/ui/scroll-area.js +13 -0
  80. package/dist/components/ui/searchable-select-model.d.ts +29 -0
  81. package/dist/components/ui/searchable-select-model.js +38 -0
  82. package/dist/components/ui/searchable-select.d.ts +26 -0
  83. package/dist/components/ui/searchable-select.js +85 -0
  84. package/dist/components/ui/select.d.ts +29 -0
  85. package/dist/components/ui/select.js +39 -0
  86. package/dist/components/ui/separator.d.ts +4 -0
  87. package/dist/components/ui/separator.js +11 -0
  88. package/dist/components/ui/sheet.d.ts +27 -0
  89. package/dist/components/ui/sheet.js +27 -0
  90. package/dist/components/ui/skeleton.d.ts +3 -0
  91. package/dist/components/ui/skeleton.js +6 -0
  92. package/dist/components/ui/switch.d.ts +4 -0
  93. package/dist/components/ui/switch.js +8 -0
  94. package/dist/components/ui/table.d.ts +27 -0
  95. package/dist/components/ui/table.js +47 -0
  96. package/dist/components/ui/tabs.d.ts +7 -0
  97. package/dist/components/ui/tabs.js +13 -0
  98. package/dist/components/ui/textarea.d.ts +8 -0
  99. package/dist/components/ui/textarea.js +9 -0
  100. package/dist/components/ui/tooltip.d.ts +7 -0
  101. package/dist/components/ui/tooltip.js +11 -0
  102. package/dist/components/use-container-width.d.ts +13 -0
  103. package/dist/components/use-container-width.js +30 -0
  104. package/dist/custom-media.css +13 -0
  105. package/dist/exports.json +178 -0
  106. package/dist/i18n/index.d.ts +27 -0
  107. package/dist/i18n/index.js +33 -0
  108. package/dist/i18n/messages.d.ts +55 -0
  109. package/dist/i18n/messages.js +110 -0
  110. package/dist/index.d.ts +56 -0
  111. package/dist/index.js +55 -0
  112. package/dist/scale.json +643 -0
  113. package/dist/shared-module.d.ts +28 -0
  114. package/dist/shared-module.js +24 -0
  115. package/dist/styles.css +3399 -0
  116. package/dist/theme.css +469 -0
  117. package/dist/tokens.css +652 -0
  118. package/dist/version.d.ts +6 -0
  119. package/dist/version.js +2 -0
  120. package/lint/eslint-plugin.mjs +128 -0
  121. package/lint/stylelint-config.mjs +43 -0
  122. package/lint/stylelint-plugin.mjs +195 -0
  123. package/lint/tailwind-classes.mjs +121 -0
  124. package/package.json +103 -3
  125. package/tokens/color.mjs +104 -0
  126. package/tokens/colors.css +220 -0
  127. package/tokens/generate.mjs +288 -0
  128. package/tokens/scale.mjs +137 -0
  129. package/tokens/tokens.mjs +362 -0
@@ -0,0 +1,492 @@
1
+ /**
2
+ * Playwright layout audit of ADR 0063 D20 第 3 条 (`@zhin.js/console-ui/audit`).
3
+ *
4
+ * Reads the computed style of every element at 375 / 768 / 1280 / 1920 px in the light and dark
5
+ * theme and checks:
6
+ * type-scale ≤ 5 font sizes, ≤ 3 weights, all on the scale (D16)
7
+ * spacing padding and gap on the space scale (or a resolved semantic spacing token)
8
+ * radius / border / shadow border-radius, border-width, box-shadow on the scale
9
+ * consistency one radius / border / shadow per component kind (`data-slot`) and width
10
+ * overflow no page-level horizontal scroll, no element pushed out of the viewport
11
+ * touch-target ≥ 44 × 44 px interactive targets at 375 (an `::after` hit area counts)
12
+ * edge-card edge-to-edge cards have no radius at 375
13
+ * static-card static cards have no shadow
14
+ * bottom-drawer open menus, selects and dialogs are bottom drawers at 375
15
+ * content-width data pages ≥ 85 % of a 1920 viewport, reading pages ≤ 60rem
16
+ * duplicate-text the same explanation at most once per page
17
+ * focus-visible every focusable element shows a focus style (D19)
18
+ * contrast text readable on its background, WCAG 4.5 / 3 (D19)
19
+ * shell-overlap page content does not use position: fixed or a z-index above the shell (D19)
20
+ *
21
+ * Gate or report: {@link auditPage} only collects violations; the caller decides. The
22
+ * `@zhin.js/console-ui` gallery is a gate (visual/audit.spec.ts); Console and plugin pages run the
23
+ * same function and only report (see audit/cli.mjs) until they join the gate (D20, D21).
24
+ *
25
+ * Exemptions (D19: only with a reason, reviewed): an element (and its subtree) with
26
+ * `data-zhin-ui-ignore="<check>[,<check>…]: <reason>"` is skipped for those checks; every exemption
27
+ * is listed in the result. Check ids are {@link AUDIT_CHECKS}.
28
+ */
29
+ import { buildScale } from '../tokens/scale.mjs';
30
+
31
+ export const AUDIT_WIDTHS = Object.freeze([375, 768, 1280, 1920]);
32
+ export const AUDIT_THEMES = Object.freeze(['light', 'dark']);
33
+ export const AUDIT_CHECKS = Object.freeze([
34
+ 'type-scale', 'spacing', 'radius', 'border', 'shadow', 'consistency', 'overflow', 'touch-target',
35
+ 'edge-card', 'static-card', 'bottom-drawer', 'content-width', 'duplicate-text', 'focus-visible',
36
+ 'contrast', 'shell-overlap',
37
+ ]);
38
+
39
+ /** Default theme switch: the Console's `.dark` class on <html>. */
40
+ export async function setConsoleTheme(page, theme) {
41
+ await page.evaluate((dark) => document.documentElement.classList.toggle('dark', dark), theme === 'dark');
42
+ }
43
+
44
+ /**
45
+ * Audits the page as it is now (viewport, theme and open overlays are the caller's).
46
+ * @param {import('@playwright/test').Page} page
47
+ * @param {object} [options]
48
+ * @param {string} [options.contentSelector] page content root (default `[data-slot=page-content]`, else body)
49
+ * @param {'data'|'reading'|'full'} [options.pageType] defaults to the content root's `data-width`, else `data`
50
+ * @param {string[]} [options.checks] subset of {@link AUDIT_CHECKS}
51
+ * @param {number} [options.maxFocusSteps] Tab presses for the focus check (default 40)
52
+ * @returns {Promise<{ width: number, height: number, theme: string, violations: object[], exemptions: object[] }>}
53
+ */
54
+ export async function auditPage(page, options = {}) {
55
+ const scale = buildScale();
56
+ const checks = new Set(options.checks ?? AUDIT_CHECKS);
57
+ const result = await page.evaluate(collect, {
58
+ scale: {
59
+ text: Object.values(scale.text),
60
+ weight: Object.values(scale.weight),
61
+ space: Object.values(scale.space).map((entry) => entry.value),
62
+ radius: Object.values(scale.radius),
63
+ border: Object.values(scale.border),
64
+ readingWidth: scale.contentWidth.reading,
65
+ touchTarget: scale.touchTarget,
66
+ breakpointSm: scale.breakpoints.sm,
67
+ },
68
+ checks: [...checks],
69
+ contentSelector: options.contentSelector ?? '[data-slot=page-content]',
70
+ pageType: options.pageType ?? null,
71
+ });
72
+ if (checks.has('focus-visible')) {
73
+ result.violations.push(...await focusViolations(page, options.maxFocusSteps ?? 40));
74
+ }
75
+ return result;
76
+ }
77
+
78
+ /**
79
+ * Runs {@link auditPage} over widths × themes. `open(page, { width, theme })` navigates (and may
80
+ * open overlays); it is called before every audit.
81
+ */
82
+ export async function runLayoutAudit(page, { open, widths = AUDIT_WIDTHS, themes = AUDIT_THEMES, setTheme = setConsoleTheme, height = 900, ...options }) {
83
+ const runs = [];
84
+ for (const theme of themes) {
85
+ for (const width of widths) {
86
+ await page.setViewportSize({ width, height });
87
+ await open(page, { width, theme });
88
+ await setTheme(page, theme);
89
+ runs.push(await auditPage(page, options));
90
+ }
91
+ }
92
+ return { runs, violations: runs.flatMap((run) => run.violations.map((violation) => ({ ...violation, width: run.width, theme: run.theme }))) };
93
+ }
94
+
95
+ /** Human-readable summary, grouped by check. */
96
+ export function formatAuditReport(report) {
97
+ const violations = report.violations ?? [];
98
+ if (!violations.length) return 'layout audit: no violations';
99
+ const byCheck = new Map();
100
+ for (const violation of violations) {
101
+ const list = byCheck.get(violation.check) ?? [];
102
+ list.push(violation);
103
+ byCheck.set(violation.check, list);
104
+ }
105
+ const lines = [`layout audit: ${violations.length} violation(s)`];
106
+ for (const [check, list] of byCheck) {
107
+ lines.push(` ${check} (${list.length})`);
108
+ for (const violation of list.slice(0, 20)) {
109
+ lines.push(` [${violation.theme ?? '-'} ${violation.width ?? '-'}px] ${violation.target ?? ''} — ${violation.message}`);
110
+ }
111
+ if (list.length > 20) lines.push(` … ${list.length - 20} more`);
112
+ }
113
+ return lines.join('\n');
114
+ }
115
+
116
+ async function focusViolations(page, maxSteps) {
117
+ const violations = [];
118
+ const seen = new Set();
119
+ await page.evaluate(() => {
120
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
121
+ });
122
+ for (let step = 0; step < maxSteps; step += 1) {
123
+ await page.keyboard.press('Tab');
124
+ const state = await page.evaluate(() => {
125
+ const element = document.activeElement;
126
+ if (!element || element === document.body) return null;
127
+ const ignored = element.closest('[data-zhin-ui-ignore]')?.getAttribute('data-zhin-ui-ignore') ?? '';
128
+ const style = getComputedStyle(element);
129
+ const outline = style.outlineStyle !== 'none' && Number.parseFloat(style.outlineWidth) > 0;
130
+ const ring = style.boxShadow !== 'none';
131
+ const describe = element.tagName.toLowerCase() + (element.id ? `#${element.id}` : '')
132
+ + (element.getAttribute('aria-label') ? `[aria-label="${element.getAttribute('aria-label')}"]` : '')
133
+ + (element.textContent?.trim() ? ` "${element.textContent.trim().slice(0, 30)}"` : '');
134
+ return { key: describe + element.getBoundingClientRect().top, describe, visible: outline || ring, ignored };
135
+ });
136
+ if (!state) break;
137
+ if (seen.has(state.key)) break;
138
+ seen.add(state.key);
139
+ if (!state.visible && !/\bfocus-visible\b/u.test(state.ignored)) {
140
+ violations.push({ check: 'focus-visible', target: state.describe, selector: state.describe, message: 'no visible focus style (outline or ring)' });
141
+ }
142
+ }
143
+ await page.evaluate(() => {
144
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
145
+ });
146
+ return violations;
147
+ }
148
+
149
+ /* ───────────────────────── browser side (serialized by page.evaluate) ───────────────────────── */
150
+
151
+ function collect({ scale, checks, contentSelector, pageType }) {
152
+ const enabled = new Set(checks);
153
+ const violations = [];
154
+ const exemptions = [];
155
+ const root = document.documentElement;
156
+ const remPx = Number.parseFloat(getComputedStyle(root).fontSize) || 16;
157
+ const px = (value) => {
158
+ const text = String(value).trim();
159
+ if (text.endsWith('rem')) return Number.parseFloat(text) * remPx;
160
+ return Number.parseFloat(text);
161
+ };
162
+ const width = window.innerWidth;
163
+ const height = window.innerHeight;
164
+ const near = (a, b) => Math.abs(a - b) <= 0.5;
165
+ const inSet = (value, set) => set.some((entry) => near(value, entry));
166
+
167
+ // Probe resolved values of a few semantic tokens and the elevations (theme-dependent strings).
168
+ const probe = document.createElement('div');
169
+ probe.style.position = 'absolute';
170
+ probe.style.visibility = 'hidden';
171
+ document.body.append(probe);
172
+ const resolve = (property, value) => {
173
+ probe.style.setProperty(property, value);
174
+ const computed = getComputedStyle(probe).getPropertyValue(property);
175
+ probe.style.removeProperty(property);
176
+ return computed;
177
+ };
178
+ const shadows = new Set(['none', ...[1, 2, 3].map((level) => resolve('box-shadow', `var(--console-elevation-${level})`))]);
179
+ probe.remove();
180
+
181
+ const spacing = [0, 1, ...scale.space.map(px)];
182
+ const pagePadding = px(getComputedStyle(root).getPropertyValue('--console-page-padding-inline')) || null;
183
+ const radii = scale.radius.map(px);
184
+ const borders = [0, ...scale.border.map(px)];
185
+ const fontSizes = scale.text.map(px);
186
+ const weights = scale.weight.map(Number);
187
+ const touch = px(scale.touchTarget);
188
+
189
+ const describe = (element) => {
190
+ let text = element.tagName.toLowerCase();
191
+ if (element.id) text += `#${element.id}`;
192
+ const slot = element.getAttribute('data-slot');
193
+ if (slot) text += `[data-slot=${slot}]`;
194
+ const classes = typeof element.className === 'string' ? element.className.trim().split(/\s+/u).filter(Boolean) : [];
195
+ const cls = classes.find((name) => name.startsWith('console-')) ?? classes[0];
196
+ if (cls) text += `.${cls}`;
197
+ const label = element.getAttribute('aria-label') || (element.childElementCount === 0 ? element.textContent?.trim() : '');
198
+ if (label) text += ` "${label.slice(0, 32)}"`;
199
+ return text;
200
+ };
201
+ const ignoredFor = (element, check) => {
202
+ const holder = element.closest('[data-zhin-ui-ignore]');
203
+ if (!holder) return false;
204
+ const spec = holder.getAttribute('data-zhin-ui-ignore') ?? '';
205
+ const [list, ...reason] = spec.split(':');
206
+ const names = list.split(',').map((name) => name.trim());
207
+ if (!names.includes(check) && !names.includes('*')) return false;
208
+ exemptions.push({ check, target: describe(holder), selector: describe(holder), reason: reason.join(':').trim() });
209
+ return true;
210
+ };
211
+ const report = (check, element, message) => {
212
+ if (!enabled.has(check)) return;
213
+ if (element && ignoredFor(element, check)) return;
214
+ const target = element ? describe(element) : 'page';
215
+ violations.push({ check, target, selector: target, message });
216
+ };
217
+
218
+ const hidden = (element) => {
219
+ if (element.closest('[aria-hidden="true"], [hidden], template')) return true;
220
+ const style = getComputedStyle(element);
221
+ if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return true;
222
+ const rect = element.getBoundingClientRect();
223
+ if (rect.width === 0 && rect.height === 0) return true;
224
+ return false;
225
+ };
226
+ const srOnlySelf = (element) => {
227
+ const style = getComputedStyle(element);
228
+ return (style.position === 'absolute' && (style.clip !== 'auto' || style.clipPath.startsWith('inset(50%'))) || (element.getBoundingClientRect().width <= 1 && element.getBoundingClientRect().height <= 1);
229
+ };
230
+ // Visually hidden itself or inside a visually hidden ancestor (e.g. the header row of a table in
231
+ // card mode, whose sort buttons stay in the accessibility tree but are not on screen).
232
+ const srCache = new Map();
233
+ const srOnly = (element) => {
234
+ if (!element || element === document.body) return false;
235
+ if (srCache.has(element)) return srCache.get(element);
236
+ const value = srOnlySelf(element) || srOnly(element.parentElement);
237
+ srCache.set(element, value);
238
+ return value;
239
+ };
240
+
241
+ const elements = [...document.body.querySelectorAll('*')].filter((element) =>
242
+ !(element instanceof SVGElement && element.tagName.toLowerCase() !== 'svg')
243
+ && !['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT', 'LINK', 'META', 'BR'].includes(element.tagName)
244
+ && !hidden(element));
245
+
246
+ // ── overflow ──
247
+ if (root.scrollWidth > width + 1) {
248
+ report('overflow', null, `page scrolls horizontally (scrollWidth ${root.scrollWidth}px > viewport ${width}px)`);
249
+ }
250
+ const clippedByAncestor = (element) => {
251
+ for (let node = element.parentElement; node && node !== document.body; node = node.parentElement) {
252
+ const style = getComputedStyle(node);
253
+ if (style.overflowX !== 'visible' || style.overflowY !== 'visible') return true;
254
+ }
255
+ return false;
256
+ };
257
+
258
+ const fontSizeSet = new Set();
259
+ const weightSet = new Set();
260
+ const groups = new Map();
261
+ const texts = new Map();
262
+ const content = document.querySelector(contentSelector);
263
+ const type = pageType ?? content?.getAttribute('data-width') ?? 'data';
264
+
265
+ for (const element of elements) {
266
+ const style = getComputedStyle(element);
267
+ const rect = element.getBoundingClientRect();
268
+ const isSvg = element instanceof SVGElement;
269
+ const directText = [...element.childNodes].filter((node) => node.nodeType === Node.TEXT_NODE).map((node) => node.textContent).join('').replace(/\s+/gu, ' ').trim();
270
+ const sr = srOnly(element);
271
+
272
+ // type scale
273
+ if (directText && !sr && !isSvg) {
274
+ const size = px(style.fontSize);
275
+ const weight = Number(style.fontWeight);
276
+ fontSizeSet.add(size);
277
+ weightSet.add(weight);
278
+ if (!inSet(size, fontSizes)) report('type-scale', element, `font-size ${style.fontSize} is not on the type scale`);
279
+ if (!weights.includes(weight)) report('type-scale', element, `font-weight ${style.fontWeight} is not regular / medium / strong`);
280
+ if (directText.length >= 16 && !element.closest('[role="listbox"], [role="menu"], pre, code')) {
281
+ const list = texts.get(directText) ?? [];
282
+ list.push(element);
283
+ texts.set(directText, list);
284
+ }
285
+ // contrast
286
+ if (enabled.has('contrast')) checkContrast(element, style, size, weight);
287
+ }
288
+ if (isSvg) continue;
289
+
290
+ // spacing
291
+ const spacingSet = pagePadding ? [...spacing, pagePadding] : spacing;
292
+ for (const side of ['top', 'right', 'bottom', 'left']) {
293
+ const value = px(style.getPropertyValue(`padding-${side}`));
294
+ if (!inSet(value, spacingSet)) report('spacing', element, `padding-${side} ${value}px is not on the space scale`);
295
+ }
296
+ if (/flex|grid/u.test(style.display)) {
297
+ for (const property of ['row-gap', 'column-gap']) {
298
+ const raw = style.getPropertyValue(property);
299
+ if (raw === 'normal') continue;
300
+ const value = px(raw);
301
+ if (!inSet(value, spacingSet)) report('spacing', element, `${property} ${value}px is not on the space scale`);
302
+ }
303
+ }
304
+
305
+ // radius
306
+ const corners = ['top-left', 'top-right', 'bottom-right', 'bottom-left'].map((corner) => style.getPropertyValue(`border-${corner}-radius`));
307
+ for (const corner of corners) {
308
+ const value = px(corner.split(' ')[0]);
309
+ if (value >= 1000 || value >= Math.min(rect.width, rect.height) / 2 && value >= radii[radii.length - 2]) continue;
310
+ if (!inSet(value, radii)) report('radius', element, `border-radius ${corner} is not r-0 … r-4 / full`);
311
+ }
312
+
313
+ // border widths
314
+ const borderWidths = ['top', 'right', 'bottom', 'left'].map((side) => (style.getPropertyValue(`border-${side}-style`) === 'none' ? 0 : px(style.getPropertyValue(`border-${side}-width`))));
315
+ for (const value of borderWidths) {
316
+ if (!inSet(value, borders)) report('border', element, `border-width ${value}px is not hairline / focus`);
317
+ }
318
+
319
+ // shadow
320
+ if (!shadows.has(style.boxShadow)) report('shadow', element, `box-shadow "${style.boxShadow}" is not e-0 … e-3`);
321
+
322
+ // consistency
323
+ const slot = element.getAttribute('data-slot');
324
+ if (slot) {
325
+ let key = slot;
326
+ if (element.parentElement?.closest(`[data-slot="${slot}"]`)) key += ':nested';
327
+ if (element.hasAttribute('data-edge')) key += ':edge';
328
+ if (element.hasAttribute('data-interactive')) key += ':interactive';
329
+ const signature = `radius ${corners.join(' / ')}; border ${borderWidths.join(' ')}; shadow ${style.boxShadow}`;
330
+ const group = groups.get(key) ?? new Map();
331
+ if (!group.has(signature)) group.set(signature, element);
332
+ groups.set(key, group);
333
+ }
334
+
335
+ // static cards
336
+ if ((slot === 'card' || slot === 'stat-card') && !element.hasAttribute('data-interactive') && style.boxShadow !== 'none') {
337
+ report('static-card', element, 'a static card has a shadow (D16: e-0, hairline)');
338
+ }
339
+
340
+ // edge cards at phone width
341
+ if (width < px(scale.breakpointSm) && slot === 'card') {
342
+ const spans = rect.left <= 0.5 && rect.right >= width - 0.5;
343
+ if ((spans || element.hasAttribute('data-edge')) && corners.some((corner) => px(corner) > 0.5)) {
344
+ report('edge-card', element, 'an edge-to-edge card has rounded corners');
345
+ }
346
+ }
347
+
348
+ // out of viewport
349
+ if (!sr && (rect.right > width + 1 || rect.left < -1) && !clippedByAncestor(element) && style.position !== 'fixed') {
350
+ report('overflow', element, `element leaves the viewport (left ${Math.round(rect.left)}px, right ${Math.round(rect.right)}px)`);
351
+ }
352
+
353
+ // touch targets at phone width
354
+ if (width < px(scale.breakpointSm) && isInteractive(element) && !sr) {
355
+ const hit = hitArea(element, rect);
356
+ if (hit.width < touch - 0.5 || hit.height < touch - 0.5) {
357
+ report('touch-target', element, `touch target ${Math.round(hit.width)}×${Math.round(hit.height)}px < 44×44px`);
358
+ }
359
+ }
360
+
361
+ // shell overlap: content must not cover the shell
362
+ if (content && content.contains(element) && element !== content) {
363
+ if (style.position === 'fixed') report('shell-overlap', element, 'page content uses position: fixed');
364
+ const z = Number.parseInt(style.zIndex, 10);
365
+ if (Number.isFinite(z) && z > 20) report('shell-overlap', element, `page content uses z-index ${z} (> 20)`);
366
+ }
367
+
368
+ // bottom drawers at phone width
369
+ if (width < px(scale.breakpointSm) && (slot === 'popover' || slot === 'dialog') && !element.parentElement?.closest('[data-slot="popover"], [data-slot="dialog"]')) {
370
+ if (!(rect.bottom >= height - 1 && rect.left <= 1 && rect.right >= width - 1)) {
371
+ report('bottom-drawer', element, `${slot} is not a bottom drawer (left ${Math.round(rect.left)}, right ${Math.round(rect.right)}, bottom ${Math.round(rect.bottom)} of ${height})`);
372
+ }
373
+ }
374
+ }
375
+
376
+ if (fontSizeSet.size > 5) report('type-scale', null, `${fontSizeSet.size} font sizes on the page (at most 5): ${[...fontSizeSet].sort((a, b) => a - b).join(', ')}px`);
377
+ if (weightSet.size > 3) report('type-scale', null, `${weightSet.size} font weights on the page (at most 3): ${[...weightSet].join(', ')}`);
378
+
379
+ for (const [key, group] of groups) {
380
+ if (group.size > 1) {
381
+ const variants = [...group.keys()];
382
+ report('consistency', group.values().next().value, `${group.size} different ${key} styles at ${width}px: ${variants.join(' | ')}`);
383
+ }
384
+ }
385
+
386
+ for (const [text, list] of texts) {
387
+ if (list.length > 1) report('duplicate-text', list[1], `"${text.slice(0, 60)}" appears ${list.length} times`);
388
+ }
389
+
390
+ // content width
391
+ if (content && enabled.has('content-width')) {
392
+ const contentWidth = content.getBoundingClientRect().width;
393
+ if (type === 'data' && width >= 1920 && contentWidth < width * 0.85) {
394
+ report('content-width', content, `data page content is ${Math.round(contentWidth)}px, < 85% of ${width}px`);
395
+ }
396
+ if (type === 'reading' && contentWidth > px(scale.readingWidth) + 0.5) {
397
+ report('content-width', content, `reading page content is ${Math.round(contentWidth)}px, > 60rem`);
398
+ }
399
+ }
400
+
401
+ return { width, height, theme: root.classList.contains('dark') ? 'dark' : 'light', violations, exemptions };
402
+
403
+ function isInteractive(element) {
404
+ if (element.closest('[inert]')) return false;
405
+ const tag = element.tagName;
406
+ if (tag === 'BUTTON' || tag === 'SELECT' || tag === 'TEXTAREA' || tag === 'SUMMARY') return true;
407
+ if (tag === 'INPUT') return element.type !== 'hidden';
408
+ if (tag === 'A') return element.hasAttribute('href') && !element.closest('p, li');
409
+ const role = element.getAttribute('role');
410
+ return ['button', 'checkbox', 'switch', 'radio', 'tab', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'combobox', 'link'].includes(role ?? '');
411
+ }
412
+
413
+ function hitArea(element, rect) {
414
+ let best = { width: rect.width, height: rect.height };
415
+ for (const pseudo of ['::after', '::before']) {
416
+ const style = getComputedStyle(element, pseudo);
417
+ if (style.content === 'none' || style.content === 'normal' || style.display === 'none') continue;
418
+ const w = px(style.width);
419
+ const h = px(style.height);
420
+ if (Number.isFinite(w) && Number.isFinite(h)) best = { width: Math.max(best.width, w), height: Math.max(best.height, h) };
421
+ }
422
+ // A label wrapping the control is its hit area too.
423
+ const label = element.closest('label');
424
+ if (label) {
425
+ const box = label.getBoundingClientRect();
426
+ best = { width: Math.max(best.width, box.width), height: Math.max(best.height, box.height) };
427
+ }
428
+ return best;
429
+ }
430
+
431
+ function checkContrast(element, style, size, weight) {
432
+ for (let node = element; node; node = node.parentElement) {
433
+ if (Number(getComputedStyle(node).opacity) < 1) return; // disabled / decorative
434
+ if (node.matches?.(':disabled, [data-disabled], [aria-disabled="true"]')) return;
435
+ }
436
+ const foreground = rgba(style.color);
437
+ const background = backgroundOf(element);
438
+ if (!foreground || !background) return;
439
+ const text = blend(foreground, background);
440
+ const ratio = contrast(text, background);
441
+ const large = size >= 24 || (size >= 18.66 && weight >= 600);
442
+ const needed = large ? 3 : 4.5;
443
+ if (ratio < needed - 0.01) report('contrast', element, `contrast ${ratio.toFixed(2)} < ${needed} (${style.color} on ${background.join(',')})`);
444
+ }
445
+
446
+ function backgroundOf(element) {
447
+ const layers = [];
448
+ for (let node = element; node; node = node.parentElement) {
449
+ const style = getComputedStyle(node);
450
+ if (style.backgroundImage !== 'none') return null; // gradients / images: not judged
451
+ const color = rgba(style.backgroundColor);
452
+ if (color && color[3] > 0) {
453
+ layers.push(color);
454
+ if (color[3] >= 1) break;
455
+ }
456
+ }
457
+ let base = [255, 255, 255, 1];
458
+ for (const layer of layers.reverse()) base = blend(layer, base);
459
+ return base;
460
+ }
461
+
462
+ function rgba(color) {
463
+ const canvas = rgba.canvas ?? (rgba.canvas = document.createElement('canvas'));
464
+ canvas.width = 1;
465
+ canvas.height = 1;
466
+ const context = canvas.getContext('2d', { willReadFrequently: true });
467
+ if (!context) return null;
468
+ context.clearRect(0, 0, 1, 1);
469
+ context.fillStyle = '#000';
470
+ context.fillStyle = color;
471
+ context.fillRect(0, 0, 1, 1);
472
+ const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data;
473
+ return [r, g, b, a / 255];
474
+ }
475
+
476
+ function blend(top, bottom) {
477
+ const alpha = top[3];
478
+ return [0, 1, 2].map((index) => top[index] * alpha + bottom[index] * (1 - alpha)).concat(1);
479
+ }
480
+
481
+ function contrast(a, b) {
482
+ const luminance = (color) => {
483
+ const [r, g, b2] = color.slice(0, 3).map((channel) => {
484
+ const value = channel / 255;
485
+ return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
486
+ });
487
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b2;
488
+ };
489
+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
490
+ return (hi + 0.05) / (lo + 0.05);
491
+ }
492
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Browser entry the plugin page audit bundles for each page (audit/plugin-pages.mjs). It renders the
3
+ * page the way the Console shell does: `PageShell` + `PageHeader` from the page meta, the page body
4
+ * inside a `PageChromeProvider`. Hand-written React pages are mounted directly; declarative
5
+ * blueprints, adapter pages and comment review pages are rendered by the Console renderers
6
+ * (`@zhin.js/client`), so they need a mount module (`mountModule` in the request) exporting
7
+ * `mountPluginPage(context)`; without one they are reported as not mounted.
8
+ *
9
+ * @typedef {object} MountPluginPageContext
10
+ * @property {HTMLElement} element root element of the page
11
+ * @property {{ default?: unknown, meta?: object }} pageModule the page module (`meta` from definePage)
12
+ * @property {string} pageName
13
+ * @property {'light' | 'dark'} theme
14
+ * @property {(body: import('react').ReactNode) => void} renderInShell renders `body` inside the shell
15
+ *
16
+ * The result is published on `window.__zhinUiAudit` = { status: 'mounted' | 'unsupported' | 'error', message? }.
17
+ */
18
+ import { Component, useState } from "react";
19
+ import { createRoot } from "react-dom/client";
20
+ import {
21
+ ConsoleUiI18nProvider,
22
+ PageChromeActions,
23
+ PageChromeProvider,
24
+ PageHeader,
25
+ PageShell,
26
+ createPageChromeStore
27
+ } from "@zhin.js/console-ui";
28
+ function publish(state) {
29
+ window.__zhinUiAudit = state;
30
+ }
31
+ class Boundary extends Component {
32
+ state = { error: void 0 };
33
+ static getDerivedStateFromError(error) {
34
+ return { error };
35
+ }
36
+ componentDidCatch(error) {
37
+ publish({ status: "error", message: error instanceof Error ? error.message : String(error) });
38
+ }
39
+ render() {
40
+ return this.state.error ? null : this.props.children;
41
+ }
42
+ }
43
+ function Shell({ pageModule, pageName, children }) {
44
+ const [store] = useState(createPageChromeStore);
45
+ const meta = pageModule.meta ?? {};
46
+ const width = meta.fullWidth ? "full" : meta.contentWidth ?? "data";
47
+ return <ConsoleUiI18nProvider locale="zh-CN">
48
+ <PageShell width={width}>
49
+ <PageHeader title={meta.title ?? pageName} description={meta.description} actions={<PageChromeActions store={store} />} />
50
+ <PageChromeProvider store={store}>
51
+ <Boundary>{children}</Boundary>
52
+ </PageChromeProvider>
53
+ </PageShell>
54
+ </ConsoleUiI18nProvider>;
55
+ }
56
+ function isBlueprint(value) {
57
+ const kind = value?.kind;
58
+ return typeof kind === "string" && kind.startsWith("zhin.console.");
59
+ }
60
+ async function mountAuditPage(pageModule, pageName, custom) {
61
+ const params = new URLSearchParams(location.search);
62
+ const theme = params.get("theme") === "dark" ? "dark" : "light";
63
+ document.documentElement.classList.toggle("dark", theme === "dark");
64
+ window.addEventListener("error", (event) => publish({ status: "error", message: event.message }));
65
+ const element = document.getElementById("root") ?? document.body.appendChild(document.createElement("div"));
66
+ const root = createRoot(element);
67
+ const renderInShell = (body) => root.render(<Shell pageModule={pageModule} pageName={pageName}>{body}</Shell>);
68
+ try {
69
+ const Page = pageModule.default;
70
+ if (custom?.mountPluginPage) {
71
+ await custom.mountPluginPage({ element, pageModule, pageName, theme, renderInShell });
72
+ } else if (isBlueprint(Page)) {
73
+ publish({ status: "unsupported", message: "declarative blueprint / adapter page: needs a renderer mount module (mountModule)" });
74
+ return;
75
+ } else if (typeof Page === "function") {
76
+ const Body = Page;
77
+ renderInShell(<Body />);
78
+ } else {
79
+ publish({ status: "error", message: "the page module has no default-exported component" });
80
+ return;
81
+ }
82
+ await new Promise((resolve) => setTimeout(resolve, 300));
83
+ if (!window.__zhinUiAudit) publish({ status: "mounted" });
84
+ } catch (error) {
85
+ publish({ status: "error", message: error instanceof Error ? error.message : String(error) });
86
+ }
87
+ }
88
+ export {
89
+ mountAuditPage
90
+ };