diff --git a/skills/scd-quickdev/references/page-acceptance.md b/skills/scd-quickdev/references/page-acceptance.md index f443c2e..545a44d 100644 --- a/skills/scd-quickdev/references/page-acceptance.md +++ b/skills/scd-quickdev/references/page-acceptance.md @@ -13,7 +13,9 @@ 3. 覆盖差异真实触发的加载、空数据、成功、失败、权限、部分成功和恢复状态; 4. 按共用视觉标准确定并记录适用视口,在布局真实变化时覆盖代表性桌面和窄屏视口; 5. 存在 UX 视觉交付时,把实际结果逐项映射到视觉 ID 并记录允许差异;不存在时把视觉 ID 标为 `N/A`,仍需验证 Issue 定义的可见结果; -6. 执行共用八维检查,另核对键盘顺序、焦点与基本无障碍名称; +6. 执行共用八维检查与双视角自审: + - **规范审(脚本量化硬底线 + 交互核对)**:在真实浏览器的受测视口与关键状态下运行零依赖探测脚本 `skills/scd-uiux/scripts/dom-audit.mjs`(通过 `node skills/scd-uiux/scripts/dom-audit.mjs --print-snippet` 获取浏览器自包含片段并在 `page.evaluate(...)` 或浏览器控制台执行,或对采集快照运行 `auditSnapshot()`),客观校验 `horizontal_overflow`、`small_body_text`、`small_touch_target`、`heading_hierarchy`、`missing_accessible_name`、`broken_image`、`low_contrast` 7 类硬底线,并人工核对键盘顺序、焦点返回与状态完备;脚本命中当前回归硬底线告警时按对应维度 `FAIL` 处理; + - **工作室主审(多模态看图主审)**:结合真实页面截图与对应产品形态轨道(展示/营销型 Web vs 高密度工具/工作台型 Web App)复核视觉层级、构图、留白与辨识度; 7. 检查与旅程相关的控制台错误和失败网络请求,并区分当前回归与已知无关基线; 8. 保存可复现的截图、录屏、浏览器追踪或等价证据引用,并链接基线、各轮自审与同条件对比。 diff --git a/skills/scd-ui-polish/SKILL.md b/skills/scd-ui-polish/SKILL.md index aeaadc1..2fb7515 100644 --- a/skills/scd-ui-polish/SKILL.md +++ b/skills/scd-ui-polish/SKILL.md @@ -15,7 +15,9 @@ description: "优化已有 Web 页面的视觉质量,按排版、留白、层 先读适用 `AGENTS.md`、`CLAUDE.md`、当前任务或 Issue、已确认视觉来源和附近组件。确定目标页面与修改边界;可从当前上下文确定时不重复询问。 -修改前读取并执行共用的[页面视觉质量](../scd-uiux/references/visual-quality.md),实际打开页面、操作主要控件、保存基线。指出至多三个最影响观感的具体问题,以及各自的改善方向,不能只给抽象“高级感”评分。 +修改存量页面(Brownfield)前,先按[设计令牌](../scd-uiux/references/design-tokens.md)扫描仓库现有 CSS 自定义属性、Tailwind 配置/主题变量与组件库变体,记录存量令牌基线后再规划视觉增量,禁止脱离现有样式体系另起炉灶。 + +修改前读取并执行共用的[页面视觉质量](../scd-uiux/references/visual-quality.md),实际打开页面、操作主要控件、保存基线,并在规范审阶段运行零依赖 `../scd-uiux/scripts/dom-audit.mjs` 量化探测客观硬底线。指出至多三个最影响观感的具体问题,以及各自的改善方向,不能只给抽象“高级感”评分。 用户只要求评审时,保持只读,交付观察与建议。缺少代码访问时可完成已授权评审,但不得声称完成实施;缺少必需页面访问时明确 `BLOCKED` 及缺口。 diff --git a/skills/scd-uiux/SKILL.md b/skills/scd-uiux/SKILL.md index 3a94a64..86cf0cd 100644 --- a/skills/scd-uiux/SKILL.md +++ b/skills/scd-uiux/SKILL.md @@ -62,23 +62,23 @@ description: "在生产实施前设计或完善 Web 产品的用户体验和界 每项已说明的用户需求都必须落到一个界面或有意设计的非 UI 行为。每个设计界面都必须支持一个具名旅程或验收行为。不得在没有产品理由时添加装饰性界面、组件或状态。 -默认复用仓库现有设计系统和组件,只定义视觉与行为增量。只有多个界面确实需要新的可复用视觉语言,且没有合适系统时,才创建更广泛的视觉系统。 +默认复用仓库现有设计系统和组件,只定义视觉与行为增量。修改或扩展存量项目(Brownfield)前,先按[设计令牌](references/design-tokens.md)扫描仓库现有 CSS 自定义属性、Tailwind 配置/主题变量与组件库变体,记录存量令牌基线后再写增量,避免另起炉灶。只有多个界面确实需要新的可复用视觉语言,且没有合适系统时,才创建更广泛的视觉系统。 ## 形成可实施的视觉交付 视觉方向、字体搭配、配色、图标、图表或动效需要具体参照时,检索内置 Web 设计知识库:`node /scripts/search.mjs <2-5 个英文设计关键词> [--domain <域>]`,域见 `--list-domains`(styles/typography/products/reasoning/ux/icons/charts/motion/landing/stacks)。底层 CSV 为英文语料,优先传入英文设计关键词(如 `dark dashboard table`);脚本内置高频中文设计词同义映射作兼容兜底。一次查询围绕单一意图;结果为空或离题时收窄或换域重试一次,仍无命中则如实报告无验证匹配,不得把一般性建议当作检索结果,也不保留未验证输出。检索所得具体值进入方向块或 UX 契约时注明来源域与条目。 -创建或验证线框图、视觉稿或原型前,阅读 `references/visual-evidence.md`。生成任何视觉产物前,先按[设计品味](references/design-taste.md)写出五项方向块并逐条排查反模式黑名单;命名不出方向时不得开始生成。 -视觉设计自动使用共用的[页面视觉质量](references/visual-quality.md):统一方向、八维检查、实际渲染的有限轮次自审与可核对对比。已有页面只需视觉打磨时可独立使用 [scd-ui-polish](../scd-ui-polish/SKILL.md);生产实施仍交给 QuickDev,清晰局部变更不增加设计阶段。 +创建或验证线框图、视觉稿或原型前,阅读 `references/visual-evidence.md`。生成任何视觉产物前,先按[设计品味](references/design-taste.md)选定产品形态轨道(展示/营销/内容型 Web 或高密度工具/工作台型 Web App)、写出五项方向块并逐条排查对应轨道反模式黑名单与共用硬底线;命名不出方向时不得开始生成。 +视觉设计自动使用共用的[页面视觉质量](references/visual-quality.md):分轨统一方向、八维检查、脚本量化规范审与多模态工作室主审结合的有限轮次自审及可核对对比。已有页面只需视觉打磨时可独立使用 [scd-ui-polish](../scd-ui-polish/SKILL.md);生产实施仍交给 QuickDev,清晰局部变更不增加设计阶段。 - 明显的文案、颜色、间距或局部组件变更继续使用简洁的交互增量说明,不强制扩大成设计项目。 - 显式 UIUX 设计、重要新页面、重要用户流程或整体改版必须生成项目内可渲染的视觉产物,不能只交付文字。 - 每个主要界面族和关键状态使用稳定视觉 ID,映射到旅程或验收、视口、保真度和仓库文件。 - 响应式布局真实变化时,至少提供代表性桌面和窄屏视口;不为没有布局差异的尺寸重复造图。 -- 多步骤、有状态或包含恢复行为的交互必须提供可点击或可运行的轻量原型。 +- 低保真默认采用纯灰度、无配色/无装饰的单文件 HTML 线框;多步骤、有状态或包含恢复行为的交互必须提供可点击或可运行的轻量原型,默认在 `.scd/ux//prototype/` 下交付基于三层 DTCG CSS Custom Properties、内嵌角落状态切换条(`loading`/`empty`/`error`/`success`/`dark`/`mobile`)的 HTML 原型。 - 品牌、视觉语言、数据密度或精确组件外观属于验收条件时,必须提供高保真关键界面和状态。 -不强制使用 Figma 或任何单一设计工具。优先使用仓库和用户已有工具。外部设计链接可以保留来源,但必须把前端实施所需的稳定导出纳入项目;外链不能成为唯一视觉交付。原型必须明确标记为非生产。每个生成的视觉产物都应在相关视口尺寸下检查,并把关键决策提取到 UX 契约。 +不强制使用 Figma 或任何单一设计工具。优先使用仓库和用户已有工具;Figma、Stitch、Excalidraw 等外部工具可作为可选上游来源,外部设计链接可以保留来源,但必须把前端实施所需的稳定导出纳入项目;外链不能成为唯一视觉交付。原型必须明确标记为非生产。每个生成的视觉产物都应在相关视口尺寸下检查,并把关键决策提取到 UX 契约。 视觉产物和 UX 契约共同构成前端交接:UX 契约负责行为、状态和响应式规则,视觉产物负责已标记视口中的布局、层级、密度和外观。二者冲突时保持 `status: draft`,明确差异并统一后再继续;不得静默选择一方,也不得让前端自行猜测。 diff --git a/skills/scd-uiux/references/design-taste.md b/skills/scd-uiux/references/design-taste.md index 4866455..3e0487b 100644 --- a/skills/scd-uiux/references/design-taste.md +++ b/skills/scd-uiux/references/design-taste.md @@ -1,40 +1,72 @@ # 设计品味 -UIUX 设计在生成任何视觉产物前共用本参考。它负责生成侧判断:先固定方向、封死模板化默认。产物验收仍按[页面视觉质量](visual-quality.md)的八维、轮次与证据执行;二者冲突时先统一再继续。 +UIUX 设计在生成任何视觉产物前共用本参考。它负责生成侧判断:先选定产品形态轨道与方向、封死模板化默认,同时避免把展示站规则机械套用到高密度工具型 Web App。产物验收仍按[页面视觉质量](visual-quality.md)的八维、轮次与证据执行;二者冲突时先统一再继续。 ## 生成前方向块 -生成线框、视觉稿或原型前,先把五项方向决策写入 UX 契约「视觉方向与系统增量」。说不出任一项时不得开始生成;说不出方向的生成必然回落均值: +生成线框、视觉稿或原型前,先把五项方向决策写入 UX 契约「视觉方向与系统增量」。说不出任一项时不得开始生成;说不出方向的生成必然回落均值。首项必须显式声明**产品形态轨道**,在以下两轨中二选一(复合产品按页面族分别声明): -- 领域与气质:产品类别,加一个结果必须成立的一个词气质(如「克制」「精密」「温暖」); +- **展示/营销/内容型 Web**:官网、着陆页、品牌展示、编辑出版与营销专题,重叙事张力、情绪辨识与转化节奏; +- **高密度工具/工作台型 Web App**:SaaS 后台、数据分析看板、监控台、专业编辑器与表单工作流,重扫视效率、首屏信息密度与操作确定性。 + +五项方向决策: + +- 领域、产品形态轨道与气质:产品类别 + 选定轨道(展示/营销/内容型 Web 或高密度工具/工作台型 Web App)+ 结果必须成立的一个词气质(如「克制」「精密」「温暖」); - 受众与语气:专家或新手、冷静或活力、高级或实用; - 动效深度:无 / 仅反馈 / 表达性编排,三选一并说明; -- 布局族:命名的分节序列,说明每节构图如何变化,不重复同一行式; +- 布局族:展示型给出命名的分节序列并说明每节构图如何变化,不重复同一行式;工作台型给出导航、指标/筛选带、主工作区与详情抽屉的骨架和聚焦关系; - 参考锚点:对标的具名系统或作品,来源可核对;无法联网对标时按页面视觉质量的外部对标规则记录。 -方向块先于产物存在。产物偏离方向块时,先改方向块或改产物并记录原因,不得事后解释成「风格选择」。清晰局部变更继承现有方向,只写增量。 +方向块先于产物存在。产物偏离方向块或跨轨混用规则时,先改方向块或改产物并记录原因,不得事后解释成「风格选择」。清晰局部变更继承现有方向与轨道,只写增量。 ## 反模式黑名单 -以下默认每一个都是缺陷,不是起点。生成时逐条规避,自审时命中即按对应维度 `FAIL`: +先守住两轨共用硬底线,再按选定产品形态轨道执行对应细则。生成时逐条规避,自审时命中即按对应维度 `FAIL`: + +### 两轨共用硬底线(全部产品形态适用) + +| 默认 | 为什么是缺陷 | 替代 | +|---|---|---| +| `#000` 压 `#fff` 或低对比灰字 | 刺眼或不可读 | 主题内暖白/浅灰底配非纯黑文字;正文对比度 ≥ 4.5:1、大字 ≥ 3:1 | +| 强调色彩虹 | 无纪律、语义混乱 | 一个主色,至多一个强调色;中性色承担主体 | +| emoji 当图标、项目符或状态点 | 最响的生成物痕迹、跨平台不一致 | 内联 SVG 图标用 `currentColor`,或纯文字 | +| 每个盒子都有投影 | 浑浊、过时的深度 | 大部分平面;阴影稀有而分层,工作台优先细边框与表面阶梯 | +| 单侧彩色边条 | 陈词滥调的装饰 | 完整细边框或面分隔;状态用图标加文字,不只靠颜色 | +| 牺牲无障碍与交互底线 | 触控难按、键盘失焦、动态不适 | 触控目标 ≥ 44×44px(间距 ≥ 8px)、可见焦点环、键盘可达、适配 `prefers-reduced-motion` | + +### 展示/营销/内容型 Web 专属黑名单 + +以下默认在展示/营销/内容型页面中均为缺陷,保留强视觉张力: | 默认 | 为什么读起来像生成物 | 替代 | |---|---|---| -| 三个或四个等权重卡片并排 | 视线无处落 | 让一个要素领先:更大、更重或独占一行 | -| 整页居中 | 无张力、无层级 | 真实网格上的不对称;居中是刻意例外 | +| 三个或四个等权重卡片机械并排 | 视线无处落 | 让一个要素领先:更大、更重或独占一行 | +| 整页居中 | 无张力、无层级 | 真实网格上的不对称构图;居中仅作刻意例外 | | 同一「左文右图」行式重复 | 明显模板化 | 每节构图有意变化 | -| 标题只是加粗正文 | 没有显示层级 | 最大标题至少 2.5 倍正文,短,18–24 字符行长 | -| 每个盒子都有投影 | 浑浊、过时的深度 | 大部分平面;阴影稀有而分层 | -| `#000` 压 `#fff` | 刺眼、业余 | 主题内的暖白底配非纯黑文字 | -| 强调色彩虹 | 无纪律 | 一个主色,至多一个强调色;中性色承担主体 | -| emoji 当图标、项目符或状态点 | 最响的生成物痕迹 | 内联 SVG 图标用 `currentColor`,或纯文字 | -| 单侧彩色边条 | 陈词滥调的装饰 | 完整细边框或面分隔;状态用图标加文字 | +| 标题只是加粗正文 | 没有显示层级 | 最大标题至少 2.5 倍正文(≥ 2.5x),短,18–24 字符行长 | | 拥挤的垂直节奏 | 密集、焦虑 | 分节之间保留慷慨的宏观留白 | +### 高密度工具/工作台型 Web App 差异化约束 + +工作台与专业 Web App 不得套用展示站审美而牺牲首屏效率,明确允许以下结构化模式: + +- **允许等权重结构化组件**:同度量 KPI 指标卡、对比定价格(Pricing Grid)、数据网格与状态看板可合理等权重并排;通过主指标高亮、状态色阶、等宽数字对齐(`tabular-nums`)与清晰区块标题建立扫描层级,不为“非对称”强行破坏横向对比; +- **允许紧凑标题层级**:主标题相对正文可收窄至 `1.35x–1.75x`(如 14px 正文配 20–24px 页头标题),配合字重、面包屑与副标签区分层级,保护首屏信息密度;仍禁止标题与正文同号仅加粗或层级跳级; +- **允许紧凑但有序的信息节奏**:按 4px 阶梯与外距大于内距组织高密度分组,消除无呼吸感的粘连堆叠。 + +工作台轨道专属反模式(命中即 `FAIL`): + +| 默认 | 为什么破坏工作台效率 | 替代 | +|---|---|---| +| 装饰性大横幅挤占首屏主工作区 | 关键数据与高频操作被推到折线以下 | 紧凑页头加即时筛选/KPI 带,让核心工作区首屏可见 | +| 高频操作仅靠 hover 暴露或藏在多层菜单 | 触控与键盘不可达、扫描成本高 | 主操作明示,次要行操作保持可见或清晰触发入口 | +| 表格/指标缺少数字对齐或无溢出承接 | 纵向扫读困难、撑破整页宽度 | 数值列右对齐与 `tabular-nums`,表格容器独立横向滚动 | + ## 文案纪律 界面文案禁用:营销填充词(「赋能」「无缝」「解锁」「极致」)、空洞三连(「强大、直观、美观」)、假结构标签(「SECTION 01」、lorem ipsum、「在此输入标题」)和过度对冲的微文案。写具体的、可验证的事;读出来像新闻稿就删短、写具体。 -## 移动优先 +## 响应式策略(移动优先 vs 纯桌面工具桌面优先) -基础样式即窄屏布局,更宽的屏幕用 `min-width` 逐层叠加。禁止桌面优先、回头再补移动端。`max-width` 属性用于阅读行长、容器上限与图片约束,不受此限制。 +- **展示/营销/内容型 Web 及面向移动端的通用 Web**:严格执行**移动优先**——基础样式即窄屏布局,更宽的屏幕用 `min-width` 逐层叠加,禁止桌面优先再回头补移动端。`max-width` 属性用于阅读行长、容器上限与图片约束,不受此限制。 +- **纯桌面专业工具/高密度工作台型 Web App**(如多栏看板、复杂表格后台、专业编辑器):允许采用**桌面优先**策略,围绕主力桌面视口建立高效分栏与信息密度;但必须在 UX 契约中明确**窄屏可用或优雅降级策略**(例如侧边栏折叠为抽屉、数据表独立横向滚动、保留关键查看/审批能力且不产生整页水平溢出;若产品契约明确不支持窄屏编辑,提供清晰的窄屏降级提示与安全只读/退出路径)。 diff --git a/skills/scd-uiux/references/design-tokens.md b/skills/scd-uiux/references/design-tokens.md index 6e67c6f..5e01a96 100644 --- a/skills/scd-uiux/references/design-tokens.md +++ b/skills/scd-uiux/references/design-tokens.md @@ -24,9 +24,18 @@ HTML 与结构表达「它是什么」,令牌表达「它看起来如何」, 原始令牌不变;暗色在语义层切换(CSS 自定义属性配合 `[data-theme]` 或 `prefers-color-scheme`)。每个组件状态都要在两种模式下核对,不得只验证亮色。 +## 存量项目(Brownfield)令牌提取 + +修改或扩展已有项目前,必须先扫描并记录仓库现有设计令牌基线,再定义视觉或组件增量,禁止另起炉灶建立第二套平行样式体系: + +1. **CSS 自定义属性**:扫描 `:root`、`[data-theme]`、`.dark` 及全局/主题样式表中的 `--*` 变量,梳理既有色板、排版、间距、圆角、阴影与语义层映射; +2. **Tailwind 配置与主题变量**:检查 `tailwind.config.*`、`@theme` 块与工具类预设中的扩展颜色、字号、断点和间距刻度; +3. **组件库变体与主题契约**:盘点现有组件库(如 shadcn/ui、Radix、MUI、Ant Design 或项目自有基础组件)已定义的 `variant`、`size`、状态类与主题覆盖方式; +4. **基线登记后写增量**:将扫描所得**存量令牌基线**记入 UX 契约或任务计划(标注来源文件路径与命名约定),新增令牌必须沿用既有层级和命名规范;只有全新项目或仓库确实无令牌体系时,才回退使用内置 `data/tokens/` DTCG 默认参照。 + ## 契约中的用法 -存在仓库设计系统时优先沿用其令牌体系,只定义增量。UX 契约的「视觉与组件增量」用语义令牌表达决策;现有令牌能够表达时禁止写一次性像素值。需要新增令牌时说明层级归属与命名。不为单个功能创建完整设计系统。 +存在仓库设计系统时优先沿用其令牌体系,先完成存量令牌提取再定义增量。UX 契约的「视觉与组件增量」用语义令牌表达决策;现有令牌能够表达时禁止写一次性像素值。需要新增令牌时说明层级归属与命名。不为单个功能创建完整设计系统。 ## 数据资产与用法 diff --git a/skills/scd-uiux/references/visual-evidence.md b/skills/scd-uiux/references/visual-evidence.md index 1191720..e31726f 100644 --- a/skills/scd-uiux/references/visual-evidence.md +++ b/skills/scd-uiux/references/visual-evidence.md @@ -25,16 +25,15 @@ 清晰的局部变更按上表直接交付增量说明,不强制两阶段。 -## 从环境中选择工具 +## 默认零歧义原型载体与工具选择 -用户已有设计来源时直接使用。否则选择成本最低且能让决策可评审的工具: +为避免设计交接落入模糊草图或一次性不可复用静态图,本技能规定两阶段默认载体;外部设计工具(Figma、Stitch、Excalidraw 等)可作为可选上游来源,但不强制指定供应商,且外链不能成为唯一视觉交付: -- 用图表或线框图表达结构; -- 用静态视觉稿比较视觉方案; -- 协作编辑重要时使用 Figma 或其他可编辑设计工具; -- 必须练习响应式行为或交互时使用本地 HTML 原型。 - -不强制指定供应商。不要仅为创建原型而加入生产框架。外部工具链接只能作为来源;前端需要使用的稳定渲染结果必须进入项目版本管理。 +- **低保真默认载体(单文件纯灰度 HTML 线框)**:用于结构与层级讨论后的低保真阶段,采用纯灰度、无配色、无装饰阴影的单文件 HTML 线框,专注信息架构、分节层级、真实文案(禁止 lorem ipsum)与三视口重排(1440px / 768px / 390px),确认即冻结结构参考; +- **高保真与交互原型默认载体(令牌驱动的状态切换条 HTML 原型)**:在 `.scd/ux//prototype/` 下产出可运行的非生产 HTML 原型,样式全部基于三层 DTCG CSS Custom Properties(原始/语义/组件层,见[设计令牌](design-tokens.md)),并内嵌轻量角落**状态切换条(State Switcher)**,支持一键切换 `loading`、`empty`、`error`、`success`、`dark`、`mobile` 状态(按需补充权限、部分成功等已触发状态): + - 评审、自审与 `scripts/dom-audit.mjs` 量化探测可直接在真实浏览器中切换各状态、暗色主题与窄屏布局,无需靠多张静态图脑补; + - 交付生产实施时,原型中的三层 DTCG CSS 自定义属性令牌可直接无损搬入生产样式层,同时保持原型目录本身为非生产文件; +- **外部工具作为可选上游来源**:用户或团队已有 Figma、Stitch、Excalidraw 等设计资产时直接复用其作为上游来源,但必须把前端实施所需的稳定渲染导出(及适用的令牌/HTML 原型)纳入项目版本管理;不要仅为创建原型而引入生产框架。 ## 建立视觉 ID 与项目结构 diff --git a/skills/scd-uiux/references/visual-quality.md b/skills/scd-uiux/references/visual-quality.md index 3d9b0c0..cc24929 100644 --- a/skills/scd-uiux/references/visual-quality.md +++ b/skills/scd-uiux/references/visual-quality.md @@ -8,7 +8,7 @@ UIUX 设计、QuickDev 的真实页面差异及 `scd-ui-polish` 共用本参考 优先沿用已确认的视觉稿、设计系统和品牌约束。需要探索方向且可联网时,实际查看 1–3 个相近产品或内容密度的优秀作品,记录来源和具体借鉴点;不能只列奖项名称。无法查看时注明未完成外部对标,仍可依据已确认来源工作,不虚构参考或获奖结论。 -在现有记录中简述统一方向:气质、排版、色彩与对比、布局与留白,以及一个与内容相关的辨识点。清晰局部修改继承现有方向,只说明增量,不扩大成整体改版、完整设计系统或装饰性动效。 +在现有记录中简述统一方向:产品形态轨道(**展示/营销/内容型 Web** 或 **高密度工具/工作台型 Web App**,见[设计品味](design-taste.md))、气质、排版、色彩与对比、布局与留白,以及一个与内容相关的辨识点。清晰局部修改继承现有方向与轨道,只说明增量,不扩大成整体改版、完整设计系统或装饰性动效。 ## 修改前基线与视口 @@ -20,27 +20,29 @@ UIUX 设计、QuickDev 的真实页面差异及 `scd-ui-polish` 共用本参考 ## 八维检查 +八维阈值区分两套产品形态轨道(**展示/营销/内容型 Web** vs **高密度工具/工作台型 Web App**),同时严守全部共用硬底线: + | 维度 | 阈值与检查方向 | 高频反模式 | |---|---|---| -| typography / 排版 | 标题、正文和辅助信息层级;字体气质、字重、字号、行高、行长与中英文混排。正文行长 45–75ch;行高正文约 1.5、大标题不超过 1.25;UI 用一族字体,编辑内容可用衬线,代码等宽;h1 每页一次且不跳级。 | 标题只是加粗正文;灰上灰;正文小于 12px。 | -| whitespace / 留白 | 一致的间距、对齐、分组和阅读节奏。间距走 4px 基数阶梯;外距大于内距(容器边距 > 元素间隙 > 元素内边距);相关元素靠得更近。不机械放大所有间距,消除无意义空洞。 | 机械放大所有间距;拥挤的垂直节奏。 | -| visual_hierarchy / 视觉层级 | 首屏主题、阅读焦点、内容顺序、主次操作与区块关系。每节一个焦点;主次操作在尺寸或权重上可区分;分节构图有意变化。 | 等权重卡片并排;整页居中;同一行式重复。 | -| color / 色彩 | 背景、文字、强调色、状态色职责清晰且一致。正文对比至少 4.5:1、大字至少 3:1;一个主色至多一个强调色;不只依赖颜色传达状态。 | 纯黑压纯白;强调色彩虹;灰上灰。 | -| motion / 动效 | 用于状态、注意力或空间关系,节奏一致且流畅;检查减少动态效果偏好。无需动效时记录理由,不为过表添加动画。 | 一个时长包打所有过渡;动画 width/height;无减少动态效果适配。 | -| micro_interaction / 微交互 | 实际操作按钮、链接、表单、导航与展开组件;核对适用的 hover、focus、active、disabled、loading 及反馈。触控目标至少 44×44px 且相邻间距至少 8px;禁止 0ms 突变。 | 仅 hover 的交互;移除焦点环。 | -| responsive / 响应式 | 布局重排、字号、间距、图片裁切、导航与阅读顺序;检查溢出、遮挡和触控区域。基础样式即窄屏布局,宽屏逐层叠加。 | 桌面等比缩小;桌面优先再补窄屏。 | -| originality / 辨识度 | 用符合产品内容的构图、排版、素材和细节形成特点;不偏离已确认视觉语言。 | emoji 当图标;单侧彩色边条;模板化装饰。 | +| typography / 排版 | 标题、正文和辅助信息层级;字体气质、字重、字号、行高、行长与中英文混排。展示/营销型大标题 ≥ 2.5x 正文;高密度工具/工作台型允许紧凑标题层级(1.35x–1.75x 保护首屏信息密度)并配数值等宽对齐。共用硬底线:正文 ≥ 12px、正文行长 45–75ch、行高约 1.5、大标题 ≤ 1.25、h1 每页一次且不跳级。 | 标题只是同号加粗正文;h1 重复或跳级;灰上灰;正文小于 12px。 | +| whitespace / 留白 | 一致的间距、对齐、分组和阅读节奏。间距走 4px 基数阶梯;外距大于内距(容器边距 > 元素间隙 > 元素内边距);相关元素靠得更近。展示型保留慷慨宏观留白,工作台型允许高密度分组但须保持清晰区块边界。 | 机械放大所有间距;展示型拥挤垂直节奏;工作台粘连堆叠。 | +| visual_hierarchy / 视觉层级 | 首屏主题、阅读焦点、内容顺序、主次操作与区块关系。展示/营销型每节一焦点、非对称构图且分节有意变化;高密度工具/工作台型允许合理等权重 KPI 指标卡、定价格与数据网格,以主指标高亮、状态色阶与区块标题建立扫描序。 | 展示型等权重卡片机械并排/整页居中/同一行式重复;工作台大横幅挤占首屏主工作区。 | +| color / 色彩 | 背景、文字、强调色、状态色职责清晰且一致。共用硬底线:正文对比至少 4.5:1、大字至少 3:1;一个主色至多一个强调色;不只依赖颜色传达状态。 | 纯黑压纯白;强调色彩虹;灰上灰。 | +| motion / 动效 | 用于状态、注意力或空间关系,节奏一致且流畅;共用硬底线:必须适配 `prefers-reduced-motion`。无需动效时记录理由,不为过表添加动画。 | 一个时长包打所有过渡;动画 width/height;无减少动态效果适配。 | +| micro_interaction / 微交互 | 实际操作按钮、链接、表单、导航与展开组件;核对适用的 hover、focus、active、disabled、loading 及反馈。共用硬底线:触控目标至少 44×44px 且相邻间距至少 8px;可见焦点与键盘可达;禁止 0ms 突变。 | 仅 hover 的交互;移除焦点环;无障碍名称缺失。 | +| responsive / 响应式 | 布局重排、字号、间距、图片裁切、导航与阅读顺序;共用硬底线:无页面级水平溢出、遮挡和不可按触控区。展示/营销及通用 Web 遵循移动优先(宽屏 `min-width` 叠加);纯桌面专业工作台允许桌面优先,但须明确并验证窄屏可用或优雅降级策略。 | 桌面等比缩小;页面水平溢出;展示站桌面优先再补窄屏;工作台窄屏无降级直接错乱裁断。 | +| originality / 辨识度 | 用符合产品内容的构图、排版、素材和细节形成特点;不偏离已确认视觉语言;共用硬底线:图片完整无断链、图标语义清晰。 | emoji 当图标;单侧彩色边条;模板化装饰;断链图片。 | -八维都要考虑;未触发维度记录 `N/A` 和具体原因。无视觉变更或无关区域不得借此扩展修改范围。生成侧完整禁令以[设计品味](design-taste.md)的反模式黑名单为准;黑名单命中计入对应维度 `FAIL`,不以风格偏好辩解。 +八维都要考虑;未触发维度记录 `N/A` 和具体原因。无视觉变更或无关区域不得借此扩展修改范围。生成侧完整分轨禁令以[设计品味](design-taste.md)的反模式黑名单为准;命中共用硬底线或所选轨道黑名单计入对应维度 `FAIL`,不以风格偏好辩解。 ## 双视角自审 -八维证据齐备后,再做一次整体判断,两个视角各出一句结论并写入轮次记录: +八维证据齐备后,再做一次整体判断,两个视角各出一句结论并写入轮次记录(**规范审先用脚本测客观硬底线,工作室主审再以多模态看图做设计判断**): -- **规范审**:可用性、一致性、无障碍与状态完备是否有证据缺口——缺角按对应维度 `FAIL` 处理(无障碍底线见[Web 平台设计原则](platform-principles.md))。 -- **工作室主审**:这个界面有没有一个观点?哪个要素在领导?是否像模板产物?(对照[设计品味](design-taste.md)黑名单与辨识度维度。) +- **规范审**:先在真实渲染页面执行零依赖 DOM 量化探测脚本 `skills/scd-uiux/scripts/dom-audit.mjs`(通过 `node /scripts/dom-audit.mjs --print-snippet` 获取浏览器自包含片段并在 `page.evaluate(...)` 或浏览器控制台运行,或对结构化快照调用 `auditSnapshot()`),客观检测 7 类硬底线缺陷:`horizontal_overflow`(水平溢出)、`small_body_text`(`<12px` 文本)、`small_touch_target`(`<44px` 触控区)、`heading_hierarchy`(多 `h1` 或跳级)、`missing_accessible_name`(缺 `alt` 或无文本交互控件缺可访问名)、`broken_image`(断链图)与 `low_contrast`(WCAG 对比度不足);同时核对键盘顺序、焦点与状态完备(无障碍底线见[Web 平台设计原则](platform-principles.md))。脚本命中未解决告警或存在证据缺口时,按对应维度 `FAIL` 处理。 +- **工作室主审**:结合真实渲染截图与交互观察做多模态主观主审——这个界面有没有一个观点?哪个要素在领导?是否贴合所选产品形态轨道,还是像模板产物?(对照[设计品味](design-taste.md)对应轨道黑名单与辨识度维度。) -主审意见不强制修改,但必须记录"接受/拒绝+理由";只报八维不报双视角的自审不完整。 +主审意见不强制修改,但必须记录"接受/拒绝+理由";只报八维不报双视角、或跳过规范审 DOM 量化探测与截图复核的自审不完整。 ## 有限自审与修正 diff --git a/skills/scd-uiux/scripts/dom-audit.mjs b/skills/scd-uiux/scripts/dom-audit.mjs new file mode 100644 index 0000000..39b8af5 --- /dev/null +++ b/skills/scd-uiux/scripts/dom-audit.mjs @@ -0,0 +1,748 @@ +#!/usr/bin/env node +// scd-uiux 浏览器 DOM 量化探测脚本:零依赖 ESM 模块。 +// 既可在 Node 中通过 auditSnapshot(snapshot) 对结构化快照做确定性审计, +// 也可通过 --print-snippet 输出自包含浏览器片段,直接传入 page.evaluate(...) 或浏览器控制台。 + +import fs from "node:fs"; +import path from "node:path"; +import process from "node:process"; +import { pathToFileURL } from "node:url"; + +export const AUDIT_RULES = Object.freeze([ + "horizontal_overflow", + "small_body_text", + "small_touch_target", + "heading_hierarchy", + "missing_accessible_name", + "broken_image", + "low_contrast", +]); + +/** + * 解析 CSS 颜色字符串,支持 #rgb / #rgba / #rrggbb / #rrggbbaa / rgb() / rgba() / transparent。 + * 返回归一化对象 { r, g, b, a }(r/g/b 为 0..255,a 为 0..1),无法解析时返回 null。 + */ +export function parseColor(input) { + if (input && typeof input === "object") { + const { r, g, b, a = 1 } = input; + if ( + Number.isFinite(r) && + Number.isFinite(g) && + Number.isFinite(b) && + Number.isFinite(a) + ) { + return { + r: Math.min(255, Math.max(0, r)), + g: Math.min(255, Math.max(0, g)), + b: Math.min(255, Math.max(0, b)), + a: Math.min(1, Math.max(0, a)), + }; + } + return null; + } + + if (typeof input !== "string") return null; + const raw = input.trim().toLowerCase(); + if (!raw) return null; + if (raw === "transparent") return { r: 0, g: 0, b: 0, a: 0 }; + + if (raw.startsWith("#")) { + const hex = raw.slice(1); + if (!/^[0-9a-f]+$/.test(hex)) return null; + if (hex.length === 3 || hex.length === 4) { + const r = parseInt(hex[0] + hex[0], 16); + const g = parseInt(hex[1] + hex[1], 16); + const b = parseInt(hex[2] + hex[2], 16); + const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1; + return { r, g, b, a }; + } + if (hex.length === 6 || hex.length === 8) { + const r = parseInt(hex.slice(0, 2), 16); + const g = parseInt(hex.slice(2, 4), 16); + const b = parseInt(hex.slice(4, 6), 16); + const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1; + return { r, g, b, a }; + } + return null; + } + + const fnMatch = raw.match(/^rgba?\(\s*([^)]+)\s*\)$/); + if (!fnMatch) return null; + + const body = fnMatch[1].trim(); + let rgbParts; + let alphaRaw = null; + + if (body.includes(",")) { + const parts = body.split(",").map((part) => part.trim()); + if (parts.length !== 3 && parts.length !== 4) return null; + rgbParts = parts.slice(0, 3); + if (parts.length === 4) alphaRaw = parts[3]; + } else { + const slashParts = body.split("/").map((part) => part.trim()); + if (slashParts.length > 2) return null; + rgbParts = slashParts[0].split(/\s+/).filter(Boolean); + if (rgbParts.length !== 3) return null; + if (slashParts.length === 2) alphaRaw = slashParts[1]; + } + + const numPattern = /^[+-]?(?:\d+\.?\d*|\.\d+)%?$/; + const channels = []; + for (const token of rgbParts) { + if (!numPattern.test(token)) return null; + const isPercent = token.endsWith("%"); + const value = Number.parseFloat(token); + if (!Number.isFinite(value)) return null; + const scaled = isPercent ? (value / 100) * 255 : value; + channels.push(Math.min(255, Math.max(0, scaled))); + } + + let alpha = 1; + if (alphaRaw !== null) { + if (!numPattern.test(alphaRaw)) return null; + const isPercent = alphaRaw.endsWith("%"); + const value = Number.parseFloat(alphaRaw); + if (!Number.isFinite(value)) return null; + alpha = Math.min(1, Math.max(0, isPercent ? value / 100 : value)); + } + + return { r: channels[0], g: channels[1], b: channels[2], a: alpha }; +} + +/** + * Porter-Duff source-over 合成:将半透明前景叠加在背景之上。 + */ +export function compositeOver(foreground, background) { + const fg = parseColor(foreground); + const bg = parseColor(background); + if (!fg || !bg) return null; + const outA = fg.a + bg.a * (1 - fg.a); + if (outA <= 0) return { r: 0, g: 0, b: 0, a: 0 }; + return { + r: (fg.r * fg.a + bg.r * bg.a * (1 - fg.a)) / outA, + g: (fg.g * fg.a + bg.g * bg.a * (1 - fg.a)) / outA, + b: (fg.b * fg.a + bg.b * bg.a * (1 - fg.a)) / outA, + a: outA, + }; +} + +/** + * 按 WCAG 2.1 sRGB 定义计算相对亮度 L ∈ [0, 1]。 + */ +export function relativeLuminance(input) { + const color = parseColor(input); + if (!color) return null; + const linearize = (channel) => { + const s = channel / 255; + return s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4); + }; + return ( + 0.2126 * linearize(color.r) + + 0.7152 * linearize(color.g) + + 0.0722 * linearize(color.b) + ); +} + +/** + * 按 WCAG 2.1 计算前景色与有效背景色的对比度(1..21)。 + * 若前景色或背景色含透明度,按白色画布基准先合成再计算。 + */ +export function contrastRatio(foreground, background) { + const fg = parseColor(foreground); + const bg = parseColor(background); + if (!fg || !bg) return null; + const canvas = { r: 255, g: 255, b: 255, a: 1 }; + const effectiveBg = bg.a < 1 ? compositeOver(bg, canvas) : bg; + const effectiveFg = fg.a < 1 ? compositeOver(fg, effectiveBg) : fg; + const l1 = relativeLuminance(effectiveFg); + const l2 = relativeLuminance(effectiveBg); + if (l1 === null || l2 === null) return null; + const lighter = Math.max(l1, l2); + const darker = Math.min(l1, l2); + return (lighter + 0.05) / (darker + 0.05); +} + +function parsePx(value) { + if (typeof value === "number") return Number.isFinite(value) ? value : null; + if (typeof value === "string") { + const parsed = Number.parseFloat(value); + return Number.isFinite(parsed) ? parsed : null; + } + return null; +} + +function isBoldWeight(weight) { + if (typeof weight === "number") return Number.isFinite(weight) && weight >= 700; + if (typeof weight === "string") { + const normalized = weight.trim().toLowerCase(); + if (normalized === "bold" || normalized === "bolder") return true; + const parsed = Number.parseFloat(normalized); + return Number.isFinite(parsed) && parsed >= 700; + } + return false; +} + +/** + * 对结构化 DOM 快照执行确定性硬底线审计,检测 7 类客观缺陷。 + */ +export function auditSnapshot(snapshot, options = {}) { + const { + minFontSizePx = 12, + minTouchTargetPx = 44, + minNormalContrast = 4.5, + minLargeContrast = 3.0, + } = options; + + const data = snapshot && typeof snapshot === "object" ? snapshot : {}; + const counts = { + horizontal_overflow: 0, + small_body_text: 0, + small_touch_target: 0, + heading_hierarchy: 0, + missing_accessible_name: 0, + broken_image: 0, + low_contrast: 0, + }; + const issues = []; + + const pushIssue = (issue) => { + counts[issue.rule] += 1; + issues.push(issue); + }; + + // 1. horizontal_overflow:页面水平溢出(scrollWidth > clientWidth) + const viewport = data.viewport && typeof data.viewport === "object" ? data.viewport : null; + if (viewport) { + const clientWidth = parsePx(viewport.clientWidth); + const scrollWidth = parsePx(viewport.scrollWidth); + if ( + clientWidth !== null && + scrollWidth !== null && + clientWidth > 0 && + scrollWidth > clientWidth + ) { + const overflowPx = Math.round((scrollWidth - clientWidth) * 100) / 100; + pushIssue({ + rule: "horizontal_overflow", + dimension: "responsive", + severity: "error", + selector: "document.documentElement", + message: `页面存在水平溢出:scrollWidth (${scrollWidth}px) > clientWidth (${clientWidth}px),超出 ${overflowPx}px`, + actual: { scrollWidth, clientWidth, overflowPx }, + expected: { maxScrollWidth: clientWidth }, + }); + } + } + + // 2. small_body_text & 7. low_contrast:可见文本字号与 WCAG 对比度 + const textNodes = Array.isArray(data.textNodes) ? data.textNodes : []; + for (const node of textNodes) { + if (!node || node.visible === false) continue; + const text = typeof node.text === "string" ? node.text.trim() : ""; + if (!text) continue; + const selector = node.selector || "(unknown-text)"; + const textPreview = text.length > 48 ? `${text.slice(0, 48)}…` : text; + const fontSize = parsePx(node.fontSize); + + if (fontSize !== null && fontSize > 0 && fontSize < minFontSizePx) { + pushIssue({ + rule: "small_body_text", + dimension: "typography", + severity: "error", + selector, + message: `可见文本字号过小:${fontSize}px < ${minFontSizePx}px(“${textPreview}”)`, + actual: { fontSize, textPreview }, + expected: { minFontSize: minFontSizePx }, + }); + } + + const ratio = contrastRatio(node.color, node.backgroundColor); + if (ratio !== null) { + const bold = isBoldWeight(node.fontWeight); + const isLargeText = + fontSize !== null && + (fontSize >= 24 || (bold && fontSize >= (14 * 96) / 72 - 0.01)); + const minRatio = isLargeText ? minLargeContrast : minNormalContrast; + if (ratio < minRatio) { + const roundedRatio = Math.round(ratio * 100) / 100; + pushIssue({ + rule: "low_contrast", + dimension: "color", + severity: "error", + selector, + message: `文本对比度不足:${roundedRatio}:1 < ${minRatio}:1(${isLargeText ? "大字" : "正文"},“${textPreview}”)`, + actual: { + ratio: roundedRatio, + color: node.color, + backgroundColor: node.backgroundColor, + fontSize, + fontWeight: node.fontWeight ?? null, + isLargeText, + textPreview, + }, + expected: { minRatio }, + }); + } + } + } + + // 3. small_touch_target & 5b. missing_accessible_name(交互控件) + const interactiveElements = Array.isArray(data.interactiveElements) + ? data.interactiveElements + : []; + for (const el of interactiveElements) { + if (!el || el.visible === false) continue; + const selector = el.selector || el.tag || "(unknown-control)"; + const width = parsePx(el.width); + const height = parsePx(el.height); + + if ( + width !== null && + height !== null && + (width < minTouchTargetPx || height < minTouchTargetPx) + ) { + pushIssue({ + rule: "small_touch_target", + dimension: "micro_interaction", + severity: "error", + selector, + message: `交互控件触控目标过小:${width}×${height}px(要求至少 ${minTouchTargetPx}×${minTouchTargetPx}px)`, + actual: { width, height }, + expected: { minWidth: minTouchTargetPx, minHeight: minTouchTargetPx }, + }); + } + + const tag = String(el.tag || "").toLowerCase(); + const inputType = String(el.type || "").toLowerCase(); + const valueAsName = + tag === "input" && + (inputType === "submit" || inputType === "button" || inputType === "reset") + ? el.value + : ""; + const nameCandidates = [ + el.ariaLabelledByText, + el.ariaLabel, + el.labelText, + el.text, + valueAsName, + el.title, + ]; + const hasAccessibleName = nameCandidates.some( + (candidate) => typeof candidate === "string" && candidate.trim().length > 0, + ); + if (!hasAccessibleName) { + pushIssue({ + rule: "missing_accessible_name", + kind: "interactive_missing_name", + dimension: "micro_interaction", + severity: "error", + selector, + message: `交互控件缺少可访问名称(无可见文本、aria-label、aria-labelledby 或关联 label)`, + actual: { tag: tag || null, role: el.role || null }, + expected: { accessibleNameRequired: true }, + }); + } + } + + // 4. heading_hierarchy:多个 h1 或标题层级跳级(如 h1 直接跳到 h3) + const headings = Array.isArray(data.headings) + ? data.headings.filter( + (h) => + h && + h.visible !== false && + Number.isInteger(h.level) && + h.level >= 1 && + h.level <= 6, + ) + : []; + const h1Headings = headings.filter((h) => h.level === 1); + if (h1Headings.length > 1) { + pushIssue({ + rule: "heading_hierarchy", + kind: "multiple_h1", + dimension: "typography", + severity: "error", + selector: h1Headings.map((h) => h.selector || "h1").join(", "), + message: `页面存在 ${h1Headings.length} 个 h1 标题,每页应至多保留一个主 h1`, + actual: { + h1Count: h1Headings.length, + selectors: h1Headings.map((h) => h.selector || "h1"), + }, + expected: { maxH1Count: 1 }, + }); + } + + let prevLevel = null; + for (const heading of headings) { + if (prevLevel !== null && heading.level > prevLevel + 1) { + pushIssue({ + rule: "heading_hierarchy", + kind: "skipped_level", + dimension: "typography", + severity: "error", + selector: heading.selector || `h${heading.level}`, + message: `标题层级跳级:从 h${prevLevel} 直接跳到 h${heading.level}`, + actual: { previousLevel: prevLevel, level: heading.level }, + expected: { maxNextLevel: prevLevel + 1 }, + }); + } + prevLevel = heading.level; + } + + // 5a. missing_accessible_name(信息性图片)& 6. broken_image(断链图片) + const images = Array.isArray(data.images) ? data.images : []; + for (const img of images) { + if (!img || img.visible === false) continue; + const selector = img.selector || "img"; + const role = String(img.role || "").trim().toLowerCase(); + const isDecorative = + img.ariaHidden === true || + img.ariaHidden === "true" || + role === "presentation" || + role === "none"; + + if (!isDecorative) { + const altText = typeof img.alt === "string" ? img.alt.trim() : ""; + const ariaLabel = typeof img.ariaLabel === "string" ? img.ariaLabel.trim() : ""; + const labelledBy = + typeof img.ariaLabelledByText === "string" ? img.ariaLabelledByText.trim() : ""; + if (!altText && !ariaLabel && !labelledBy) { + pushIssue({ + rule: "missing_accessible_name", + kind: "image_missing_alt", + dimension: "micro_interaction", + severity: "error", + selector, + message: `信息性图片缺少有效 alt 文本或可访问名称(装饰性图片请显式标记 aria-hidden="true" 或 role="presentation")`, + actual: { src: img.src ?? null, alt: img.alt ?? null }, + expected: { altOrDecorativeMarker: true }, + }); + } + } + + if ( + img.complete === true && + typeof img.naturalWidth === "number" && + img.naturalWidth === 0 + ) { + pushIssue({ + rule: "broken_image", + dimension: "visual_hierarchy", + severity: "error", + selector, + message: `检测到断链图片:complete 为 true 且 naturalWidth 为 0(src: ${img.src || "(空)"})`, + actual: { + src: img.src ?? null, + complete: true, + naturalWidth: img.naturalWidth, + naturalHeight: img.naturalHeight ?? null, + }, + expected: { minNaturalWidth: 1 }, + }); + } + } + + const rulesTriggered = Object.keys(counts).filter((rule) => counts[rule] > 0); + return { + ok: issues.length === 0, + url: data.url ?? null, + viewport, + summary: { + status: issues.length === 0 ? "PASS" : "FAIL", + totalIssues: issues.length, + rulesTriggered, + }, + counts, + issues, + }; +} + +function stripExport(fn) { + return fn.toString().replace(/^export\s+/, ""); +} + +/** + * 完整自包含的浏览器可执行函数源码字符串: + * 可直接传入 Playwright/Puppeteer page.evaluate(BROWSER_AUDIT_SNIPPET) 或粘贴至浏览器控制台运行。 + */ +export const BROWSER_AUDIT_SNIPPET = `(() => { + ${stripExport(parseColor)} + ${stripExport(compositeOver)} + ${stripExport(relativeLuminance)} + ${stripExport(contrastRatio)} + ${stripExport(parsePx)} + ${stripExport(isBoldWeight)} + ${stripExport(auditSnapshot)} + + const SKIP_TAGS = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "SVG", "HEAD", "META", "LINK", "TITLE"]); + + function selectorOf(el) { + if (!el || !el.tagName) return "(unknown)"; + let sel = el.tagName.toLowerCase(); + if (el.id) sel += "#" + el.id; + const rawClass = typeof el.className === "string" ? el.className : ""; + const classes = rawClass.trim().split(/\\s+/).filter(Boolean).slice(0, 2); + if (classes.length) sel += "." + classes.join("."); + return sel; + } + + function isStyleVisible(el, win) { + let current = el; + while (current && current.nodeType === 1) { + const style = win.getComputedStyle(current); + if (!style) return false; + if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") return false; + const opacity = Number.parseFloat(style.opacity); + if (Number.isFinite(opacity) && opacity <= 0) return false; + current = current.parentElement; + } + return true; + } + + function isElementVisible(el, win) { + if (!el || !el.getBoundingClientRect) return false; + if (!isStyleVisible(el, win)) return false; + const style = win.getComputedStyle(el); + const rect = el.getBoundingClientRect(); + if (!rect || rect.width <= 0 || rect.height <= 0) return false; + if (rect.width <= 1 && rect.height <= 1 && style.overflow === "hidden") return false; + return true; + } + + function resolveEffectiveBackground(el, win) { + const layers = []; + let current = el; + while (current && current.nodeType === 1) { + const style = win.getComputedStyle(current); + const parsed = style ? parseColor(style.backgroundColor) : null; + if (parsed && parsed.a > 0) { + layers.push(parsed); + if (parsed.a >= 0.999) break; + } + current = current.parentElement; + } + let resolved = { r: 255, g: 255, b: 255, a: 1 }; + for (let i = layers.length - 1; i >= 0; i -= 1) { + resolved = compositeOver(layers[i], resolved) || resolved; + } + return \`rgb(\${Math.round(resolved.r)}, \${Math.round(resolved.g)}, \${Math.round(resolved.b)})\`; + } + + function resolveAriaLabelledBy(el, doc) { + const raw = el.getAttribute && el.getAttribute("aria-labelledby"); + if (!raw || !doc.getElementById) return ""; + return raw + .trim() + .split(/\\s+/) + .map((id) => { + const ref = doc.getElementById(id); + return ref && ref.textContent ? ref.textContent.trim() : ""; + }) + .filter(Boolean) + .join(" "); + } + + function resolveFormLabel(el, doc) { + if (el.labels && el.labels.length > 0) { + const joined = Array.from(el.labels) + .map((label) => (label.textContent || "").trim()) + .filter(Boolean) + .join(" "); + if (joined) return joined; + } + if (el.id && doc.querySelector) { + const escaped = el.id.replace(/["\\\\]/g, "\\\\$&"); + const matched = doc.querySelector(\`label[for="\${escaped}"]\`); + if (matched && matched.textContent && matched.textContent.trim()) { + return matched.textContent.trim(); + } + } + const parentLabel = el.closest ? el.closest("label") : null; + return parentLabel && parentLabel.textContent ? parentLabel.textContent.trim() : ""; + } + + function collectAccessibleText(el) { + const ownText = (el.innerText ?? el.textContent ?? "").trim(); + if (ownText) return ownText; + if (el.querySelectorAll) { + const imgs = Array.from(el.querySelectorAll("img[alt]")); + const alts = imgs.map((img) => (img.getAttribute("alt") || "").trim()).filter(Boolean); + if (alts.length) return alts.join(" "); + } + return ""; + } + + function collectSnapshot(doc, win) { + const docEl = doc.documentElement; + const body = doc.body; + const viewport = { + clientWidth: docEl ? docEl.clientWidth : 0, + scrollWidth: Math.max(docEl ? docEl.scrollWidth : 0, body ? body.scrollWidth : 0), + clientHeight: docEl ? docEl.clientHeight : 0, + scrollHeight: Math.max(docEl ? docEl.scrollHeight : 0, body ? body.scrollHeight : 0), + }; + + const textNodes = []; + const allElements = doc.querySelectorAll ? Array.from(doc.querySelectorAll("*")) : []; + for (const el of allElements) { + if (!el.tagName || SKIP_TAGS.has(el.tagName.toUpperCase())) continue; + if (!isElementVisible(el, win)) continue; + const directText = Array.from(el.childNodes || []) + .filter((node) => node.nodeType === 3) + .map((node) => node.nodeValue || "") + .join(" ") + .trim(); + if (!directText) continue; + const style = win.getComputedStyle(el); + textNodes.push({ + selector: selectorOf(el), + text: directText, + fontSize: parsePx(style.fontSize), + fontWeight: style.fontWeight, + color: style.color, + backgroundColor: resolveEffectiveBackground(el, win), + visible: true, + }); + } + + const interactiveSelector = [ + "button", + "a[href]", + 'input:not([type="hidden"])', + "select", + "textarea", + "summary", + '[role="button"]', + '[role="link"]', + '[role="checkbox"]', + '[role="radio"]', + '[role="switch"]', + '[role="tab"]', + '[role="menuitem"]', + ].join(", "); + const interactiveElements = []; + const interactiveList = doc.querySelectorAll ? Array.from(doc.querySelectorAll(interactiveSelector)) : []; + for (const el of interactiveList) { + if (!isElementVisible(el, win)) continue; + const rect = el.getBoundingClientRect(); + interactiveElements.push({ + selector: selectorOf(el), + tag: el.tagName ? el.tagName.toLowerCase() : "", + role: (el.getAttribute && el.getAttribute("role")) || null, + type: (el.getAttribute && el.getAttribute("type")) || "", + width: Math.round(rect.width * 100) / 100, + height: Math.round(rect.height * 100) / 100, + text: collectAccessibleText(el), + ariaLabel: (el.getAttribute && el.getAttribute("aria-label")) || "", + ariaLabelledByText: resolveAriaLabelledBy(el, doc), + labelText: resolveFormLabel(el, doc), + value: typeof el.value === "string" ? el.value : "", + title: (el.getAttribute && el.getAttribute("title")) || "", + visible: true, + }); + } + + const headings = []; + const headingList = doc.querySelectorAll + ? Array.from(doc.querySelectorAll('h1, h2, h3, h4, h5, h6, [role="heading"]')) + : []; + for (const el of headingList) { + if (!isElementVisible(el, win)) continue; + const tag = el.tagName ? el.tagName.toLowerCase() : ""; + let level = /^h[1-6]$/.test(tag) + ? Number.parseInt(tag.slice(1), 10) + : Number.parseInt((el.getAttribute && el.getAttribute("aria-level")) || "", 10); + if (!Number.isInteger(level) || level < 1 || level > 6) continue; + headings.push({ + selector: selectorOf(el), + level, + text: (el.textContent || "").trim(), + visible: true, + }); + } + + const images = []; + const imageList = doc.querySelectorAll ? Array.from(doc.querySelectorAll('img, [role="img"]')) : []; + for (const el of imageList) { + const isImgTag = el.tagName && el.tagName.toLowerCase() === "img"; + const isBrokenImg = isImgTag && Boolean(el.complete) && typeof el.naturalWidth === "number" && el.naturalWidth === 0; + if (!(isElementVisible(el, win) || (isBrokenImg && isStyleVisible(el, win)))) continue; + const hiddenAttr = el.getAttribute && el.getAttribute("aria-hidden") === "true"; + const hiddenAncestor = Boolean(el.closest && el.closest('[aria-hidden="true"]')); + images.push({ + selector: selectorOf(el), + tag: el.tagName ? el.tagName.toLowerCase() : "img", + src: (el.getAttribute && el.getAttribute("src")) || el.currentSrc || null, + hasAltAttr: Boolean(el.hasAttribute && el.hasAttribute("alt")), + alt: el.getAttribute ? el.getAttribute("alt") : null, + ariaLabel: (el.getAttribute && el.getAttribute("aria-label")) || "", + ariaLabelledByText: resolveAriaLabelledBy(el, doc), + ariaHidden: hiddenAttr || hiddenAncestor, + role: (el.getAttribute && el.getAttribute("role")) || "", + complete: isImgTag ? Boolean(el.complete) : false, + naturalWidth: isImgTag && typeof el.naturalWidth === "number" ? el.naturalWidth : null, + naturalHeight: isImgTag && typeof el.naturalHeight === "number" ? el.naturalHeight : null, + visible: true, + }); + } + + return { + url: win.location && win.location.href ? win.location.href : null, + viewport, + textNodes, + interactiveElements, + headings, + images, + }; + } + + return auditSnapshot(collectSnapshot(document, window)); +})()`; + +function usage() { + return [ + "用法:", + " node dom-audit.mjs --print-snippet 输出自包含浏览器 DOM 探测代码片段", + " node dom-audit.mjs --snapshot 对结构化 DOM 快照 JSON 运行量化审计", + ].join("\n"); +} + +function main() { + const argv = process.argv.slice(2); + if (argv.includes("--help") || argv.includes("-h")) { + console.log(usage()); + process.exit(0); + } + + if (argv.includes("--print-snippet")) { + console.log(BROWSER_AUDIT_SNIPPET); + process.exit(0); + } + + const snapshotIndex = argv.indexOf("--snapshot"); + if (snapshotIndex !== -1) { + const target = argv[snapshotIndex + 1]; + if (!target) { + console.error("缺少 --snapshot 文件路径\n" + usage()); + process.exit(2); + } + const raw = + target === "-" + ? fs.readFileSync(0, "utf8") + : fs.readFileSync(path.resolve(target), "utf8"); + const snapshot = JSON.parse(raw); + const result = auditSnapshot(snapshot); + console.log(JSON.stringify(result, null, 2)); + process.exit(result.ok ? 0 : 1); + } + + console.error(usage()); + process.exit(2); +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href +) { + main(); +} diff --git a/tests/dom-audit.test.mjs b/tests/dom-audit.test.mjs new file mode 100644 index 0000000..e53947b --- /dev/null +++ b/tests/dom-audit.test.mjs @@ -0,0 +1,568 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import vm from "node:vm"; + +import { + AUDIT_RULES, + BROWSER_AUDIT_SNIPPET, + auditSnapshot, + compositeOver, + contrastRatio, + parseColor, +} from "../skills/scd-uiux/scripts/dom-audit.mjs"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const scriptPath = path.join(root, "skills", "scd-uiux", "scripts", "dom-audit.mjs"); + +function makeCleanSnapshot() { + return { + url: "http://localhost:3000/workspace", + viewport: { + clientWidth: 1440, + scrollWidth: 1440, + clientHeight: 900, + scrollHeight: 1600, + }, + textNodes: [ + { + selector: "h1.page-title", + text: "运营工作台", + fontSize: 24, + fontWeight: 600, + color: "#0f172a", + backgroundColor: "#ffffff", + }, + { + selector: "p.body-copy", + text: "正文内容清晰易读,对比度达标。", + fontSize: 14, + fontWeight: 400, + color: "#1e293b", + backgroundColor: "#ffffff", + }, + { + selector: "p.large-muted", + text: "24px 大号标题适用 3.0:1 阈值", + fontSize: 24, + fontWeight: 400, + color: "#949494", + backgroundColor: "#ffffff", + }, + { + selector: "p.large-bold-muted", + text: "14pt 粗体同样适用 3.0:1 阈值", + fontSize: 18.67, + fontWeight: 700, + color: "#949494", + backgroundColor: "#ffffff", + }, + ], + interactiveElements: [ + { + selector: "button.primary-submit", + tag: "button", + width: 120, + height: 44, + text: "保存配置", + }, + { + selector: "button.icon-close", + tag: "button", + width: 44, + height: 44, + text: "", + ariaLabel: "关闭抽屉", + }, + { + selector: "button.icon-delete", + tag: "button", + width: 44, + height: 44, + text: "", + ariaLabelledByText: "删除当前条目", + }, + { + selector: "input#email", + tag: "input", + type: "email", + width: 260, + height: 44, + labelText: "工作邮箱", + }, + { + selector: "input.submit-btn", + tag: "input", + type: "submit", + width: 96, + height: 44, + value: "立即提交", + }, + ], + headings: [ + { selector: "h1.page-title", level: 1, text: "运营工作台" }, + { selector: "h2.kpi-section", level: 2, text: "核心指标" }, + { selector: "h3.kpi-sub", level: 3, text: "近七日趋势" }, + { selector: "h2.table-section", level: 2, text: "任务列表" }, + ], + images: [ + { + selector: "img.hero-diagram", + src: "/assets/architecture.png", + alt: "系统数据流架构图", + complete: true, + naturalWidth: 800, + naturalHeight: 450, + }, + { + selector: "img.decor-dots", + src: "/assets/dots.svg", + alt: "", + ariaHidden: true, + complete: true, + naturalWidth: 24, + naturalHeight: 24, + }, + { + selector: "img.decor-divider", + src: "/assets/divider.svg", + alt: "", + role: "presentation", + complete: true, + naturalWidth: 120, + naturalHeight: 2, + }, + ], + }; +} + +test("parseColor and contrastRatio implement WCAG 2.1 across hex, rgb and rgba formats", () => { + assert.deepEqual(parseColor("#000"), { r: 0, g: 0, b: 0, a: 1 }); + assert.deepEqual(parseColor("#fff"), { r: 255, g: 255, b: 255, a: 1 }); + assert.deepEqual(parseColor("#2563EB"), { r: 37, g: 99, b: 235, a: 1 }); + assert.deepEqual(parseColor("rgb(15, 23, 42)"), { r: 15, g: 23, b: 42, a: 1 }); + assert.deepEqual(parseColor("rgba(15, 23, 42, 0.5)"), { + r: 15, + g: 23, + b: 42, + a: 0.5, + }); + assert.deepEqual(parseColor("rgb(15 23 42 / 50%)"), { + r: 15, + g: 23, + b: 42, + a: 0.5, + }); + assert.deepEqual(parseColor("transparent"), { r: 0, g: 0, b: 0, a: 0 }); + assert.equal(parseColor("not-a-color"), null); + assert.equal(parseColor("#12"), null); + + assert.equal(Math.round(contrastRatio("#000", "#fff") * 100) / 100, 21); + assert.equal(Math.round(contrastRatio("#fff", "#fff") * 100) / 100, 1); + + const passNormal = contrastRatio("#767676", "#ffffff"); + const failNormal = contrastRatio("#777777", "#ffffff"); + assert.ok(passNormal >= 4.5, `expected #767676 on #fff >= 4.5, got ${passNormal}`); + assert.ok(failNormal < 4.5, `expected #777777 on #fff < 4.5, got ${failNormal}`); + + const semiOverWhite = contrastRatio("rgba(0, 0, 0, 0.5)", "#ffffff"); + assert.ok(semiOverWhite > 3.9 && semiOverWhite < 4.0, `got ${semiOverWhite}`); + + const blended = compositeOver("rgba(0, 0, 0, 0.5)", "#ffffff"); + assert.equal(Math.round(blended.r), 128); +}); + +test("auditSnapshot returns ok: true with zero alerts on a clean compliant snapshot", () => { + const result = auditSnapshot(makeCleanSnapshot()); + assert.equal(result.ok, true); + assert.equal(result.summary.status, "PASS"); + assert.equal(result.summary.totalIssues, 0); + assert.deepEqual(result.summary.rulesTriggered, []); + assert.deepEqual(result.issues, []); + for (const rule of AUDIT_RULES) { + assert.equal(result.counts[rule], 0, rule); + } +}); + +test("auditSnapshot detects rule 1: horizontal_overflow (positive and negative)", () => { + const snap = makeCleanSnapshot(); + snap.viewport = { clientWidth: 390, scrollWidth: 428 }; + const result = auditSnapshot(snap); + assert.equal(result.ok, false); + assert.equal(result.counts.horizontal_overflow, 1); + assert.equal(result.issues[0].rule, "horizontal_overflow"); + assert.equal(result.issues[0].actual.overflowPx, 38); + + snap.viewport = { clientWidth: 390, scrollWidth: 390 }; + assert.equal(auditSnapshot(snap).ok, true); +}); + +test("auditSnapshot detects rule 2: small_body_text (positive and negative)", () => { + const snap = makeCleanSnapshot(); + snap.textNodes.push( + { + selector: "span.tiny-caption", + text: "超小辅助说明", + fontSize: 10.5, + fontWeight: 400, + color: "#1e293b", + backgroundColor: "#ffffff", + }, + { + selector: "span.hidden-tiny", + text: "不可见元素不误报", + fontSize: 9, + fontWeight: 400, + color: "#1e293b", + backgroundColor: "#ffffff", + visible: false, + }, + { + selector: "span.boundary-ok", + text: "12px 合法下限", + fontSize: 12, + fontWeight: 400, + color: "#1e293b", + backgroundColor: "#ffffff", + }, + ); + const result = auditSnapshot(snap); + assert.equal(result.ok, false); + assert.equal(result.counts.small_body_text, 1); + assert.equal(result.issues[0].selector, "span.tiny-caption"); +}); + +test("auditSnapshot detects rule 3: small_touch_target (positive and negative)", () => { + const snap = makeCleanSnapshot(); + snap.interactiveElements.push( + { + selector: "button.too-short", + tag: "button", + width: 60, + height: 32, + text: "筛选", + }, + { + selector: "a.too-narrow", + tag: "a", + width: 28, + height: 44, + text: "详情", + }, + { + selector: "button.exact-44", + tag: "button", + width: 44, + height: 44, + text: "确定", + }, + ); + const result = auditSnapshot(snap); + assert.equal(result.ok, false); + assert.equal(result.counts.small_touch_target, 2); + assert.deepEqual( + result.issues.map((i) => i.selector), + ["button.too-short", "a.too-narrow"], + ); +}); + +test("auditSnapshot detects rule 4: heading_hierarchy (multiple h1 and skipped levels)", () => { + const multiH1 = makeCleanSnapshot(); + multiH1.headings = [ + { selector: "h1.first", level: 1, text: "主标题一" }, + { selector: "h2.sub", level: 2, text: "分节" }, + { selector: "h1.second", level: 1, text: "主标题二" }, + ]; + const r1 = auditSnapshot(multiH1); + assert.equal(r1.ok, false); + assert.equal(r1.counts.heading_hierarchy, 1); + assert.equal(r1.issues[0].kind, "multiple_h1"); + + const skipped = makeCleanSnapshot(); + skipped.headings = [ + { selector: "h1.main", level: 1, text: "主标题" }, + { selector: "h3.jumped", level: 3, text: "跳级三级标题" }, + ]; + const r2 = auditSnapshot(skipped); + assert.equal(r2.ok, false); + assert.equal(r2.counts.heading_hierarchy, 1); + assert.equal(r2.issues[0].kind, "skipped_level"); + assert.equal(r2.issues[0].selector, "h3.jumped"); +}); + +test("auditSnapshot detects rule 5: missing_accessible_name for informative images and controls while skipping decorative images", () => { + const snap = makeCleanSnapshot(); + snap.images.push( + { + selector: "img.no-alt", + src: "/chart.png", + alt: null, + complete: true, + naturalWidth: 400, + naturalHeight: 200, + }, + { + selector: "img.blank-alt-non-decor", + src: "/chart-2.png", + alt: "", + complete: true, + naturalWidth: 400, + naturalHeight: 200, + }, + { + selector: "img.role-none-decor", + src: "/bg.svg", + alt: null, + role: "none", + complete: true, + naturalWidth: 16, + naturalHeight: 16, + }, + ); + snap.interactiveElements.push( + { + selector: "button.nameless-icon", + tag: "button", + width: 44, + height: 44, + text: "", + ariaLabel: "", + }, + { + selector: "input.unlabelled-text", + tag: "input", + type: "text", + width: 200, + height: 44, + value: "已有输入值不等于可访问名称", + }, + ); + + const result = auditSnapshot(snap); + assert.equal(result.ok, false); + assert.equal(result.counts.missing_accessible_name, 4); + assert.deepEqual( + result.issues.map((i) => i.selector).sort(), + [ + "button.nameless-icon", + "img.blank-alt-non-decor", + "img.no-alt", + "input.unlabelled-text", + ], + ); +}); + +test("auditSnapshot detects rule 6: broken_image (complete && naturalWidth === 0)", () => { + const snap = makeCleanSnapshot(); + snap.images.push( + { + selector: "img.broken-banner", + src: "/missing.png", + alt: "产品横幅", + complete: true, + naturalWidth: 0, + naturalHeight: 0, + }, + { + selector: "img.still-loading", + src: "/loading.png", + alt: "加载中图片", + complete: false, + naturalWidth: 0, + naturalHeight: 0, + }, + ); + + const result = auditSnapshot(snap); + assert.equal(result.ok, false); + assert.equal(result.counts.broken_image, 1); + assert.equal(result.issues[0].selector, "img.broken-banner"); +}); + +test("auditSnapshot detects rule 7: low_contrast for normal and large text thresholds", () => { + const snap = makeCleanSnapshot(); + snap.textNodes.push( + { + selector: "p.weak-body", + text: "低对比正文", + fontSize: 14, + fontWeight: 400, + color: "#777777", + backgroundColor: "#ffffff", + }, + { + selector: "p.non-bold-19", + text: "19px 非粗体仍需 4.5:1", + fontSize: 19, + fontWeight: 400, + color: "#949494", + backgroundColor: "#ffffff", + }, + { + selector: "h2.weak-large", + text: "24px 大字低于 3.0:1", + fontSize: 24, + fontWeight: 600, + color: "#969696", + backgroundColor: "#ffffff", + }, + ); + + const result = auditSnapshot(snap); + assert.equal(result.ok, false); + assert.equal(result.counts.low_contrast, 3); + assert.deepEqual( + result.issues.map((i) => i.selector), + ["p.weak-body", "p.non-bold-19", "h2.weak-large"], + ); +}); + +test("BROWSER_AUDIT_SNIPPET has valid syntax and runs end-to-end against a mock browser DOM", () => { + // 语法合法性校验 + assert.doesNotThrow(() => new Function(BROWSER_AUDIT_SNIPPET)); + assert.doesNotThrow(() => new Function(`return (${BROWSER_AUDIT_SNIPPET});`)); + + function createMockEl({ + tagName, + id = "", + className = "", + attrs = {}, + text = "", + style = {}, + rect = { width: 120, height: 48 }, + parentElement = null, + complete = false, + naturalWidth = undefined, + naturalHeight = undefined, + value = "", + }) { + const computed = { + display: "block", + visibility: "visible", + opacity: "1", + overflow: "visible", + fontSize: "14px", + fontWeight: "400", + color: "rgb(30, 41, 59)", + backgroundColor: "rgba(0, 0, 0, 0)", + ...style, + }; + const el = { + nodeType: 1, + tagName: tagName.toUpperCase(), + id, + className, + parentElement, + complete, + naturalWidth, + naturalHeight, + value, + innerText: text, + textContent: text, + childNodes: text ? [{ nodeType: 3, nodeValue: text }] : [], + _computed: computed, + getAttribute: (name) => (Object.hasOwn(attrs, name) ? attrs[name] : null), + hasAttribute: (name) => Object.hasOwn(attrs, name), + getBoundingClientRect: () => rect, + closest: () => null, + querySelectorAll: () => [], + }; + return el; + } + + const bodyEl = createMockEl({ + tagName: "body", + style: { backgroundColor: "rgb(255, 255, 255)" }, + }); + const h1El = createMockEl({ + tagName: "h1", + className: "title", + text: "主标题", + style: { fontSize: "24px", fontWeight: "700", color: "rgb(15, 23, 42)" }, + parentElement: bodyEl, + }); + const h3El = createMockEl({ + tagName: "h3", + className: "skipped", + text: "跳级小标题", + style: { fontSize: "11px", color: "rgb(150, 150, 150)" }, + parentElement: bodyEl, + }); + const badButton = createMockEl({ + tagName: "button", + className: "icon-only", + text: "", + rect: { width: 32, height: 32 }, + parentElement: bodyEl, + }); + const brokenImg = createMockEl({ + tagName: "img", + className: "broken", + attrs: { src: "/404.png" }, + rect: { width: 0, height: 0 }, + complete: true, + naturalWidth: 0, + naturalHeight: 0, + parentElement: bodyEl, + }); + + const mockDocument = { + documentElement: { clientWidth: 390, scrollWidth: 440, clientHeight: 844, scrollHeight: 900 }, + body: { scrollWidth: 440, scrollHeight: 900 }, + getElementById: () => null, + querySelector: () => null, + querySelectorAll: (selector) => { + if (selector === "*") return [bodyEl, h1El, h3El, badButton, brokenImg]; + if (selector.includes("button")) return [badButton]; + if (selector.includes("h1")) return [h1El, h3El]; + if (selector.includes("img")) return [brokenImg]; + return []; + }, + }; + const mockWindow = { + location: { href: "http://localhost:4173/demo" }, + getComputedStyle: (el) => el._computed, + }; + + const audited = vm.runInNewContext(BROWSER_AUDIT_SNIPPET, { + document: mockDocument, + window: mockWindow, + }); + + assert.equal(audited.ok, false); + for (const rule of AUDIT_RULES) { + assert.ok(audited.counts[rule] >= 1, `expected browser snippet to detect ${rule}`); + } +}); + +test("CLI supports --print-snippet and --snapshot stdin evaluation", () => { + const printed = spawnSync(process.execPath, [scriptPath, "--print-snippet"], { + cwd: root, + encoding: "utf8", + }); + assert.equal(printed.status, 0, printed.stderr); + assert.equal(printed.stdout.trim(), BROWSER_AUDIT_SNIPPET.trim()); + assert.doesNotThrow(() => new Function(printed.stdout)); + + const cleanRun = spawnSync(process.execPath, [scriptPath, "--snapshot", "-"], { + cwd: root, + input: JSON.stringify(makeCleanSnapshot()), + encoding: "utf8", + }); + assert.equal(cleanRun.status, 0, cleanRun.stderr); + assert.equal(JSON.parse(cleanRun.stdout).ok, true); + + const badSnap = makeCleanSnapshot(); + badSnap.viewport = { clientWidth: 390, scrollWidth: 450 }; + const badRun = spawnSync(process.execPath, [scriptPath, "--snapshot", "-"], { + cwd: root, + input: JSON.stringify(badSnap), + encoding: "utf8", + }); + assert.equal(badRun.status, 1); + const badReport = JSON.parse(badRun.stdout); + assert.equal(badReport.ok, false); + assert.equal(badReport.counts.horizontal_overflow, 1); +}); diff --git a/tests/uiux-contract.test.mjs b/tests/uiux-contract.test.mjs index ac98dbf..61e110a 100644 --- a/tests/uiux-contract.test.mjs +++ b/tests/uiux-contract.test.mjs @@ -164,3 +164,50 @@ test("the approved uiux specification retains A1 through A9", () => { assert.match(specification, new RegExp(`^- A${index}:`, "m")); } }); + +test("uiux differentiates showcase web and high-density workbench taste tracks with shared guardrails", () => { + const taste = read("skills/scd-uiux/references/design-taste.md"); + + assert.match(taste, /展示\/营销\/内容型 Web/); + assert.match(taste, /高密度工具\/工作台型 Web App/); + assert.match(taste, /2\.5x|2\.5 倍/); + assert.match(taste, /不对称/); + assert.match(taste, /KPI 指标卡/); + assert.match(taste, /定价格/); + assert.match(taste, /数据网格/); + assert.match(taste, /1\.35x–1\.75x/); + assert.match(taste, /移动优先/); + assert.match(taste, /桌面优先/); + assert.match(taste, /窄屏可用或优雅降级策略/); + assert.match(taste, /4\.5:1/); + assert.match(taste, /3:1/); + assert.match(taste, /#000/); + assert.match(taste, /强调色彩虹/); + assert.match(taste, /emoji/); + assert.match(taste, /prefers-reduced-motion/); +}); + +test("uiux requires Brownfield token extraction and unambiguous state-switcher HTML prototype carriers", () => { + const skill = read("skills/scd-uiux/SKILL.md"); + const tokens = read("skills/scd-uiux/references/design-tokens.md"); + const polish = read("skills/scd-ui-polish/SKILL.md"); + const visual = read("skills/scd-uiux/references/visual-evidence.md"); + + for (const doc of [skill, tokens, polish]) { + assert.match(doc, /Brownfield/); + assert.match(doc, /CSS 自定义属性/); + assert.match(doc, /Tailwind/); + assert.match(doc, /组件库变体/); + assert.match(doc, /存量令牌基线/); + } + + assert.match(visual, /纯灰度/); + assert.match(visual, /单文件 HTML 线框/); + assert.match(visual, /三层 DTCG CSS Custom Properties/); + assert.match(visual, /\.scd\/ux\/\/prototype\//); + assert.match(visual, /状态切换条|State Switcher/); + for (const state of ["loading", "empty", "error", "success", "dark", "mobile"]) { + assert.match(visual, new RegExp(`\`${state}\``)); + } + assert.match(visual, /Figma.*Stitch.*Excalidraw/); +}); diff --git a/tests/visual-quality-contract.test.mjs b/tests/visual-quality-contract.test.mjs index d347c86..970e336 100644 --- a/tests/visual-quality-contract.test.mjs +++ b/tests/visual-quality-contract.test.mjs @@ -64,8 +64,45 @@ test("new skill and shared references remain readable in supported installation for (const target of localLinks(path.join(destination, "scd-ui-polish/SKILL.md"))) { assert.ok(fs.existsSync(path.resolve(destination, "scd-ui-polish", target)), `${platform.id}: ${target}`); } + assert.ok( + fs.existsSync(path.join(destination, "scd-uiux/scripts/dom-audit.mjs")), + `${platform.id}: dom-audit.mjs must be present`, + ); } } finally { fs.rmSync(temporary, { recursive: true, force: true }); } }); + +test("visual quality and page acceptance integrate dual-track thresholds and dom-audit norm review", () => { + const quality = fs.readFileSync(path.join(root, "skills", canonical), "utf8"); + const pageAcceptance = fs.readFileSync( + path.join(root, "skills/scd-quickdev/references/page-acceptance.md"), + "utf8", + ); + + assert.match(quality, /展示\/营销\/内容型 Web/); + assert.match(quality, /高密度工具\/工作台型 Web App/); + assert.match(quality, /1\.35x–1\.75x/); + assert.match(quality, /KPI 指标卡/); + assert.match(quality, /桌面优先/); + assert.match(quality, /窄屏可用或优雅降级/); + + for (const doc of [quality, pageAcceptance]) { + assert.match(doc, /dom-audit\.mjs/); + assert.match(doc, /--print-snippet/); + assert.match(doc, /规范审/); + assert.match(doc, /工作室主审/); + for (const rule of [ + "horizontal_overflow", + "small_body_text", + "small_touch_target", + "heading_hierarchy", + "missing_accessible_name", + "broken_image", + "low_contrast", + ]) { + assert.match(doc, new RegExp(rule)); + } + } +});