/** * Page UI checks of `zhin plugin check` (ADR 0063 决策 4 / D20): rules 1–6 over a plugin's `pages/**`. * * For third-party plugins every finding is a hint: it never counts as an error or a warning, so it * does not block `zhin plugin check --strict`, a build or `zhin pub`. The official plugins of * zhinjs/zhin treat the same findings as errors in CI (`pnpm check:plugin`, gate list * `scripts/plugin-ui-gate.json`). A finding is waived only by an inline comment that names the rule * and a reason (see {@link IGNORE_DIRECTIVE}); there is no per-plugin or per-file switch. * * Only Node built-ins and the optional `typescript` peer are used (the repository gate imports this * file straight from source). */ import fs from 'node:fs'; import { createRequire } from 'node:module'; import path from 'node:path'; export type PageUiRuleId = 1 | 2 | 3 | 4 | 5 | 6; export interface PageUiRule { readonly id: PageUiRuleId; readonly key: string; readonly title: string; /** Why the pattern is a problem. */ readonly meaning: string; /** How to align it with `@zhin.js/console-ui`. */ readonly fix: string; } export const PAGE_UI_RULES: readonly PageUiRule[] = Object.freeze([ { id: 1, key: 'native-select', title: '原生 ` or `padding: 12px`. */ readonly detail: string; } /** An inline `zhin-ui-ignore` comment (static rules 1–6). */ export interface PageUiExemption { readonly rules: readonly PageUiRuleId[]; readonly reason: string; readonly file: string; /** Line of the comment. */ readonly line: number; /** Line it waives. */ readonly target: number; /** Findings it waived. */ readonly waived: readonly PageUiFinding[]; } /** A `data-zhin-ui-ignore` attribute: a waiver for one check of the Playwright layout audit. */ export interface PageUiAuditExemption { readonly check: string; readonly reason: string; readonly file: string; readonly line: number; } export interface PageUiDirectiveProblem { readonly file: string; readonly line: number; readonly message: string; } export interface PageUiReport { /** Page source files that were checked. */ readonly files: number; /** Findings not waived by an exemption. */ readonly findings: readonly PageUiFinding[]; readonly exemptions: readonly PageUiExemption[]; readonly auditExemptions: readonly PageUiAuditExemption[]; /** Malformed or unused ignore comments / attributes. */ readonly directiveProblems: readonly PageUiDirectiveProblem[]; /** Set when script sources could not be parsed (no `typescript`); CSS files are still checked. */ readonly skipped?: string; } /** * Inline ignore comment: `zhin-ui-ignore : ` in a `//`, `/* *\/` or `{/* *\/}` comment. * `` is one rule number or several separated by commas (`4,6`). A comment after code waives * its own line; a comment on a line of its own waives the next line with code. */ export const IGNORE_DIRECTIVE = 'zhin-ui-ignore'; /** JSX attribute that waives one Playwright audit check for an element and its descendants. */ export const AUDIT_IGNORE_ATTRIBUTE = 'data-zhin-ui-ignore'; const SCRIPT_EXTENSIONS = /\.(?:[cm]?[jt]s|[jt]sx)$/u; const STYLE_EXTENSIONS = /\.(?:css|scss|less)$/u; const SKIPPED_FILES = /\.d\.[cm]?ts$|\.(?:test|spec)\.[cm]?[jt]sx?$/u; // --------------------------------------------------------------------------------------------- // Value rules shared by CSS text and style objects // --------------------------------------------------------------------------------------------- /** CSS properties whose literal values rule 4 reports (kebab-case). */ const RAW_STYLE_PROPERTY = new RegExp( '^(?:font|font-size|font-weight|box-shadow|gap|row-gap|column-gap' + '|border-radius|border-(?:top|bottom|start|end)-(?:left|right|start|end)-radius' + '|(?:padding|margin)(?:-(?:top|right|bottom|left|inline|block)(?:-(?:start|end))?)?)$', 'u', ); const CSS_WIDE_KEYWORDS = new Set(['inherit', 'initial', 'unset', 'revert', 'revert-layer']); const STYLE_VALUE_KEYWORDS = new Set([...CSS_WIDE_KEYWORDS, 'none', 'auto', 'normal', 'calc', 'min', 'max', 'clamp']); /** Removes `var(--console-…)` references (fallbacks included). */ function stripConsoleVariables(value: string): string { let out = ''; let index = 0; while (index < value.length) { const start = value.indexOf('var(', index); if (start < 0) { out += value.slice(index); break; } out += value.slice(index, start); let depth = 0; let end = start + 3; for (; end < value.length; end += 1) { if (value[end] === '(') depth += 1; else if (value[end] === ')' && --depth === 0) break; } const reference = value.slice(start, end + 1); out += /^var\(\s*--console-/u.test(reference) ? ' ' : reference; index = end + 1; } return out; } /** Whether a CSS value for a rule-4 property is a literal rather than `0`, a keyword or a Console token. */ export function isRawStyleValue(value: string): boolean { const input = value.replace(/!important\s*$/u, ''); const rest = stripConsoleVariables(input); // `calc(var(--console-…) * 2)` scales a token: unitless factors next to a token are fine. const scalesToken = rest !== input; const tokens = rest.split(/[\s,()/*+]+/u).filter((token) => token !== '' && token !== '-'); return tokens.some((token) => token !== '0' && !STYLE_VALUE_KEYWORDS.has(token.toLowerCase()) && !(scalesToken && /^-?\d+(?:\.\d+)?$/u.test(token))); } const PX_CONTENT_WIDTH = 640; const REM_CONTENT_WIDTH = 40; /** Whether a width value fixes a content width (≥ 640px or ≥ 40rem / 40em). */ export function isFixedContentWidth(value: string): boolean { for (const match of value.matchAll(/(\d+(?:\.\d+)?)(px|rem|em)\b/gu)) { const amount = Number(match[1]); if (match[2] === 'px' ? amount >= PX_CONTENT_WIDTH : amount >= REM_CONTENT_WIDTH) return true; } return false; } function camelToKebab(name: string): string { return name.replace(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`); } const CSS_DECLARATION = /(? number, push: (rule: PageUiRuleId, line: number, detail: string) => void): void { for (const match of text.matchAll(CSS_DECLARATION)) { const property = match[1]!.toLowerCase(); const value = match[2]!.replace(/["'`]+\s*$/u, '').trim(); if (value === '' || value.startsWith('//')) continue; const line = lineOf(match.index!); if (property === '--console-content-max') { push(3, line, `${property}: ${value}`); } else if ((property === 'width' || property === 'max-width') && isFixedContentWidth(value)) { push(3, line, `${property}: ${value}`); } else if (RAW_STYLE_PROPERTY.test(property) && isRawStyleValue(value)) { push(4, line, `${property}: ${value}`); } } } // --------------------------------------------------------------------------------------------- // Tailwind class names (rule 5, and the content-width part of rule 3) // --------------------------------------------------------------------------------------------- const VARIANTS = '(?:[a-z0-9@*[\\]&=_-]+:)*!?'; const SPACING_UTILITY = '(?:p[xytrblse]?|m[xytrblse]?|gap(?:-[xy])?|space-[xy]|scroll-[mp][xytrblse]?)'; const STYLE_UTILITY = `(?:${SPACING_UTILITY}|rounded(?:-(?:[trblse]|tl|tr|br|bl|ss|se|es|ee))?|text|font|shadow|leading|tracking|border(?:-[xytrblse])?)`; const ARBITRARY_STYLE_CLASS = new RegExp(`^${VARIANTS}-?${STYLE_UTILITY}-(\\[[^\\]]+\\]|\\([^)]+\\))!?$`, 'u'); const SPACING_CLASS = new RegExp(`^${VARIANTS}-?${SPACING_UTILITY}-(\\d+(?:\\.\\d+)?)!?$`, 'u'); const DEFAULT_SHADOW_CLASS = new RegExp(`^${VARIANTS}shadow(?:-(?:2xs|xs|sm|md|lg|xl|2xl|inner))?!?$`, 'u'); const WIDTH_ARBITRARY_CLASS = new RegExp(`^${VARIANTS}(?:max-)?w-\\[([^\\]]+)\\]!?$`, 'u'); const WIDTH_NAMED_CLASS = new RegExp(`^${VARIANTS}max-w-(?:[2-7]xl|prose|screen-[a-z0-9]+)!?$`, 'u'); const SPACING_KEYS = new Set(['0', '1', '2', '3', '4', '6', '8', '12', '16']); /** The rule a single class name breaks, if any. */ export function classNameRule(token: string): PageUiRuleId | undefined { const arbitrary = ARBITRARY_STYLE_CLASS.exec(token); if (arbitrary) { // `p-[var(--console-…)]` / `p-(--console-…)` reference a Console token and are fine. return /^[[(](?:var\()?--console-/u.test(arbitrary[1]!) ? undefined : 5; } const spacing = SPACING_CLASS.exec(token); if (spacing) return SPACING_KEYS.has(spacing[1]!) ? undefined : 5; if (DEFAULT_SHADOW_CLASS.test(token)) return 5; const width = WIDTH_ARBITRARY_CLASS.exec(token); if (width) return isFixedContentWidth(width[1]!) ? 3 : undefined; if (WIDTH_NAMED_CLASS.test(token)) return 3; return undefined; } function checkClassNames(text: string, lineOf: (offset: number) => number, push: (rule: PageUiRuleId, line: number, detail: string) => void): void { for (const match of text.matchAll(/\S+/gu)) { const rule = classNameRule(match[0]); if (rule !== undefined) push(rule, lineOf(match.index!), match[0]); } } // --------------------------------------------------------------------------------------------- // Ignore directives // --------------------------------------------------------------------------------------------- interface ParsedDirective { readonly line: number; readonly target: number; readonly rules?: readonly PageUiRuleId[]; readonly reason?: string; readonly problem?: string; } const DIRECTIVE_PATTERN = new RegExp(`(?:\\/\\/|\\/\\*)\\s*${IGNORE_DIRECTIVE}\\b(.*)$`, 'u'); function parseDirectives(lines: readonly string[]): ParsedDirective[] { const directives: ParsedDirective[] = []; for (let index = 0; index < lines.length; index += 1) { const text = lines[index]!; const match = DIRECTIVE_PATTERN.exec(text); if (!match) continue; const before = text.slice(0, match.index).replace(/\{\s*$/u, '').trim(); let target = index + 1; if (before === '') { target = 0; for (let next = index + 1; next < lines.length; next += 1) { const candidate = lines[next]!.trim(); if (candidate !== '' && !DIRECTIVE_PATTERN.test(candidate)) { target = next + 1; break; } } } const body = match[1]!.replace(/\*\/\s*\}?\s*$/u, '').trim(); const parsed = /^(\d+(?:\s*,\s*\d+)*)\s*[::]\s*(.*)$/u.exec(body); if (!parsed) { directives.push({ line: index + 1, target, problem: `${IGNORE_DIRECTIVE} 写法应为「${IGNORE_DIRECTIVE} <检查项>: <理由>」,例如「${IGNORE_DIRECTIVE} 6: 画布内的原生