feat: hero 三拍改一条连续长镜头 + 睿视 landing 收进本仓(含四道门禁) #70

Merged
zhangxiang merged 5 commits from feat/porsche-ui-replica into dev 2026-12-03 23:24:45 +08:00
38 changed files with 3904 additions and 48 deletions
Showing only changes of commit 99eaa8c66a - Show all commits

No files matched your search

+1 -1
View File
@@ -47,7 +47,7 @@
- [ ] `npm run check:contrast` 与 `npm run check:headings` 通过(WCAG 2.1 AA)
- [ ] `npm run lighthouse` 满足 `lhci` 断言(性能/CSP/可访问性预算未回退)
- [ ] `npm run test:security:headers` 通过(若改动涉及响应头、CSP 或部署配置)
- [ ] 文档已同步:`README.md` / `CONTEXT.md` / `CLAUDE.md` / `DESIGN.md` / `PRODUCT.md` 及 `docs/` 下受影响文件;代码注释给出决策佐证来源
- [ ] 文档已同步:`README.md` / `CONTEXT.md` / `AGENTS.md` / `DESIGN.md` / `PRODUCT.md` 及 `docs/` 下受影响文件;代码注释给出决策佐证来源
- [ ] 提交信息符合 Conventional Commits,且每个 commit 是可独立评审的垂直切片
- [ ] 破坏性/共享状态动作(seed 重跑、DB 写入、force push、合并、删分支、部署)已单独取得授权,未夹带在常规变更里
+6 -1
View File
@@ -42,6 +42,9 @@ playwright-traces/
# E2E test results
e2e/test-results/
# landing 门禁(`npm run test:landing`)的独立 outputDir:配置在
# e2e/playwright.landing.config.ts,与主 config 分开以免两次运行的 trace 互相覆盖。
e2e/test-results-landing/
e2e/playwright-report/
e2e/allure-results/
e2e/allure-report/
@@ -313,7 +316,9 @@ findings.md
# Git will track them because they are not in test-results/ or allure-results/
# AGENTS
AGENTS.md
# 2026-12-03:AGENTS.md 转为**受版本跟踪的唯一 agent 文档**(对齐 novavis-desktop:
# 该仓只有 AGENTS.md、无 CLAUDE.md)。此前这里忽略它,导致仓库里唯一受跟踪的 agent
# 文档反而是 CLAUDE.md —— 与 desktop 口径相反,且新人 clone 后拿不到工作流指南。
# dogfood
dogfood-output*/
+3
View File
@@ -1,5 +1,8 @@
{
"!(public)/**/*.{js,jsx,ts,tsx}": [
"eslint --fix"
],
"public/novavis/js/**/*.js": [
"eslint --fix"
]
}
+282 -25
View File
@@ -1,8 +1,245 @@
# CLAUDE.md
# Novalon Website 开发工作流指南
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
本文件定义 AI 代理与开发者在参与本项目时应遵循的标准工作流。核心目标是**在需求清晰、文档一致、测试覆盖的前提下交付可验证的代码变更**。
## Common Commands
## 1. 工作流总览
新功能或复杂变更按以下流水线执行:
```
/入口判断
↓
/grill-with-docs → 需求梳理:在项目语境中通过结构化问答形成文档化共识
↓
/context7 → 官方实践:涉及第三方库 / 框架 / API 时查询官方文档与最佳实践
↓
/to-prd → 需求文档化:将澄清后的需求综合为结构化 PRD (必须包含 mermaid 架构/数据流/时序图)
↓
/to-issues → 任务拆解:按 tracer-bullet 垂直切片将 PRD 拆为独立 Issues
↓
/tdd → TDD 实现:RED-GREEN-REFACTOR 循环逐个实现
↓
/systematic-debugging → 系统调试:遇到 bug 时收集症状→形成假设→验证→修复根因
↓
/verification → 验证门禁:类型检查、Lint、单元测试、E2E、可访问性、Lighthouse
↓
/文档同步 → 更新 README.md / CONTEXT.md / AGENTS.md 及受影响的设计文档
```
## 2. 入口判断
### 2.1 必须使用
- 新功能开发
- 跨模块变更(如同时修改组件、API、测试)
- 涉及数据模型 / API 变更
- 设计 DNA、HSI 架构、四层叙事模型相关的页面重构
### 2.2 建议使用
- 需求不清晰的变更
- 需要多人协作的功能
- 涉及第三方库升级或替换
- 性能优化、可访问性改进等横向改造
### 2.3 可跳过
- 单行修复
- 文档更新(仍需满足「文档同步」要求)
- 配置变更
- 明显的拼写 / 类型错误
## 3. 核心原则
| 原则 | 含义 |
|------|------|
| **不跳步** | 不要在需求不清晰时直接编码(跳过 grill-with-docs)。 |
| **不猜测** | PRD 未形成共识前,不进行任务拆解。 |
| **不偷懒** | TDD 循环中必须先写失败测试再看实现。 |
| **不掩饰** | 遇到 bug 时先诊断根因再修复,不要随机尝试。 |
| **零编造** | 禁止凭空创造 API / 数据结构 / 未经验证的配置。所有产出必须有至少一个可信来源支撑。 |
| **文档同步** | 任何变更必须同步更新相关文档(注释、README.md、CONTEXT.md、AGENTS.md、docs/ 下受影响文件)。 |
| **交叉验证** | 关键决策须从至少两个独立可信源(官方文档 + 既有代码库模式 / 设计规范)比对求证。 |
| **双归零** | 任何错误立即暂停,执行技术归零(定位机理、复现、修复)与管理归零(追溯流程漏洞、更新检查清单)。 |
## 4. 阶段详解
### 4.1 /grill-with-docs — 需求梳理
**目标**:将模糊需求转化为基于项目共享语言的文档化共识。
**必须引用**:
- [CONTEXT.md](CONTEXT.md) — 领域术语表与关键决策
- [AGENTS.md](AGENTS.md) §9 — 命令速查与架构(原 CLAUDE.md 正文,已并入)
- [README.md](README.md) — 项目规划与进度
**输出**:
- 更新后的 `CONTEXT.md`(若引入新术语或变更决策)
- 问题清单与决策记录
**关键问题**:
1. 变更属于哪种页面类型?(首页 / Hub / Spoke / Independent / 详情页)
2. 是否涉及四层叙事模型(Hero → 价值 → 信任 → CTA)调整?
3. 是否引入新的设计令牌、动画或第三方依赖?
4. 是否需要同步更新跨页面链接(产品 ↔ 方案 ↔ 服务)?
### 4.2 /context7 — 官方实践
**目标**:在涉及第三方库 / 框架 / API 时,获取官方文档与最佳实践。
**触发条件**:
- 使用新依赖(如 Radix UI、Framer Motion、Zod、Prisma 的新特性)
- Next.js App Router、React Server Components、API Routes 相关变更
- Tailwind CSS、shadcn/ui 组件模式变更
**输出**:
- 引用来源清单
- 关键 API 用法示例
- 与项目现有模式的差异说明
### 4.3 /to-prd — 需求文档化
**目标**:将澄清后的需求综合为结构化 PRD。
**PRD 必须包含**:
- 背景与目标
- 范围与不在范围内
- 用户故事或验收标准
- 受影响的页面 / 组件 / API / 数据模型
- 设计约束(品牌红、动效四原则、Mobile First、standalone 混合渲染下「API/ISR 需 Node 运行时、图片 unoptimized」等)
- 风险与依赖
- 验证方式
### 4.4 /to-issues — 任务拆解
**目标**:按 tracer-bullet 垂直切片将 PRD 拆为独立可追踪的 Issues。
**切片原则**:
- 每个 Issue 可独立开发、独立测试、独立交付
- 优先完成一条端到端 tracer-bullet(如一个页面的 Hero → 价值 → 信任 → CTA)
- 标注优先级、依赖关系、信源与验证命令
### 4.5 /tdd — TDD 实现
**目标**:RED-GREEN-REFACTOR 循环逐个实现。
**适用层级**:
- 单元测试:工具函数、Hooks、CMS 渲染器、组件行为
- E2E 测试:关键用户路径(导航、表单、Hero 区域可见性)
- 视觉回归:涉及 UI 样式调整的变更
**纪律**:
1. 先写 failing test
2. 用最简单实现让测试通过
3. 重构并确保测试仍通过
### 4.6 /systematic-debugging — 系统调试
**目标**:遇到 bug、测试失败或异常行为时,先诊断根因再修复。
**流程**:
1. 收集症状(日志、截图、复现步骤)
2. 形成假设
3. 最小化验证
4. 修复根因
5. 补充回归测试
## 5. 质量门禁
变更提交前必须通过以下检查:
| 检查项 | 命令 | 通过标准 |
|--------|------|---------|
| 类型检查 | `npm run type-check` | 无类型错误 |
| 代码风格 | `npm run lint` | 0 error(warning 不判红;**实测 105 条**,2026-09-23 最终树复测):55 `no-console`、25 `@typescript-eslint/no-explicit-any`、12 `react-hooks/set-state-in-effect`、10 `@next/next/no-img-element`、1 `@next/next/no-sync-scripts`、1 `@next/next/no-html-link-for-pages`、1 `Unused eslint-disable directive`(死抑制)。分项相加 = 105,口径自洽。**2026-10-08 本树复测**:`npm run lint` EXIT=0、**0 error / 104 warning**(`npm run type-check` 同 EXIT=0)⇒ 本行 105 为 2026-09-23 历史读数,现行权威位在 `docs/development/quality-gates.md`,引用计数须附复算命令 |
| 单元测试 | `npm run test:unit` | 全部通过 |
| 单元覆盖率 | `npm run test:coverage` | 阈值单一真源为 [config/test/jest.config.js](config/test/jest.config.js) 的 `coverageThreshold`(根 `jest.config.js` 仅转发):global 门限 branches 82 / functions 75 / lines 75 / statements 75,**2026-09-23 收尾树复测 134 套件 / 1697 例全通过,EXIT=0,0 条阈值告警**;global 实测 **stmts 85.59 / branch 87.5 / funcs 80.67 / lines 85.59**(目录级:`components/content` 100×4、`components/sections` 72.77/90.79/73.8/72.77、`lib/cms` 91.93/92.77/92.68/91.93)。⚠ global 实测已高于门限 5.6–12.5 个点,棘轮当前偏松,上调须作为独立动作 |
| E2E 测试 | `npm run test` | 全部通过。**但默认 webServer 是 `npm run dev`,16 个 `@critical` GA4 用例(TC-GA4-001..004 × 4 project)在这一轮里是 skipped 而不是 passed**——`NEXT_PUBLIC_GA_MEASUREMENT_ID` 只存在于 `.env.production`,dev 下 `GoogleAnalytics.tsx` 提前返回 null,用例内 `test.skip` 触发(证据 `docs/acceptance/2026-09-21-gates/skipped-tests-final-tree.json`:28 skipped 中该组恰为 16)。故 `npm run test` 绿 **不等于** GA4 覆盖已验证 |
| E2E 测试(产物目标) | `npm run test:e2e:prod` | `E2E_TARGET=production` → harness 新起 `node dist/standalone/server.js`(**不是** `npm run start`;standalone 下 `next start` 不受支持)。那 16 个 GA4 用例只在这里真正断言(2026-09-23 实测:`@smoke\|@critical\|@journey` 排除 2 个写库 spec 后 **92 例通过 / 0 skipped / EXIT=0**)。⚠ **生产响应头不在该 grep 集合里**——它在 `@security`(`security-headers.spec.ts`)下,别把两者混为一谈。**须先自行 `npm run build`(harness 不代跑),且 `postbuild` 须已装配 `dist/static` + `public`** |
| 视觉回归 | `npm run test:visual:all -- --update-snapshots=none`(**只读比对**,不写参照;缺省不带 `--update-snapshots=none` 时 Playwright 会**静默创建**缺失基线) | ⚠ **2026-09-23 最终树实测 EXIT=1,21 失败 / 104 通过,其中 0 例是像素不符**。红因全部是测试装配缺陷(记为 N-15,见 `docs/acceptance/2026-09-23-gates/final-verdict.md` §3 与 `docs/lessons-learned.md` §5.29):10 例基线文件从不存在(`/products/erp-upgrade`、`/about/brand` × 5 project)、10 例死在选择器(`[class*="card"]` 零匹配;`input[type="text"]` 的 `.first()` 命中按设计隐藏的**反垃圾蜜罐**字段)、1 例移动端窄视口按钮不可见。**判读必须分层**:现存参照层面 104 例全绿(含 `/contact` 全页)⇒ 本轮修复无视觉外溢;装配层面转绿需 §5.1 的基线写授权 + 修 N-15 选择器,二者缺一不可。另注:磁盘上 85 张基线 PNG 相对 HEAD 处于 modified(2026-09-22 重生成、未提交),故"绿"依赖未提交状态。**2026-10-08 复核更正**:`git ls-files e2e/visual-snapshots` 现取为 **107 张、全部已入库且工作树干净**,「85 张未提交」不成立(同 `docs/lessons-learned.md:505`),本行原文仅作 2026-09-23 当时的叙述保留。**2026-10-08 同日再更(AUTH-D3 已闭合)**:写入 38 张(25 新 + 13 覆盖,逐张读图追认)后独立只读复跑 **125 passed / 0 failed / EXIT=0**,参照现取 **132 张**(5 project 各 26 + `manual-acceptance/` 2)⇒ 本行的 21 失败 / 104 通过 / 94-31 系列读数全部作废,改以 `docs/acceptance/qa-tracker.md` §9 与 `docs/acceptance/2026-10-08-baselines/attribution.md` 为准。另更正机制描述:**裸 `--update-snapshots`(带旗标不带值)取 `changed`** 而非 `missing`(`node_modules/playwright/lib/program.js:202` 的 `preset`),只写缺失/不符、不重写通过项;「静默创建缺失基线」对应的是**完全不带该旗标**时的缺省 `missing`(`common/index.js:584`)。 |
| 可访问性 | `npm run check:a11y`(= `check:contrast` + `check:headings` + `check:brand-token`) | WCAG AA 通过;`check:a11y` 已并入 `npm run test:all` |
| Landing 门禁 | `npm run test:landing` | 四道门禁(`e2e/landing/{layout,motion,demo,a11y}.spec.ts`,2026-12-03 从 `novavis-authority` 的四个 python 脚本移植):布局几何与焦点 / 渐进生长与 reduced-motion / 首屏剧本与无 JS 降级(四层真实可见性 + 徽标一一对应)/ 结构与全量对比度(同色无条件阻断 + axe critical/serious=0)。**已并入 `test:all`**;独立 config `e2e/playwright.landing.config.ts`(单引擎单 project,串行)。口径与判别性取证见 [docs/landing.md](docs/landing.md) §3 |
| 全量门禁 | `npm run test:all` | type-check + **check:package-keys** + **type-check:e2e** + lint + test:coverage + test:integration:real + check:a11y + **test:landing** + **check:visual** + test:e2e:fast + test:security:headers。⚠ 以 `package.json` 的 `scripts.test:all` 为唯一真源;本行曾漏记后三项,导致 `check:visual` 恒红期间「`test:all` 全绿」的宣称无法被核对(2026-11-26 补齐) |
| 真库集成层 | `npm run test:integration:real` | `config/test/jest.integration.config.js` → `tests-integration/*.itest.ts`,一次性临时 SQLite(`/tmp/novalon-itest.db`),teardown 以 inode+size+mtime 守卫 `prisma/dev.db` 未被写入。原 `test:integration`(跑 mock 版 `src/app/api/**` 路由单测)已改名 `test:integration:mocked`,A-8 的「命名误导」由此收口 |
| 性能 | `npm run lighthouse` | 满足 lhci 断言 |
> ✅ **2026-09-23 最终树数字已回填**:type-check EXIT=0(0 error)、lint EXIT=0(0 error / 105 warning)、`test:coverage` EXIT=0(134 套件 / 1697 例,global 85.56/86.86/80.59/85.56)。本轮另把 **axe 全站节点计数**与 **Lighthouse** 在**装配后的 standalone 产物**上跑通:axe `PASSED=true`(`chromium|firefox × light|dark` 各 34 页,`bgMismatch=0`、`contrastNodes=0`、`violationNodes=0`),Lighthouse 27 次运行断言全通过、**a11y 9/9 URL 均为 100**、对比度与 `aria-required-children` 失败节点 **0**(上一轮为 92-97 分 + 10 个失败节点)。前提是先修掉 N-9:standalone 产物不含 `dist/static`,此前两条门禁是在全站 CSS 404 的裸 HTML 上出数的。另修掉 N-11:`/contact` 的 CSP 违规源自 Zod 的 eval 能力探测,以 `z.config({ jitless: true })` 消除后 Lighthouse best-practices 由「8/9 齐平 + `/contact` 96」变为 **9/9 均为 100**。完整证据、未闭环项与待授权清单见 `docs/acceptance/2026-09-23-gates/final-verdict.md`;另见 `docs/acceptance/2026-09-21-gates/final-tree-results.md` 与 `CONTEXT.md` 决策表末尾新增行。
>
> **axe 节点计数门禁已于本轮落地**(2026-09-23 复核):`check:axe:routes` / `check:axe` 现指向真实存在的 `scripts/accessibility/{crawl-routes,axe-node-count}.mjs`(由 `docs/acceptance/2026-09-21-axe/` 平移而来),判定升级为**退出码** 0 通过 / 1 判红 / 2 清单缺失或 0 条;CI 在 `Jenkinsfile`「♿♿ 全站 axe 节点计数」阶段(仅 `main`)用 `node dist/standalone/server.js` 在专用端口 3100 跑,路由清单 = sitemap ∪ 预渲染产物 ∪ BFS。两条仍**不在** `test:all` 内,本地需手动跑。详见 `docs/testing.md` ⑤ 节与 `docs/development/quality-gates.md` §5。
> 提交信息须符合 Conventional Commits 规范,详见 [docs/development/quality-gates.md](docs/development/quality-gates.md)。
### 5.1 提交流程(PR-First,2026-09-20 对齐 novavis §27)
`dev`/`main` 一律经功能分支 + PR 合入,执行顺序固定:**同步 dev → rebase → push → PR 门禁 → rebase 合并**。
```bash
git fetch origin dev && git rebase origin/dev # ⚠️ 以 origin/dev 为准,本地 dev 可能陈旧
git push -u origin <feature-branch> # 改写历史后仅用 --force-with-lease,禁裸 --force
bash scripts/check-pr-checklist.sh <PR描述文件> # 未通过不得创建 PR
```
- PR 模板:[.gitea/PULL_REQUEST_TEMPLATE.md](.gitea/PULL_REQUEST_TEMPLATE.md);功能分支合并方式选 Gitea 的 **Rebase**(保持线性历史),不选 merge commit。
- 门禁校验模板三节完整(全链路检查 / 测试分层检查 / 质量门禁)+ checklist 子项 ≥ 20 + 描述文件所有子项已勾选。不适用项**仍须勾选**并注明 `N/A:理由`。
- 破坏性/共享状态动作(seed 重跑、DB 写入、force push、合并、删分支、部署)须单独取得授权,不夹带在常规变更里。
## 6. 文档同步清单
任何非单行变更都必须评估并同步更新以下文档:
- [ ] [README.md](README.md) — 规划、进度、技术栈、脚本
- [ ] [CONTEXT.md](CONTEXT.md) — 新增或变更的术语、决策
- [ ] [AGENTS.md](AGENTS.md) §9 — 新命令、架构变化、约束更新
- [ ] 受影响的设计 / 测试 / 部署文档(`docs/` 目录)
- [ ] 代码注释(说明关键决策的佐证来源)
## 7. 循环控制与错误处理
### 7.1 循环检测
若连续步骤出现以下情况,判定为循环风险:
- 输出内容实质性重复(语义相同,仅措辞变化)
- 引用的信源或推理路径与前一步完全相同,且未引入新信息
- 结论已包含在上一轮已知结论集中
### 7.2 退出流程
一旦检测到循环:
1. 立即停止当前推理链,不回退至更早步骤重试。
2. 提取当前已验证的稳定结论。
3. 生成终结性输出,标题为「基于交叉验证的最终结论」。
4. 列出未解决的歧义(不超过 2 条)。
5. 严禁在终结输出后再追加「进一步思考」或「另一种可能」。
### 7.3 双归零
任何错误立即暂停:
- **技术归零**:定位机理、复现、修复。
- **管理归零**:追溯流程漏洞、更新检查清单(如本文件或 `docs/lessons-learned.md`)。
## 8. 关键约束速查
| 约束 | 来源 |
|------|------|
| 渲染模式为 `output: 'standalone'` 混合渲染(`output: 'export'` 已移除并被 standalone 取代):营销页预渲染/ISR,`/api/*` 与 `/admin/*` 需 Node 运行时 | `next.config.mjs:85`、本文件 §9 `Build Output` |
| 静态资源走 Nginx + CDN,`images.unoptimized: true` 是部署形态的要求(无 Node 接管 `/_next/image` 时改回 `false` 会导致图片全量 404) | `next.config.mjs:8-14` |
| `next start`(= `npm run start`/`preview`)在 standalone 下会打 `"next start" does not work with "output: standalone"` 警告;受支持启动方式是 `node dist/standalone/server.js` | `node_modules/next/dist/server/next.js`、本文件 §9 `Build Output` |
| **standalone 产物不自带静态资源**:`next build` 只产出 `dist/standalone/{server.js,dist/server}`,`dist/static` 与 `public` 必须拷入 `dist/standalone/dist/static`、`dist/standalone/public`(镜像由 `Dockerfile:53-57` 的 `COPY` 完成)。本地/CI 直跑 `node dist/standalone/server.js` 前必须执行 `npm run build`(`postbuild` 钩子自动拷贝),否则全站 CSS/JS 404,`check:axe` 会以 `bgMismatch` 报红而 **Lighthouse 仍错误地 exit 0**。复验时换端口——残留 server 会给出修复前的假 404 | `Dockerfile:5-9,53-57`、`docs/acceptance/2026-09-23-gates/final-verdict.md` N-9 |
| 默认 E2E 打 dev server;GA4 与生产头只在 `npm run test:e2e:prod` 下真正断言 | `e2e/playwright.config.ts:130` |
| 品牌红 `#C41E3A` 每页 ≥ 3 处触达点,面积 ≤ 10% | `CONTEXT.md` |
| 动效时长**按类别分档**(AGENTS.md 早期把三档压成一句「180–280ms」,与 `CONTEXT.md:76` 冲突 ⇒ 已按原文改正):入场 **180–280ms**(`--transition-fast`…`--transition-normal`)、hover **150ms**、反馈 **100ms**;且**禁止超过 700ms 的入场动效**(`CONTEXT.md:82`)。缓动统一 `ease-ink` [0.22, 1, 0.36, 1] | `CONTEXT.md` §动效设计四原则 |
| 所有字体使用本地文件,禁止外部字体 CDN | 项目记忆 |
| `experimental.webpackBuildWorker` 必须禁用 | 项目记忆 |
| 组件旧版本归档到 `_archive/`,排除 TypeScript 编译 | 本文件 §9 `Archiving Convention` |
## 9. 命令速查与架构(原 CLAUDE.md 正文,2026-12-03 并入)
> 本节内容原在 `CLAUDE.md`。按 `novavis-desktop` 的口径(该仓只有 `AGENTS.md` 一份 agent 文档、`git ls-files` 无 `CLAUDE.md`),本仓 2026-12-03 收敛为单文档:`AGENTS.md` 是唯一真源,`CLAUDE.md` 已删除。历史文档里对 `CLAUDE.md` 的引用一律改指本文件对应小节。
### Common Commands
```bash
# Development
@@ -58,6 +295,7 @@ npm run test:visual # Visual regression (Desktop Chrome)
npm run test:visual:all # Visual regression (all projects)
npm run test:visual:update # Update visual snapshots
npx playwright test --grep "test name" # Run a single E2E test by name
npm run test:landing # Landing 四道门禁(layout/motion/demo/a11y);独立 config,单引擎串行;已并入 test:all
# ⚠ E2E 目标口径(默认跑的是 dev server,不是产物)
# `npm run test` / `test:functional` 的 webServer 是 `npm run dev`(`e2e/playwright.config.ts:132-135`),
@@ -96,7 +334,7 @@ npm run check:axe # 双引擎(chromium/firefox)×双主题(light/da
# docs/acceptance/2026-09-21-axe/axe-evidence.json。需一个生产服务在 :3100:
# PORT=3100 HOSTNAME=127.0.0.1 node dist/standalone/server.js(先拷 dist/static 与 public,见上文)
# CI 侧由 Jenkinsfile「♿♿ 全站 axe 节点计数」阶段(仅 main)自动串起
npm run test:all # type-check + check:package-keys + type-check:e2e + lint + test:coverage + test:integration:real + check:a11y + check:visual + test:e2e:fast + test:security:headers
npm run test:all # type-check + check:package-keys + type-check:e2e + lint + test:coverage + test:integration:real + check:a11y + test:landing + check:visual + test:e2e:fast + test:security:headers
npm run test:e2e:prod # E2E_TARGET=production(构建产物目标);harness **不代跑构建**,须先 `npm run build`
# (standalone 根目录的 dist/static + public 由 postbuild 自动装配,见上文)
npm run lighthouse # Lighthouse CI(配置 config/test/lighthouserc.json;axe critical/serious 逐条 minScore:1;inspector-issues 亦判红——CSP/弃用类问题只走 DevTools issue 通道,errors-in-console 与 0.9 分类阈值都看不见它;报告落 lighthouse-reports/)
@@ -106,9 +344,9 @@ npm run db:seed # Seed the dev database
npm run db:reset # Reset database with migrations
```
## Architecture
### Architecture
### Tech Stack
#### Tech Stack
- **Next.js 16.3**(App Router)混合渲染 — SSG/ISR 静态页 + API routes;`output: 'standalone'`(`next.config.mjs:44`)、`distDir: 'dist'`(`:46`)。standalone 入口是 `node dist/standalone/server.js`,需另拷 `dist/static` 与 `public`;`npm run start`(= `next start`)在 standalone 下只算不受支持的降级路径,见下文 Build Output
- **中间件命名为 `proxy.ts`**(Next 16 起 `middleware.ts` 更名);其 matcher 排除 `/api/*`,因此每个 API 路由必须自行做鉴权
- **React 18**, **TypeScript 5** (strict mode with `noUncheckedIndexedAccess`)
@@ -117,15 +355,15 @@ npm run db:reset # Reset database with migrations
- **shadcn/ui** pattern (Radix UI + class-variance-authority + tailwind-merge)
- **Prisma** with SQLite for backend data (admin, auth, CMS)
### Path Alias
#### Path Alias
`@/` maps to `src/` — configured in both `tsconfig.json` (`paths`) and `jest.config.js` (`moduleNameMapper`).
### TypeScript Strictness
#### TypeScript Strictness
Beyond `strict: true`, the project enables:
- `noUncheckedIndexedAccess: true` — array/object index access returns `T | undefined`, requiring null checks. This is a significant constraint to be aware of when writing code.
- `noImplicitReturns`, `noFallthroughCasesInSwitch`, `noUnusedLocals`, `noUnusedParameters`
### Route Structure (App Router)
#### Route Structure (App Router)
```
src/app/
├── layout.tsx # Root layout: fonts, metadata, theme, analytics, SEO schemas
@@ -154,10 +392,10 @@ src/app/
└── fonts/ # Local font files (Geist Sans/Mono)
```
### Archiving Convention
#### Archiving Convention
When replacing a page or component with a new version, move the old one to an `_archive/` subdirectory (e.g., `src/app/(marketing)/_archive/` for old homepage iterations). The archive is excluded from TypeScript compilation via `tsconfig.json`.
### Dark Mode
#### Dark Mode
Dark mode uses the `data-theme="dark"` HTML attribute (not Tailwind's `dark:` class). Tailwind is configured with `darkMode: ['variant', '[data-theme="dark"] &']` — use the **variant** form, not `['selector', ...]`, because the selector form is accepted by the config but JIT emits zero `dark:` rules under Turbopack + Next.js 16.
**Three-state preference model** (`src/lib/theme.ts` is the single source of truth):
@@ -171,13 +409,13 @@ Dark mode uses the `data-theme="dark"` HTML attribute (not Tailwind's `dark:` cl
- `src/components/theme/theme-toggle.tsx` cycles `跟随系统 → 浅色 → 深色`. It listens to `matchMedia('(prefers-color-scheme: dark)')` for live OS changes (only effective in the `system` state) and to `storage` events for cross-tab sync.
- `html[data-theme]` is an **output** of preference resolution — never read it back as the user's preference, or the `system` state collapses into `dark` on dark-OS machines and the cycle deadlocks.
### HSI Information Architecture
#### HSI Information Architecture
The site follows a **Hub-Spoke-Independent** model (see `CONTEXT.md` and ADR-0002):
- **Hub**: `/products` — product catalog, split into "企业套装" (6 enterprise products) and "专业产品" (standalone)
- **Spoke**: `/solutions` — industry scenarios, each recommending product combinations from the Hub
- **Independent**: Standalone products in the specialized zone have their own narrative path
### Four-Layer Narrative Model
#### Four-Layer Narrative Model
Every detail page (product/service/solution/standalone) follows the same four-layer structure:
1. **L1 Hero**: Emotional entry with visual, title, value prop, status badge
2. **L2 Value Rationale**: Product-specific — features/benefits for products, pain-points→architecture for solutions, challenges→results for services
@@ -189,7 +427,7 @@ The detail components implementing this live in `src/components/detail/`:
- `solution-value.tsx`, `service-value.tsx` (type-specific L2 variants)
- `detail-cross-recommend.tsx` (cross-links between products↔solutions↔services)
### CMS Content Architecture
#### CMS Content Architecture
`src/lib/cms/` is a **real, server-side CMS layer over Prisma** — there is no mock layer and no client-side CMS SDK (the historical names `mock-home.ts`, `ContentZoneRenderer.tsx`, `component-registry.ts`, `src/components/cms/` do not exist in the tree; do not look for them):
- `types.ts` — `FieldType`/`FieldDefinition`, `ContentModel`, `ContentStatus`, `ContentItem`, `ContentZone`, `ThemeConfig` definitions
- `content-types.ts` — `CONTENT_TYPE_CONFIGS` + `registerAllContentTypes()`: the per-model field schemas the admin form and the validator both read
@@ -199,7 +437,7 @@ The detail components implementing this live in `src/components/detail/`:
The homepage is `src/app/(marketing)/page.tsx` (server component, `export const revalidate = 3600` at `:5`): it resolves the home zones with `getResolvedHomeZones()` (`:8`) and, when the CMS has nothing configured, falls back to per-model `getPublishedItems(...)` calls (`:23-29`); the markup lives in `home-content-v15.tsx`. Earlier documents calling it `home-content-cms.tsx` are stale.
### Design Token System
#### Design Token System
All visual tokens are defined as **CSS custom properties** in `src/app/globals.css` (`:root` block) and mapped into Tailwind's config via `var()` references:
- **Colors**: `--color-ink` (deep charcoal #0A0E14), `--color-brand` (vermilion #C41E3A), accent colors for service-coding (blue, teal, amber, purple), functional colors (success, warning, error, info), dark-section overrides
- **Typography**: `--font-size-*`, `--line-height-*`, `--letter-spacing-*` all mapped to Tailwind's `fontSize`/`lineHeight`/`letterSpacing` scales
@@ -212,7 +450,7 @@ All visual tokens are defined as **CSS custom properties** in `src/app/globals.c
- **Motion tokens are gated, and the gate is currently RED**: `scripts/utils/check-motion-constraints.ts` (`npm run check:motion`, 配套 `npm run check:motion:test`) enforces the `CONTEXT.md` §动效设计四原则 bands (entrance 180–280ms, ≤700ms ceiling, durations must flow through `--transition-*` tokens, bezier allow-list **parsed from the CSS `--ease-*` tokens** — `--ease-out` is an alias of `ease-ink`, and the token layer deliberately carries 5 further curves). It is deliberately **not** part of `check:a11y`: the tree measures 23 violations / 13 files, so wiring it in would make the aggregate permanently red. `scripts/**` is eslint-ignored, so adding it did not move the lint baseline.
### Design DNA Framework
#### Design DNA Framework
The site follows a three-dimensional design system (see `CONTEXT.md`):
- **Dimension 1 — Design System**: Quantifiable tokens (colors, typography, spacing, radius, shadows, motion, components)
- **Dimension 2 — Design Style**: Qualitative perception (atmosphere, visual language, composition, imagery, brand tone)
@@ -224,7 +462,7 @@ The **Consulting Professional** aesthetic (inspired by Accenture + Bain) is the
**Motion design**: Animations are purposeful (not decorative). Durations come from tokens, **not** from a free-form "150-300ms" range — that phrasing conflicted with `CONTEXT.md`「动效设计四原则」and is replaced by its three tiers: **入场 180–280ms**(`--transition-fast: 180ms` … `--transition-normal: 280ms`,`src/app/globals.css:264-265`)· **hover 150ms** · **反馈 100ms**;`--transition-slow: 450ms` / `--transition-slower: 700ms` 只用于揭示型动效。`ease-ink` `[0.22, 1, 0.36, 1]`(`globals.css:280`)为默认缓动,children stagger 30-60ms、Section 间 stagger 100-150ms。No continuous looping animations except `pulse-soft` for skeletons. No spring easings for content entry(spring 仅用于按钮按压反馈). **No entry animations >700ms.** Note that `duration-300` 一类的 Tailwind 预设时长绕过令牌、且 300ms 不属任何档位(残留清点见 `CONTEXT.md`「duration-300 → 动效令牌」行,该项 in flight,勿引用其计数)。
### Data Layer
#### Data Layer
Most structured marketing content is still `src/lib/constants/` TypeScript constants, and the pages render from them; on top of that, published CMS items now override specific slots — the home page's hero/services/cases/stats/news data comes from `lib/cms/data-server` (Prisma) and only falls back to constants when the CMS has nothing configured (`src/app/(marketing)/page.tsx:8-36`), and per-section copy comes from `getHomePageCopy()` with in-component fallbacks. "Marketing content has no database" is therefore no longer true:
- `products.ts` — 6 enterprise products (ERP, CRM, CMS, BI, SDS, OA) + standalone products (NovaVis)
- `services.ts`, `solutions.ts` — Service and solution definitions
@@ -236,16 +474,16 @@ Most structured marketing content is still `src/lib/constants/` TypeScript const
Each product/solution/service implements the `Product`/`Solution`/`Service` interface which includes `caseStudies[]`, `dataProofs[]`, `certifications[]`, etc. for the four-layer narrative.
### Backend Layer (Prisma + API Routes)
#### Backend Layer (Prisma + API Routes)
The project has a backend layer for admin/auth/CMS functionality:
- **Prisma** with SQLite (`prisma/dev.db`) for admin user data, auth, and CMS content management
- API routes at `src/app/api/admin/`, `auth/`, `cms/`, `contact/`
- The marketing read path and the admin write path share this backend: pages fetch published items through `src/lib/cms/data-server.ts`, while `api/admin/*` writes drafts and `api/cms/*` (`draft/enable`, `draft/disable`, `revalidate`) handles preview cache invalidation
### Error Monitoring (Sentry)
#### Error Monitoring (Sentry)
`@sentry/nextjs@10` is wired through `src/instrumentation.ts` (server/edge, incl. `onRequestError`) and `src/instrumentation-client.ts` (client init + `onRouterTransitionStart`); `next.config.mjs` exports `withSentryConfig(nextConfig)`. **This Next 16 build defaults to Turbopack, which never loads the root `sentry.client.config.ts`** — client init therefore lives in `instrumentation-client.ts`, and the old file is kept as an empty stub solely to prevent a double `Sentry.init` on the `--webpack` path. Everything is gated on `NEXT_PUBLIC_SENTRY_DSN`: absent it, `Sentry.init` is skipped, both hooks no-op, **and the CSP is byte-identical** (`connect-src`/`worker-src` only gain the DSN's `protocol//host` when a valid DSN is present, `next.config.mjs:17-26`). Verify "is this inert?" by building without a DSN and diffing the emitted header, not by reading the source.
### Component Organization
#### Component Organization
```
src/components/
├── ui/ # Base: Button, Card, Input, Badge, ScrollReveal, AnimatedCounter, etc.
@@ -260,11 +498,11 @@ src/components/
```
> 口径核对(2026-09-23,验收 N-33「不存在的目录」一项):`cms/`、`providers/`、`effects/` 三个目录在工作树与 `git ls-tree -r HEAD` 中**均不存在**,旧图里的对应条目是残留。`ContentRenderer` / `SectionRenderer` / `FieldRenderer` 三个标识符在 `src/**/*.{ts,tsx}` 中零命中,CMS 区块渲染实际由 `src/components/content/sections.tsx` + `src/lib/cms/` 承担;`effects/` 一族已在提交 `37296b5`(2026-05-10)删除,见 `CONTEXT.md`「特效组件」。
### Testing Setup
#### Testing Setup
- **Jest** (unit): Tests alongside source in `src/**/*.test.{ts,tsx}`, coverage **thresholds** live in `config/test/jest.config.js` (global 75% stmts/lines/funcs, 82% branches) and are the single source of truth — root `jest.config.js` only re-exports it, never duplicate thresholds. **Measured values are recorded in exactly one place: `docs/development/quality-gates.md` §3** (2026-09-23 本树复跑:134 suites / 1697 tests / EXIT=0);该文件顶部注释里的百分比是滞后快照,引用前先复跑。Uses `@/` path alias and ts-jest with `jsx: 'react-jsx'` transform (since tsconfig uses `'preserve'`). Run single tests with `npx jest --testPathPattern="component-name"`.
- **Playwright** (E2E): Tests in `e2e/`, config in `e2e/playwright.config.ts` — run from `cd e2e` (`npm run test` does this). webServer is `HOSTNAME=localhost PORT=3000 node dist/standalone/server.js` when `E2E_TARGET=production` (`e2e/playwright.config.ts:132-135` — build artifacts, real security headers; CI gate uses `npm run test:e2e:prod`, and `npm run build` + the `dist/static` / `public` copies must already exist because the harness never builds) and `npm run dev` otherwise; `reuseExistingServer` is disabled for production targets, so a busy :3000 aborts the run. Functional projects: chromium, chromium-mobile (iPhone 14, 390×844), firefox, webkit — plus 5 visual-regression projects at desktop/tablet/mobile breakpoints; snapshots in `e2e/visual-snapshots/`. `mobile-*.spec.ts` must pin their own viewport because they also execute under the desktop projects. Touch-target gate lives in `e2e/touch-targets.ts` (AA SC 2.5.8 ≥24px hard, AAA SC 2.5.5 44px advisory). Visual snapshots are server-target independent — every spec imports `test` from `e2e/fixtures.ts`, whose `context` fixture injects an init script that removes the `next dev`-only `<nextjs-portal>` devtools indicator (MutationObserver on `document`, because `documentElement` is still null at document start). The indicator's shadow-DOM `<footer class="error-overlay-footer">` is pierced by Playwright's CSS engine and made `locator('footer')` resolve to 2 elements (56 failures). `devIndicators: false` is *not* a fix here — measured: the CSP-blocked-`eval` dev error keeps the overlay mounted, so the portal survives; don't reintroduce that env gate. `visual-regression.spec.ts` additionally pins the cookie-consent state via `addInitScript` (constant timestamp) because the banner renders on a 2 s timer and the `visual-firefox-desktop` / `visual-webkit-desktop` projects use an empty storage state — without the pin, slower engines photograph the banner into the first viewport and faster ones don't (34 engine-specific failures). Client-component interactions must call `expectHydrated()` from `e2e/hydrated.ts` before hover/click — SSR HTML is visible ~1.7 s before React attaches handlers, and pointer events in that window are dropped without replay. Hover-driven UI additionally needs `expect(...).toPass()` re-driving the pointer, because a single `hover()` can land mid-layout-transition and `mouseenter` never re-fires. Run single tests with `npx playwright test --grep "test name"`.
### Build Output
#### Build Output
The project builds to `dist/` (`distDir` in `next.config.mjs:46`) with **`output: 'standalone'`** (`next.config.mjs:44`) — this is a hybrid render model, *not* a static export (`output: 'export'` was dropped and the project has since moved on to standalone; `CONTEXT.md`「生产部署模式」records the 2026-08 switch). Concretely:
- **Prerendered/ISR**: the marketing pages, `privacy`, `terms`, `sitemap.ts`, `robots.ts`.
@@ -273,17 +511,36 @@ The project builds to `dist/` (`distDir` in `next.config.mjs:46`) with **`output
- **Images are unoptimized** (`next.config.mjs:48-61`, value at `:58`) because distribution goes through Nginx + CDN, and flipping it to `false` would require every environment to have a Node runtime taking over `/_next/image` (otherwise every image 404s). The reason is *deployment topology*, not a static-export limitation.
- **Boot command**: `npm run start` / `npm run preview` both run `next start -p 3000`, which Next 16 warns "does not work with output: standalone" (warning only — see the Build & Preview note above). The supported server is `dist/standalone/server.js`; `public/` and `dist/static` are copied into the standalone root **automatically by `package.json:9` 的 `postbuild`**,所以 `npm run build` 之后直接 `node dist/standalone/server.js` 即可。该启动方式仍没有包成 npm script —— CI 在 `Jenkinsfile:353-355` 复用产物时重做同套拷贝,发布侧由 `scripts/deploy.sh:162-175` 把 `public/` 与 `dist/static → dist/_next/static` 同步进 Nginx 站点根。
### Commit Convention
#### Commit Convention
Uses Conventional Commits with commitlint (`@commitlint/config-conventional`). Husky + lint-staged enforces linting on pre-commit.
### Submission Flow (PR-First)
#### Submission Flow (PR-First)
`dev`/`main` are only reached via feature branch + PR: sync `origin/dev` → rebase → push → PR gate → merge by **Rebase** (linear history, no merge commit).
`bash scripts/check-pr-checklist.sh <pr-description-file>` must pass before opening a PR — it verifies `.gitea/PULL_REQUEST_TEMPLATE.md` has the three required sections (全链路检查 / 测试分层检查 / 质量门禁) with ≥20 checklist items, and that every item in the PR body is checked (mark irrelevant ones as `N/A:<reason>`).
Rebase rewrites hashes: an already-pushed branch may only be updated with `--force-with-lease`. Always rebase onto `origin/dev`, never a possibly-stale local `dev`.
### Component Versioning History
#### Component Versioning History
The project has gone through multiple design iterations. Older component versions:
- `components/detail-v2/` — previous iteration (deleted per git status, migration to `detail/` completed)
- `components/detail-v3/` — another iteration (deleted, same reason)
- `home-content-v2.tsx` through `home-content-v11.tsx` — archived homepage iterations in `(marketing)/_archive/`
- The current canonical components are in `components/detail/` and `home-content-cms.tsx`
## 10. 相关资源
- [CONTEXT.md](CONTEXT.md) — 领域术语与关键决策
- [AGENTS.md](AGENTS.md) §9 — 开发命令与架构指南(本文件,单文档真源)
- [README.md](README.md) — 项目概览与进度
- [docs/development/quality-gates.md](docs/development/quality-gates.md) — 质量门禁详情
- [docs/testing.md](docs/testing.md) — 测试策略与指南
- [docs/lessons-learned.md](docs/lessons-learned.md) — 跨任务经验教训
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+2 -1
View File
@@ -323,7 +323,8 @@ Novalon 的 6 个核心产品,互为互补关系,常以组合形式出现在
| **营销面影像整批退役:正文改内容图、首屏纯排版** | 四次否决(矢量条 / 混凝土 / 技术静物 / 首页底图)指向同一件事:**照片不承担语义**——本仓没有真实项目摄影,替代品只能是装饰,而「实施流程 / 企业套装 / 解决方案」说的是关系与阶段。撤除 `hub/**` 4 张、`body/**` 14 张、`home/hero-architecture` 1 张,以及 `ui/hero-plate.tsx`、`ui/editorial-figure.tsx` 两个组件。正文改 `StageIndex`(序号脊线,数据取 `process` / `solutions`)与 `BandIndex`(满幅文字索引带,取方案 / 新闻条目);17 个营销首屏退为纯排版。判据同时掉头:**R22** 由「必须有影像」改为「零影像即判红」(分母 16→17,首页并入且只扫首屏区块),**R23** 改按载体标记判型(分母 9→5,`/cases` 零数据不进表)。⚠ 首屏「排版支点」没有机器判据,只能由视觉基线 + 人工评审兜 | ✅ 2026-12-01(ADR-0011 §8.5 / §8.6;台账 `public/images/LEDGER.md`)|
| **首页首屏右栏:双 V 滚动提示 + 工程网格,持久态底部锚定不转译** | 影像退役后右 4 栏成纯虚空(8 栏骨架是全幅影像时代遗留)。实测保时捷持久态同样 66% 靠左(`c-collageOverlay__textbox` col 1/5),右侧靠视频 + 错位副图 + 双V scroller 兜底;其「居中声明」只是 2–14.3s 开场过场。零影像转译只取第三件:右栏 `DoubleChevron(down)` `text-white/40` **静态**(对标 6s 循环脉冲被禁)+ 复用 `hero-grid-overlay--dark`;移动/md 档 hidden。红不出 eyebrow+主 CTA。**底部对齐 + 贴左缘实块裁定不转译**:其为「错位副图从下方升起」服务,无副图时沉底即失衡 | ✅ 2026-12-02(E 案;台账 §28;attribution `docs/acceptance/2026-12-02-baselines/`)|
| **首页首屏全幅 3D 场景(数据中心走廊,三镜头分镜)** | 用户裁定「做成保时捷那样一组多场景动画」⇒ 首屏改全幅 three.js 场景:S1 走廊纵深 16s / S2 俯视阵列 13s / S3 柜排斜看 13s,镜头间压黑 420ms,一轮 43.26s。E 案退役为**降级层与移动档正选**。三条不改的约束:reduced-motion 定格、<1024px 不跑 WebGL、WebGL 失败静默回落。资产调研结论:高保真机房资产均为 UE/Unity 工程(Fab《Data Center》仅 UE 5.6–5.7),能直接进 three.js 的最高精度是单柜级(EntropyNine 27.8k 面 GLB,CC BY 4.0,需署名),走廊靠实例化拼 | ✅ 2026-12-02(ADR-0016 §1–§12;台账 §31;证据 `docs/acceptance/2026-12-02-hero-scene/`)。同日 **R22 改「视觉层登记制」**(载体白名单 + 海报存在性 + 表过期)、**R26 新增「场景契约」**(周期/定格/离屏停/禁自转)。U5 落地:轮换的是**场景角标**(不改 h1),真源 `lib/constants/hero-scenes.ts`,切镜事件 `hero-scene:shot` |
| **产品独立站化:每条产品线一个独立 landing 站,官网退为入口层** | 用户裁定 ERP 等产品最终都像睿视 NovaVis 一样做独立站。模式四要素(ADR-0014 §2):纯静态零 CDN / 独立子域 `{product}.p.novalon.cn` / 官网导航 = 外链 + 状态徽标(badge 状态机与独立站上线事实强制同步)/ landing 四道门禁 + 生产 CSP 实测(零内联脚本硬约束)。官网镜像 `public/{product}/` 原样拷贝不承担演进;**第二等产品镜像起必须子目录化 + rewrites 前缀映射并回溯睿视**(睿视按源站形态暂占 `/css` `/js` `/assets` 根命名空间)。阶段:睿视 Phase 0 ✅ → ERP Phase 1 → BI/CRM Phase 2 → 其余 Phase 3,入口判据 = 产品事实可验证,非时间表 | ✅ 2026-12-02(ADR-0014;睿视镜像 commit `901e1025`,与源站 novavis.p.novalon.cn 逐字段一致)|
| **产品独立站化:每条产品线一个独立 landing 站,官网退为入口层** | 用户裁定 ERP 等产品最终都像睿视 NovaVis 一样做独立站。模式四要素(ADR-0014 §2):纯静态零 CDN / 独立子域 `{product}.p.novalon.cn` / 官网导航 = 外链 + 状态徽标(badge 状态机与独立站上线事实强制同步)/ landing 四道门禁 + 生产 CSP 实测(零内联脚本硬约束)。官网镜像 `public/{product}/` 原样拷贝不承担演进;**第二等产品镜像起必须子目录化 + rewrites 前缀映射并回溯睿视**。阶段:睿视 Phase 0 ✅ → ERP Phase 1 → BI/CRM Phase 2 → 其余 Phase 3,入口判据 = 产品事实可验证,非时间表 | ✅ 2026-12-02(ADR-0014;睿视镜像 commit `901e1025`,与源站 novavis.p.novalon.cn 逐字段一致)|
| **睿视 landing 由本仓统一管理(含门禁与发布)** | landing 源码 / 四道门禁 / 发布职责**全部在本仓**:源码 `public/novavis/`(9 文件,`index.html` 引用仍是站点级绝对路径),`next.config.mjs` 用 **4 条 prefix rewrite**(`/css` `/js` `/assets` `/images/logos`)映射进子目录 —— 因为子域页面在**根路径**,改绝对路径会把子域首页变成 `/novavis/`。门禁 = `npm run test:landing`(`e2e/landing/{layout,motion,demo,a11y}.spec.ts`,从 authority 的四个 python 脚本移植,**已并入 `test:all`**)。authority 侧已退役 `landing/`、四脚本、Dockerfile `COPY landing`、deploy 阶段六。**「回溯睿视」由待办变已完成先例**:第二等产品照抄「子目录 + 4 条 prefix rewrite + 子域平铺」。细节见 `docs/landing.md` | ✅ 2026-12-03(迁移 + 门禁移植 + authority 退役;判别性取证三处注入均判红)|
| **02b 翻转:桌面端滚动收成白方汉堡 + 左侧抽屉;键盘契约方向改为「正文位置 Shift+Tab 向上」** | 用户裁定翻转 ADR-0012 的「02b 不做」。规格(ADR-0015 §3):`scrollY>20`(仅 `md+`)浮条收窄成 64×64 方块(`md:w-[var(--header-height)]`,**px 令牌**——`w-16` 在 ≥1024 根字号 18px 下漂到 72px)、内联导航/CTA **卸载**(不留焦点幽灵站)、logo `md:hidden`(CSS 级隐藏,明暗双版恒挂载契约不破);抽屉左侧滑入 250ms,`DrawerNavList` 与移动抽屉**同源渲染**完整双轴 + ThemeToggle + CTA。连带修掉一个真缺陷:**带 scroll restoration 的整页刷新不触发 scroll 事件**,页头在滚动位仍显示顶部态——挂载时补一拍同步(`header.tsx` `didMountRef` effect,单测钉住)。⚠ 键盘契约方向的教训:从 body 正向 Tab 的第一站是顶部跳转链接,浏览器为显焦把页面滚回页首、收起态**正确地**撤销——「Tab 到汉堡」在收起态不是可达语义,契约改写为「正文位置 8 次 Shift+Tab 内到达」(页首态正向 Tab 契约原样保留)。判据:`data-header-collapsed` + 浮条 border-box 64×64 + 内联导航 count 0;原 nav-dropdown/nav-keyboard 断言一字未改;移动端 5 spec 69 passed / 7 skipped;基线预测 0 张重采 | ✅ 2026-12-02(ADR-0015;`OPEN-02b` 关闭)|
| **「红不做面」替代色 = 中性面留红点缀;语法棘轮批 3 清零、R13–R17 上限归 0** | ADR-0013 §6 三翻转条件满足后清零批 3 存量 15 处(detail 件 10 + hub 箭头 3 + erp-upgrade 卡片 2)。R16 替代色用户裁定 A 方案:红底面(`bg-brand-soft`/30、`/80`)→ 中性面(`bg-bg-elevated` / `bg-bg-primary/80`),红色降级为 `text-brand-ink` 文字/图标点缀——与 L3 卡片主体、批 2「去面留点」、保时捷「红只点缀」语法一致。归因教训:**11-26 的「95 张/19 页」基线成本口径是静态估算**——R14 两处是 hover 态改动静态零漂移、`l3-signals-slot` 所在首页实际渲染 L3 空态兜底 ⇒ 实写仅 35 张(erp-upgrade-v3 ×5 + services ×12 + solutions ×18,预测==git status)。判据:`check:grammar` 25/25 · R13–R17 实测 0 / 上限 0(棘轮转硬禁)· selftest 双向 · jest 161/1899 · 独立只读复跑 225/0 | ✅ 2026-12-02(ADR-0013 §8;`OPEN-05b` 关闭;attribution `docs/acceptance/2026-12-02-grammar-batch3/`)|
#### 门禁断言的有效性口径(chain6/chain7 新增)
Vendored
+6
View File
@@ -229,6 +229,12 @@ pipeline {
npm run check:brand-token
echo "🧱 标题层级..."
npm run check:headings
echo "🖼️ Landing 四道门禁(布局/动效/剧本降级/结构与对比度)..."
# 2026-12-03:landing 迁入本仓后,四道门禁从 authority 的 python 脚本
# 移植为 e2e/landing/*.spec.ts。放在本 stage 而非 E2E stage:它判的是
# 「页面在真实视口下几何/动效/对比度是否成立」,与可访问性门禁同族;
# 且它自带 webServer(npm run dev),不依赖 E2E stage 先 build 的产物。
npm run test:landing
'''
}
}
+4 -3
View File
@@ -111,7 +111,7 @@ npm run preview # == npm run start == `next start -p 3000`(不是 `npx serv
- `npm run test:e2e:prod` 走的是上面这条受支持路径(`e2e/playwright.config.ts:132-135`),**不是** `next start`。
- `npm run check:headings` 存在产物时直起 standalone,仅在产物缺失时回退 `npm run preview` 并打印告警(`scripts/utils/check-heading-hierarchy.ts:52-67`,验收 N-24③)。
详见 `CLAUDE.md`「Build & Preview」。
详见 `AGENTS.md` §9「Build & Preview」。
## 项目结构
@@ -204,6 +204,7 @@ novalon-website/
| `npm run test:e2e:mobile` | 运行移动端 E2E 测试(`@mobile` 标签:**55 个用例**(16 `mobile.spec.ts` + 5 `mobile-user-journeys.spec.ts` + 14 `mobile-accessibility.spec.ts` + 18 `mobile-performance.spec.ts` + 2 `uj-11-home-conversion.spec.ts`),4 个功能 project 全跑 ⇒ **220 个实例**;`cd e2e && npx playwright test --list --grep @mobile` 实测 `Total: 220 tests in 5 files`) |
| `npm run test:e2e:mobile:performance` | 运行移动端性能基线测试(FCP/LCP/加载时间) |
| `npm run test:e2e:mobile:accessibility` | 运行移动端可访问性测试(axe-core WCAG 2.1 AA) |
| `npm run test:landing` | **睿视 landing 四道门禁**(2026-12-03 从 `novavis-authority` 的四个 python 脚本移植):`e2e/landing/{layout,motion,demo,a11y}.spec.ts` —— 布局几何与焦点 / 渐进生长与 reduced-motion / 首屏剧本与无 JS 降级(四层真实可见性 + 徽标一一对应)/ 结构与全量对比度(同色无条件阻断 + axe critical/serious=0)。独立 config `e2e/playwright.landing.config.ts`(单引擎单 project、串行),现测 **13 passed / EXIT=0(1.4m)**;已并入 `test:all` 与 Jenkins「♿ 可访问性门禁」阶段。口径见 [docs/landing.md](docs/landing.md) §3 |
| `npm run test:mutation` | 运行变异测试(Stryker,评估测试质量)。**分数不在此声明**:全量轮耗时以十分钟计且 `--inPlace` 会改动工作树,本轮未复跑;最近一次落盘记录为整体 **36.98%**(`docs/test-strategy-plan.md` P4.5 / 验收清单条目,2026-08 轮次),引用时须附该出处与 `npm run test:mutation` 复算命令 |
| `npm run test:mutation:quick` | 快速变异测试(`--mutate 'src/lib/utils.ts'`,同一落盘记录 **91.18%**,出处同上) |
| `npm run test:security` | 安全扫描(npm audit + 安全响应头检查) |
@@ -211,7 +212,7 @@ novalon-website/
| `npm run check:a11y` | 可访问性静态门禁伞:`check:contrast`(令牌对比度,只读 `globals.css`)+ `check:headings`(标题层级,有产物直起 standalone、缺产物才回退 preview)+ `check:brand-token`(双通道红) |
| `npm run check:axe:routes` | 生成全站路由清单:sitemap ∪ 预渲染产物 ∪ 站内链接 BFS → `/tmp/axe-routes.xml`(`scripts/accessibility/crawl-routes.mjs`;退出码 0/2) |
| `npm run check:axe` | 双引擎 × 双主题逐页 axe **节点计数** + 三条规则级通道的分母断言(`scripts/accessibility/axe-node-count.mjs`);退出码 0 通过 / 1 判红 / 2 清单缺失。**需先有 `node dist/standalone/server.js` 在 :3100**;不在 `test:all` 内,CI 由 `Jenkinsfile`「♿♿」阶段(仅 main)执行 |
| `npm run test:all` | 全量门禁检查,现取十段:`type-check` + **`check:package-keys`**(JSON 重复键)+ **`type-check:e2e`**(e2e 静态口径)+ `lint` + `test:coverage` + **`test:integration:real`** + `check:a11y` + `check:visual` + fast E2E + security headers;其 E2E 段仍是 dev 目标,GA4 `@critical` 在其中 skipped,需另跑 `test:e2e:prod` |
| `npm run test:all` | 全量门禁检查,现取十一段:`type-check` + **`check:package-keys`**(JSON 重复键)+ **`type-check:e2e`**(e2e 静态口径)+ `lint` + `test:coverage` + **`test:integration:real`** + `check:a11y` + **`test:landing`**(睿视四门禁,2026-12-03 新增)+ `check:visual` + fast E2E + security headers;其 E2E 段仍是 dev 目标,GA4 `@critical` 在其中 skipped,需另跑 `test:e2e:prod` |
| `npm run lighthouse` | 运行 Lighthouse 性能测试 |
## 代码质量门禁
@@ -221,7 +222,7 @@ novalon-website/
- **ESLint**: 代码风格检查(pre-commit 经 husky + lint-staged 跑 `eslint --fix`,CI 跑全仓 `npm run lint`;判定口径 0 error,warning 不判红)
- **commitlint**: 提交信息规范(`.husky/commit-msg`)
- **Jest**: 代码覆盖率检查(阈值单一真源 `config/test/jest.config.js`)
- **可访问性**: `npm run check:a11y`(对比度 / 标题层级 / 双通道红),CI 在「♿ 可访问性门禁」阶段逐条执行同一组
- **可访问性**: `npm run check:a11y`(对比度 / 标题层级 / 双通道红)+ `npm run test:landing`(睿视 landing 的对比度/几何/动效,浏览器内实测),CI 在「♿ 可访问性门禁」阶段逐条执行同一组
- **TypeScript**: `npm run type-check` —— **不在 pre-commit**(`.lintstagedrc.json` 只跑 `eslint --fix`),推送前须自行执行
- **E2E 目标**: `npm run test` 打 dev server;GA4 的 16 个 `@critical` 实例在该轮为 skipped,产物口径见 `npm run test:e2e:prod`(详见 [docs/development/quality-gates.md](docs/development/quality-gates.md) §5–§7)
+115
View File
@@ -2346,3 +2346,118 @@ S1 首版镜头朝下看地板 ⇒ 改为朝走廊深处看,纵深才立起来
取 40 的理由:比 16 档多覆盖一倍纵深(约 26m),又给较弱 GPU 留余量;60 是 vsync 上限,
「60」不代表无上限余量。海报帧重生成 17KB;对比度最低 5.14:1(AA 通过)。
资产出处已登记 `docs/design/asset-provenance.md` §6(含 §5.4 旧判据描述的订正)。
## §32 2026-12-03 · 睿视 landing 由本仓统一管理(源码 + 四门禁 + 发布职责)
承接 §29(2026-12-02 原样迁入)。§29 只搬了**字节**:源码落在 `public/` 根命名空间、
四道门禁仍留在 `novavis-authority` 且**不在任何门禁链里**。本轮把「三件事」一起收进本仓 ——
源码、门禁、发布职责。
### 32.1 源码收敛:`public/novavis/` 子目录 + 4 条 prefix rewrite
9 个文件 `git mv` 到 `public/novavis/{css,js,assets,images/logos}/`,根 `public/{css,js,assets,images/logos}`
清空删除(否则两处同时命中同一前缀,rewrite 不是唯一消费者)。`next.config.mjs` 新增:
```js
{ source: '/novavis', destination: '/novavis/index.html' },
{ source: '/css/:path*', destination: '/novavis/css/:path*' },
{ source: '/js/:path*', destination: '/novavis/js/:path*' },
{ source: '/assets/:path*', destination: '/novavis/assets/:path*' },
{ source: '/images/logos/:path*', destination: '/novavis/images/logos/:path*' },
```
**`index.html` 的引用一个字未改**(仍是 `/css/style.css` 等站点级绝对路径)。理由不是省事:
子域 `novavis.p.novalon.cn` 的 nginx `root /var/www/novavis-landing`,页面在**根路径**;
改绝对路径会把子域首页变成 `novavis.p.novalon.cn/novavis/`。同一份字节要服务两个落点。
实测(dev server,浏览器):`/novavis` 200、`/novavis/` 308→200、四个前缀全部 200、
7 张图全载、零 4xx/5xx、零 pageerror、`document.styleSheets.length === 1`(CSS 真生效)。
### 32.2 四门禁移植为 Playwright spec(并进链)
`e2e/playwright.landing.config.ts` + `e2e/landing/{layout,motion,demo,a11y}.spec.ts`,
`package.json` 注册 `test:landing` 并**插入 `test:all`**(`check:a11y` 之后、`check:visual` 之前)。
全量 13 例 **13 passed / EXIT=0(1.4m)**。
**为什么必须移植而不是留着 python**:那四个脚本在 authority 仓**从未进过任何门禁链**。
本仓已有 `@playwright/test` + `@axe-core/playwright` + `e2e/` harness(含 dev / standalone 双目标),
`page.goto('/novavis')` 直接可用,不需要另起静态服务;而 Jenkins(`agent any`)不保证
`python3 + python-playwright` 存在。
**移植中修掉的三个真缺陷(都是「TS 与 Python 语义不同」而不是判据放宽)**:
1. **`page.evaluate(string)` 不是函数体**。python 绑定的 `evaluate("() => {...}")` 把字符串当函数体,
TS 版把字符串当**表达式**求值 ⇒ 箭头函数被序列化成 `undefined` ⇒
`TypeError: Cannot read properties of undefined (reading 'length')`。改成真函数引用 `readTabInfo`。
2. **viewport 被 project 层盖掉**。`use: { ...devices['Desktop Chrome'], viewport: {1440,900} }` 里
`devices` 自带 1280×720,**展开顺序决定谁赢**;初版 720 高视口下 hero 落在首屏外,
IntersectionObserver 不触发,剧本采样到**空序列**而假失败。修法是 project 层显式覆盖。
3. **分母金丝雀取错变量**。对比度扫描里 `total`(低于判据的条数)在全绿时恒为 0,
拿它当金丝雀会把「没扫到」与「扫到了 423 个且全达标」判成同一个 0。
新增 `scanned`(实际评估元素数)作为分母断言。
另:axe 的 `color-contrast` 会把 `.process-step-number`(01/02/03 水印,作者已标
`data-audit-decorative` ∧ 在 `aria-hidden` 子树内)报成 serious。处置是 `.exclude()` 该选择器
而不是关掉整条规则 —— 排除面越小,假绿空间越小。
### 32.3 判别性取证(三处注入均判红,复原后 `diff` 为零)
| 注入 | 判红输出 |
|---|---|
| `.features .section-title { color: transparent }` | `P1 同色前景/背景 rgb(255,255,255) on rgb(255,255,255)(对比度 1)@32px/700 — #main-content > #features > … > #features-heading «覆盖数据分析全流程»`(三视口全红) |
| `html:not(.js-demo) .nv-home-rows { opacity:0; visibility:hidden }` | `无 JS 时任务行不可见:0/4(内容在、但被 opacity/visibility 藏起来)` |
| `.demo-chrome-badge-item { display:inline-flex !important }` | `step1-create: demo-step-1 应恰好显示 1 个徽标,实测 4 个`(五步全红) |
### 32.4 lint 收口(迁移暴露的既存红)
`public/js/main.js` 有 **6 处** `catch (e)` / `catch (err)` 未使用绑定 ⇒ `@typescript-eslint/no-unused-vars`。
该文件自 `901e1025` 起就在树里,但 `.lintstagedrc.json` 用 `!(public)/**` 把整个 `public/` 排除在
lint 之外,所以从没人看见 —— **而 `npm run lint` 一直是 EXIT=1**。迁移后 landing 进入门禁面,一并修掉:
6 处改 `catch {}`(语义等价),`.lintstagedrc.json` 增 `public/novavis/js/**/*.js`,
`eslint.config.mjs` 忽略 `.next-dev-live/**`(未忽略时 21195 errors,全是构建产物)与 `.workbuddy/**`。
现 `npm run lint` = **0 error / 89 warning / EXIT=0**。
### 32.5 authority 侧退役
删 `landing/`(10 文件)+ 四脚本 + 夹具;`Dockerfile` 去掉 `COPY landing`;
`deploy-prod.sh` 删阶段六并**重编号 7→6**;`selfcheck-gates.sh` 删 P3 探针与随之失效的
`PORT`/`--port`(保留一个无人读取的参数会让「传了却没生效」被当成已配置)。
验证:`selfcheck-gates.sh` **EXIT=0**(跳过 2 项慢探针)、`quality-check-fast.sh` **EXIT=0**。
### 32.6 单 agent 文档收敛(对齐 novavis-desktop)
desktop 仓只有 `AGENTS.md`、`git ls-files` 无 `CLAUDE.md`;本仓恰好相反(`CLAUDE.md` 已入库、
`AGENTS.md` 被 `.gitignore:316` 排除)。结果 clone 下来的人拿不到工作流指南,只有命令手册。
本轮:`CLAUDE.md` 正文并入 `AGENTS.md` §9、删 `CLAUDE.md`、解除 `AGENTS.md` 的忽略、
同步 6 处活文档引用(`README.md` / `docs/testing.md` / `docs/troubleshooting.md` /
`docs/development/quality-gates.md` / `.gitea/PULL_REQUEST_TEMPLATE.md`)。
`next dev` 不会重建 `CLAUDE.md`(`hasCurrentAgentRules()` 命中 `AGENTS.md` 的托管块即返回)——
已实跑确认。
### 32.7 CTA 表单端点断点修复(迁移暴露的第一个真实缺陷)
landing 的 `main.js` 固定 `POST /api/v1/contact`(JSON)且**只认 `data.code === 200`**,
而本仓只有 `/api/contact`(formData + 必填 `subject`、成功判据 `success`)⇒
**官网镜像 `/novavis/` 的表单一提交就 404,永远落进失败兜底**。迁移前没人从官网入口点过它。
处置:新增 `src/app/api/v1/contact/route.ts`(契约匹配的薄适配层),**不改 landing**
(同一份字节要服务两个落点,子域上 authority 的契约就是 JSON + `code:200`)。
`org` 由服务端合成为 `subject`;失败返回 HTTP 200 + `code!==200` 而非 4xx(4xx 会被中间层
替换成 HTML 错误页 ⇒ `res.json()` 抛异常 ⇒ 用户只看到「网络异常」)。
三个坑:
1. **zod 4 的两级消息**:`.min(1, msg)` 只管「存在但为空」,字段**缺失**走构造器参数;
只写 `.min` 会返回英文 `Invalid input: expected string, received undefined`。实测确认。
2. **限流桶污染测试**:进程内单例跨用例共享,第 6 例必 429。测试 `beforeEach` 里 `reset()`。
3. **探针等待窗口**:上游 formsubmit.co 耗时 **5s+**,6s 窗口的首次探针把成功判成失败。
验证:契约测试 **9/9**、`test:coverage` **163 套件 / 1912 例 EXIT=0**、
浏览器端到端(填表 → 提交 → `POST` 200 → `.cta-form-success` 渲染)、
curl 三条校验分支文案正确。
### 32.8 未做(明确不在本轮)
深色主题(landing 现 0 处)、仿真外壳与 desktop 最新 UI 的差距(hero 仍画 `/home` 台账页,
而 desktop 已于 ADR-0437 退役该页)、文案事实核对(`TSV` 导入 / 物流单据 / 监管报送格式 /
4 类原生安装包)、`scripts/deploy.sh landing` 子命令(须先登记 `LANDING_REMOTE_DIR` 与
`docker inspect` 挂载读数,且**未获生产写授权**)。
+12 -2
View File
@@ -49,13 +49,23 @@ Phase 0(睿视 NovaVis)当日落地;其余产品为规划态,**排期未
- **主发布面** = 独立子域(各产品仓库自带 deploy,authority 模式平移)。
- **官网镜像**(`public/{product}/`)= 原样拷贝,不承担内容演进;内容演进只发生在
产品仓库,镜像随阶段手动/CI 同步。作用:官网域内可达、独立站故障兜底。
睿视镜像已落(本轮);`/novavis` 入口 rewrite 见 `next.config.mjs`(Next public 层
睿视镜像已落(2026-12-02);`/novavis` 入口 rewrite 见 `next.config.mjs`(Next public 层
不做目录默认文档补全)。
- **命名空间隔离(硬约定)**:睿视镜像按源站形态占用站点级根命名空间
> **2026-12-03 修订(睿视「产品仓库」即本仓)**:睿视 landing 的源码、四道门禁与发布职责
> 已从 `novavis-authority` **迁入本仓**(`public/novavis/`),故对本产品而言「内容演进只发生
> 在产品仓库」与「镜像原样拷贝」合并为一件事 —— 本仓既是产品仓库也是镜像宿主。
> 其余产品(ERP / BI / CRM / CMS / 供应链 / 协同)仍按「独立仓 → 本仓镜像」的模式。
> 细节见 `docs/landing.md`。
- **命名空间隔离(硬约定)**:睿视镜像**最初**按源站形态占用站点级根命名空间
(`/css` `/js` `/assets` `/images/logos`)。**第二等产品镜像迁入时,必须改用
`public/{product}/` 子目录 + rewrites 前缀映射,并回溯睿视**——两个产品共用
`/css/style.css` 这类无归属路径必然撞车。新产品 landing 从创建起就按
`/assets/{product}/…` 相对子目录组织,可免去这条回溯。
> **2026-12-03 回溯已执行**:睿视 9 个文件已收敛到 `public/novavis/{css,js,assets,images/logos}/`,
> 根命名空间释放;`index.html` 的引用**仍是站点级绝对路径**(子域页面在根路径,不能改),
> 由 `next.config.mjs` 的 4 条 prefix rewrite 映射进子目录。于是本条的「回溯睿视」从
> **待办**变为**已完成先例**:第二等产品可照抄「子目录 + 4 条 prefix rewrite + 子域平铺」
> 这套做法,见 `docs/landing.md` §2。
## 5. 官网侧处置
+48
View File
@@ -601,3 +601,51 @@ mkdir -p dist/_next && cp -R dist/static dist/_next/static && cp -R public/. dis
1. `cmd_rollback` 只恢复 `dist/` 并重载 nginx,**不重建 Next.js 容器** ⇒ 若在新容器已起的情况下回滚,会出现「旧静态资源 + 新服务端代码」的 Server Reference ID 不匹配。正确手工回滚 = 恢复 `dist_backup_*` 后**再**跑一次 `docker-compose -f docker-compose.server.yml build && up -d`。
2. 服务器侧 `docker-compose.server.yml` 仍是旧挂载 `./uploads:/app/uploads`,而仓内版本已改为 `./uploads:/app/public/uploads`(`src/lib/media/storage.ts:141` 的落盘根是 `cwd/public/uploads`)。`deploy.sh` **从不同步 compose 与 Dockerfile**,所以该修复从未生效——现取 `docker inspect novalon-website` 的 Mounts 仍是 `/app/uploads`。影响:后台上传写进容器可写层,重建即丢;宿主 `./uploads` 至今只有两个空目录(`image/`、`document/`),无数据可损。
## 八、睿视 landing 的发布(2026-12-03 迁入本仓后)
**契约变更**:landing 的源码、四道门禁、发布职责**都在本仓**(原在 `novavis-authority`)。
口径详见 [docs/landing.md](landing.md);此处只记发布面。
### 8.1 官网镜像(与主站同一份 `deploy.sh`)
`public/novavis/**` 由 `scripts/deploy.sh` **步骤 1.5** 的 `cp -R public/. dist/` 一并拷进
web root 镜像(该步骤 2026-10-08 事故后已固化,见 §七),因此 `/novavis/` 随官网一起发布,
**不需要新增发布步骤**。四个资源前缀由 `next.config.mjs` 的 prefix rewrite 在 Node 侧解析,
与磁盘布局无关 —— 只要 `public/novavis/` 进了 `dist/`,`/css/style.css` 这类 URL 就能命中。
> 注意:`next build` 只把 `public/` 拷进 `dist/standalone/public`(供容器用),
> **不会**把它拷进 nginx 的 `dist/` 根。§七 的步骤 1.5 才是官网侧的唯一装配点。
### 8.2 子域 `novavis.p.novalon.cn`(独立于官网镜像)
**实测口径(2026-12-03 现取 `docker inspect novalon-nginx-secure`)**:
| 项 | 值 |
|---|---|
| 宿主目录 | `/home/novalon/docker-app/novalon-static` |
| 容器挂载 | `/var/www/novavis-landing`(`:ro`) |
| nginx root | `/var/www/novavis-landing`(`conf.d/novavis-authority.conf:42`) |
| 页面位置 | **根路径**(`index.html` 在目录根) |
同步 = 把 `public/novavis/.` **平铺**到该宿主目录(`index.html` 与 4 个子目录一起落到根):
```bash
# 须显式设置,未设置即拒绝执行(防呆:写错目录 = 覆盖官网根)
: "${LANDING_REMOTE_DIR:?未设置 LANDING_REMOTE_DIR}"
rsync -avz --delete public/novavis/ "$LANDING_REMOTE_DIR"/
```
**`--delete` 是有意的**:authority 旧脚本用 `cp -a` 覆盖式,历史上出现过「仓库里删掉的资产
在宿主机残留并被继续服务」(v1.0.38 的 Swiper 与白 logo 就是这样漏的)。
> ⚠ **本轮未执行任何生产写入**。子域发布属破坏性/共享状态动作,须单独授权(AGENTS.md §5.1)。
> `scripts/deploy.sh` 目前**没有** `landing` 子命令;在它落地前,上述命令只能手工跑,
> 且必须先 `docker inspect` 复核挂载(挂载点会随 compose 改动而变,不要凭记忆写路径)。
### 8.3 authority 侧已无 landing
`novavis-authority` 的 `Dockerfile` 不再 `COPY landing`,`deploy-prod.sh` 的阶段六已移除
(阶段总数 7 → 6)。子域 nginx 仍把 `/authority/` 与 `/api/v1/*` 反代到 `novavis-authority:8080`,
**只有静态页那一半换了主人**。因此 authority 部署与 landing 发布现在是两条独立的线:
改 landing 不必重新部署 authority 镜像,反之亦然。
+1 -1
View File
@@ -136,7 +136,7 @@ Closes #123
**通过标准**(阈值单一真源:`config/test/jest.config.js` 的 `coverageThreshold`,根 `jest.config.js` 仅转发):
- 全局: statements / lines / functions ≥ 75%,branches ≥ 82%
- 目录级棘轮按各目录实测值下调 3–5 个点设定,只允许上调
- **实测值的权威记录位就是本节**(`README.md` / `CLAUDE.md` 不再复制百分比,只指向这里;`config/test/jest.config.js` 顶部注释只是写死的快照,会滞后于树,见下方告警)
- **实测值的权威记录位就是本节**(`README.md` / `AGENTS.md` 不再复制百分比,只指向这里;`config/test/jest.config.js` 顶部注释只是写死的快照,会滞后于树,见下方告警)
- 实测(**2026-09-23 本树复跑** `npm run test:coverage` ⇒ **134 suites / 1697 tests,`EXIT=0`、0 条 threshold 告警**):
statements 85.66% / branches 87.49% / functions 80.67% / lines 85.66%
- 目录级:`components/content` 100×4 · `components/sections` 73.69 / 90.71 / 73.8 / 73.69 · `lib/cms` 91.93 / 92.77 / 92.68 / 91.93
+262
View File
@@ -0,0 +1,262 @@
# Landing(睿视 NovaVis 产品站)· 归属、URL 契约与门禁
> **一句话**:landing 的源码、门禁与发布职责都在**本仓**(2026-12-03 从 `novavis-authority`
> 迁入)。`novavis-authority` 不再持有 landing 的任何字节。
---
## 1. 归属变更(2026-12-03)
| 项 | 迁移前 | 迁移后 |
|---|---|---|
| 源码 | `novavis-authority/landing/` | **本仓 `public/novavis/`** |
| 四道门禁 | `novavis-authority/scripts/{verify-landing-layout,verify-landing-motion,landing-demo-verify,landing-audit}.py` | **本仓 `e2e/landing/*.spec.ts`**(`npm run test:landing`) |
| 门禁在链里? | **否**(一直手动跑) | **是**(已并入 `npm run test:all` 与 Jenkinsfile) |
| 发布 | authority `deploy-prod.sh` 阶段六 | 本仓 `scripts/deploy.sh`(官网镜像)+ 子域同步(见 §4) |
| Docker 镜像 | authority `Dockerfile` 的 `COPY landing` | **已移除**;authority 镜像不含 landing |
**为什么迁**:landing 的内容演进与产品 UI 强耦合(仿真外壳要跟 desktop 改版),而 desktop 与官网
都在本侧维护;留在 authority 会形成「改一次要跨两个仓、且四道门禁谁都不在链里」的双重失效。
迁移同时消解了 authority 仓「一个 Java 后端仓里躺着一份前端静态站」的结构错位。
**为什么 URL 一个字不改**:同一份字节要服务两个落点(官网 `/novavis/` 与子域根路径
`novavis.p.novalon.cn/`),见 §2。
---
## 2. 目录结构与 URL 契约
### 2.1 物理布局
```
public/novavis/
├── index.html
├── css/style.css
├── js/main.js
├── assets/{favicon.png,novavis-logo-icon.png}
└── images/logos/{apple.svg,windows.svg,uos-symbol.svg,kylin.png}
```
**一棵树自成一体**:landing 的全部资源都在 `public/novavis/` 下,不占任何站点级根命名空间。
### 2.2 URL 契约(保持源站形态不变)
`index.html` 里的引用**仍是站点级绝对路径**,一个字未改:
```html
<link rel="stylesheet" href="/css/style.css" />
<script src="/js/main.js"></script>
<img src="/assets/novavis-logo-icon.png" />
<img src="/images/logos/windows.svg" />
```
**为什么不能改成 `/novavis/css/style.css`**:子域 `novavis.p.novalon.cn` 的 nginx
`root /var/www/novavis-landing`,页面在**根路径**。改绝对路径会把子域首页变成
`novavis.p.novalon.cn/novavis/` —— 产品站首页带路径,不可接受。
### 2.3 官网侧的 4 条 prefix rewrite
`next.config.mjs` 的 `rewrites()` 把这四个前缀映射进子目录:
```js
{ source: '/novavis', destination: '/novavis/index.html' }, // 入口:public 层不做目录默认文档补全
{ source: '/css/:path*', destination: '/novavis/css/:path*' },
{ source: '/js/:path*', destination: '/novavis/js/:path*' },
{ source: '/assets/:path*', destination: '/novavis/assets/:path*' },
{ source: '/images/logos/:path*', destination: '/novavis/images/logos/:path*' },
```
**前提**:根 `public/{css,js,assets,images/logos}` 已删除 ⇒ 这四条是这些前缀的**唯一**占用者。
新增任何页面若要用同名前缀,必须先改本文件的登记。
> 这是 ADR-0014 §4「子目录化 + rewrites 前缀映射」模式**回溯到睿视**的落地 ——
> 原文写的就是「第二等产品镜像迁入时,必须改用 `public/{product}/` 子目录 + rewrites 前缀映射,
> 并回溯睿视」。
### 2.4 子域侧:平铺
子域发布时把 `public/novavis/{css,js,assets,images}` **平铺**到宿主目录根,于是
`/css/style.css` 等 URL 在子域上原样成立:
```bash
cp -R public/novavis/. "$LANDING_REMOTE_DIR"/ # index.html 与 4 个子目录一起落到根
```
---
## 3. 四道门禁(`npm run test:landing`)
### 3.1 为什么移植成 Playwright spec
迁移前是四个 python 脚本,**只在 authority 仓手动跑、从不在任何门禁链里**。本仓反复记录过那个
失效模式:**门禁不在链里就等于没有**。而本仓 CI(`Jenkinsfile`,`agent any`)不保证
`python3 + python-playwright` 存在;本仓已有 `@playwright/test` + `@axe-core/playwright`,
`e2e/` harness 现成(含 dev / `dist/standalone/server.js` 两种 webServer),
`page.goto('/novavis')` 直接可用 —— 不需要另起静态服务。
**移植纪律**:原 python 版**原样保留**在 `scripts/landing/`(参考实现 + 双跑对照用),
TS 版通过后才可视为完成;两者的判据映射见下表。
### 3.2 判据映射(一条不放宽)
| 原 python 门禁 | 新 spec | 判据 |
|---|---|---|
| `verify-landing-layout.py` | `e2e/landing/layout.spec.ts` | 五视口下 `.showcase-tabs` 每个 tab 中心不被 `#showcasePause` 覆盖、中心在视口内、页面横向溢出 ≤1px;焦点进入卡片后轮播让位;持焦 tab 不被摘 `tabindex`;失焦后轮播恢复;方向键后 roving tabindex 单点且焦点跟随 active;nav 转化入口与信息链接分层 |
| `verify-landing-motion.py` | `e2e/landing/motion.spec.ts` | `html.js-grow` 挂载;hero 剧本 `demo-step-1..4` 单向推进;四屏切 tab 后重播到峰值 = 目标总数;离开视口复位为 0;`prefers-reduced-motion` 直达终态;装饰图形 `aria-hidden="true"` 且子树内无可聚焦元素;暂停控件存在且带 `aria-pressed`;无 JS 运行时错误 |
| `landing-demo-verify.py` | `e2e/landing/demo.spec.ts` | 四步类名采样(1.4/4.4/7.6/11.6/16.4s,**时刻未改**)+ 徽标一一对应(每步恰好 1 个且文案同义);**无 JS 上下文四层真实可见性**;`badge_visible===0` 反向断言 + `badge_count>0` 金丝雀;reduced-motion 终态 |
| `landing-audit.py` | `e2e/landing/a11y.spec.ts` | 三视口结构项(横向溢出 / `img` 缺 alt / 可聚焦元素无无障碍名 / `h1` 数量 ≠ 1);全量可见文字对比度(**前景先按背景合成 alpha 再算**);同色无条件阻断;P2 只打印不判红;装饰豁免(主动标注 ∧ `aria-hidden` 子树,两条缺一不可)逐条 NOTE;axe critical/serious = 0 |
### 3.3 三条口径(原脚本用注入探针钉过,不许简化)
1. **前景必须先按背景合成 alpha**。`ratio()` 只吃 rgb 三元组、不看 alpha;带 alpha 的前景直接
喂进去会得到「把半透明色当不透明色」的对比度,alpha 越低算出的对比度越**高**:
`color: rgba(0,0,0,.05)` 未合成报 21.00:1、真值 1.12:1;`color: transparent` 未合成报 21.00:1、
真值 1.00:1 —— 后者正是「标题消失」的常见写法。
2. **同色无条件阻断、与阈值解耦**。只按 `ratio < 3.0` 判的话,把阈值调到 ≤1.0 时同色(恒 1.00)
会被静默放行 —— 正好复现 2026-11-04 Blocking① 的形态。
3. **分母金丝雀**。`a11y.spec.ts` 断言 `scanned > 0`(实际评估过的元素数),**不是**
`total > 0`(低于判据的条数 —— 全绿时恒为 0,拿它当金丝雀会把「没扫到」与「扫到了且全达标」
判成同一个数)。
### 3.4 判别性取证(已实做,2026-12-03)
门禁改动最容易被读成「改测试迁就实现」。三处注入探针确认 TS 版**仍能判红**:
| 注入 | 结果 |
|---|---|
| `.features .section-title { color: transparent }` | a11y spec 三视口全红,报 `P1 同色前景/背景 rgb(255,255,255) on rgb(255,255,255)(对比度 1)` 并点名 `#features-heading` |
| `html:not(.js-demo) .nv-home-rows { opacity:0; visibility:hidden }` | demo spec 红:`无 JS 时任务行不可见:0/4` |
| `.demo-chrome-badge-item { display:inline-flex !important }` | demo spec 红:每步「应恰好显示 1 个徽标,实测 4 个」 |
注入后均已复原,`diff` 确认 `style.css` / `main.js` 与源站原件逐字节一致(`main.js` 仅 6 处
`catch` 绑定改动,见 §6)。
### 3.5 运行方式
```bash
npm run test:landing # 独立 config:单引擎、单 project、串行(判据含视口,串行才可复现)
cd e2e && npx playwright test --config=playwright.landing.config.ts landing/a11y.spec.ts # 单文件
```
`playwright.landing.config.ts` 与主 config 分开的理由写在文件头:若塞进主 config 的 4 个功能
project,同一套断言会在 4 引擎 × 4 视口下重复执行,而判据里多处「窄视口下 X 不可见」会被 spec
自己的 `setViewportSize` 覆盖 —— 跑 4 遍等于跑 1 遍却贵 4 倍,还会把引擎差异混进读数。
---
## 4. 发布
### 4.1 官网镜像(本仓 `scripts/deploy.sh`)
`public/` 由 `deploy.sh` 步骤 1.5 拷进 `dist/`(既有机制,**零改动**),`/novavis/` 随官网一起发布。
### 4.2 子域(`novavis.p.novalon.cn`)
**实测口径(2026-12-03 现取 `docker inspect novalon-nginx-secure`)**:
| 项 | 值 |
|---|---|
| 宿主目录 | `/home/novalon/docker-app/novalon-static` |
| 容器挂载 | `/var/www/novavis-landing`(`:ro`) |
| nginx root | `/var/www/novavis-landing`(`conf.d/novavis-authority.conf:42`) |
| 页面位置 | **根路径**(`index.html` 在目录根) |
**同步动作**:把 `public/novavis/.` 平铺到该宿主目录。注意 authority 的旧脚本是
`cp -a` 覆盖式(无 `--delete`),历史上出现过「仓库里删掉的资产在宿主机残留并被继续服务」
(v1.0.38 的 Swiper 与白 logo 就踩过),故同步后应显式清理已下线路径。
> ⚠ **未在本次迁移中执行任何生产写入**。子域发布属破坏性/共享状态动作,须单独授权
> (AGENTS.md §5.1)。
---
## 5. 与 authority 的边界(迁移后)
authority 侧已移除:
- `landing/`(10 文件)
- `scripts/{landing-audit,landing-demo-verify,verify-landing-layout,verify-landing-motion}.py`
- `scripts/selfcheck/fixture-failing-landing.html` 与 `selfcheck-gates.sh` 的 P3 探针
(连同随之失效的 `PORT` / `--port` 参数)
- `Dockerfile` 的 `COPY landing`
- `deploy-prod.sh` 阶段六(landing 静态资源同步),阶段总数 7 → 6
**authority 仍保留**:`/authority/` 管理台、`/api/v1/*` 后端。子域 nginx 仍把这些路径反代到
`novavis-authority:8080`;**只有静态页那一半换了主人**。
---
## 6. 已知差异与未闭环项
| 项 | 状态 |
|---|---|
| `public/novavis/js/main.js` 与源站原件 | 仅 6 处 `catch (e)` / `catch (err)` → `catch`(未使用的绑定),语义等价。原因:迁移前 `.lintstagedrc.json` 用 `!(public)/**` 把整个 `public/` 排除在 lint 之外,而这 6 处会让 `npm run lint` 恒红(EXIT=1)。迁移后 landing 纳入本仓门禁面,故修掉并同步把 `public/novavis/js/**` 加进 lint-staged |
| 深色主题 | landing 现 **0 处**深色支持;desktop 已有三档主题。**未做**,登记为后续项 |
| 仿真外壳与 desktop 最新 UI 的差距 | 未在本轮处理。hero 画的 `/home` 任务台账页已于 2026-11-16 在 desktop 退役(ADR-0437),外壳几何(header 48 / 侧栏 212 单列 / 导航 9 组)也停在 2026-11-06。**登记为独立的 UI 对齐批次** |
| 文案事实核对 | 未在本轮处理。已知需核对项:`TSV` 导入(引擎 `Dialect` 无 tsv)、物流单据(78 条规则无物流族)、「监管报送格式」(报告只出 docx)、「4 类桌面系统原生安装包」(`electron-builder.yml` 仅 mac arm64 / win x64 / linux x64,无 UOS/麒麟专用包) |
| `scripts/landing/*.py` | 作为**参考实现**保留(双跑对照与判据溯源用),**不在任何 CI 链里**。若后续确认 TS 版完全覆盖,可整体删除 |
| CTA 表单端点 | **已修(2026-12-03)**:landing 固定向 `/api/v1/contact` POST JSON 且只认 `data.code === 200`,而本仓只有 `/api/contact`(formData + 必填 `subject`)⇒ 镜像侧表单一提交就落进失败兜底。新增 `src/app/api/v1/contact/route.ts` 匹配该契约(9 例契约测试 + 浏览器端到端实测:`POST` → 200 → 成功块渲染)。见本文 §8 |
---
## 7. 变更历史
| 日期 | 变更 |
|---|---|
| 2026-12-02 | landing 从 `novavis-authority/landing` **原样**迁入 `public/` 根命名空间(commit `901e1025`),内容零修改 |
| 2026-12-03 | **本仓接管**:9 文件收敛到 `public/novavis/` 子目录 + 4 条 prefix rewrite;四道门禁移植为 Playwright spec 并进 `test:all`;authority 侧退役;单 agent 文档收敛(`CLAUDE.md` 删除,正文并入 `AGENTS.md` §9) |
---
## 8. CTA 表单端点 `/api/v1/contact`
### 8.1 为什么需要它(迁移暴露的第一个真实缺陷)
landing 的 `js/main.js` 固定:
```js
fetch('/api/v1/contact', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) })
.then(...)
.then(({ok, data}) => { if (ok && data.code === 200) { /* 成功 */ } else { /* 失败兜底 */ } })
```
这个契约来自 `novavis-authority`(子域上由它的 Java 后端 `/api/v1/contact` 响应)。
但本仓只有 `/api/contact`(formData + 必填 `subject`,成功判据是 `success`)。
于是**官网镜像 `/novavis/` 的转化路径一直 404** —— 表单一提交就落进「服务器返回异常」的兜底。
迁移前没人从官网入口点过那个表单,所以这个断点一直没被看见。
### 8.2 处置:加一个契约匹配的薄适配层,而不是改 landing
| 方案 | 结论 |
|---|---|
| 改 `main.js` 去打 `/api/contact` + formData | ❌ 同一份字节要服务两个落点。子域上 authority 的契约是 JSON + `code:200`,改前端等于把「适配本仓」的成本转嫁给子域,且两侧成功判据会分叉 |
| **新增 `/api/v1/contact` 路由** | ✅ 本仓多一个薄层,landing 与 authority 都不动;可逆 |
**不复用 `/api/contact` 的实现**:输入形状(JSON vs formData)与成功判据(`code` vs `success`)
都不同,硬合并会造出一个两套语义的分支函数。但**投递通道一致**:都走 formsubmit.co 到
`COMPANY_INFO.email`。字段映射:`org` 由服务端合成为 `subject`(`睿视试用申请 · {org}`),
因为 landing 表单里没有 subject 字段。
### 8.3 三个不显然的决定
1. **失败也返回 HTTP 200 + `code !== 200`**(除 429/500)。landing 只看 `data.code`;
而 4xx 响应在某些中间层(CDN/WAF)会被替换成 HTML 错误页 ⇒ `res.json()` 直接抛异常 ⇒
用户只能看到最不具体的「网络异常」。用 200 + 结构化 message 能让文案落到具体原因上。
2. **zod 4 的两级消息都要给**。`.min(1, "请输入您的姓名")` 只管「存在但为空」;
字段**缺失**(undefined)走构造器参数,只写 `.min` 会返回英文
`Invalid input: expected string, received undefined` —— 直接展示给用户就是一句没法读的话。
实测确认:`z.string({ error: '…' })` 生效,`.min(1, '…')` 对 undefined 不生效。
3. **两个端点的限流桶独立**。共享会让「官网留言 5 次」把「睿视申请」也堵死。
默认同为 5 次/小时/IP,可用 `CONTACT_RATE_LIMIT_MAX` 覆盖。
### 8.4 验证
- 契约测试 `src/app/api/v1/contact/route.test.ts` **9/9**:成功形状 / org→subject 合成 /
选填字段缺失 / 必填缺失给出具体字段名 / 手机号格式 / 非 JSON 请求 / 危险字符过滤 /
上游失败不透传 5xx / 限流 429。
- 浏览器端到端(Playwright,真实 dev server):填表 → `#submitBtn` → `POST /api/v1/contact`
**200** → `.cta-form-success` 渲染。**注意上游 formsubmit.co 耗时 5s+**,
探针等待窗口小于 5s 会误判为失败(首次探针就是这么假红的)。
- 实测 curl 三条校验分支:缺 `org` → `{"code":400,"message":"请输入您所在的单位名称"}`;
手机号错 → `{"code":400,"message":"请输入正确的手机号码"}`;
非 JSON → `{"code":400,"message":"请求格式无效(需要 JSON)"}`。
@@ -0,0 +1,409 @@
# 产品独立站拆分方案(睿视 NovaVis 为模式先例)
- 状态:**方案待评审**(grill 阶段产出,尚未进入 PRD / 任务拆解)
- 日期:2026-12-03
- 依据:ADR-0014、`docs/landing.md`、`public/novavis/**`、`prisma/seeds/{products,standalone-products,case-studies}.ts`、`/Users/zhangxiang/Codes/Novalon/nova-enterprise-suite/docs/audit-2026-12/**`
- 关联决策:本轮 grill 共 20 项裁定,记录见 §9
---
## 0. 一句话结论
**照睿视的结构做一套可复用的纯静态产品站模板,但不要把睿视的「DOM 仿真界面」当成模板基线**;先用 **ERP + OA** 两个事实密度够高的产品把模板、门禁、发布链路跑通,其余四个产品**在产品实体出现之前不上站**。ADR-0014 原有的排期(ERP→BI+CRM→CMS/SDS/OA)与产品事实相反,须修订。
---
## 1. 三条必须先纠正的前提
### 1.1 ADR-0014 §3 的排期与产品事实相反
`nova-enterprise-suite`(下称 suite 仓)勘察结论:
| 官网产品 | suite 仓 | 代码体量 | 验收证据 | 事实密度 | ADR 原排期 |
|---|---|---|---|---|---|
| 睿新 ERP 管理系统 | `nova-erp`(NovaCore ERP / 睿枢) | 5,945 行 Java + 99 TS/TSX + 17 迁移 | 272 用例、行覆盖 85–95%、O2C 6 步 / P2P 8 步 SOP | **高** | Phase 1 ✅ |
| 睿新协同办公系统 | `nova-oa`(NovaFlow OA / 流程) | 4,533 行 + 16 模型 + 10 迁移 | **58/58 真库 E2E**、96/87/98% 覆盖率、577 行真 SVG 流程设计器 | **高** | Phase 3 ❌ |
| 睿新客户关系管理系统 | `nova-crm`(NovaLink CRM / 智链) | 1,889 行,2 迁移 | 79 用例;**前端仅 2 个列表、点行空白、3/6 列幻影字段** | 中 | Phase 2 |
| 睿新商业智能平台 | `nova-bi`(NovaLens BI / 明镜) | **0 行** | 无 | 低 | Phase 2 ❌ |
| 睿新供应链决策支持系统 | **仓不存在**(`nova-sds` 实测无) | 0 | 文档 467 行为规划值 | 文档中/产品无 | Phase 3 |
| 睿新内容管理系统 | **不存在**(仅 4 行占位) | 0 | 无 | **无** | Phase 3 ❌ |
ADR 自己写的入口判据是「产品事实是否足以支撑独立站内容」,按该判据重排后顺序应为 **ERP + OA → CRM → 其余冻结**。
### 1.2 六个产品共同缺四类 landing 必备素材
1. 客户案例:`prisma/seeds/case-studies.ts:11` 为 `CASE_STUDIES: CaseStudy[] = []`,并由 `src/lib/constants/case-publish-gate.ts:44-52` 在数据层 fail-closed。
2. 性能/规模实测:suite 仓零实测并发/数据量/响应时间,只有 SDS 的目标值。
3. 合规声明:suite 审计实测 8 项中国合规门槛 **6 项为 0**;无信创适配清单、无等保测评、无国密改造。
4. UI 素材:suite 仓 22 张图片全是 coverage 产出的 favicon;官网 `public/images/products/` **目录不存在**(7 条种子 `image` 指向 404,`git log --all -- 'public/images/products/*'` 零提交)。
⇒ 任何产品站的 L3 信任层必须**重写结构**,不能沿用途睿视的「客户 / 案例 / 指标」三段。
### 1.3 suite 文档不可直接作为文案来源
suite 仓 `docs/audit-2026-12/README.md` 列了 **20 条「文档 vs 代码」矛盾**,例:
- 台账写「审批流已达标」,代码里待办列表恒空(`ApprovalService.java:91-93`);
- 写「PDF 导出已提交」,实际是 `window.print()`(`ReportService.java:60`);
- 写「文档可在线预览」,实际零权限控制且从未在浏览器打开过(`DocController.java:93`)。
⇒ 从 suite 抄任何「已具备 XX 能力」,都必须回代码取证。这直接推导出 §5.3 的第五道门禁。
---
## 2. 目标形态
### 2.1 与 ADR-0014 的一致项(不变)
- 主发布面 = 独立子域 `{product}.p.novalon.cn`。
- 站体 = 纯静态、零运行时、零第三方 CDN、系统字体栈。
- 官网镜像 `public/{product}/` + rewrites 前缀映射(第二站起强制子目录化)。
- 官网导航 = 外链 + 状态徽标,与独立站上线事实强制同步。
- 零内联脚本(生产 CSP `script-src 'self'`)。
### 2.2 与 ADR-0014 的修订项
| 条目 | 原 ADR | 修订后 |
|---|---|---|
| 排期 | ERP→BI+CRM→CMS/SDS/OA | **ERP + OA 同批 Phase 1 → CRM Phase 2 → 其余冻结待产品实体** |
| 仓库 | 独立仓 → 本仓镜像 | **全部在本仓 `product-sites/{id}/` 统一管理**,模板成形后再考虑拆仓 |
| 站体形态 | 每站一份手写 HTML/CSS/JS | **共享模板 + 每产品一份数据文件,构建期生成静态产物** |
| 详情页退役 | 上线后 301 | **不上 301**,保留详情页 + 加「前往产品站」主 CTA |
| 命名 | 沿用官网「睿新 XXX」 | **全面迁到 suite 的 Nova 系命名**(本次裁定,见 §6) |
| CMS `siteUrl` | 「Phase 1 一并做」 | 仍要做,但**当前代码中不存在**(`siteUrl` 全仓 0 命中),列为 Phase 1 任务项 |
### 2.3 与「统一产品平台」的叙事边界(重要)
suite 仓 `nova-platform/web/packages/shell/src/components/ProductSwitcher.tsx:15-22` 已实现六产品切换器(2 个启用),架构文档把「一次登录、全产品通行、界面统一无缝切换」列为核心设计目标,并把「独立产品线 vs 无感集成」明确写成核心矛盾。
裁定:**独立站只做获客层,不与统一壳叙事争抢**。约束:
- 允许:每个站一句「{产品} 是 Novalon 企业套件的一员」,站间互链。
- **禁止**:承诺「一处登录全产品通行」——统一 API 网关 0 代码、Module Federation 0 实现、三块基石 ADR(009/010/011)全部仍是 Proposed。
- **唯一可承诺的跨产品协同**:CRM 赢单 → ERP 自动建单(suite 唯一真机验证过的跨仓链路,2 passed)。ERP / OA 站可写,CRM 站可写,其余站不可写。
---
## 3. 产品站模板架构
### 3.1 目录布局
```
product-sites/
├── _template/ # 模板(唯一真源,禁止逐站复制)
│ ├── layout.html # 骨架:14 个区块的插槽
│ ├── tokens.css # 令牌层:字体/字号/间距/圆角/动效档位
│ ├── base.css # 组件层:nav/section/card/form/faq/footer
│ ├── main.js # 行为层:渐显/轮播/表单/reduced-motion
│ └── themes/ # 表现层:每产品一套 hero 视觉变体
│ ├── _default.css
│ └── {theme}.css
├── _build.mjs # 构建脚本:数据 + 模板 → 纯静态产物
├── novavis/ # 睿视(回迁,见 §7 Phase 4)
│ ├── product.json # 唯一数据文件
│ └── assets/
├── erp/
│ ├── product.json
│ └── assets/
└── oa/
├── product.json
└── assets/
```
产物落到 `public/{product}/`,仍是 Next public 层直出 + rewrites 映射,**不引入任何打包器**(`_build.mjs` 是零依赖 Node 脚本)。
### 3.2 `product.json` schema(产品事实包的机读形态)
对应本轮裁定的「产品事实包」六项硬要求 + 一项软要求:
```jsonc
{
"id": "erp",
"name": { "en": "NovaCore ERP", "zh": "睿枢" },
"tagline": "一句话定位", // 硬
"audience": "目标客群", // 硬
"status": "研发中 | 内测中 | 已发布", // 硬,与导航徽标强制同步
"siteUrl": "https://erp.p.novalon.cn",
"theme": "datafield",
"hero": { "title": "...", "subtitle": "...", "storyboard": [...] },
"capabilities": [ // 硬:模块 + 一句话职责
{ "name": "销售", "duty": "...", "evidence": "nova-erp/erp-sale" }
],
"flow": { "title": "三步/五步路径", "steps": [...] }, // 硬
"deployment": { "form": "私有化/Docker/K8s", "requirements": [...] }, // 硬
"proofs": [ // 硬:至少 1 条代码验证过的断言
{ "claim": "...", "evidence": "测试名 / 文件:行 / 迁移号" }
],
"visual": { "kind": "abstract | screenshot | none", "items": [] }, // 软
"trust": { "l3Variant": "verifiable-facts" }, // 见 §3.4
"faq": [ ... ],
"crossLinks": [ { "product": "crm", "how": "赢单自动建单" } ]
}
```
**缺任一硬字段 ⇒ 该产品不进构建清单**,构建脚本 fail-closed 并打印缺失项。
### 3.3 三层分离
| 层 | 内容 | 复用度 |
|---|---|---|
| 令牌层 | 字体栈、字号梯度、间距、圆角、动效档位(instant 100 / fast 180–280 / hover 150 / 反馈 100)、`prefers-reduced-motion` 硬开关 | **七个站全共享** |
| 组件层 | nav、section、card、form、faq、footer、showcase 容器、返回顶部 | **全共享** |
| 表现层 | hero 视觉变体(数据场 / 几何 / 图文)、产品主色 | **每产品一套** |
主色策略:**产品主色自定,母品牌红不入产品站主色,但页脚必须有 ≥1 处母品牌回归链接**(承接「品牌触达」精神,不硬套 `#C41E3A`)。睿视保留 Police Blue `#0033A0` 不回退。
### 3.4 L3 信任层的替代结构
睿视的 L3 有三个区块:`#scenarios`(行业场景,替代客户案例)、`#customers`(**可核验事实矩阵**:结论 / 事实 / 你怎么自己验证)、`#trust`(OS 兼容 + 指标条)。
六个企业产品**只有 `#customers` 这一型可复用**——因为案例、认证、指标全空。模板的 L3 默认形态:
1. `#facts`:可核验事实矩阵(每条挂 `evidence` 指针)— **必填**
2. `#scenarios`:行业/角色场景(规范描述,不声称已服务某客户)— 选填
3. `#trust`:部署形态 + 技术栈 + 集成边界 — 必填(数据来自 `deployment`)
明确不做:客户 logo 墙、认证徽章墙、业绩数字条(无数据支撑)。
### 3.5 视觉展示槽位
裁定为「抽象数据可视化优先,真界面仿真为辅」:
- `visual.kind = "abstract"`:模板给一套抽象图形(数据流 / 图谱 / 流程节点),不绑产品。
- `visual.kind = "screenshot"`:仅当产品有可运行前端入口时启用。当前 suite 仓**业务仓前端在浏览器里没有入口**(`nova-erp/web`、`nova-crm/web`、`nova-oa/web` 均为库包,唯一宿主是 platform shell),故 ERP/OA 首发只能用 abstract,或把「素材生产」列独立前置任务。
- `visual.kind = "none"`:允许,但 hero 必须靠排版与叙事撑住。
**睿视的真 DOM 仿真不回迁到模板基线**——它按 `docs/landing.md:195` 已停在 2026-11-06 的 UI 形态,且与 desktop 改版强耦合;它是睿视站的说服力来源,但不是可复制的模板资产。
---
## 4. 页面区块与四层叙事(模板默认编排)
沿用睿视的 14 区块骨架,删掉睿视专属,补 L3 替代:
| 层 | 区块 | 进模板 | 说明 |
|---|---|---|---|
| 前置 | 公告条 | ✅ 参数化 | ≤3 条卖点,≤640px 换短文案 |
| L1 | nav(含 1 个可辨 CTA) | ✅ | CTA 与信息链接样式必须分层(睿视门禁 ①-4 已锁) |
| L1 | hero + 剧本 | ✅ storyboard 参数化 | 4 步剧本时长由数据驱动,不再硬编码 `DUR` |
| L1 | hero-highlights | ✅ | 4 条横排事实,不做渐显 |
| L2 | showcase(tab 轮播) | ✅ 容器复用,内容按产品 | 睿视是 DOM 仿真;模板是抽象可视化或图文 |
| L2 | features / capabilities | ✅ | 静态网格,**卡片零 hover**(沿用睿视的做法与理由) |
| L2 | deliverables | ✅ | 睿视叫 `#products`,模板改名 `#deliverables` 避免与官网产品矩阵混淆 |
| L2 | process | ✅ | 序号做装饰水印(`data-audit-decorative` + `aria-hidden`) |
| L3 | facts(可核验事实矩阵) | ✅ **新** | 替睿视 `#customers`,每条挂 evidence |
| L3 | scenarios | ✅ 选填 | |
| L3 | trust(部署 + 技术栈 + 集成边界) | ✅ | 替睿视 OS 卡(除 ERP/OA 站外无信创清单) |
| L4 | faq | ✅ | 原生 `<details>`,无 JS 可用 |
| L4 | contact 表单 | ✅ | 端点见 §5.4 |
| 收尾 | backToTop / footer | ✅ | 页脚含母品牌回归链接 |
| — | DOM 仿真界面层 | ❌ | 睿视专属,不进模板 |
| — | 授权治理叙事 | ❌ | 睿视专属 |
---
## 5. 门禁设计
### 5.1 分层
睿视现有 13 个用例(4 个 spec)拆成两包:
**A. 通用包 `e2e/landing/_shared/`(每站必跑)**
| 原用例 | 断言 | 参数化来源 |
|---|---|---|
| ①-1 几何 | 五视口无横向溢出、tab 行不被暂停按钮覆盖 | 区块清单 |
| ①-2 轮播让位 | `focusin` 暂停 / `focusout` 恢复 | 轮播配置 |
| ①-3 roving tabindex | 恰好 1 个 `tabindex="0"` 且等于 active | — |
| ①-4 CTA 分层 | nav 内 CTA 与信息链接样式不完全相等 | — |
| ②-1 动效挂载 | `js-grow` 存在;首屏剧本 ≥3 步且首步为 1 | storyboard |
| ②-2 reduced-motion | 直达终态;装饰层 `aria-hidden`;承载控件的父容器不可 aria-hidden;可聚焦元素不在 aria-hidden 子树 | — |
| ③-1 剧本推进 | 每步徽标**恰好 1 个**且文案同义;循环复位 | storyboard 时刻表 |
| ③-2 无 JS 降级 | 关键读数可见、行数 >0 全可见、徽标可见数 === 0 | 区块清单 |
| ③-3 reduced 终态 | `demo-final` 类 + 读数不变 | — |
| ④-1 结构 + 对比度 | 零溢出 / `<img>` 必写 `alt` / 可及名 / `h1` 唯一;对比度先按背景合成 alpha、同色无条件阻断;`scanned > 0` 金丝雀 | — |
| ④-2 axe | critical/serious === 0,仅排除 `[data-audit-decorative][aria-hidden="true"]` | — |
**B. 专属包 `e2e/landing/{product}.spec.ts`(按需)**
睿视专属的「`nv-home-pager b === '6'`」「`demo-step-1..4` 的 1.4/4.4/7.6/11.6/16.4s」这类**具体读数**归此包,不进通用包。
### 5.2 配置
沿用 `e2e/playwright.landing.config.ts` 的形态(单引擎单 project、串行、`workers: 1`),扩展为 `testDir: './landing'` + `LANDING_URL` 由环境变量或 project 提供,按产品跑。
### 5.3 第五道门禁:文案事实性(新增)
`npm run check:landing:claims` —— 读 `product-sites/{id}/product.json` 的 `proofs[]` 与 `capabilities[].evidence`,逐条验证:
| evidence 形态 | 判定方式 |
|---|---|
| `path/to/File.java:91-93` | suite 仓(可配置路径)中该文件存在且行号范围内含断言关键词 |
| `migration:V12` | 迁移文件存在 |
| `test:SomeTestClass#method` | 测试文件中存在该用例名 |
缺指针、指向不存在、或指向的行不含关键词 ⇒ **判红**。
这是整套方案里唯一能防住「三个月后 landing 说的和产品做的不是一回事」的机制,直接对应 §1.3 的 20 条矛盾。
### 5.4 表单与转化链路
- 端点:`POST /api/v1/contact`,payload 增加 `product` 字段分流。
- **限流桶必须按产品分桶**:现有 `src/app/api/v1/contact/route.ts:43-48` 已确立「两个端点桶独立」的原则,理由同样适用于七条产品入口——共享 5 次/小时/IP 的桶会让打满一个产品堵死其余六个。
- 注意:`createMemoryRateLimiter` 是**进程内**的(`src/lib/rate-limit.ts`),多副本下每副本各自计数,实际宽松于配置值。这是既有形态,本方案不改,但登记在风险表。
- 子域侧:纯静态站无运行时,POST 必须回到 `novalon.cn`;跨域需 CORS 白名单(当前无 CORS 配置,属新增项)。
### 5.5 子域 404
睿视子域实测:任意不存在路径 → **200 + 整份首页**(SPA 式 fallback)。模板脚手架必须加 `try_files ... =404` + 静态 404 页。单站无害,七站是 SEO 隐患。
---
## 6. 命名统一(本次裁定:全面迁到 Nova 系)
### 6.1 目标命名
| 产品 | 新主名 | 中文代号 | suite 仓对应 |
|---|---|---|---|
| ERP | **NovaCore ERP** | 睿枢 | `nova-erp` |
| CRM | **NovaLink CRM** | 智链 | `nova-crm` |
| OA | **NovaFlow OA** | 流程 | `nova-oa` |
| BI | **NovaLens BI** | 明镜 | `nova-bi` |
| 供应链决策 | **NovaMind DSS** | 智策 | `nova-sds`(未建仓) |
| CMS | **NovaPress CMS** | 发布 | 不存在 |
| 专业产品 | 睿视 NovaVis | — | 不在 suite 仓 |
依据:`nova-platform/docs/superpowers/specs/2026-05-03-novalon-platform-architecture.md:30-39` 的六产品家族表 + `ProductSwitcher.tsx:15-22` 的代码实体。
**「NovaMind DSS」与「nova-sds」在 suite 仓内部并存**(4 处 vs 数十处),先行统一描述为 NovaMind DSS,仓名待定。
**待确认的不对称**:睿视是「睿视 NovaVis」(中文在前 + 英文名),而六产品新命名是「英文在前 + 中文代号」。同一品牌体系两种语序。建议保持睿视现状不回改(已上线、已入导航、已有镜像),仅在新产品上使用新语序;如需语序一致,睿视侧改动归入独立动作。
### 6.2 改名的爆炸半径(必须按此清单执行,禁止全局替换)
关键陷阱:**「睿新」既是公司简称(睿新致远 / 四川睿新致远科技有限公司),也是六个产品名的前缀。** 全局替换会连公司名、隐私政策、服务条款、成立新闻一起改。
必须改(产品名):
- `prisma/seeds/products.ts` — 6 条 `title`(`:7,64,121,178,235,292`)+ 6 条 `overview` 开头
- `src/app/(marketing)/products/products-content-v3.tsx:21-26` — `PRODUCT_ICONS` 键
- `src/app/(marketing)/products/product-detail-content-v3.tsx:16-21` — 同名键(**6 个键里 3 个已是错的**:`睿视商业智能分析平台` / `睿新协同办公平台` / `睿新供应链数字化平台` 均与种子 title 不符,导致 3 个产品落回 `Package` 兜底图标。改名时一并修复)
- `src/app/(marketing)/solutions/solutions-content-v3.tsx:151` — `name.replace('睿新','')`。**此逻辑在改名后静默失效**(英文主名没有「睿新」可替换,会渲染完整英文名),必须改为读结构化字段而非字符串运算
- `src/app/(marketing)/products/erp-upgrade-v3/page.tsx:15`、`erp-upgrade/page.tsx:10`、`erp-upgrade-content-v2.tsx:150,406`
- `src/lib/constants/navigation.ts:129-134` — 6 条导航 title
- 相关单测:`products-content-v3.test.tsx:96,123,150,247,248`、`solutions-content-v3.test.tsx:114`、`detail-page-hero.test.tsx:15`、`standalone/[id]/page.test.tsx:68-69`
**不得改**(公司实体):`src/lib/constants/company.ts:2-4,44`、`prisma/seeds/legal-pages.ts:13,16,203,217,220,349`、`prisma/seed.ts:679,852,1050`、`src/lib/constants/news.ts:67-76`、`privacy/page.tsx`、`terms/page.tsx`、`header.tsx` 书法字标、`structured-data.tsx:17` 的 `alternateName`。
### 6.3 改名的连带成本
- **全部 50 张产品视觉基线(10×5 project)会因文本变化而失配**,需重采。
- e2e 中 16 个文件 114 处 `/products` 引用中,含文本断言的部分需逐个核对。
- `title` 变化会影响 `generateMetadata` 与 `<title>`,进而影响 SEO 快照;改名属对外变更,需与公司确认对外口径后再合入。
⚠️ 建议:**改名作为独立 PR 单独合入并在合入前重采基线**,不要夹在模板/站点建设里——否则一旦站点出问题,无法判断是模板问题还是改名问题。
---
## 7. 阶段计划
判据仍是 ADR 的「产品事实可验证」,不设时间表。
### Phase 0 — 前置缺陷收口(与拆分解耦,但阻塞 Phase 1)
1. **修 `/api/v1/contact`**:`src/app/api/v1/contact/route.ts` 现为 untracked,线上 `novalon.cn/api/v1/contact` 实测 **404**,`/api/contact` 实测 **500**。即官网睿视镜像的 CTA 表单当前必然落进失败兜底分支。子域 `novavis.p.novalon.cn/api/v1/contact` 为 200(走 authority Java 后端)。
2. **入库三份 untracked 资产**:`e2e/landing/`、`docs/landing.md`、`src/app/api/v1/`(`git ls-tree HEAD e2e/landing` = 0 条)。
3. **修子域 404 fallback**(§5.5)。
4. **命名统一**(§6,独立 PR)。
### Phase 1 — 模板 + ERP + OA
1. `product-sites/_template/` 骨架 + `_build.mjs` + `product.json` schema + 事实性门禁。
2. 抽通用门禁包(§5.1 A),睿视现有 4 spec 迁到「通用包 + 专属包」两段。
3. **ERP 站**:`erp.p.novalon.cn`,数据来自 suite `nova-erp` 的 SOP 与能力清单。
4. **OA 站**:`oa.p.novalon.cn`,数据来自 suite `nova-oa`(58/58 真库 E2E 是最强信任素材)。
- OA 的唯一 UI 差异化是 577 行真 SVG 拖拽流程设计器,但**浏览器无入口**(`nova-oa/web` 是库包)⇒ 素材生产为独立前置任务,不阻塞站体。
5. 官网侧:`siteUrl` 字段落地(当前 0 命中)、导航外链切换、badge 状态机与上线事实同步、详情页加「前往产品站」CTA(**不 301**)。
6. 子域 nginx 配置入库。⚠️ 现状:**睿视子域配置不在本仓**(服务器 `conf.d/novavis-authority.conf`),`nginx-static-production.conf:84-86` 的 `upstream novavis_authority` 零引用。模板要「照抄睿视」在本仓无源可抄,须先从服务器取回并入库。
### Phase 2 — CRM
待补前端(当前点行空白、3/6 列幻影字段)与目标客群描述后再上站。
### Phase 3 — BI / 供应链 / CMS:**冻结**
- BI 零代码、SDS 仓不存在、CMS 连规划都没进版本线。按入口判据,三者均不满足。
- 官网详情页继续占位,不提前上线、不改 badge。
### Phase 4 — 睿视回迁模板
**时机**:第二站上线并稳定后。**验收**:视觉回归逐屏比对 + 四道门禁零退化。
---
## 8. 风险登记
| # | 风险 | 影响 | 缓解 |
|---|---|---|---|
| R1 | 统一壳与独立站叙事冲突 | 品牌口径自相矛盾 | §2.3 边界;站面只承诺真机验证过的协同链路 |
| R2 | suite 文档与代码有 20 条矛盾 | landing 承诺不存在的能力 | §5.3 第五道门禁;文案逐条取证 |
| R3 | 六个产品零案例/零实测/零合规 | L3 层无内容 | §3.4 改结构;`case-publish-gate` 的 fail-closed 原则适用到 landing |
| R4 | 睿视 DOM 仿真随 desktop 改版腐化 | 模板若复用它会被一起拖死 | 仿真层不进模板(§3.5) |
| R5 | 七站共用限流桶 | 一个产品被打满堵死其余 | 按产品分桶(§5.4) |
| R6 | 子域配置不在本仓 | 模板无源可抄 | Phase 0 从服务器取回入库 |
| R7 | 改名致 50 张基线失配 | 视觉回归读数污染 | 改名独立 PR + 提前重采 |
| R8 | `images.unoptimized: true` 与「零 CDN」冲突 | 照抄官网图片策略会 404 | 产品站自带 assets,走自身目录,不用 next/image |
| R9 | `test:all` 不含视觉回归 | 拆分后基线漂移不报警 | 视觉回归须在 Jenkins `main` 单 project 之外单独确认 |
| R10 | CSP 实际含 `'unsafe-inline'`(ADR 声称不含) | 「零内联脚本」约束的实际强度弱于文档 | 门禁层面自行约束(通用包 ③-2 无 JS 降级 + ⑤ 事实门禁);文档口径按代码修正 |
| R11 | `PRODUCT_ICONS` 3 个键已错 | 3 个产品视觉无差别 | 改名时一并修复(§6.2) |
---
## 9. 本轮裁定的 20 项决策
| # | 问题 | 裁定 |
|---|---|---|
| Q1 | 交付物边界 | 只交文档,不写代码 |
| Q2 | 拆分范围 | 先一站跑通端到端,其余按模板批量 |
| Q3 | 站体形态 | 共享模板 + 每产品数据文件,构建期生成静态产物 |
| Q4 | 仓库结构 | 全部在本仓 `product-sites/{id}/` 统一管理 |
| Q5 | 页面粒度 | 单页 + 结构上预留可选页接口 |
| Q6 | 设计语言 | 令牌层共享 + 表现层分站 |
| Q7 | 官网详情页 | 保留 + 加「前往产品站」CTA,不 301 |
| Q8 | 事实不足的产品 | 先做事实盘点,未达标不上线 |
| Q1' | DOM 仿真层 | 抽象数据可视化优先,真截图仅当有可运行界面 |
| Q2' | 品牌关系 | 产品主色自定,页脚 ≥1 处母品牌回归 |
| Q3' | 门禁分层 | 通用包 + 产品专属 spec 两段 |
| Q4' | 表单端点 | 共用 `/api/v1/contact`,按产品分桶 |
| Q5' | 子域 404 | 加 `try_files ... =404` + 静态 404 页 |
| Q6' | 文案真源 | 新建「产品事实库」,官网详情页与产品站同源 |
| Q7' | 睿视回迁 | 第二站稳定后回迁,验收 = 视觉比对 + 门禁零退化 |
| Q1'' | 排期修订 | 重排为 ERP+OA → CRM → 其余冻结 |
| Q2'' | 平台叙事 | 独立站只做获客层,站间互链,不承诺统一登录 |
| Q3'' | 命名 | **全面迁到 Nova 系**(本次指定) |
| Q4'' | platform 底座 | 不做独立站,但在产品站里作为「技术底座」一提 |
| Q5'' | 事实包必填 | 六项硬要求 + 视觉素材为软要求 |
| Q6'' | 文案门禁 | 新增第五道「文案事实性」门禁 |
| Q7'' | 素材来源 | 素材生产为独立前置任务,不阻塞站体 |
---
## 10. 未决项(不阻塞本方案,但需在 PRD 阶段定向)
1. **语序不对称**:睿视「睿视 NovaVis」vs 六品「NovaCore ERP(睿枢)」(§6.1)。
2. **NovaMind DSS 与 nova-sds 的仓名/产品名统一**:suite 仓内部两套并存,需一方归口。
3. **跨域 CORS 白名单**:子域纯静态站 POST 回 `novalon.cn` 需要,当前零配置,方案未定具体白名单机制。
4. **`siteUrl` 落在哪个 CMS 模型**:`standalone-product` 还是 `product`(企业套装 6 条是 `product` 模型,ADR 只提了 standalone)。
---
## 11. 验收标准(Phase 1)
- [ ] `product-sites/_template/` + `_build.mjs` 存在,`product.json` schema 有 JSON Schema 定义与自检
- [ ] `erp` / `oa` 两站产物可由一条命令生成,产物零运行时、零第三方域名、零内联脚本
- [ ] 两站各通过「通用门禁包」全绿 + 各自专属 spec 全绿
- [ ] `check:landing:claims` 对两站的 `proofs[]` 全绿;删除任一 evidence 指针时判红(判别性取证)
- [ ] 两站子域 404 返回真 404
- [ ] 官网导航两产品 `href` 指向子域,`badge` 与上线事实一致
- [ ] 官网详情页保留,含「前往产品站」主 CTA,无 301
- [ ] 表单从子域提交成功,且按产品分桶限流(灌满 A 产品后 B 产品仍可提交)
- [ ] 文档同步:ADR-0014 修订、`CONTEXT.md` 命名对照表、`docs/landing.md` 扩展为多产品口径、`AGENTS.md` §9 命令表新增 `check:landing:claims` 与构建命令
+1 -1
View File
@@ -155,7 +155,7 @@ cd e2e && npx playwright test --project=chromium-mobile
npm run check:a11y # 静态令牌门禁伞:check:contrast + check:headings + check:brand-token(已并入 test:all)
npm run check:contrast # 只读 globals.css 令牌表做配对计算(不启服务)
npm run check:headings # 自起服务扫描渲染后的标题层级:存在 dist/standalone/server.js 时**直起 standalone**,
# 产物缺失才回退 `npm run preview` 并打印告警(验收 N-24③,见 CLAUDE.md「Build & Preview」)
# 产物缺失才回退 `npm run preview` 并打印告警(验收 N-24③,见 AGENTS.md §9「Build & Preview」)
npm run check:brand-token # 品牌红文字通道令牌化检查(静态扫描源码)
npx playwright test --grep @accessibility # 浏览器内 axe / 触摸目标用例
```
+1 -1
View File
@@ -13,7 +13,7 @@
| Google Analytics 不生效 | 未配置 GA4 ID | [GA4 配置](./GOOGLE_ANALYTICS_SETUP.md) |
| Sentry 错误上报失败 | 未配置 DSN | [监控配置](./LIGHTWEIGHT_MONITORING.md) |
| 测试覆盖率不达标 | 工具函数/hooks 未覆盖 | [测试覆盖率改进计划](./test-coverage-improvement-plan.md) |
| E2E 测试视觉回归失败 | 快照过期 | [更新快照](../CLAUDE.md#common-commands) |
| E2E 测试视觉回归失败 | 快照过期 | [更新快照](../AGENTS.md#common-commands) |
| 单元测试 Jest 报错 | 配置/路径别名问题 | [测试配置](../config/test/jest.config.js) |
---
+433
View File
@@ -0,0 +1,433 @@
import { test, expect, type Page } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
/**
* Landing 门禁 ④:结构与全量可见文字对比度(移植自 `novavis-authority/scripts/landing-audit.py`)
*
* ## 这道门禁为什么必须存在
*
* 2026-11-04 的 Blocking①(屏 2 整屏白底白字)能连过前三道门禁,因为那三道**根本不读颜色**。
* 本门禁是唯一覆盖「标题是否可见」的一道:它遍历所有直接含文字的元素,读 computed
* foreground / background 实算对比度。
*
* ## 判据分级(与迁移前逐条一致)
*
* | 级别 | 判据 | 结果 |
* |---|---|---|
* | P1 阻断 | 同色前景/背景(`rgb(x,x,x)` on `rgb(x,x,x)`) | 无条件失败,**不受阈值影响** |
* | P1 阻断 | 对比度 < 3.0(WCAG 大号文本线) | 失败 |
* | P1 阻断 | 结构项:横向溢出 / `img` 缺 `alt` / 可聚焦元素无无障碍名 / `h1` 数量 ≠ 1 | 失败 |
* | P2 警告 | 对比度落在 [3.0, 4.5) | **不失败**,但逐条打印(须人工定夺) |
* | P2 警告 | 焦点指示缺失 | **不失败**,逐条打印 |
* | NOTE | 装饰豁免(作者以 `data-audit-decorative` 主动标注 **且** 在 `aria-hidden` 子树内) | 逐条打印,不计入 |
*
* ## 三条必须知道的口径(原脚本用注入探针钉过,不许简化)
*
* 1. **前景必须先按背景合成 alpha 再算对比度**。`ratio()` 只吃 rgb 三元组、不看 alpha;
* 把带 alpha 的前景直接喂进去,alpha 越低算出的对比度越**高**:
* `color: rgba(0,0,0,.05)` 未合成报 21.00:1,真值 1.12:1;`color: transparent` 未合成报
* 21.00:1,真值 1.00:1 —— 后者正是「标题消失」的常见写法。本文件 `compositeFg()` 补齐。
* 2. **同色无条件阻断、与阈值解耦**。若只按 `ratio < 3.0` 判,把阈值调到 ≤1.0 时同色
* (恒 1.00)会被静默放行 —— 正好复现 Blocking① 的形态。
* 3. **装饰豁免必须两条同时满足**:作者主动标注 `data-audit-decorative` **且** 该文字在
* `aria-hidden` 子树内。只标属性而不 `aria-hidden` 的正文不成立豁免(否则一段真的低对比度
* 正文只要打上标记就能逃逸)。同色永远阻断、不受豁免影响。
*
* ## 与 axe 的分工
*
* 本门禁的对比度扫描覆盖「所有直接含文字的元素」(含 SVG `<text>`,且按真实背景合成),
* axe 的 `color-contrast` 规则覆盖的是它自己的可达元素集。两者**都跑**:axe 提供标准的
* 无障碍树口径,自写扫描提供「标题是否消失」这个 axe 判不出的角度(axe 跳过 `aria-hidden`
* 子树,而本门禁刻意连它一起扫)。
*/
const LANDING_URL = '/novavis';
/** 阻断级对比度下限(WCAG 大号文本线)。同色不受此参数影响。 */
const FAIL_MIN = 3.0;
/** 警告级对比度上限(WCAG 正文 AA 线)。 */
const WARN_MIN = 4.5;
const VIEWPORTS = [
{ name: 'desktop', width: 1440, height: 900 },
{ name: 'tablet', width: 768, height: 1024 },
{ name: 'mobile', width: 390, height: 844 },
] as const;
/**
* 把所有动效门控的初始隐藏态解除,让每一屏、每一个生长元素都真实呈现后再测。
* (未解除时 `js-grow` 下的元素 opacity 为 0,会被 `visible()` 过滤掉 ⇒ 扫描面大幅缩水,
* 而门禁仍然「绿」——那是分母静默变小。)
*/
function revealAll() {
const root = document.documentElement;
root.classList.remove('js-grow', 'js-reveal');
document.querySelectorAll<HTMLElement>('.rv').forEach((el) => el.classList.add('in'));
document.querySelectorAll<HTMLElement>('[data-grow]').forEach((host) => {
host.classList.add('is-grown');
host.querySelectorAll('*').forEach((c) => c.classList.add('is-grown'));
if (!host.querySelector('[data-grow]')) host.classList.add('is-grown');
});
document.querySelectorAll<HTMLElement>('.showcase-panel').forEach((p) => {
p.hidden = false;
p.classList.add('active');
p.style.display = 'grid';
});
const hero = document.querySelector<HTMLElement>('#heroDemo');
if (hero) hero.className = hero.className.replace(/demo-step-\d/g, 'demo-final');
['#showcasePause', '#demoPause'].forEach((sel) => {
const b = document.querySelector<HTMLElement>(sel);
if (b && b.getAttribute('aria-pressed') === 'false') b.click();
});
return {
panels: document.querySelectorAll('.showcase-panel').length,
heroClass: hero ? hero.className : null,
};
}
/**
* 全量可见文字对比度扫描(与迁移前 `CONTRAST_SCAN_JS` 逐条同义)。
*
* 参数是普通对象:Playwright 的 JS 版 `evaluate` 支持「函数 + 一个可序列化入参」。
*/
function contrastScan(args: { failMin: number; warnMin: number }) {
const { failMin, warnMin } = args;
interface Rgba {
r: number;
g: number;
b: number;
a: number;
}
const parse = (s: string | null): Rgba | null => {
if (!s) return null;
const m = s.match(/rgba?\(([^)]+)\)/);
if (!m || m[1] === undefined) return null;
const p = m[1]
.split(/[\s,/]+/)
.filter(Boolean)
.map(parseFloat);
if (p.length < 3 || p.some(Number.isNaN)) return null;
return { r: p[0]!, g: p[1]!, b: p[2]!, a: p.length > 3 ? p[3]! : 1 };
};
const chan = (c: number): number => {
const v = c / 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
};
const lum = (c: Rgba): number => 0.2126 * chan(c.r) + 0.7152 * chan(c.g) + 0.0722 * chan(c.b);
const ratio = (fg: Rgba, bg: Rgba): number => {
const l1 = lum(fg) + 0.05;
const l2 = lum(bg) + 0.05;
return l1 >= l2 ? l1 / l2 : l2 / l1;
};
const over = (top: Rgba, bottom: Rgba): Rgba => ({
r: top.r * top.a + bottom.r * (1 - top.a),
g: top.g * top.a + bottom.g * (1 - top.a),
b: top.b * top.a + bottom.b * (1 - top.a),
a: 1,
});
const SVG_TEXT_TAGS = new Set(['text', 'tspan']);
const isSvgText = (el: Element): boolean =>
SVG_TEXT_TAGS.has(el.tagName.toLowerCase()) && !!(el as SVGElement).ownerSVGElement;
// 前景:HTML 取 color;SVG 文字取 paint 的 fill(color 只是继承值,不是画出来的色)
// 返回的是**已解析但未合成**的色(可能带 alpha),调用方必须先 compositeFg。
const fgOf = (el: Element, st: CSSStyleDeclaration): Rgba | null => {
if (isSvgText(el)) {
if (st.fill === 'none') return null;
const f = parse(st.fill);
return f && f.a > 0 ? f : null;
}
return parse(st.color);
};
// 前景按背景合成:见文件头口径 ①,不合成会把半透明前景算成「高对比」。
const compositeFg = (fg: Rgba, bg: Rgba): Rgba => (fg.a >= 0.999 ? { ...fg, a: 1 } : over(fg, bg));
const bgOfAncestors = (el: Element): Rgba => {
const layers: Rgba[] = [];
let n: Element | null = el;
while (n && n.nodeType === 1) {
const c = parse(getComputedStyle(n).backgroundColor);
if (c) {
if (c.a >= 0.999) {
layers.push(c);
break;
}
layers.push(c);
}
n = n.parentElement;
}
let base: Rgba = { r: 255, g: 255, b: 255, a: 1 };
for (let i = layers.length - 1; i >= 0; i--) base = over(layers[i]!, base);
return base;
};
// SVG 文字的真实底:同一容器内、绘制顺序在它之前且有不透明 fill 的形状
const shapeUnder = (el: Element): Rgba | null => {
const parent = el.parentElement;
if (!parent) return null;
let hit: Rgba | null = null;
for (const k of Array.from(parent.children)) {
if (k === el) break;
const t = k.tagName.toLowerCase();
if (t === 'text' || t === 'tspan') continue;
const f = parse(getComputedStyle(k).fill as string);
if (f && f.a >= 0.9) hit = f;
}
return hit;
};
const effectiveBg = (el: Element): Rgba => {
const canvas = bgOfAncestors(el);
if (isSvgText(el)) {
const shape = shapeUnder(el);
if (shape) return over(shape, canvas);
}
return canvas;
};
const pathOf = (el: Element): string => {
const parts: string[] = [];
let n: Element | null = el;
while (n && n.nodeType === 1 && parts.length < 4) {
let s = n.id ? `#${n.id}` : n.tagName.toLowerCase();
if (!n.id && typeof n.className === 'string' && n.className.trim() !== '') {
const c = n.className.trim().split(/\s+/).filter(Boolean).slice(0, 2);
if (c.length > 0) s += `.${c.join('.')}`;
}
parts.unshift(s);
n = n.parentElement;
}
return parts.join(' > ');
};
const hasDirectText = (el: Element): boolean =>
Array.from(el.childNodes).some((n) => n.nodeType === 3 && (n.textContent ?? '').trim().length > 0);
const visible = (el: Element): boolean => {
const st = getComputedStyle(el);
if (st.visibility === 'hidden' || st.display === 'none' || parseFloat(st.opacity) < 0.05) return false;
const r = el.getBoundingClientRect();
return r.width >= 2 && r.height >= 2;
};
interface Offender {
path: string;
ratio: number;
need: number;
fg: string;
bg: string;
font: string;
text: string;
hidden: boolean;
decorative: boolean;
}
const out: Offender[] = [];
const seen = new Set<string>();
// 分母计数:实际评估过的「可见且直接含文字」元素数。
// 为什么单独数:`out` 只收**低于判据**的项,全绿时它是 0 —— 用 `out.length > 0` 当金丝雀
// 会让「扫描器什么都没看到」与「扫描器看到 423 个元素且全达标」显示成同一个 0(本仓反复踩)。
let scanned = 0;
for (const el of Array.from(document.querySelectorAll('body *'))) {
if (!hasDirectText(el) || !visible(el)) continue;
const st = getComputedStyle(el);
const fg = fgOf(el, st);
if (!fg) continue;
scanned += 1;
const bg = effectiveBg(el);
const fsz = parseFloat(st.fontSize);
const weight = parseInt(st.fontWeight, 10) || 400;
const need = fsz >= 24 || (fsz >= 18.66 && weight >= 700) ? 3.0 : 4.5;
// 必须先按背景合成再算 ratio(见文件头口径 ①)
const fgSolid = compositeFg(fg, bg);
const r = ratio(fgSolid, bg);
if (r >= need) continue;
const key = `${pathOf(el)}|${(el.textContent ?? '').trim().slice(0, 24)}`;
if (seen.has(key)) continue;
seen.add(key);
out.push({
path: pathOf(el),
ratio: +r.toFixed(2),
need,
fg: `rgb(${Math.round(fgSolid.r)}, ${Math.round(fgSolid.g)}, ${Math.round(fgSolid.b)})`,
bg: `rgb(${Math.round(bg.r)}, ${Math.round(bg.g)}, ${Math.round(bg.b)})`,
font: `${fsz}px/${weight}`,
text: (el.textContent ?? '').trim().replace(/\s+/g, ' ').slice(0, 40),
hidden: !!el.closest('[aria-hidden="true"]'),
// 显式装饰标记:**只有作者主动标注**才算,绝不从 aria-hidden 推断。
// 装饰子图里同样可能藏真缺陷;用 aria-hidden 推断豁免等于给「整块藏起来」开后门。
decorative: !!el.closest('[data-audit-decorative]'),
});
}
out.sort((a, b) => a.ratio - b.ratio);
// 同色检测在全量 out 上做,不能被 worst 的截断吃掉
const sameColor = out.filter((o) => o.fg === o.bg);
// 装饰豁免两条缺一不可:主动标注 ∧ 在 aria-hidden 子树内;同色永不受豁免
const isDeco = (o: Offender): boolean => o.decorative && o.hidden && o.fg !== o.bg;
const deco = out.filter(isDeco);
const real = out.filter((o) => !isDeco(o));
return {
worst: real.slice(0, 80),
/** 实际评估过的「可见且直接含文字」元素数(分母金丝雀用)。 */
scanned,
total: real.length,
belowFail: real.filter((o) => o.ratio < failMin).length,
belowWarn: real.filter((o) => o.ratio < warnMin).length,
minRatio: real.length > 0 ? real[0]!.ratio : null,
sameColor: sameColor.length,
sameColorKeys: sameColor.map((o) => `${o.path}|${o.text}`),
blocked: real.filter((o) => o.ratio < failMin || o.fg === o.bg).length,
warned: real.filter((o) => o.ratio >= failMin && o.ratio < warnMin && o.fg !== o.bg).length,
decorative: deco.length,
decorativeItems: deco.map((o) => ({ path: o.path, ratio: o.ratio, text: o.text })),
};
}
/** 结构项(P1)+ 焦点指示(P2)。 */
async function structuralChecks(page: Page): Promise<{ blocking: string[]; warnings: string[] }> {
const blocking: string[] = [];
const warnings: string[] = [];
const scrollW = await page.evaluate(() => document.documentElement.scrollWidth);
const clientW = await page.evaluate(() => window.innerWidth);
if (scrollW > clientW) blocking.push(`horizontal overflow: ${scrollW} > ${clientW}`);
const imgNoAlt = await page.evaluate(() =>
[...document.querySelectorAll('img')]
.filter((img) => img.getAttribute('alt') === null)
.map((img) => img.getAttribute('src') ?? ''),
);
for (const src of imgNoAlt) blocking.push(`img missing alt: src=${src}`);
const noName = await page.evaluate(() => {
const els = Array.from(
document.querySelectorAll('a, button, input, textarea, select, [role="tab"], summary'),
);
return els
.filter((el) => {
const name =
el.getAttribute('aria-label') ??
el.getAttribute('title') ??
(el.textContent ?? '').trim() ??
'';
const fallback = (el as HTMLInputElement).getAttribute?.('placeholder') ?? '';
return (name === '' || name === null) && fallback === '';
})
.map((el) => el.outerHTML.slice(0, 120));
});
for (const b of noName.slice(0, 5)) blocking.push(`interactive element without accessible name: ${b}`);
const h1Count = await page.locator('h1').count();
if (h1Count !== 1) blocking.push(`heading hierarchy: ${h1Count} h1`);
for (const sel of ['.nav-links a', '#navToggle']) {
const loc = page.locator(sel).first();
try {
if (!(await loc.isVisible())) continue;
await loc.focus();
const outline = await loc.evaluate((el) => getComputedStyle(el).outlineWidth);
if (outline === '0px') warnings.push(`focus indicator missing on ${sel}`);
} catch {
// 元素不存在或不可聚焦:跳过(与迁移前一致)
}
}
return { blocking, warnings };
}
test.describe('landing ④ 结构与对比度', () => {
for (const vp of VIEWPORTS) {
test(`结构与全量对比度 @ ${vp.name} (${vp.width}×${vp.height})`, async ({ page }) => {
await page.setViewportSize({ width: vp.width, height: vp.height });
await page.goto(LANDING_URL, { waitUntil: 'networkidle' });
await page.waitForTimeout(600);
const structural = await structuralChecks(page);
const revealed = await page.evaluate(revealAll);
await page.waitForTimeout(200);
expect(revealed.panels, `${vp.name}: .showcase-panel 一个都没展开(判据分母为空)`).toBeGreaterThan(0);
const scan = await page.evaluate(contrastScan, { failMin: FAIL_MIN, warnMin: WARN_MIN });
// 分母金丝雀:扫描器必须真的看到东西,否则「0 条违规」是空跑。
// 用 `scanned`(实际评估过的元素数)而不是 `total`(低于判据的条数)——
// 后者在全绿时恒为 0,拿它当金丝雀等于把「没扫到」和「扫到了且全达标」判成同一个数。
expect(
scan.scanned,
`${vp.name}: 对比度扫描没有评估到任何元素(分母为空 ⇒ 通过无意义)`,
).toBeGreaterThan(0);
const sameKeys = new Set(scan.sameColorKeys);
// 阻断级 = 对比度 < FAIL_MIN ∪ 同色(同色无条件阻断,见文件头口径 ②)
const blocking = scan.worst.filter(
(o) => o.ratio < FAIL_MIN || sameKeys.has(`${o.path}|${o.text}`),
);
const blockingMessages = blocking.map((o) => {
const same = sameKeys.has(`${o.path}|${o.text}`);
return same
? `P1 同色前景/背景 ${o.fg} on ${o.bg}(对比度 ${o.ratio})@${o.font} — ${o.path} «${o.text}»`
: `P1 contrast ${o.ratio} < ${FAIL_MIN} (需 ${o.need}) ${o.fg} on ${o.bg} @${o.font} — ${o.path} «${o.text}»`;
});
// P2 只打印不判红(迁移前口径:exit 0)
const band = scan.worst.filter(
(o) => o.ratio >= FAIL_MIN && o.ratio < WARN_MIN && !sameKeys.has(`${o.path}|${o.text}`),
);
if (band.length > 0) {
console.log(
`[${vp.name}] P2 警告(不判红,须人工定夺):\n` +
band
.slice(0, 20)
.map((o) => ` contrast ${o.ratio} < ${WARN_MIN} — ${o.path} «${o.text}»`)
.join('\n'),
);
}
// 装饰豁免逐条打印为 NOTE(即使全绿也打印:豁免必须可审计,不能因为「没红」就从报告里消失)
if (scan.decorativeItems.length > 0) {
console.log(
`[${vp.name}] NOTE 装饰豁免(作者以 data-audit-decorative 标注 ∧ aria-hidden 子树内,不计入):\n` +
scan.decorativeItems.map((o) => ` contrast ${o.ratio} — ${o.path} «${o.text}»`).join('\n'),
);
}
expect(
[...structural.blocking, ...blockingMessages],
`${vp.name}: P1 阻断项(\n${[...structural.blocking, ...blockingMessages].join('\n')}\n)`,
).toEqual([]);
});
}
test('axe 无障碍扫描:无 critical/serious 违规', async ({ page }) => {
await page.goto(LANDING_URL, { waitUntil: 'networkidle' });
await page.waitForTimeout(600);
await page.evaluate(revealAll);
await page.waitForTimeout(200);
const results = await new AxeBuilder({ page })
/*
* 排除**已登记的装饰豁免**节点:`.process-step-number`(流程卡右上角的 01/02/03 水印数字)
* 同时满足本仓装饰豁免的两条(作者 `data-audit-decorative` 主动标注 ∧ 在 `aria-hidden`
* 子树内,见 `scripts/landing/README` 与上一组用例的 NOTE 输出),对比度约 1.08:1 是
* 刻意淡化。axe 的 `color-contrast` 不认识这套豁免,会把它报成 serious。
*
* 为什么不干脆关掉整条 color-contrast 规则:本组用例的自写扫描虽更严(含 alpha 合成、
* 覆盖 aria-hidden 子树),但它是**本仓自研口径**;axe 是标准无障碍树口径,两者互补。
* 只排除登记过的节点,其余仍由 axe 判 —— 排除面越小,假绿空间越小。
*/
.exclude('[data-audit-decorative][aria-hidden="true"]')
.analyze();
const serious = results.violations.filter(
(v) => v.impact === 'critical' || v.impact === 'serious',
);
expect(
serious.map((v) => `${v.id} (${v.impact}, ${v.nodes.length} nodes): ${v.help}`),
`axe critical/serious 违规`,
).toEqual([]);
});
});
+216
View File
@@ -0,0 +1,216 @@
import { test, expect, type Page } from '@playwright/test';
/**
* Landing 门禁 ③:首屏演示剧本 + 无 JS 降级 + reduced-motion(移植自
* `novavis-authority/scripts/landing-demo-verify.py`)
*
* ## 这道门禁守的是「内容在、但看不见」
*
* 2026-11-04 的 Blocking①(屏 2 白底白字)与 2026-11-07 的 BLOCKING-2(nojs 断言只读
* `textContent` + computed `display`,注入 `opacity:0;visibility:hidden` 后仍 PASS)是同一
* 失效模式。所以无 JS 断言必须是**四层真实可见性**,缺一不可:
*
* ① `checkVisibility({checkOpacity, checkVisibilityCSS})` —— 浏览器自己的口径
* ② 祖先链上 opacity 有效值 > 0.05(旧内核 checkVisibility 对 opacity 的处理不一致)
* ③ 元素矩形有面积(排除被 layout 折叠)
* ④ 文字非空
*
* 另加两条**防恒真**的断言(本仓反复踩过「判据通过态是 0 或空集时,0 本身不是证据」):
* - 反向:仅动画层的步骤徽标在无 JS 时必须**不可见**(`badge_visible === 0`);
* - 金丝雀:徽标选择器必须真的命中元素(`badge_count > 0`),否则上一条恒真。
*
* ## 采样时刻未改
*
* `DUR = {s1:2.6, s2:3.4, s3:3.2, s4:3.8, hold:1.6}`,故 1.4 / 4.4 / 7.6 / 11.6 / 16.4 的
* 采样点落在各自的步内。**时刻不改**,因为改动时刻会让「脚本采样点」与「动画真实时间轴」
* 脱钩,那是判据自伤而不是适配(原脚本注释原文)。
*/
const LANDING_URL = '/novavis';
/** 采样时刻(秒,相对页面 load 完成)。 */
const STEPS = [
{ name: 'step1-create', at: 1.4 },
{ name: 'step2-open', at: 4.4 },
{ name: 'step3-import', at: 7.6 },
{ name: 'step4-ready', at: 11.6 },
{ name: 'loop-restart', at: 16.4 },
] as const;
/** 步号 → 该步应显示的徽标文案(与 index.html 的 `data-badge` 一一对应)。 */
const BADGE_OF_STEP: Record<string, string> = {
'demo-step-1': '新建任务',
'demo-step-2': '打开任务',
'demo-step-3': '导入数据',
'demo-step-4': '就绪',
};
async function heroClass(page: Page): Promise<string> {
return page.evaluate(() => document.getElementById('heroDemo')?.className ?? '');
}
/**
* 当前**真实可见**的徽标文案(三层可见性,与 nojs 判定同口径)。
*/
async function visibleBadges(page: Page): Promise<string[]> {
return page.evaluate(() => {
const els = [...document.querySelectorAll<HTMLElement>('.demo-chrome-badge-item')];
return els
.filter((el) => {
const r = el.getBoundingClientRect();
if (!el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) return false;
if (r.width <= 0 || r.height <= 0) return false;
let op = 1;
let n: Element | null = el;
while (n && n.nodeType === 1) {
const o = parseFloat(getComputedStyle(n).opacity);
if (!Number.isNaN(o)) op *= o;
if (op <= 0.05) return false;
n = n.parentElement;
}
return true;
})
.map((el) => (el.textContent ?? '').trim());
});
}
/**
* 徽标正向断言:每个采样点上当前步必须**恰好显示 1 个**徽标,且文案与该步同义。
*
* 为什么是「恰好 1 个」而不是「>= 1」:同时显示两个说明映射有重叠(正是 2026-11-07 首轮
* 「徽标错位一整步」的伴生症状),那会让观众同时看到两个互斥的进度。
*/
function checkBadgeMatchesStep(
classSamples: Record<string, string>,
badgeSamples: Record<string, string[]>,
): string[] {
const problems: string[] = [];
for (const [name, cls] of Object.entries(classSamples)) {
const step = Object.keys(BADGE_OF_STEP).find((st) => cls.includes(st));
if (step === undefined) continue; // loop-restart 采样点落在复位瞬间,不判
const want = BADGE_OF_STEP[step];
const got = badgeSamples[name] ?? [];
if (got.length !== 1) {
problems.push(`${name}: ${step} 应恰好显示 1 个徽标,实测 ${got.length} 个 ${JSON.stringify(got)}`);
} else if (got[0] !== want) {
problems.push(`${name}: ${step} 应显示「${want}」,实测「${got[0]}」`);
}
}
return problems;
}
test.describe('landing ③ 首屏剧本与降级', () => {
test('剧本四步推进 + 徽标一一对应 + 循环复位', async ({ page }) => {
const pageErrors: string[] = [];
page.on('pageerror', (e) => pageErrors.push(String(e)));
await page.goto(LANDING_URL, { waitUntil: 'load' });
const start = Date.now();
const classSamples: Record<string, string> = {};
const badgeSamples: Record<string, string[]> = {};
for (const step of STEPS) {
const delta = step.at * 1000 - (Date.now() - start);
if (delta > 0) await page.waitForTimeout(delta);
classSamples[step.name] = await heroClass(page);
badgeSamples[step.name] = await visibleBadges(page);
}
expect(pageErrors, `landing 页有 JS 运行时错误:${pageErrors.join(' | ')}`).toEqual([]);
// 循环复位:采样到第 1 步说明时间轴在循环
expect(
classSamples['loop-restart'],
`剧本未循环复位到 demo-step-1:实测 ${classSamples['loop-restart']}`,
).toContain('demo-step-1');
const problems = checkBadgeMatchesStep(classSamples, badgeSamples);
expect(problems, problems.join('\n')).toEqual([]);
});
test('无 JS 降级:内容在且看得见(四层真实可见性)', async ({ browser }) => {
// 独立 context 关掉 JS:用 browser 而不是 page fixture(后者已带 JS)
const context = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 1440, height: 900 } });
const page = await context.newPage();
await page.goto(LANDING_URL, { waitUntil: 'load' });
await page.waitForTimeout(500);
const nojs = await page.evaluate(() => {
const rows = [...document.querySelectorAll<HTMLElement>('.nv-home-row')];
const visibleRows = rows.filter((el) => {
const r = el.getBoundingClientRect();
// ② 祖先链有效 opacity
let op = 1;
let n: Element | null = el;
while (n && n.nodeType === 1) {
const o = parseFloat(getComputedStyle(n).opacity);
if (!Number.isNaN(o)) op *= o;
if (op <= 0.05) return false;
n = n.parentElement;
}
// ① + ③ + ④
return (
el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) &&
r.width > 0 &&
r.height > 0 &&
(el.textContent ?? '').trim().length > 0
);
}).length;
const badgeItems = [...document.querySelectorAll<HTMLElement>('.demo-chrome-badge-item')];
const visibleBadge = badgeItems.filter((el) => {
const r = el.getBoundingClientRect();
return el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) && r.width > 0 && r.height > 0;
}).length;
const pager = document.querySelector<HTMLElement>('.nv-home-pager b');
const cols = document.querySelector<HTMLElement>('.nv-home-cols');
return {
taskTotal: pager?.textContent ?? null,
currentRow: document.querySelectorAll('.nv-home-row.is-current').length,
colsVisible: cols ? cols.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) : false,
demoRowsSeen: rows.length,
rowsVisible: visibleRows,
badgeCount: badgeItems.length,
badgeVisible: visibleBadge,
// 状态栏的静态读数:无 JS 时也应直接可见
bodyText: (document.body.textContent ?? '').length,
};
});
// 台账读数是**静态数据**(6 个任务),不是动画指标 —— 它旁边就列着 4 行真实任务,
// 若写成 0 就与内容自相矛盾。故无 JS 时必须等于 6。
expect(nojs.taskTotal, `无 JS 时任务总数应为 6,实测 ${nojs.taskTotal}`).toBe('6');
expect(nojs.currentRow, '无 JS 时当前行(is-current 是静态类,不靠 JS 加)应恰有 1 行').toBe(1);
expect(nojs.colsVisible, '无 JS 时列头不可见(视口锁定后列头只渲染一次,它是纯静态结构)').toBe(true);
expect(nojs.demoRowsSeen, '无 JS 时一行任务都没渲染(判据分母为空)').toBeGreaterThan(0);
expect(
nojs.rowsVisible,
`无 JS 时任务行不可见:${nojs.rowsVisible}/${nojs.demoRowsSeen}(内容在、但被 opacity/visibility 藏起来)`,
).toBe(nojs.demoRowsSeen);
// 反向断言 + 金丝雀:仅动画层的徽标无 JS 时不得可见;选择器必须非空否则上一条恒真
expect(nojs.badgeCount, '徽标选择器零命中(反向断言会恒真)').toBeGreaterThan(0);
expect(nojs.badgeVisible, `仅动画层的徽标在无 JS 时不得可见,实测 ${nojs.badgeVisible} 个`).toBe(0);
await context.close();
});
test('prefers-reduced-motion:直达终态、不排时间轴', async ({ page }) => {
await page.emulateMedia({ reducedMotion: 'reduce' });
await page.goto(LANDING_URL, { waitUntil: 'load' });
await page.waitForTimeout(1200);
const hero = await heroClass(page);
expect(hero, `reduced-motion 下应挂 demo-final,实测 className="${hero}"`).toContain('demo-final');
const readings = await page.evaluate(() => ({
taskTotal: document.querySelector<HTMLElement>('.nv-home-pager b')?.textContent ?? null,
currentRow: document.querySelectorAll('.nv-home-row.is-current').length,
}));
expect(readings.taskTotal, 'reduced-motion 下任务总数应为 6').toBe('6');
expect(readings.currentRow, 'reduced-motion 下当前行应恰有 1 行').toBe(1);
});
});
+240
View File
@@ -0,0 +1,240 @@
import { test, expect, type Page } from '@playwright/test';
/**
* Landing 门禁 ①:布局几何与焦点管理(移植自 `novavis-authority/scripts/verify-landing-layout.py`)
*
* ## 判据来源与迁移口径
*
* 迁移前的脚本是 python + playwright,只在 authority 仓手动跑、从不在任何门禁链里
* (本仓反复记录过那个失效模式:**门禁不在链里就等于没有**)。2026-12-03 landing 迁入本仓,
* 四道门禁一并移植为 Playwright spec,由 `npm run test:landing` 承载并进 `test:all`。
*
* **判据一个不放宽**,逐条对应原脚本:
*
* | 原检查项 | 本文件 |
* |---|---|
* | 1 tabs:各视口下 `.showcase-tabs` 每个 tab 中心不被 `#showcasePause` 覆盖,且无横向溢出 | `showcase tab 行与暂停按钮几何` |
* | 2a focus:焦点进入卡片后轮播让位 | `焦点进入卡片后轮播让位` |
* | 2b focus:持焦 tab 不被摘掉 tabindex | 同上 |
* | 2c focus:失焦后轮播恢复(证明 2a 不是「轮播整体坏了」的假通过) | 同上 |
* | 3 roving:方向键后整组只留一只可 Tab 到达,且该只即 active、焦点跟随 | `键盘 roving tabindex 单点不变量` |
* | 4 cta:nav 转化入口与信息链接有可视分层 | `nav 转化入口与信息链接分层` |
*
* ## 两个必须知道的操作前提(原脚本注释里踩过)
*
* 1. **悬停会冻结轮播**(既有设计)。focus 项全程把鼠标移到 (0,0),否则测的是 hover 冻结
* 而不是 focusin 暂停。
* 2. **视口是被测对象**:每条用例自己 `setViewportSize`,不依赖 project 的 viewport。
*/
const LANDING_URL = '/novavis';
/** 与迁移前一致的五个视口(桌面 / 笔记本 / 平板竖屏 / 手机 480 / 手机 375)。 */
const VIEWPORTS = [
{ name: '桌面 1440', width: 1440, height: 900 },
{ name: '笔记本 1024', width: 1024, height: 768 },
{ name: '平板竖屏 768', width: 768, height: 1024 },
{ name: '手机 480', width: 480, height: 900 },
{ name: '手机 375', width: 375, height: 812 },
] as const;
/** 轮播周期 5500ms + 余量:等待窗口内若未暂停,active tab 必定已切换。 */
const CYCLE_MS = 5500;
const WAIT_MS = CYCLE_MS + 2000;
/**
* tab 行的几何读数(与迁移前 `TAB_INFO` 逐字同义)。
*
* 注意这里必须是**真函数**而不是字符串:Playwright 的 JS 版 `page.evaluate(string)` 把入参
* 当「表达式」求值,`"() => {...}"` 求值结果是一个函数对象、序列化成 undefined
* (python 版把字符串当函数体,所以原脚本能用字符串;两个绑定语义不同)。
*/
function readTabInfo() {
const pause = document.querySelector<HTMLElement>('#showcasePause');
const pr = pause && getComputedStyle(pause).display !== 'none' ? pause.getBoundingClientRect() : null;
const covers = (r: DOMRect): boolean => {
if (!pr) return false;
const cx = r.left + r.width / 2;
const cy = r.top + r.height / 2;
return pr.left <= cx && cx <= pr.right && pr.top <= cy && cy <= pr.bottom;
};
return [...document.querySelectorAll<HTMLElement>('.showcase-tab')].map((t) => {
const r = t.getBoundingClientRect();
const cx = r.left + r.width / 2;
const cy = r.top + r.height / 2;
return {
id: t.id,
covered: covers(r),
centerInViewport: cx >= 0 && cy >= 0 && cx <= window.innerWidth && cy <= window.innerHeight,
};
});
}
interface TabInfo {
id: string;
covered: boolean;
centerInViewport: boolean;
}
async function gotoLanding(page: Page): Promise<void> {
await page.goto(LANDING_URL, { waitUntil: 'load' });
// CSS 与 main.js 都是同源静态资源,等 1.2s 让 scroll-spy / 轮播完成首轮初始化
// (迁移前脚本同样 sleep 1.2s,理由相同:过早采样会读到轮播尚未挂上的中间态)。
await page.waitForTimeout(1200);
}
async function activeTabId(page: Page): Promise<string | null> {
return page.evaluate(() => document.querySelector<HTMLElement>('.showcase-tab.active')?.id ?? null);
}
async function focusedTabState(page: Page): Promise<{ id: string; tabindex: string | null } | null> {
return page.evaluate(() => {
const el = document.activeElement;
if (!el || !el.classList || !el.classList.contains('showcase-tab')) return null;
return { id: (el as HTMLElement).id, tabindex: el.getAttribute('tabindex') };
});
}
test.describe('landing ① 布局几何与焦点', () => {
test.beforeEach(async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await gotoLanding(page);
});
test('showcase tab 行与暂停按钮几何(五视口)', async ({ page }) => {
const failures: string[] = [];
for (const vp of VIEWPORTS) {
await page.setViewportSize({ width: vp.width, height: vp.height });
await page.evaluate(() => window.scrollTo(0, 0));
await page.mouse.move(0, 0);
await page.locator('.showcase-tabs').scrollIntoViewIfNeeded();
await page.waitForTimeout(300);
const tabs = (await page.evaluate(readTabInfo)) as TabInfo[];
expect(tabs.length, `${vp.name}: .showcase-tab 一个都没选中(判据的分母为空)`).toBeGreaterThan(0);
const covered = tabs.filter((t) => t.covered).map((t) => t.id);
const offscreen = tabs.filter((t) => !t.centerInViewport).map((t) => t.id);
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
);
if (covered.length > 0) failures.push(`${vp.name}: tab 被 #showcasePause 覆盖 ${covered.join(',')}`);
if (offscreen.length > 0) failures.push(`${vp.name}: tab 中心不在视口内 ${offscreen.join(',')}`);
if (overflow > 1) failures.push(`${vp.name}: 页面横向溢出 ${overflow}px`);
}
expect(failures, failures.join('\n')).toEqual([]);
});
test('焦点进入卡片后轮播让位、持焦不被摘 tabindex、失焦后恢复', async ({ page }) => {
await page.mouse.move(0, 0);
await page.locator('.showcase-tabs').scrollIntoViewIfNeeded();
await page.waitForTimeout(600);
await page.mouse.move(0, 0);
const before = await activeTabId(page);
expect(before, 'showcase 轮播没有 active tab(用例前提不成立)').not.toBeNull();
await page.evaluate(() => {
const t = document.querySelector<HTMLElement>('.showcase-tab.active');
t?.focus();
});
const state = await focusedTabState(page);
expect(state, '未能把焦点放进 tablist(用例前提不成立)').not.toBeNull();
// 2a:持焦期间轮播必须让位
await page.waitForTimeout(WAIT_MS);
const after = await activeTabId(page);
expect(after, `焦点在卡片内时轮播未让位:active ${before} → ${after}`).toBe(before);
// 2b:持焦 tab 不得被摘成 tabindex="-1"(摘掉即被移出 tab 序列,键盘焦点无处可回)
const held = await focusedTabState(page);
if (held) {
expect(held.tabindex, `持焦 tab ${held.id} 的 tabindex 被摘成 -1`).not.toBe('-1');
}
// 2c:失焦后必须恢复轮播 —— 否则上一条「不变」可能只是轮播整体失效的假通过
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
await page.evaluate(() => window.scrollTo(0, 0));
await page.mouse.move(0, 0);
await page.locator('#nav').scrollIntoViewIfNeeded();
await page.locator('.showcase-tabs').scrollIntoViewIfNeeded();
await expect
.poll(async () => await activeTabId(page), {
timeout: WAIT_MS + 1000,
message: `失焦后轮播未恢复:active 恒为 ${before}(前一条「持焦不变」可能是轮播整体失效的假通过)`,
})
.not.toBe(before);
});
test('键盘 roving tabindex 单点不变量', async ({ page }) => {
await page.mouse.move(0, 0);
await page.locator('.showcase-tabs').scrollIntoViewIfNeeded();
await page.waitForTimeout(400);
await page.evaluate(() => {
const t = document.querySelector<HTMLElement>('.showcase-tab.active');
t?.focus();
});
expect(await focusedTabState(page), '未能把焦点放进 tablist(roving 不变量前提不成立)').not.toBeNull();
await page.keyboard.press('ArrowRight');
await page.waitForTimeout(300);
const state = await page.evaluate(() => {
const tabs = [...document.querySelectorAll<HTMLElement>('.showcase-tab')];
const isTab = (el: Element | null): el is HTMLElement =>
!!el && el.classList.contains('showcase-tab');
return {
zero: tabs.filter((t) => t.getAttribute('tabindex') === '0').map((t) => t.id),
active: tabs.filter((t) => t.classList.contains('active')).map((t) => t.id),
focused: isTab(document.activeElement) ? document.activeElement.id : null,
};
});
// 单点不变量:整组只能有一只 tab 可被 Tab 键到达
expect(
state.zero.length,
`方向键切换后整组有 ${state.zero.length} 只 tab 可被 Tab 键到达(${state.zero.join(',')}),违反 roving tabindex 单点(旧 tab 仍留在序列里)`,
).toBe(1);
expect(state.active.length, '方向键切换后无 active tab').toBeGreaterThan(0);
expect(state.zero[0], `可被 Tab 键到达的 tab(${state.zero[0]})不是 active tab(${state.active[0]})`).toBe(
state.active[0],
);
expect(state.focused, `方向键切换后焦点未跟随 active tab(持焦 ${state.focused})`).toBe(state.active[0]);
});
test('nav 转化入口与信息链接分层', async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.evaluate(() => window.scrollTo(0, 0));
const styles = await page.evaluate(() => {
const links = [...document.querySelectorAll<HTMLElement>('.nav-links a')];
const info = links.find((a) => a.getAttribute('href') === '#features');
const cta = links.find((a) => a.getAttribute('href') === '#contact');
const pick = (el: HTMLElement | undefined) => {
if (!el) return null;
const s = getComputedStyle(el);
return {
cls: el.className,
border: `${s.borderTopWidth} ${s.borderTopStyle} ${s.borderTopColor}`,
bg: s.backgroundColor,
color: s.color,
};
};
return { info: pick(info), cta: pick(cta) };
});
expect(styles.info, 'nav 信息链接(#features)不存在').not.toBeNull();
expect(styles.cta, 'nav 转化入口(#contact)不存在').not.toBeNull();
expect(
styles.cta,
'nav 转化入口与信息链接样式完全相同(无分层)',
).not.toEqual(styles.info);
});
});
+193
View File
@@ -0,0 +1,193 @@
import { test, expect, type Page } from '@playwright/test';
/**
* Landing 门禁 ②:渐进生长动效(移植自 `novavis-authority/scripts/verify-landing-motion.py`)
*
* ## 判据(与迁移前逐条对应,一条不放宽)
*
* 1. `html.js-grow` 已挂载 —— CSS 初始隐藏态生效的前提(没挂上时所有元素本来就是可见的,
* 后面的「生长」判据会退化成恒真)。
* 2. Hero 首屏演示推进:`demo-step-1..4` 按序出现且单向(不回头)。
* hero 在 2026-11-07 改画 `/home` 任务工作台后不再有 `data-grow` 元素,
* 「动画在跑」这件事改由步骤类推进来证明(原脚本的等价迁移)。
* 3. Showcase 四个 panel 切 tab 后各自重播到**峰值 = 目标总数**(不锁死具体数字)。
* 4. 离开视口后 `is-grown` 复位为 0(否则「重播」可能是残留态)。
* 5. `prefers-reduced-motion` 下直达终态(`is-grown == 总数`)。
* 6. 装饰性图形对 AT 隐藏(`aria-hidden="true"`),且其子树内**无可聚焦元素**
* (axe `aria-hidden-focus` 的静态等价物);暂停控件存在且带 `aria-pressed`。
* 7. 无 JS 运行时错误。
*
* ## 为什么用「密集采样取峰值」而不是末次快照
*
* 剧本播完会循环复位,固定短窗口采样会读到复位后的 0 而假失败。原脚本的 `watch_growth`
* 就是为此写的,这里保持同口径:峰值须等于总数。
*/
const LANDING_URL = '/novavis';
const PANELS = [
{ tab: '#showcase-tab-graph', panel: '#showcase-panel-graph', name: '账户综合关联' },
{ tab: '#showcase-tab-flow', panel: '#showcase-panel-flow', name: '进出统计分析' },
{ tab: '#showcase-tab-ai', panel: '#showcase-panel-ai', name: '智能问答' },
{ tab: '#showcase-tab-process', panel: '#showcase-panel-process', name: '生成分析报告' },
] as const;
/** 待点亮目标总数(与 `main.js` 的 targetsOf 同规则:`<g>` 按子元素数计,其余算 1)。 */
async function totalTargets(page: Page, selector: string): Promise<number> {
return page.evaluate((sel) => {
const root = document.querySelector(sel);
if (!root) return 0;
let n = 0;
root.querySelectorAll('[data-grow]').forEach((el) => {
n += el.tagName.toLowerCase() === 'g' ? el.children.length : 1;
});
return n;
}, selector);
}
async function grown(page: Page, selector: string): Promise<number> {
return page.locator(`${selector} .is-grown`).count();
}
/** 密集采样到峰值(剧本会循环复位,故以「是否曾到达终态」判定)。 */
async function watchGrowth(
page: Page,
selector: string,
total: number,
windowMs = 12000,
intervalMs = 400,
): Promise<{ peak: number; samples: number[] }> {
const samples: number[] = [];
let peak = 0;
const deadline = Date.now() + windowMs;
while (Date.now() < deadline) {
const cur = await grown(page, selector);
peak = Math.max(peak, cur);
samples.push(cur);
if (peak === total) break;
await page.waitForTimeout(intervalMs);
}
return { peak, samples };
}
/** 采样 `demo-step-*` 的推进序列(去重、保序)。 */
async function watchDemoSteps(page: Page, selector: string, windowMs = 14000): Promise<string[]> {
const seen: string[] = [];
const deadline = Date.now() + windowMs;
while (Date.now() < deadline) {
const cls = await page.evaluate(
(sel) => document.querySelector<HTMLElement>(sel)?.className ?? '',
selector,
);
const cur = ['demo-step-1', 'demo-step-2', 'demo-step-3', 'demo-step-4'].find((s) => cls.includes(s));
if (cur && !seen.includes(cur)) seen.push(cur);
await page.waitForTimeout(250);
}
return seen;
}
test.describe('landing ② 动效与生长', () => {
test('js-grow 挂载 + hero 剧本单向推进 + 四屏重播 + 离开复位', async ({ page }) => {
const pageErrors: string[] = [];
page.on('pageerror', (e) => pageErrors.push(String(e)));
await page.goto(LANDING_URL, { waitUntil: 'load' });
await page.waitForTimeout(1500);
// 1. js-grow 挂载
const jsGrow = await page.evaluate(() => document.documentElement.classList.contains('js-grow'));
expect(jsGrow, 'html.js-grow 未挂载(CSS 初始隐藏态不生效 ⇒ 后续「生长」判据会退化成恒真)').toBe(true);
// 2. hero 剧本推进
const heroTotal = await totalTargets(page, '.hero-visual');
const stepsSeen = await watchDemoSteps(page, '#heroDemo');
expect(
stepsSeen.length,
`Hero 剧本未推进:只观察到 ${JSON.stringify(stepsSeen)}`,
).toBeGreaterThanOrEqual(3);
expect(stepsSeen[0], `Hero 剧本未从第 1 步开始:${JSON.stringify(stepsSeen)}`).toBe('demo-step-1');
expect(
stepsSeen.some((s) => s === 'demo-step-3' || s === 'demo-step-4'),
`Hero 剧本未走完前半程:${JSON.stringify(stepsSeen)}`,
).toBe(true);
// hero 上出现 data-grow 目标说明 DOM 又画回了图窗形态,此时期望值需重钉(原脚本同样打印该提示)
expect(heroTotal, `hero 上出现 ${heroTotal} 个 data-grow 目标,与「/home 剧本无生长目标」的口径不符`).toBe(0);
// 3. 四屏重播
await page.locator('#showcase').scrollIntoViewIfNeeded();
await page.waitForTimeout(500);
for (const { tab, panel, name } of PANELS) {
await page.click(tab);
await page.waitForTimeout(200);
const total = await totalTargets(page, panel);
expect(total, `${name}: data-grow 目标总数为 0(判据分母为空)`).toBeGreaterThan(0);
const before = await grown(page, panel);
const { peak } = await watchGrowth(page, panel, total);
expect(
peak === total || before < peak,
`${name} 切换后未重播:峰值 ${peak}(切换后 ${before},总数 ${total})`,
).toBe(true);
expect(peak, `${name} 未跑完:峰值 ${peak}/${total}`).toBe(total);
}
// 4. 离开视口复位
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForTimeout(1000);
const afterLeave = await grown(page, '#showcase-panel-process');
expect(afterLeave, `离开视口未复位: ${afterLeave}(期望 0)`).toBe(0);
// 7. 无 JS 运行时错误
expect(pageErrors, `landing 页有 JS 运行时错误:${pageErrors.join(' | ')}`).toEqual([]);
});
test('reduced-motion 直达终态 + 装饰图形对 AT 隐藏', async ({ page }) => {
await page.emulateMedia({ reducedMotion: 'reduce' });
await page.goto(LANDING_URL, { waitUntil: 'load' });
await page.waitForTimeout(1200);
await page.locator('#showcase').scrollIntoViewIfNeeded();
await page.waitForTimeout(400);
const rTotal = await totalTargets(page, '#showcase-panel-graph');
const rGrown = await grown(page, '#showcase-panel-graph');
expect(rTotal, 'reduced-motion 下 showcase 目标总数为 0(判据分母为空)').toBeGreaterThan(0);
expect(rGrown, `reduced-motion 未直达终态: ${rGrown}/${rTotal}`).toBe(rTotal);
// 6. 装饰性图形无障碍属性
const a11y = await page.evaluate(() => {
const FOCUSABLE = 'a[href], button, input, select, textarea, [tabindex]';
const heroDemo = document.querySelector('#heroDemo')?.getAttribute('aria-hidden') ?? null;
const showcaseVisuals = [...document.querySelectorAll('.showcase-visual')].map((e) =>
e.getAttribute('aria-hidden'),
);
const heroVisual = document.querySelector('.hero-visual')?.getAttribute('aria-hidden') ?? null;
const focusableInHidden = [...document.querySelectorAll('[aria-hidden="true"]')]
.flatMap((root) => [...root.querySelectorAll(FOCUSABLE)])
.filter((e) => !e.hasAttribute('disabled') && (e as HTMLElement).tabIndex >= 0)
.map((e) => `${e.tagName.toLowerCase()}#${e.id}`);
const btn = document.querySelector('#demoPause');
const demoPause = btn
? {
exists: true,
label: btn.getAttribute('aria-label'),
pressed: btn.getAttribute('aria-pressed'),
}
: { exists: false, label: null, pressed: null };
return { heroDemo, showcaseVisuals, heroVisual, focusableInHidden, demoPause };
});
expect(a11y.heroDemo, `演示层未对 AT 隐藏: ${a11y.heroDemo}`).toBe('true');
expect(a11y.showcaseVisuals.length, '.showcase-visual 一个都没选中(判据分母为空)').toBeGreaterThan(0);
expect(
new Set(a11y.showcaseVisuals),
`.showcase-visual aria-hidden 应全为 true,实测 ${JSON.stringify(a11y.showcaseVisuals)}`,
).toEqual(new Set(['true']));
// .hero-visual 承载暂停按钮,隐藏会连带隐藏控件 ⇒ 必须为 null
expect(a11y.heroVisual, '.hero-visual 不应 aria-hidden(它承载暂停控件)').toBeNull();
expect(a11y.focusableInHidden, `aria-hidden 子树内有可聚焦元素: ${a11y.focusableInHidden.join(',')}`).toEqual(
[],
);
expect(a11y.demoPause.exists, '暂停控件 #demoPause 不存在(WCAG 2.2.2 要求自动播放内容可暂停)').toBe(true);
expect(a11y.demoPause.label, '暂停控件缺 aria-label').toBeTruthy();
expect(a11y.demoPause.pressed, '暂停控件缺 aria-pressed 状态').not.toBeNull();
});
});
+72
View File
@@ -0,0 +1,72 @@
import { defineConfig, devices } from '@playwright/test';
import path from 'path';
/**
* Landing 门禁专用 Playwright 配置(`npm run test:landing`)。
*
* ## 为什么单独一份配置
*
* landing 的四道门禁原本是 `novavis-authority` 仓里的四个 python 脚本
* (`verify-landing-layout` / `verify-landing-motion` / `landing-demo-verify` /
* `landing-audit`),2026-12-03 随 landing 源码一起迁入本仓。它们**只在 chrome 单引擎、
* 单 project 下跑**,且每条用例自己 setViewportSize(视口是被测对象的一部分)。
*
* 若塞进 `playwright.config.ts` 的 4 个功能 project(chromium / chromium-mobile /
* firefox / webkit),同一套断言会在 4 个引擎 × 4 个视口下重复执行:
* ① 判据里有多处「窄视口下 X 不可见」的断言,在 mobile project 的固定 390 视口下会被
* spec 自己的 setViewportSize 覆盖,跑 4 遍等于跑 1 遍却贵 4 倍;
* ② webkit/firefox 上 `checkVisibility({checkVisibilityCSS})` 与 `:has()` 支持面不同,
* 会把「引擎差异」混进「landing 是否合规」的读数里。
*
* 所以用独立 config + 独立 project:**一个引擎、一份读数**,与迁移前的四道门禁口径一致。
* 主 config 完全不动(`test:functional` 显式传 --project,不会捡到本文件)。
*
* ## webServer
*
* 与主 config 同源:默认 `npm run dev`;`E2E_TARGET=production` 时打 `dist/standalone/server.js`。
* landing 是 `public/` 下的静态文件 + 4 条 rewrite(`next.config.mjs`),dev 与产物都能服务。
*/
export default defineConfig({
testDir: './landing',
fullyParallel: false, // 门禁共享同一个 dev server 且会改视口/注入 CSS,串行才能保证读数可复现
forbidOnly: !!process.env.CI,
retries: 0,
workers: 1,
reporter: [['list', { printSteps: true }]],
outputDir: path.join(__dirname, 'test-results-landing'),
use: {
baseURL: process.env.E2E_BASE_URL || 'http://localhost:3000',
trace: 'off',
screenshot: 'only-on-failure',
// 门禁自身会按需 setViewportSize,这里给一个与迁移前一致的初始视口
viewport: { width: 1440, height: 900 },
// landing 页无登录态:清空 storageState,避免把主站 cookie 带进来影响读数
storageState: { cookies: [], origins: [] },
ignoreHTTPSErrors: true,
actionTimeout: 15000,
navigationTimeout: 30000,
},
expect: { timeout: 15000 },
projects: [
{
name: 'landing',
// 顺序有意义:`devices[...]` 自带 viewport 1280×720,必须**在展开之后**覆盖,
// 否则 `use` 层写的 1440×900 会被 project 层盖掉(实测:hero 在 720 高视口下
// 落在首屏之外,IntersectionObserver 不触发,剧本采样到空序列而假失败)。
use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } },
},
],
webServer: {
command:
process.env.E2E_TARGET === 'production'
? 'HOSTNAME=localhost PORT=3000 node dist/standalone/server.js'
: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI && process.env.E2E_TARGET !== 'production',
timeout: 180000,
cwd: '..',
env: {
CMS_REVALIDATE_SECRET: process.env.CMS_REVALIDATE_SECRET || 'e2e-test-secret',
},
},
});
+7
View File
@@ -94,6 +94,13 @@ const config = [
// 本仓库自己的 0 error 口径被噪声淹没。
'.qoder/**',
'.stryker-tmp/**',
// 本地 dev 构建目录(`NEXT_DIST_DIR=.next-dev-live` 的产物)。
// 2026-12-03 实测:未忽略时 `eslint .` 会扫出 **21195 errors**(全是构建产物里的
// 压缩代码风格问题),把「0 error」的口径整体淹没;而该目录本就未入库。
'.next-dev-live/**',
// 本地 agent 工具目录(已 gitignore)。未忽略时其下的临时脚本会贡献 8 条 error,
// 同样不属于本仓门禁面。
'.workbuddy/**',
'out/**',
'build/**',
'dist/**',
+25 -5
View File
@@ -115,14 +115,34 @@ const nextConfig = {
},
async rewrites() {
return [
// 睿视 NovaVis landing 入口(2026-12-02 从 novavis-authority/landing **原样**迁入
// public/novavis/,内容零修改):源站按目录默认文档约定服务(https://novavis.p.novalon.cn/),
// Next 的 public 文件层不做目录 → index.html 补全(实测 /novavis/ 308 → /novavis → 404),
// 故入口用 rewrite 补齐。资产绝对路径(/css/style.css、/js/main.js、/assets/*、
// /images/logos/*)已按同名落 public 根,与源站 URL 语义一致、无需改写。
// ========================================================================
// 睿视 NovaVis landing(2026-12-03 起由**本仓**统一管理,authority 已退役该目录)
//
// 物理布局:`public/novavis/{index.html,css,js,assets,images/logos}` 一棵树自成一体。
// URL 契约:**保持源站形态不变** —— 页面引用仍是 `/css/style.css`、`/js/main.js`、
// `/assets/*`、`/images/logos/*` 这些站点级绝对路径。
//
// 为什么 URL 不能改:同一份字节要服务两个落点 ——
// ① 官网镜像 `novalon.cn/novavis/`(本仓 Next public 层);
// ② 独立子域 `novavis.p.novalon.cn/`(nginx `root /var/www/novavis-landing`,
// 页面在**根路径**)。改 HTML 为 `/novavis/...` 会把子域首页变成
// `novavis.p.novalon.cn/novavis/`,产品站首页带路径不可接受。
//
// 于是用 4 条 prefix rewrite 把根命名空间映射进子目录(ADR-0014 §4 的
// 「子目录化 + rewrites 前缀映射」模式,由此回溯到睿视)。根 `public/{css,js,assets,
// images/logos}` 已删除 ⇒ 这四条是这些前缀的**唯一**占用者,无歧义。
// 子域发布时把 `public/novavis/{css,js,assets,images}` 平铺到宿主目录根,URL 零变化。
//
// 入口 `/novavis` 单条:Next 的 public 文件层不做目录 → index.html 补全
// (实测 `/novavis/` 308 → `/novavis` → 404),故用 rewrite 补齐。
// landing 零内联脚本(唯一 script 为同源 /js/main.js)+ 4 处内联 style 属性,
// 生产 CSP(script-src 'self' + style-src 'self' 'unsafe-inline')实测放行。
// ========================================================================
{ source: '/novavis', destination: '/novavis/index.html' },
{ source: '/css/:path*', destination: '/novavis/css/:path*' },
{ source: '/js/:path*', destination: '/novavis/js/:path*' },
{ source: '/assets/:path*', destination: '/novavis/assets/:path*' },
{ source: '/images/logos/:path*', destination: '/novavis/images/logos/:path*' },
];
},
async headers() {
+2 -1
View File
@@ -37,6 +37,7 @@
"test:smoke": "cd e2e && npx playwright test --grep @smoke",
"test:critical": "cd e2e && npx playwright test --grep @critical",
"test:e2e:fast": "cd e2e && npx playwright test --grep '@smoke|@critical'",
"test:landing": "cd e2e && npx playwright test --config=playwright.landing.config.ts",
"test:e2e:standard": "cd e2e && npx playwright test --grep @regression",
"test:e2e:journey": "cd e2e && npx playwright test --grep @journey",
"test:e2e:prod": "cd e2e && E2E_TARGET=production npx playwright test --grep '@smoke|@critical|@journey' --project=chromium --project=chromium-mobile --project=firefox --project=webkit",
@@ -46,7 +47,7 @@
"test:e2e:mobile:accessibility": "cd e2e && npx playwright test --grep @mobile.*@accessibility",
"test:mutation": "rm -rf .stryker-tmp && npx stryker run",
"test:mutation:quick": "rm -rf .stryker-tmp && npx stryker run --mutate 'src/lib/utils.ts'",
"test:all": "npm run type-check && npm run check:package-keys && npm run type-check:e2e && npm run lint && npm run test:coverage && npm run test:integration:real && npm run check:a11y && npm run check:visual && npm run test:e2e:fast && npm run test:security:headers",
"test:all": "npm run type-check && npm run check:package-keys && npm run type-check:e2e && npm run lint && npm run test:coverage && npm run test:integration:real && npm run check:a11y && npm run test:landing && npm run check:visual && npm run test:e2e:fast && npm run test:security:headers",
"check:contrast": "tsx scripts/utils/check-color-contrast.ts",
"check:headings": "tsx scripts/utils/check-heading-hierarchy.ts",
"check:brand-token": "tsx scripts/utils/check-brand-text-token.ts",
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -53,11 +53,11 @@ const GROW = (() => {
try {
this.svg.pauseAnimations();
this.svg.setCurrentTime(0);
} catch (e) { /* 浏览器不支持 SMIL 控制时忽略 */ }
} catch { /* 浏览器不支持 SMIL 控制时忽略 */ }
}
releaseSmil() {
try { this.svg.unpauseAnimations(); } catch (e) { /* 同上 */ }
try { this.svg.unpauseAnimations(); } catch { /* 同上 */ }
}
stop() {
@@ -153,7 +153,7 @@ const DEMO = (() => {
this.stop();
if (this.grow) {
this.grow.stop();
try { if (this.grow.svg) this.grow.svg.pauseAnimations(); } catch (e) { /* 不支持 SMIL 控制时忽略 */ }
try { if (this.grow.svg) this.grow.svg.pauseAnimations(); } catch { /* 不支持 SMIL 控制时忽略 */ }
}
this.root.classList.add('demo-paused');
}
@@ -287,7 +287,7 @@ document.addEventListener('DOMContentLoaded', () => {
revealEls.forEach(revealIn);
}
document.documentElement.classList.add('js-reveal');
} catch (err) {
} catch {
document.documentElement.classList.remove('js-reveal');
}
@@ -588,7 +588,7 @@ document.addEventListener('DOMContentLoaded', () => {
demoPlayer.play();
}
}
} catch (err) {
} catch {
// 动效初始化失败:移除标记,图形恢复为完整可见的静态态
document.documentElement.classList.remove('js-grow');
document.documentElement.classList.remove('js-demo');
@@ -739,7 +739,7 @@ document.addEventListener('DOMContentLoaded', () => {
document.body.appendChild(ta);
ta.select();
let ok = false;
try { ok = document.execCommand('copy'); } catch (err) { ok = false; }
try { ok = document.execCommand('copy'); } catch { ok = false; }
document.body.removeChild(ta);
return ok;
}
+439
View File
@@ -0,0 +1,439 @@
#!/usr/bin/env python3
"""Landing page 审计门禁:结构可访问性 + 全量可见文字对比度扫描。
用法(在仓库根目录,先起静态服务):
cd landing && python3 -m http.server 8099 --bind 127.0.0.1
/usr/bin/python3 scripts/landing-audit.py --url http://127.0.0.1:8099/
/usr/bin/python3 scripts/landing-audit.py --url http://127.0.0.1:8099/ --shots /tmp/out --json
分级判据(第四道 landing 门禁):
阻断级 P1(任一命中 → 退出码 1):
- 同色前景/背景:`rgb(x, x, x) on rgb(x, x, x)`。**无条件阻断**,不受 --fail 影响——
否则把 --fail 调到 ≤ 1.0 时同色(1.00:1)会静默放行,这正是 2026-11-04 Blocking① 的形态。
- 对比度 < --fail(默认 3.0,WCAG 大号文本线)
- 结构项:横向溢出 / 缺 alt / 可聚焦元素无名称 / h1 数量 ≠ 1
警告级 P2(逐条打印,**退出码仍为 0**,须人工定夺,不得静默忽略):
- 对比度落在 [--fail, --warn)(默认 4.5 = WCAG AA 正文线)
- 焦点指示缺失
退出码:有阻断级 P1 → 1;仅警告级 P2 → 0。
结束行打印 `AUDIT_RESULT: PASS|FAIL` 及阻断/警告分项计数。
为什么扫「全量」而不是点选若干选择器:2026-11-04 的 Blocking①(屏 2 白底白字,
对比度 1.05:1)之所以从三道门禁缝里漏掉,是因为点选式断言只覆盖被想到的选择器。
本脚本改为遍历所有直接含文字的元素,并先解除动效的初始隐藏态
(js-grow / js-reveal / showcase-panel hidden),把每一屏都点亮后再测——
包括当前不在视口内、以及 aria-hidden 装饰子树内的文字。
SVG 文字按 paint 的 fill 判,并以同组内先绘制的形状为底:否则会把继承来的
color(深色主题下是白)当成画出来的颜色,整片图谱标签误报 1.05:1。
"""
from playwright.sync_api import sync_playwright
import argparse, json, math, sys
from pathlib import Path
FAIL_MIN_DEFAULT = 3.0 # WCAG 大号文本线;低于此视为不可读
WARN_MIN_DEFAULT = 4.5 # WCAG 正文 AA 线
# 把所有动效门控的初始隐藏态解除,让每一屏、每一个生长元素都真实呈现后再测
REVEAL_ALL_JS = """
() => {
const root = document.documentElement;
root.classList.remove('js-grow', 'js-reveal');
document.querySelectorAll('.rv').forEach((el) => el.classList.add('in'));
// 生长元素:直接落到终态
document.querySelectorAll('[data-grow]').forEach((host) => {
host.classList.add('is-grown');
host.querySelectorAll('*').forEach((c) => c.classList.add('is-grown'));
if (!host.querySelector('[data-grow]')) host.classList.add('is-grown');
});
// 轮播面板全部展开(默认 hidden + 非 active 不渲染)
document.querySelectorAll('.showcase-panel').forEach((p) => {
p.hidden = false;
p.classList.add('active');
p.style.display = 'grid';
});
// 首屏演示:停在终态并暂停,避免计时器改 DOM
const hero = document.querySelector('#heroDemo');
if (hero) hero.className = hero.className.replace(/demo-step-\\d/g, 'demo-final');
['#showcasePause', '#demoPause'].forEach((sel) => {
const b = document.querySelector(sel);
if (b && b.getAttribute('aria-pressed') === 'false') b.click();
});
return {
panels: document.querySelectorAll('.showcase-panel').length,
heroClass: hero ? hero.className : null,
};
}
"""
CONTRAST_SCAN_JS = """
(args) => {
const {failMin, warnMin} = args;
const parse = (s) => {
if (!s) return null;
const m = s.match(/rgba?\\(([^)]+)\\)/);
if (!m) return null;
const p = m[1].split(/[\\s,\\/]+/).filter(Boolean).map(parseFloat);
if (p.length < 3 || p.some(isNaN)) return null;
return {r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1};
};
const chan = (c) => { c /= 255; return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); };
const lum = (c) => 0.2126 * chan(c.r) + 0.7152 * chan(c.g) + 0.0722 * chan(c.b);
const ratio = (fg, bg) => {
const l1 = lum(fg) + 0.05, l2 = lum(bg) + 0.05;
return l1 >= l2 ? l1 / l2 : l2 / l1;
};
const over = (top, bottom) => ({
r: top.r * top.a + bottom.r * (1 - top.a),
g: top.g * top.a + bottom.g * (1 - top.a),
b: top.b * top.a + bottom.b * (1 - top.a),
a: 1,
});
const SVG_TEXT_TAGS = new Set(['text', 'tspan']);
const isSvgText = (el) => SVG_TEXT_TAGS.has(el.tagName.toLowerCase()) && !!el.ownerSVGElement;
// 前景:HTML 取 color;SVG 文字取 paint 的 fill(color 只是继承值,不是画出来的色)
//
// ⚠️ 返回的是**已解析但未合成**的色(可能带 alpha)。调用方必须在下结论前用
// compositeFg() 把前景叠到真实背景上——**不要直接拿它算 ratio**,见下方长注释。
const fgOf = (el, st) => {
if (isSvgText(el)) {
if (st.fill === 'none') return null;
const f = parse(st.fill);
return f && f.a > 0 ? f : null;
}
return parse(st.color);
};
// 前景按背景合成。
//
// 【为什么必须有这一步 —— 2026-11-07 §28.2 评审 BLOCK 落项】
// ratio() 只吃 rgb 三元组、不看 alpha。若把带 alpha 的前景直接喂进去,得到的是
// 「把这个半透明颜色当成不透明色」的对比度,即 alpha 越低算出的对比度越**高**:
// color: rgba(0,0,0,.05) 在白底上 → 直接算 21.00:1(完美),真实 1.12:1(不可见)
// color: transparent → 解析成 rgba(0,0,0,0) → 直接算 21.00:1,真实 1.00:1
// 后者正是「标题消失」的常见写法之一,会让本门禁对同类回归零判别力
// (本轮的立论点就是「它是唯一覆盖标题是否可见的门禁」)。
// 实测佐证:`.process-step-number`(rgba(15,23,42,.04)) 真值 1.08:1,未合成时报 16.63:1。
//
// 背景侧 bgOfAncestors() 一直是逐层 over() 合成到不透明底的(那段是对的),
// 缺的一直只有前景这一侧——补上后两侧口径才一致。
// 返回 a=1 的实色;透明度为 0 的前景与背景同色,ratio 自然是 1.00,落入同色阻断。
const compositeFg = (fg, bg) => (fg.a >= 0.999 ? {r: fg.r, g: fg.g, b: fg.b, a: 1} : over(fg, bg));
const bgOfAncestors = (el) => {
const layers = [];
let n = el;
while (n && n.nodeType === 1) {
const c = parse(getComputedStyle(n).backgroundColor);
if (c) {
if (c.a >= 0.999) { layers.push(c); break; }
layers.push(c);
}
n = n.parentElement;
}
let base = {r: 255, g: 255, b: 255, a: 1};
for (let i = layers.length - 1; i >= 0; i--) base = over(layers[i], base);
return base;
};
// SVG 文字的真实底:同一容器内、绘制顺序在它之前且有不透明 fill 的形状
const shapeUnder = (el) => {
const parent = el.parentElement;
if (!parent) return null;
let hit = null;
for (const k of parent.children) {
if (k === el) break;
const t = k.tagName.toLowerCase();
if (t === 'text' || t === 'tspan') continue;
const f = parse(getComputedStyle(k).fill);
if (f && f.a >= 0.9) hit = f;
}
return hit;
};
const effectiveBg = (el) => {
const canvas = bgOfAncestors(el);
if (isSvgText(el)) {
const shape = shapeUnder(el);
if (shape) return over({r: shape.r, g: shape.g, b: shape.b, a: shape.a}, canvas);
}
return canvas;
};
const pathOf = (el) => {
const parts = [];
let n = el;
while (n && n.nodeType === 1 && parts.length < 4) {
let s = n.id ? '#' + n.id : n.tagName.toLowerCase();
if (!n.id && n.className && typeof n.className === 'string') {
const c = n.className.trim().split(/\\s+/).filter(Boolean).slice(0, 2);
if (c.length) s += '.' + c.join('.');
}
parts.unshift(s);
n = n.parentElement;
}
return parts.join(' > ');
};
const hasDirectText = (el) => [...el.childNodes].some(
(n) => n.nodeType === 3 && n.textContent.trim().length > 0
);
const visible = (el) => {
const st = getComputedStyle(el);
if (st.visibility === 'hidden' || st.display === 'none' || parseFloat(st.opacity) < 0.05) return false;
const r = el.getBoundingClientRect();
return r.width >= 2 && r.height >= 2;
};
const out = [];
const seen = new Set();
for (const el of document.querySelectorAll('body *')) {
if (!hasDirectText(el) || !visible(el)) continue;
const st = getComputedStyle(el);
const fg = fgOf(el, st);
if (!fg) continue;
const bg = effectiveBg(el);
const fsz = parseFloat(st.fontSize);
const weight = parseInt(st.fontWeight, 10) || 400;
const need = (fsz >= 24 || (fsz >= 18.66 && weight >= 700)) ? 3.0 : 4.5;
// 必须先按背景合成再算 ratio:否则半透明/透明前景会被算成「高对比」(见 compositeFg 注释)
const fgSolid = compositeFg(fg, bg);
const r = ratio(fgSolid, bg);
if (r >= need) continue;
const key = pathOf(el) + '|' + (el.textContent || '').trim().slice(0, 24);
if (seen.has(key)) continue;
seen.add(key);
out.push({
path: pathOf(el),
ratio: +r.toFixed(2),
need,
fg: `rgb(${Math.round(fgSolid.r)}, ${Math.round(fgSolid.g)}, ${Math.round(fgSolid.b)})`,
bg: `rgb(${Math.round(bg.r)}, ${Math.round(bg.g)}, ${Math.round(bg.b)})`,
font: `${fsz}px/${weight}`,
text: (el.textContent || '').trim().replace(/\\s+/g, ' ').slice(0, 40),
hidden: !!el.closest('[aria-hidden="true"]'),
// 显式装饰标记:**只有作者主动标注**才算,绝不从 aria-hidden 推断。
// 为什么不做自动推断:装饰子图里同样可能藏真缺陷(本脚本刻意连 aria-hidden 子树一起扫),
// 用 aria-hidden 推断豁免等于给「整块藏起来」开了后门,与本门禁的立论点冲突。
decorative: !!el.closest('[data-audit-decorative]'),
});
}
out.sort((a, b) => a.ratio - b.ratio);
// 同色检测在全量 out 上做,不能被 worst 的 80 条截断吃掉
const sameColor = out.filter((o) => o.fg === o.bg);
// 装饰豁免的成立条件(**两条缺一不可**):
// ① 作者以 data-audit-decorative **主动标注**(不从 aria-hidden 自动推断,那等于给"整块藏起来"开后门);
// ② 该文字本身在 aria-hidden 子树里 —— 即它对辅助技术不存在、没有信息量。
// 只标属性而不 aria-hidden 的正文**不成立豁免**:否则一段真的低对比度正文
// 只要被打上装饰标记就能逃逸,豁免就变成绕过通道了(已用注入探针验证过这个边界)。
// 另外同色**永远**阻断、不受豁免影响:透明标题是最典型的"标题消失"形态,
// 让它可以靠标属性混过去,本门禁就等于没有(同样有注入探针钉住)。
const isDeco = (o) => o.decorative && o.hidden && o.fg !== o.bg;
const deco = out.filter(isDeco);
const real = out.filter((o) => !isDeco(o));
return {
worst: real.slice(0, 80),
total: real.length,
belowFail: real.filter((o) => o.ratio < failMin).length,
belowWarn: real.filter((o) => o.ratio < warnMin).length,
minRatio: real.length ? real[0].ratio : null,
sameColor: sameColor.length,
sameColorKeys: sameColor.map((o) => o.path + '|' + o.text),
blocked: real.filter((o) => o.ratio < failMin || o.fg === o.bg).length,
warned: real.filter((o) => o.ratio >= failMin && o.ratio < warnMin && o.fg !== o.bg).length,
// 装饰豁免项照常回报(逐条打印成 NOTE,不静默吞掉),但不计入阻断/警告
decorative: deco.length,
decorativeItems: deco.map((o) => ({path: o.path, ratio: o.ratio, text: o.text})),
};
}
"""
def structural_checks(page, name):
"""P1/P2 结构项:溢出、alt、可访问名、h1、焦点指示。"""
issues = []
scroll_w = page.evaluate("() => document.documentElement.scrollWidth")
client_w = page.evaluate("() => window.innerWidth")
if scroll_w > client_w:
issues.append(f"P1 [{name}] horizontal overflow: {scroll_w} > {client_w}")
for img in page.locator("img").all():
if img.get_attribute("alt") is None:
issues.append(f"P1 [{name}] img missing alt: src={img.get_attribute('src')}")
bad = page.evaluate(
"""() => {
const els = Array.from(document.querySelectorAll(
'a, button, input, textarea, select, [role="tab"], summary'));
return els.filter(el => {
const name = el.getAttribute('aria-label') || el.getAttribute('title') ||
el.textContent.trim() || el.getAttribute('placeholder') || '';
return !name;
}).map(el => el.outerHTML.slice(0, 120));
}"""
)
for b in bad[:5]:
issues.append(f"P1 [{name}] interactive element without accessible name: {b}")
h1s = page.locator("h1").count()
if h1s != 1:
issues.append(f"P1 [{name}] heading hierarchy: {h1s} h1")
for sel in (".nav-links a", "#navToggle"):
loc = page.locator(sel).first
try:
if not loc.is_visible():
continue
loc.focus()
if loc.evaluate("el => getComputedStyle(el).outlineWidth") == "0px":
issues.append(f"P2 [{name}] focus indicator missing on {sel}")
except Exception:
pass
return issues, (scroll_w, client_w)
def audit_page(browser, base_url, width, height, name, args, report):
page = browser.new_page(viewport={"width": width, "height": height})
page.goto(base_url, wait_until="networkidle")
page.wait_for_timeout(600)
issues, dims = structural_checks(page, name)
if args.shots:
out_dir = Path(args.shots)
out_dir.mkdir(parents=True, exist_ok=True)
shot = str(out_dir / f"audit-{name}-{width}.png")
page.screenshot(path=shot, full_page=True)
else:
shot = None
reveal = page.evaluate(REVEAL_ALL_JS)
page.wait_for_timeout(200)
scan = page.evaluate(CONTRAST_SCAN_JS, {"failMin": args.fail, "warnMin": args.warn})
same_ids = set(scan["sameColorKeys"])
# 阻断级 = 对比度 < --fail ∪ 同色(同色无条件阻断:--fail 调到 ≤ 1.0 时 1.00:1 不得放行)
blocking = [
o for o in scan["worst"]
if o["ratio"] < args.fail or (o["path"] + "|" + o["text"]) in same_ids
]
band = [
o for o in scan["worst"]
if args.fail <= o["ratio"] < args.warn
and (o["path"] + "|" + o["text"]) not in same_ids
]
for o in blocking:
suffix = " [aria-hidden]" if o["hidden"] else ""
if (o["path"] + "|" + o["text"]) in same_ids:
issues.append(
f"P1 [{name}] 同色前景/背景 {o['fg']} on {o['bg']}(对比度 {o['ratio']})"
f"@{o['font']} — {o['path']} «{o['text']}»{suffix}"
)
else:
issues.append(
f"P1 [{name}] contrast {o['ratio']} < {args.fail} (需 {o['need']}) "
f"{o['fg']} on {o['bg']} @{o['font']} — {o['path']} «{o['text']}»{suffix}"
)
for o in band[: args.list]:
issues.append(
f"P2 [{name}] contrast {o['ratio']} < {args.warn} (需 {o['need']}) "
f"{o['fg']} on {o['bg']} @{o['font']} — {o['path']} «{o['text']}»"
+ (" [aria-hidden]" if o["hidden"] else "")
)
if len(band) > args.list:
issues.append(f"P2 [{name}] …另有 {len(band) - args.list} 条对比度落在 [{args.fail},{args.warn})")
# 装饰豁免项:逐条打印为 NOTE(不静默),但不进阻断/警告计数。
# 「不静默」是刻意的——豁免必须是可审计的,不能因为标了个属性就从报告里消失。
for o in scan["decorativeItems"]:
issues.append(
f"NOTE [{name}] 装饰豁免 contrast {o['ratio']} — {o['path']} «{o['text']}»"
"(作者以 data-audit-decorative 标注为刻意淡化,不计入阻断/警告)"
)
page_errors = []
report[name] = {
"viewport": [width, height],
"screenshot": shot,
"scrollWidth": dims[0],
"clientWidth": dims[1],
"revealedPanels": reveal["panels"],
"contrast": {
"minRatio": scan["minRatio"],
"offenders": scan["total"],
"belowFail": scan["belowFail"],
"belowWarn": scan["belowWarn"],
"sameColor": scan["sameColor"],
"decorative": scan["decorative"],
},
"blocked": scan["blocked"],
"warned": scan["warned"],
"issues": issues,
}
page.close()
def main():
ap = argparse.ArgumentParser(description="Landing page 结构与对比度审计门禁")
ap.add_argument("--url", default="http://127.0.0.1:8088/", help="已启动的 landing 静态服务地址")
ap.add_argument("--shots", default="", help="传入目录则输出整页截图")
ap.add_argument("--fail", type=float, default=FAIL_MIN_DEFAULT,
help="阻断级对比度下限(默认 3.0);同色前景/背景不受此参数影响,始终阻断")
ap.add_argument("--warn", type=float, default=WARN_MIN_DEFAULT,
help="警告级对比度上限(默认 4.5);落在 [--fail, --warn) 只打印不阻断")
ap.add_argument("--list", type=int, default=20, help="每个视口最多打印多少条 P2(默认 20)")
ap.add_argument("--json", action="store_true", help="额外打印 JSON 报告")
args = ap.parse_args()
report = {}
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
for width, height, name in (
(1440, 900, "desktop"),
(768, 1024, "tablet"),
(390, 844, "mobile"),
):
audit_page(browser, args.url, width, height, name, args, report)
browser.close()
p1 = [i for v in report.values() for i in v["issues"] if i.startswith("P1")]
p2 = [i for v in report.values() for i in v["issues"] if i.startswith("P2")]
notes = [i for v in report.values() for i in v["issues"] if i.startswith("NOTE")]
same_total = sum(v["contrast"]["sameColor"] for v in report.values())
print("== Landing 全量可见文字对比度扫描(已解除动效隐藏态)==")
for name, v in report.items():
c = v["contrast"]
print(
f" {name:>8} 展开面板 {v['revealedPanels']} 最低 {c['minRatio']} "
f"低于判据 {c['offenders']} 条 其中同色 {c['sameColor']} "
f"阻断级(P1) {v['blocked']} 警告级(P2) {v['warned']}"
)
if p1 or p2:
print("\n== 问题清单 ==")
for i in p1:
print(" " + i[:220])
for i in p2:
print(" " + i[:220])
else:
print("\n== 无问题 ==")
# 装饰豁免始终单独列出(即使全绿):豁免必须可审计,不能因为"没红"就从报告里消失
if notes:
print("\n== 装饰豁免(作者以 data-audit-decorative 主动标注,不计入阻断/警告)==")
for i in notes:
print(" " + i[:220])
if args.json:
print(json.dumps(report, indent=2, ensure_ascii=False))
print("\n" + "=" * 46)
blocked_total = sum(v["blocked"] for v in report.values())
warned_total = sum(v["warned"] for v in report.values())
if p1:
print(
f"AUDIT_RESULT: FAIL (阻断 P1={len(p1)} [同色 {same_total}] "
f"警告 P2={len(p2)} 全量: 阻断 {blocked_total} / 警告 {warned_total})"
)
sys.exit(1)
print(
f"AUDIT_RESULT: PASS (阻断 P1=0 警告 P2={len(p2)} "
f"全量: 阻断 0 / 警告 {warned_total})"
)
sys.exit(0)
if __name__ == "__main__":
main()
+247
View File
@@ -0,0 +1,247 @@
#!/usr/bin/env python3
"""Hero Live Demo 演示动画验证脚本(landing/index.html #heroDemo)。
用法:
NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1 \
python3 scripts/landing-demo-verify.py [--url http://127.0.0.1:8088/] [--out /tmp/demo-verify]
验证内容:
1. 四步剧本各阶段截图(导入 → 图谱 → 检测 → AI 结论)
2. 循环重播(第二轮 demo-step-1 回归)
3. 无 JS 降级:演示层不可见、静态 mockup 完整、指标为终值
4. prefers-reduced-motion:demo-final 终态一次呈现
5. console error / pageerror 收集
"""
import argparse
import json
import sys
import time
from pathlib import Path
from playwright.sync_api import sync_playwright
# 剧本阶段与采样时刻(秒)。2026-11-07 hero 主图由图窗改为 /home 任务工作台后,
# 四步语义随之重写(新建任务 → 打开任务 → 导入数据 → 就绪),阶段名同步改掉;
# DUR = {s1:2.6, s2:3.4, s3:3.2, s4:3.8, hold:1.6},故 1.4 / 4.4 / 7.6 / 11.6 / 16.4 的
# 采样点相对于新剧本仍然落在各自的步内——**时刻未改,只改了阶段名**,因为改动时刻会让
# 「脚本采样点」与「动画真实时间轴」脱钩,那是判据自伤而不是适配。
STEPS = [
("step1-create", 1.4),
("step2-open", 4.4),
("step3-import", 7.6),
("step4-ready", 11.6),
("loop-restart", 16.4),
]
def cls_of(page):
return page.evaluate("document.getElementById('heroDemo').className")
# 步号 → 该步应当显示的徽标文案(与 index.html 的 data-badge 一一对应)
BADGE_OF_STEP = {
"demo-step-1": "新建任务",
"demo-step-2": "打开任务",
"demo-step-3": "导入数据",
"demo-step-4": "就绪",
}
def badges_now(page):
"""当前**真实可见**的徽标文案列表(三层可见性,与 nojs 判定同口径)。"""
return page.evaluate("""
() => [...document.querySelectorAll('.demo-chrome-badge-item')]
.filter((el) => {
const r = el.getBoundingClientRect();
if (!el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true})) return false;
if (r.width <= 0 || r.height <= 0) return false;
let op = 1, n = el;
while (n && n.nodeType === 1) {
const o = parseFloat(getComputedStyle(n).opacity);
if (!Number.isNaN(o)) op *= o;
if (op <= 0.05) return false;
n = n.parentElement;
}
return true;
})
.map((el) => el.textContent.trim())
""")
def check_badge_matches_step(cls_samples, badge_samples):
"""【SHOULD-FIX-2 / 2026-11-07 复审】
徽标是 BLOCKING-1 修完后的核心资产(「徽标与步号同义」),但此前**只靠人眼守**:
复审的 PROBE-E 把 style.css 里整块徽标显示规则删掉,四道门禁仍然全绿。
这里补正向断言:四个采样点上,当前步必须**恰好显示 1 个**徽标,且文案与该步同义。
为什么是"恰好 1 个"而不是">= 1":同时显示两个徽标说明映射有重叠(正是首轮
「错位一整步」的伴生症状),那会让观众同时看到两个互斥的进度。
"""
problems = []
for name, cls in cls_samples.items():
step = next((st for st in BADGE_OF_STEP if st in cls), None)
if step is None:
continue # loop-restart 采样点落在复位瞬间,不判
want = BADGE_OF_STEP[step]
got = badge_samples.get(name, [])
if len(got) != 1:
problems.append(f"{name}: {step} 应恰好显示 1 个徽标,实测 {len(got)} 个 {got}")
elif got[0] != want:
problems.append(f"{name}: {step} 应显示「{want}」,实测「{got[0]}」")
return {"ok": not problems, "problems": problems}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--url", default="http://127.0.0.1:8088/")
ap.add_argument("--out", default="/tmp/demo-verify")
args = ap.parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
report = {"console_errors": [], "page_errors": []}
with sync_playwright() as p:
browser = p.chromium.launch(channel="chrome", headless=True)
# ---- 场景 1:正常播放,分阶段截图 + 类名采样 ----
pg = browser.new_page(viewport={"width": 1440, "height": 900})
pg.on("console", lambda m: report["console_errors"].append(m.text) if m.type == "error" else None)
pg.on("pageerror", lambda e: report["page_errors"].append(str(e)))
pg.goto(args.url, wait_until="load", timeout=60000)
samples = {}
badges = {}
start = time.time()
for name, at in STEPS:
delta = at - (time.time() - start)
if delta > 0:
pg.wait_for_timeout(delta * 1000)
samples[name] = cls_of(pg)
badges[name] = badges_now(pg)
pg.screenshot(path=str(out / f"{name}.png"), clip={"x": 620, "y": 120, "width": 800, "height": 620})
report["class_samples"] = samples
report["badge_samples"] = badges
report["badge_step_check"] = check_badge_matches_step(samples, badges)
# ---- 场景 2:无 JS 降级 ----
ctx2 = browser.new_context(java_script_enabled=False, viewport={"width": 1440, "height": 900})
pg2 = ctx2.new_page()
pg2.goto(args.url, wait_until="load", timeout=60000)
pg2.wait_for_timeout(500)
# 无 JS 降级(2026-11-07 口径迁移):原断言挂在图窗的 .demo-import / .demo-ai /
# [data-count-to=2046](= 关系数)/ .app-mockup-alert 上,那四样随 hero 改画 /home 已不存在。
# 新口径问的是同一个问题——"没有 JS 时,首屏该看见的数是不是已经看得见":
# · 任务总数读数 = 6(而不是被脚本归零的 0)
# · 当前打开行仍在(is-current 是静态类,不靠 JS 加)
# · 列头可见(视口锁定后列头只渲染一次,它是纯静态结构)
# 【2026-11-07 §28.2 评审 BLOCKING-2 修法:判据收紧,不是放宽】
# 上一版只读 textContent + computed display,对「内容在、但看不见」零判别力:
# 评审用 `html:not(.js-demo) .nv-home-rows{opacity:0!important;visibility:hidden!important}`
# 注入后本门禁仍然 PASS,截图是空白台账。那与 2026-11-04 的 Blocking① 是同一失效模式
# (那一轮也是"内容在、看不见、门禁全绿")。
# 现改为**真实可见性**判定,四层缺一不可:
# ① checkVisibility({checkOpacity, checkVisibilityCSS}) —— 浏览器自己的口径
# ② 祖先链上 opacity 有效值 > 0.05(checkVisibility 对 opacity 的处理在旧内核不一致)
# ③ 元素矩形有面积(width/height > 0,排除被 layout 折叠)
# ④ 文字非空
report["nojs"] = {
# 台账读数是**静态数据**(6 个任务),不是动画指标——它旁边列着 4 行真实任务,
# 若写成 0 就与内容自相矛盾。故这里断言它无 JS 时就等于 6。
"task_total": pg2.evaluate(
"document.querySelector('.nv-home-pager b').textContent"),
"current_row": pg2.evaluate(
"document.querySelectorAll('.nv-home-row.is-current').length"),
# 列头 + 第一行任务:不仅看 display,还要真的**看得见**
"cols_visible": pg2.evaluate(
"document.querySelector('.nv-home-cols').checkVisibility("
"{checkOpacity:true, checkVisibilityCSS:true})"),
"rows_visible": pg2.evaluate("""
() => {
const rows = [...document.querySelectorAll('.nv-home-row')];
if (rows.length === 0) return 0;
return rows.filter((el) => {
const st = getComputedStyle(el);
const r = el.getBoundingClientRect();
// ② 祖先链有效 opacity
let op = 1, n = el;
while (n && n.nodeType === 1) {
const o = parseFloat(getComputedStyle(n).opacity);
if (!Number.isNaN(o)) op *= o;
if (op <= 0.05) return false;
n = n.parentElement;
}
// ① + ③ + ④
const visible = el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});
return visible && r.width > 0 && r.height > 0
&& (el.textContent || '').trim().length > 0;
}).length;
}
"""),
"demo_rows_seen": pg2.evaluate(
"document.querySelectorAll('.nv-home-row').length"),
# 反向断言:**仅动画层**的徽标在无 JS 时必须不可见。
# 它只在演示推进时有意义("现在走到哪一步"),无 JS 时没有步骤可指,
# 显示出来就是一条没有指涉的标签。评审用
# `.demo-chrome-badge{display:flex!important}` 注入出一条,上一版断言放过了它。
"badge_visible": pg2.evaluate("""
() => [...document.querySelectorAll('.demo-chrome-badge-item')]
.filter((el) => {
const r = el.getBoundingClientRect();
return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true})
&& r.width > 0 && r.height > 0;
}).length
"""),
# 正向金丝雀:选择器必须真的命中元素。
# 否则 `badge_visible == 0` 会因为"一个徽标都没选中"而恒真——恒真的断言等于没有断言
# (本仓反复踩过这个形状:判据通过态是 0 或空集时,"0"本身不是证据)。
"badge_count": pg2.evaluate(
"document.querySelectorAll('.demo-chrome-badge-item').length"),
}
pg2.screenshot(path=str(out / "nojs-static.png"), clip={"x": 620, "y": 120, "width": 800, "height": 620})
ctx2.close()
# ---- 场景 3:prefers-reduced-motion ----
ctx3 = browser.new_context(reduced_motion="reduce", viewport={"width": 1440, "height": 900})
pg3 = ctx3.new_page()
pg3.on("pageerror", lambda e: report["page_errors"].append("reduced: " + str(e)))
pg3.goto(args.url, wait_until="load", timeout=60000)
pg3.wait_for_timeout(1200)
report["reduced"] = {
"hero_class": pg3.evaluate("document.getElementById('heroDemo').className"),
"task_total": pg3.evaluate(
"document.querySelector('.nv-home-pager b').textContent"),
"current_row": pg3.evaluate(
"document.querySelectorAll('.nv-home-row.is-current').length"),
}
pg3.screenshot(path=str(out / "reduced-final.png"), clip={"x": 620, "y": 120, "width": 800, "height": 620})
ctx3.close()
browser.close()
print(json.dumps(report, ensure_ascii=False, indent=2))
# 判定:无 pageerror + 循环回归 demo-step-1 + 无 JS 降级成立
ok = (
not report["page_errors"]
and "demo-step-1" in report["class_samples"].get("loop-restart", "")
# 无 JS 时必须直接看到终值 6(脚本未接管就不该出现 0)
and report["nojs"]["task_total"] == "6"
and report["nojs"]["current_row"] == 1
# 列头与**全部**任务行必须真的可见(不是"存在但被 opacity/visibility 藏起来")
and report["nojs"]["cols_visible"] is True
and report["nojs"]["demo_rows_seen"] > 0
and report["nojs"]["rows_visible"] == report["nojs"]["demo_rows_seen"]
# 仅动画层在无 JS 时不得可见;且选择器必须非空(否则上一条恒真)
and report["nojs"]["badge_count"] > 0
and report["nojs"]["badge_visible"] == 0
and "demo-final" in report["reduced"]["hero_class"]
# 徽标正向:每步恰好 1 个且与步号同义(SHOULD-FIX-2)
and report["badge_step_check"]["ok"]
)
print("VERIFY_RESULT:", "PASS" if ok else "FAIL")
return ok
if __name__ == "__main__":
# 判据必须同时体现在 stdout 和退出码上:只打印 FAIL 而恒 exit 0,
# 会让 §19/§21 引用的「门禁 exit 0」失去证明力(自检见 scripts/selfcheck-gates.sh)
sys.exit(0 if main() else 1)
@@ -0,0 +1,31 @@
<!doctype html>
<!--
门禁自检夹具(scripts/selfcheck-gates.sh 使用)
这是一个「必然让 landing-demo-verify.py 判 FAIL、但自己不抛异常」的页面:
演示容器、无 JS 降级节点、reduced-motion 节点都存在(选择器齐全 ⇒ 不产生 pageerror),
但类名与数值全部不符合剧本判据。用它证明被检门禁「有能力失败」。
Last updated: 2026-09-20
-->
<html lang="zh">
<head>
<meta charset="utf-8">
<title>gate selfcheck fixture</title>
<style>
/* 截图裁剪区为 x620 y120 w800 h620,页面须铺满 1440x900 视口 */
html, body { width: 1440px; height: 900px; min-width: 1440px; min-height: 900px; margin: 0; }
.demo-import, .demo-ai, .demo-ai-msg, .app-mockup-alert { display: block; }
</style>
</head>
<body>
<div id="heroDemo" class="hero-demo-static">
<div class="demo-import">import</div>
<div class="demo-ai">
<div class="demo-ai-msg">ai</div>
</div>
<div class="app-mockup-alert">alert</div>
<span data-count-to="2046">0</span>
</div>
</body>
</html>
+305
View File
@@ -0,0 +1,305 @@
#!/usr/bin/env python3
"""landing 布局几何与焦点管理验证(复评 P2-7 / P2-8 / P2-9 的判别性门禁)。
前置:先起本地静态服务
python3 -m http.server 8088 --bind 127.0.0.1 --directory landing
用法:
NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1 \
python3 scripts/verify-landing-layout.py [--url http://127.0.0.1:8088/] [--only tabs,focus,cta] [--shots /tmp/landing-shots]
检查项:
1. tabs:各视口下 .showcase-tabs 的每个 tab 中心不被 #showcasePause 覆盖
(窄视口下绝对定位的暂停按钮压在 tab 行之上),且无横向溢出
2. focus:showcase 轮播的焦点管理(WCAG 2.2.2 精神)
a. 焦点进入卡片后自动轮播让位(持焦期间 active tab 不变)
b. 持焦 tab 不被摘掉 tabindex(摘掉即被移出 tab 序列,键盘焦点无处可回)
c. 失焦后轮播恢复(证明 a 不是「轮播整体坏了」的假通过)
3. roving:方向键切换后整组只留一只 tab 可被 Tab 键到达,且该只即 active 那只
(roving tabindex 单点不变量;焦点须跟随 active)
4. cta:nav 转化入口与信息链接有可视分层(描边/底色至少一项不同)
5. --shots:把上述几处截成图片,供人工看几何与视觉权重(像素层面的重叠、
留白、按钮挤行无法靠数值断言穷尽)
注意:悬停会冻结轮播(既有设计),故 focus 项全程把鼠标移到 (0,0) 并显式核对
卡片已滚入视口——否则测的是 hover 冻结而非 focusin 暂停(本仓踩过)。
2b 与 3 分工:2b 只在「持焦期间不切」的暂停语义下观察,真正判别 tabindex 时序
缺陷的是 3(方向键切换 → syncRovingTabindex 与 focus() 的先后决定旧 tab 是否残留
tabindex="0")。二者都不覆盖 2b 所防的那个竞态窗口(轮播回调已在 focusin 之前入队),
该分支须驱动闭包内部函数才能命中,不为其暴露生产 API,仅由代码注释交代。
Last updated: 2026-09-20
maintainer: novavis-authority
"""
import argparse
import sys
import time
from pathlib import Path
from playwright.sync_api import sync_playwright
VIEWPORTS = [
("桌面 1440", 1440, 900),
("笔记本 1024", 1024, 768),
("平板竖屏 768", 768, 1024),
("手机 480", 480, 900),
("手机 375", 375, 812),
]
CYCLE_MS = 5500
# 轮播间隔 + 余量:等待窗口内若未暂停,active tab 必定已切换
WAIT_S = (CYCLE_MS / 1000) + 2.0
TAB_INFO = """() => {
const pause = document.querySelector('#showcasePause');
const pr = pause && getComputedStyle(pause).display !== 'none'
? pause.getBoundingClientRect() : null;
const covers = (r) => {
if (!pr) return false;
const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
return pr.left <= cx && cx <= pr.right && pr.top <= cy && cy <= pr.bottom;
};
return [...document.querySelectorAll('.showcase-tab')].map((t) => {
const r = t.getBoundingClientRect();
return {
id: t.id,
covered: covers(r),
centerInViewport: (() => {
const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
return cx >= 0 && cy >= 0 && cx <= innerWidth && cy <= innerHeight;
})(),
};
});
}"""
def check_tabs(page, failures):
"""1. tab 行与暂停按钮不重叠、无横向溢出"""
for name, w, h in VIEWPORTS:
page.set_viewport_size({"width": w, "height": h})
page.evaluate("() => window.scrollTo(0, 0)")
page.mouse.move(0, 0)
page.locator(".showcase-tabs").scroll_into_view_if_needed()
time.sleep(0.3)
tabs = page.evaluate(TAB_INFO)
covered = [t["id"] for t in tabs if t["covered"]]
offscreen = [t["id"] for t in tabs if not t["centerInViewport"]]
overflow = page.evaluate(
"() => document.documentElement.scrollWidth - document.documentElement.clientWidth"
)
print(f" {name:>12} 被暂停按钮覆盖={covered or '无'} 出视口={offscreen or '无'} 横向溢出={overflow}px")
if covered:
failures.append(f"{name}: tab 被 #showcasePause 覆盖 {covered}")
if offscreen:
failures.append(f"{name}: tab 中心不在视口内 {offscreen}")
if overflow > 1:
failures.append(f"{name}: 页面横向溢出 {overflow}px")
def active_tab(page):
return page.evaluate("() => document.querySelector('.showcase-tab.active')?.id ?? null")
def focused_tab_state(page):
return page.evaluate(
"""() => {
const el = document.activeElement;
if (!el || !el.classList || !el.classList.contains('showcase-tab')) return null;
return { id: el.id, tabindex: el.getAttribute('tabindex') };
}"""
)
def check_focus(page, failures):
"""2. 焦点进入卡片期间轮播让位;持焦 tab 不被摘 tabindex;失焦后轮播恢复"""
page.set_viewport_size({"width": 1440, "height": 900})
page.reload(wait_until="load")
page.mouse.move(0, 0)
page.locator(".showcase-tabs").scroll_into_view_if_needed()
time.sleep(0.6)
page.mouse.move(0, 0)
before = active_tab(page)
page.evaluate(
"""() => { const t = document.querySelector('.showcase-tab.active'); t && t.focus(); }"""
)
state = focused_tab_state(page)
print(f" 持焦 tab = {state}")
if not state:
failures.append("未能把焦点放进 tablist(用例前提不成立)")
return
time.sleep(WAIT_S)
after = active_tab(page)
print(f" 持焦 {WAIT_S:.1f}s 后 active = {after}(持焦前 {before},期望不变)")
if after != before:
failures.append(f"焦点在卡片内时轮播未让位:active {before} → {after}")
held = focused_tab_state(page)
print(f" 持焦元素 tabindex = {held}")
if held and held.get("tabindex") == "-1":
failures.append(f"持焦 tab {held['id']} 的 tabindex 被摘成 -1(键盘焦点会被移出序列)")
# 失焦后须恢复轮播:否则上一条「不变」可能只是轮播整体失效
page.evaluate("() => document.activeElement && document.activeElement.blur()")
page.evaluate("() => window.scrollTo(0, 0)")
page.mouse.move(0, 0)
page.locator("#nav").scroll_into_view_if_needed()
page.locator(".showcase-tabs").scroll_into_view_if_needed()
deadline = time.time() + WAIT_S + 1.0
resumed = None
while time.time() < deadline:
current = active_tab(page)
if current != before:
resumed = current
break
time.sleep(0.5)
print(f" 失焦后轮播恢复 = {resumed}(期望 ≠ {before})")
if not resumed:
failures.append("失焦后轮播未恢复:前一条「持焦不变」可能是轮播整体失效的假通过")
def check_roving(page, failures):
"""3. 方向键切换后 roving tabindex 单点不变量"""
page.set_viewport_size({"width": 1440, "height": 900})
page.reload(wait_until="load")
page.mouse.move(0, 0)
page.locator(".showcase-tabs").scroll_into_view_if_needed()
time.sleep(0.4)
page.evaluate(
"""() => { const t = document.querySelector('.showcase-tab.active'); t && t.focus(); }"""
)
if focused_tab_state(page) is None:
failures.append("未能把焦点放进 tablist(roving 不变量前提不成立)")
return
page.keyboard.press("ArrowRight")
time.sleep(0.3)
state = page.evaluate(
"""() => {
const tabs = [...document.querySelectorAll('.showcase-tab')];
const isTab = (el) => !!el && el.classList && el.classList.contains('showcase-tab');
return {
zero: tabs.filter((t) => t.getAttribute('tabindex') === '0').map((t) => t.id),
active: tabs.filter((t) => t.classList.contains('active')).map((t) => t.id),
focused: isTab(document.activeElement) ? document.activeElement.id : null,
};
}"""
)
print(f" 方向键后 tabindex=0 = {state['zero']},active = {state['active']},持焦 = {state['focused']}")
if len(state["zero"]) != 1:
failures.append(
f"方向键切换后整组有 {len(state['zero'])} 只 tab 可被 Tab 键到达({state['zero']}),"
"违反 roving tabindex 单点(旧 tab 仍留在序列里)"
)
elif not state["active"] or state["zero"][0] != state["active"][0]:
failures.append(
f"可被 Tab 键到达的 tab({state['zero']})不是 active tab({state['active']})"
)
if not state["active"]:
failures.append("方向键切换后无 active tab")
elif state["focused"] != state["active"][0]:
failures.append(f"方向键切换后焦点未跟随 active tab(持焦 {state['focused']})")
def check_cta(page, failures):
"""3. nav 转化入口与信息链接分层"""
page.set_viewport_size({"width": 1440, "height": 900})
page.evaluate("() => window.scrollTo(0, 0)")
styles = page.evaluate(
"""() => {
const links = [...document.querySelectorAll('.nav-links a')];
const info = links.find((a) => a.getAttribute('href') === '#features');
const cta = links.find((a) => a.getAttribute('href') === '#contact');
const pick = (el) => {
if (!el) return null;
const s = getComputedStyle(el);
return {
cls: el.className,
border: `${s.borderTopWidth} ${s.borderTopStyle} ${s.borderTopColor}`,
bg: s.backgroundColor,
color: s.color,
};
};
return { info: pick(info), cta: pick(cta) };
}"""
)
print(f" 信息链接 = {styles['info']}")
print(f" 转化入口 = {styles['cta']}")
if not styles["info"] or not styles["cta"]:
failures.append("nav 信息链接或 #contact 转化入口不存在")
return
if styles["info"] == styles["cta"]:
failures.append("nav 转化入口与信息链接样式完全相同(无分层)")
# 转化入口须比信息链接更醒目:文字更亮(白色)
print(" 判据:转化入口须与信息链接在描边/底色/文字色上至少一项不同")
def take_shots(page, out):
"""4. 人工评审截图:nav 分层(宽/窄)、窄视口 showcase tab 行"""
page.set_viewport_size({"width": 1440, "height": 900})
page.reload(wait_until="load")
page.mouse.move(0, 0)
time.sleep(1.0)
page.locator("#nav").screenshot(path=str(out / "nav-1440.png"))
page.set_viewport_size({"width": 375, "height": 812})
page.evaluate("() => window.scrollTo(0, 0)")
page.click("#navToggle")
time.sleep(0.5)
# 展开面板是 #nav 的绝对定位子元素,元素截图会裁到导航条自身高度,故截整个视口
page.screenshot(path=str(out / "nav-375-open.png"))
page.click("#navToggle")
for w in (480, 375):
page.set_viewport_size({"width": w, "height": 900})
page.locator(".showcase-tabs").scroll_into_view_if_needed()
page.mouse.move(0, 0)
time.sleep(0.5)
page.locator(".showcase-card").screenshot(path=str(out / f"showcase-{w}.png"))
print(f" 截图已写入 {out}:nav-1440 / nav-375-open / showcase-480 / showcase-375")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--url", default="http://127.0.0.1:8088/")
ap.add_argument("--only", default="tabs,focus,roving,cta")
ap.add_argument("--shots", default="", help="传入目录则产出人工评审用截图")
args = ap.parse_args()
only = {s.strip() for s in args.only.split(",") if s.strip()}
failures = []
with sync_playwright() as p:
browser = p.chromium.launch(channel="chrome", headless=True)
page = browser.new_page(viewport={"width": 1440, "height": 900})
page.goto(args.url, wait_until="load")
time.sleep(1.2)
if "tabs" in only:
print("== 1. showcase tab 行与暂停按钮几何 ==")
check_tabs(page, failures)
if "focus" in only:
print("\n== 2. showcase 轮播焦点管理 ==")
check_focus(page, failures)
if "roving" in only:
print("\n== 3. 键盘 roving tabindex 单点 ==")
check_roving(page, failures)
if "cta" in only:
print("\n== 4. nav 转化入口分层 ==")
check_cta(page, failures)
if args.shots:
print("\n== 5. 人工评审截图 ==")
out = Path(args.shots)
out.mkdir(parents=True, exist_ok=True)
take_shots(page, out)
browser.close()
print("\n" + "=" * 46)
if failures:
print("RESULT: FAIL")
for f in failures:
print(" -", f)
sys.exit(1)
print("RESULT: PASS")
if __name__ == "__main__":
main()
+226
View File
@@ -0,0 +1,226 @@
#!/usr/bin/env python3
"""验证 landing 页面的渐进生长动效(GROW 模块)。
前置:先起本地静态服务
cd landing && python3 -m http.server 8088 --bind 127.0.0.1
用法:
python3 scripts/verify-landing-motion.py [base_url]
检查项:
1. html.js-grow 已挂载(CSS 初始隐藏态生效的前提)
2. Hero mockup 在进入视口后元素依次点亮(密集采样至终态,剧本会循环复位)
3. Showcase 四个 panel 切 tab 后各自重播到全部点亮
4. 离开视口后复位(is-grown 清零)
5. prefers-reduced-motion 下直接呈现终态
6. 装饰性图形对 AT 隐藏,且 aria-hidden 子树内无可聚焦元素(axe aria-hidden-focus)
7. 无 JS 运行时错误
注意:生长动效由剧本时间轴驱动(Hero 约 7s 到终态后循环复位),固定短窗口采样会假失败,
故 2/3 用「密集采样取峰值」判定,峰值须等于目标总数。
Last updated: 2026-09-19
"""
import sys
import time
from playwright.sync_api import sync_playwright
BASE = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8088/"
PANELS = [
("#showcase-tab-graph", "#showcase-panel-graph", "关系图谱"),
("#showcase-tab-flow", "#showcase-panel-flow", "资金流向"),
("#showcase-tab-ai", "#showcase-panel-ai", "AI 分析"),
("#showcase-tab-process", "#showcase-panel-process", "分析过程"),
]
def total_targets(page, sel):
"""统计该容器内的待点亮目标总数(与 JS targetsOf 的规则一致)。"""
return page.evaluate(
"""(s) => {
const root = document.querySelector(s);
if (!root) return 0;
let n = 0;
root.querySelectorAll('[data-grow]').forEach(el => {
n += (el.tagName.toLowerCase() === 'g') ? el.children.length : 1;
});
return n;
}""",
sel,
)
def grown(page, sel):
return page.locator(f"{sel} .is-grown").count()
def watch_growth(page, sel, total, window=12.0, interval=0.4):
"""密集采样到峰值:剧本会循环复位,故以「是否曾到达终态」而非末次快照判定。"""
peak, samples, waited = 0, [], 0.0
while waited < window:
cur = grown(page, sel)
peak = max(peak, cur)
samples.append(cur)
if peak == total:
break
time.sleep(interval)
waited += interval
return peak, samples
def watch_demo_steps(page, selector, window=14.0):
"""采样 demo-step-* 类的推进序列(去重、保序)。
用于 /home 剧本:hero 改画任务工作台后不再有 data-grow 元素,
「动画在跑」这件事改由步骤类推进来证明。
"""
seen = []
samples = []
t0 = time.time()
while time.time() - t0 < window:
cls = page.evaluate(
"sel => document.querySelector(sel)?.className ?? ''", selector)
cur = None
for step in ("demo-step-1", "demo-step-2", "demo-step-3", "demo-step-4"):
if step in cls:
cur = step
samples.append(cur)
if cur is not None and cur not in seen:
seen.append(cur)
time.sleep(0.25)
return seen, samples
def main():
failures = []
with sync_playwright() as p:
browser = p.chromium.launch(channel="chrome", headless=True)
page = browser.new_page(viewport={"width": 1440, "height": 900})
errors = []
page.on("pageerror", lambda e: errors.append(str(e)))
page.goto(BASE, wait_until="load")
time.sleep(1.5)
print("== 1. html.js-grow 挂载 ==")
ok = page.evaluate("document.documentElement.classList.contains('js-grow')")
print(f" js-grow = {ok}")
if not ok:
failures.append("html.js-grow 未挂载")
# == 2. Hero 首屏演示推进 ==
# 2026-11-07:hero 主图由图窗改为 /home 任务工作台,图窗那批 data-grow 元素随之移出 hero,
# 故"生长"这一判据在 hero 上已无作用对象(目标总数恒 0)。判据换成**同一意图的等价物**:
# 首屏演示是否真的在推进 —— 采样 demo-step-* 类为单一线性推进(1→2→3→4),
# 且不回头。这与"元素逐批生长"检验的是同一件事:剧本在跑、不是冻在第一帧。
# 四屏 showcase 的 data-grow 判据(第 3 节)保持原样不动,那里仍有 37/6/7/7 个生长目标。
print("\n== 2. Hero 首屏演示推进(/home 剧本)==")
h_total = total_targets(page, ".hero-visual")
steps_seen, step_samples = watch_demo_steps(page, "#heroDemo", window=14.0)
print(f" data-grow 目标={h_total}(/home 上预期 0) 观察到的步骤={steps_seen}")
if h_total != 0:
print(f" 注:hero 上出现 {h_total} 个 data-grow 目标,将同时按生长判据检查")
if len(steps_seen) < 3:
failures.append(f"Hero 剧本未推进:只观察到 {steps_seen}(样本 {step_samples})")
if "demo-step-1" not in steps_seen or not any(
x in steps_seen for x in ("demo-step-3", "demo-step-4")):
failures.append(f"Hero 剧本未走完前半程:{steps_seen}")
print("\n== 3. Showcase 四个 panel 重播 ==")
page.locator("#showcase").scroll_into_view_if_needed()
time.sleep(0.5)
for tab_sel, panel_sel, name in PANELS:
page.click(tab_sel)
time.sleep(0.2)
total = total_targets(page, panel_sel)
before = grown(page, panel_sel)
peak, samples = watch_growth(page, panel_sel, total, window=10.0)
grew = before < peak or peak == total
print(f" {name}: 总数={total:>3} 切换后={before:>3} 峰值={peak:>3} "
f"采样步数={len(samples)}")
if not grew:
failures.append(f"{name} 切换后未重播: 峰值 {peak}(切换后 {before})")
if peak != total:
failures.append(f"{name} 未跑完: 峰值 {peak}/{total}")
print("\n== 4. 离开视口复位 ==")
page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(1.0)
after_leave = grown(page, "#showcase-panel-process")
print(f" 滚到页面底部后 is-grown = {after_leave} (期望 0)")
if after_leave != 0:
failures.append(f"离开视口未复位: {after_leave}")
print("\n== 5. prefers-reduced-motion 直接终态 ==")
page.emulate_media(reduced_motion="reduce")
page.reload(wait_until="load")
time.sleep(1.2)
page.locator("#showcase").scroll_into_view_if_needed()
time.sleep(0.4)
r_total = total_targets(page, "#showcase-panel-graph")
r_grown = grown(page, "#showcase-panel-graph")
print(f" reduced-motion 下 is-grown = {r_grown}/{r_total} (期望相等)")
if r_grown != r_total:
failures.append(f"reduced-motion 未直达终态: {r_grown}/{r_total}")
page.emulate_media(reduced_motion="no-preference")
print("\n== 6. 装饰性图形无障碍属性 ==")
a11y = page.evaluate(
"""() => {
const FOCUSABLE = 'a[href], button, input, select, textarea, [tabindex]';
const focusable = (sel) => [...document.querySelectorAll(sel)]
.filter(e => e.matches(FOCUSABLE) || e.querySelector(FOCUSABLE))
.map(e => e.id || e.className);
return {
heroDemo: document.querySelector('#heroDemo')?.getAttribute('aria-hidden') ?? null,
showcaseVisuals: [...document.querySelectorAll('.showcase-visual')]
.map(e => e.getAttribute('aria-hidden')),
heroVisual: document.querySelector('.hero-visual')?.getAttribute('aria-hidden') ?? null,
focusableInHidden: [...document.querySelectorAll('[aria-hidden="true"]')]
.flatMap(root => [...root.querySelectorAll(FOCUSABLE)])
.filter(e => !e.hasAttribute('disabled') && e.tabIndex >= 0)
.map(e => `${e.tagName.toLowerCase()}#${e.id}`),
demoPause: (() => {
const btn = document.querySelector('#demoPause');
return btn ? { exists: true, label: btn.getAttribute('aria-label'),
pressed: btn.getAttribute('aria-pressed') } : { exists: false };
})(),
};
}"""
)
print(f" #heroDemo aria-hidden = {a11y['heroDemo']} (期望 true)")
print(f" .showcase-visual aria-hidden = {set(a11y['showcaseVisuals'])} (期望 {{'true'}})")
print(f" .hero-visual aria-hidden = {a11y['heroVisual']!r} "
f"(期望 None——容器承载暂停按钮,隐藏会连带隐藏控件)")
print(f" aria-hidden 子树内可聚焦元素 = {a11y['focusableInHidden'] or '无'} (期望 无)")
print(f" 暂停控件 = {a11y['demoPause']}")
if a11y["heroDemo"] != "true":
failures.append(f"演示层未对 AT 隐藏: {a11y['heroDemo']}")
if set(a11y["showcaseVisuals"]) != {"true"} or not a11y["showcaseVisuals"]:
failures.append(f"showcase 装饰图形 aria-hidden 异常: {a11y['showcaseVisuals']}")
if a11y["heroVisual"] == "true":
failures.append(".hero-visual 不应整体 aria-hidden(内含暂停按钮)")
if a11y["focusableInHidden"]:
failures.append(f"aria-hidden 子树内含可聚焦元素: {a11y['focusableInHidden']}")
if not a11y["demoPause"].get("exists") or not a11y["demoPause"].get("label"):
failures.append(f"暂停按钮缺失或无无障碍名: {a11y['demoPause']}")
print("\n== 7. JS 运行时错误 ==")
print(f" {errors or '无'}")
if errors:
failures.append(f"JS 错误: {errors}")
browser.close()
print("\n" + "=" * 46)
if failures:
print("RESULT: FAIL")
for f in failures:
print(" -", f)
sys.exit(1)
print("RESULT: PASS")
if __name__ == "__main__":
main()
+155
View File
@@ -0,0 +1,155 @@
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
import type { NextRequest } from 'next/server';
const mockFetch = jest.fn<(input: unknown, init?: unknown) => Promise<Response>>();
jest.unmock('./route');
import { POST, LANDING_CONTACT_RATE_LIMIT_MAX, landingContactRateLimiter } from './route';
/**
* `/api/v1/contact` 的契约测试。
*
* 这个路由的存在理由是**landing 的判据**:`public/novavis/js/main.js` 只认
* `ok && data.code === 200` 为成功。所以本文件的断言核心不是「有没有发邮件」,
* 而是**响应形状是否让 landing 走进成功分支**——判据错位时表单会静默落进失败兜底,
* 而那种失败在浏览器里只表现为一句「服务器返回异常」,没人能从文案定位到是 code 字段。
*/
function createJsonRequest(body: unknown, ip = '1.2.3.4'): NextRequest {
return {
url: 'http://localhost:3000/api/v1/contact',
headers: new Headers({ 'x-forwarded-for': ip }),
json: async () => body,
} as unknown as NextRequest;
}
function createBadJsonRequest(ip = '1.2.3.4'): NextRequest {
return {
url: 'http://localhost:3000/api/v1/contact',
headers: new Headers({ 'x-forwarded-for': ip }),
json: async () => {
throw new SyntaxError('Unexpected token');
},
} as unknown as NextRequest;
}
const validBody = {
name: '张三',
org: '某某律师事务所',
phone: '13812345678',
email: 'zhang@example.com',
message: '想了解睿视在资金流水研判上的能力',
};
beforeEach(() => {
jest.clearAllMocks();
// 每个用例从空桶开始:限流器是进程内单例,跨用例共享会让第 6 个用例莫名 429
// (本文件里就有一条用例要故意打满额度,不清空会污染后面所有用例)。
landingContactRateLimiter.reset();
global.fetch = mockFetch as unknown as typeof fetch;
mockFetch.mockResolvedValue(
new Response(JSON.stringify({ success: 'true' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
}),
);
});
afterEach(() => {
jest.restoreAllMocks();
});
describe('POST /api/v1/contact —— landing 契约', () => {
it('合法请求返回 HTTP 200 且 code === 200(landing 的唯一成功判据)', async () => {
const res = await POST(createJsonRequest(validBody));
const data = await res.json();
expect(res.status).toBe(200);
expect(data.code).toBe(200);
});
it('把 landing 的 org 合成为 subject 投递(表单里没有 subject 字段)', async () => {
await POST(createJsonRequest(validBody));
expect(mockFetch).toHaveBeenCalledTimes(1);
const [, init] = mockFetch.mock.calls[0]!;
const body = String((init as { body: string }).body);
const params = new URLSearchParams(body);
expect(params.get('name')).toBe('张三');
expect(params.get('phone')).toBe('13812345678');
expect(params.get('subject')).toBe('睿视试用申请 · 某某律师事务所');
expect(params.get('_captcha')).toBe('false');
});
it('email / message 选填:缺失时仍成功,且不投递空 email', async () => {
const res = await POST(
createJsonRequest({ name: '李四', org: '某公司', phone: '13912345678' }),
);
const data = await res.json();
expect(data.code).toBe(200);
const body = String((mockFetch.mock.calls[0]![1] as { body: string }).body);
const params = new URLSearchParams(body);
expect(params.get('email')).toBeNull();
expect(params.get('message')).toBe('(未填写)');
});
it('缺必填字段:code !== 200 且 message 指出具体字段(不是笼统的"无效")', async () => {
const res = await POST(createJsonRequest({ name: '王五', phone: '13812345678' }));
const data = await res.json();
expect(data.code).not.toBe(200);
expect(data.message).toContain('单位名称');
expect(mockFetch).not.toHaveBeenCalled();
});
it('手机号格式错:code !== 200(与 landing 的 validatePhone 同口径)', async () => {
const res = await POST(createJsonRequest({ ...validBody, phone: '12345' }));
const data = await res.json();
expect(data.code).not.toBe(200);
expect(data.message).toContain('手机');
});
it('请求体不是 JSON:明确报「格式」而不是把锅推给用户字段', async () => {
const res = await POST(createBadJsonRequest());
const data = await res.json();
expect(data.code).not.toBe(200);
expect(data.message).toContain('JSON');
});
it('危险字符被过滤后才投递', async () => {
await POST(createJsonRequest({ ...validBody, name: '张<script>三' }));
const body = String((mockFetch.mock.calls[0]![1] as { body: string }).body);
const params = new URLSearchParams(body);
expect(params.get('name')).toBe('张script三');
});
it('上游投递失败:不透传 5xx,仍返回可被 landing 展示的 message', async () => {
mockFetch.mockResolvedValue(new Response('bad gateway', { status: 502 }));
const res = await POST(createJsonRequest(validBody));
const data = await res.json();
expect(data.code).not.toBe(200);
expect(data.message).toBeTruthy();
expect(res.status).not.toBe(502);
});
it('限流:同一 IP 超过额度后返回 429 且 code !== 200', async () => {
const ip = '9.9.9.9';
for (let i = 0; i < LANDING_CONTACT_RATE_LIMIT_MAX; i++) {
const r = await POST(createJsonRequest(validBody, ip));
expect(r.status).toBe(200);
}
const limited = await POST(createJsonRequest(validBody, ip));
const data = await limited.json();
expect(limited.status).toBe(429);
expect(data.code).not.toBe(200);
});
});
+154
View File
@@ -0,0 +1,154 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { COMPANY_INFO } from "@/lib/constants";
import { getClientIp } from "@/lib/client-ip";
import { createMemoryRateLimiter } from "@/lib/rate-limit";
import { readRateLimitMax } from "@/lib/rate-limit-config";
/**
* `POST /api/v1/contact` —— 睿视 landing 的 CTA 表单端点。
*
* ## 为什么需要这个路由(2026-12-03)
*
* landing 的 `public/novavis/js/main.js` 固定向 `/api/v1/contact` POST JSON,且**只认
* `data.code === 200` 为成功**(其余一律走失败兜底)。这个契约来自 `novavis-authority`:
* 子域 `novavis.p.novalon.cn` 上该路径由 authority 的 Java 后端(`/api/v1/contact`)响应。
*
* 但 landing 同时被镜像到本仓的 `/novavis/`,而本仓只有 `/api/contact`(formData + 必填
* `subject`)。于是**镜像侧的转化路径一直 404** —— 表单一提交就落进失败兜底。这是 landing
* 迁入本仓后暴露的第一个真实缺陷(迁移前没人从官网入口点过那个表单)。
*
* ## 为什么不改 landing 去适配 `/api/contact`
*
* 同一份字节要服务两个落点。若把 `main.js` 改成打 `/api/contact` + formData,子域上就必须
* 有对应端点;而 authority 的契约是 JSON + `{code:200}`。改前端等于把「适配本仓」的成本
* 转嫁给子域,且会让两个落点的成功判据不一致。**加一个契约匹配的路由更小、更可逆**:
* 本仓多一个薄适配层,landing 与 authority 两侧都不动。
*
* ## 与 `/api/contact` 的关系
*
* 两者**不复用实现**,因为输入形状与成功判据都不同(JSON/`code` vs formData/`success`)。
* 但投递通道一致:都走 formsubmit.co 到 `COMPANY_INFO.email`。字段映射:
*
* | landing 字段 | 说明 |
* |---|---|
* | `name` | 必填 |
* | `org` | 必填(单位名,拼进 subject) |
* | `phone` | 必填 |
* | `email` | 选填 |
* | `message` | 选填 |
*
* `subject` 由服务端合成(`睿视试用申请 · {org}`),因为 landing 表单里没有这个字段。
*
* ## 限流
*
* 与 `/api/contact` 同族:进程内内存桶,默认 5 次/小时/IP,可用
* `CONTACT_RATE_LIMIT_MAX` 覆盖(E2E 的 server 跨整轮存活,不抬高必 429)。
* **两个端点各有独立的桶** —— 这是有意的:它们是两条独立的入口,共享桶会让
* 「官网留言 5 次」把「睿视申请」也堵死。
*/
const landingContactSchema = z.object({
// 注意 zod 4 的两级消息:字段**缺失**(undefined)走构造器参数,`.min(1)` 只管
// 「存在但为空」。只写 `.min(1, "请输入您的姓名")` 时缺字段会返回
// `Invalid input: expected string, received undefined` —— 英文、且把「没填」说成类型错误,
// 直接展示给用户就是一句没法读的话。两级都要给。
name: z.string({ error: "请输入您的姓名" }).trim().min(1, "请输入您的姓名").max(50, "姓名不能超过50个字符"),
org: z
.string({ error: "请输入您所在的单位名称" })
.trim()
.min(1, "请输入您所在的单位名称")
.max(100, "单位名称不能超过100个字符"),
// 与 landing 的 `validatePhone` 同口径(大陆手机号),服务端不依赖前端校验
phone: z.string({ error: "请输入您的联系电话" }).trim().regex(/^1[3-9]\d{9}$/, "请输入正确的手机号码"),
email: z
.string()
.trim()
.email("请输入正确的邮箱地址")
.max(100, "邮箱地址过长")
.optional()
.or(z.literal("")),
message: z.string().trim().max(2000, "留言内容不能超过2000个字符").optional().or(z.literal("")),
});
export const LANDING_CONTACT_RATE_LIMIT_MAX = readRateLimitMax("CONTACT_RATE_LIMIT_MAX", 5);
export const landingContactRateLimiter = createMemoryRateLimiter({
windowMs: 60 * 60 * 1000, // 1 小时
max: LANDING_CONTACT_RATE_LIMIT_MAX,
});
/** 与 `/api/contact` 同口径:去首尾空白并过滤潜在危险标签。 */
function sanitizeInput(input: string): string {
return input.trim().replace(/[<>]/g, "");
}
/**
* 成功响应形状:landing 只认 `code === 200`。
*
* 失败也返回 **HTTP 200 + `code !== 200`**:`main.js` 的判据是 `ok && data.code === 200`,
* 用 4xx 会让 `res.json()` 之后仍进失败分支(行为相同),但 HTTP 200 能让错误信息走
* `data.message` 而不是被某些中间层(CDN/WAF)替换成 HTML 错误页 —— 那样 `res.json()`
* 直接抛异常,用户只能看到「网络异常」这个最不具体的兜底文案。
*/
function okResponse(): NextResponse {
return NextResponse.json({ code: 200, message: "提交成功" });
}
function failResponse(message: string, status = 200): NextResponse {
return NextResponse.json({ code: status === 200 ? 400 : status, message }, { status });
}
export async function POST(request: NextRequest) {
try {
const clientIp = getClientIp(request.headers);
if (landingContactRateLimiter.isLimited(clientIp)) {
return failResponse("提交过于频繁,请稍后再试", 429);
}
// landing 发的是 JSON;不是 JSON 时明确报 400,而不是让 zod 收到 null 后给出
// 「请输入您的姓名」这种把「请求格式错」说成「用户没填」的误导性文案。
let raw: unknown;
try {
raw = await request.json();
} catch {
return failResponse("请求格式无效(需要 JSON)", 400);
}
const parseResult = landingContactSchema.safeParse(raw);
if (!parseResult.success) {
const firstError = parseResult.error.issues[0];
return failResponse(firstError?.message ?? "表单数据无效", 400);
}
const { name, org, phone, email, message } = parseResult.data;
const subject = `睿视试用申请 · ${org}`;
const formBody = new URLSearchParams();
formBody.append("name", sanitizeInput(name));
formBody.append("phone", sanitizeInput(phone));
if (email) formBody.append("email", sanitizeInput(email));
formBody.append("subject", sanitizeInput(subject));
formBody.append("message", sanitizeInput(message || "(未填写)"));
formBody.append("_subject", `网站留言: ${sanitizeInput(subject)}`);
formBody.append("_captcha", "false");
formBody.append("_template", "table");
const response = await fetch(`https://formsubmit.co/ajax/${COMPANY_INFO.email}`, {
method: "POST",
headers: { Accept: "application/json" },
body: formBody.toString(),
});
if (!response.ok) {
// 上游失败不把 5xx 透给 landing:`main.js` 只看 `data.code`,
// 透传会变成「服务器返回异常」这种无法定位的文案。
return failResponse("提交失败,请稍后重试或直接联系我们");
}
return okResponse();
} catch (error) {
console.error("Landing contact form error:", error);
return failResponse("服务器内部错误", 500);
}
}