Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

test(e2e): 设计决定用例按区域拆成六个文件,浏览器用例按文件并发

longmeidao4b9029ddd9ea
diff --git a/.claude/skills/peach-web-ui/SKILL.md b/.claude/skills/peach-web-ui/SKILL.md
index 65cebcdc4..a69c4bddb 100644
--- a/.claude/skills/peach-web-ui/SKILL.md
+++ b/.claude/skills/peach-web-ui/SKILL.md
@@ -92,7 +92,7 @@ description: 在新增、修改或复核 Peach 页面、控件、提示、错误
1. 先确认失败模式与现有覆盖,再选择组件、API/数据层或浏览器测试。纯文案、等价重构不补源码文本断言;通用规范由 lint 或集中扫描检查,具体分工见 `docs/TESTING.md`。
2. Windows 从隔离 worktree 根运行 `& .\scripts\test.ps1`,默认 `auto`;按影响域补测,规则见 `peach-worktree`。
-3. 桌面与 390×844 的通用不变量(无横向溢出、无越出视口的元素、等待态会结束、控制台无错误、无失败请求)由 `web` 域的 `tests/test_web_e2e.py` 执行,不再逐页手测;新路由加进 `frontend/e2e/smoke.test.ts` 的 `ROUTES`,分区 tab 由用例逐格切过去再测。用例靠 `aria-busy` 与 `data-skeleton` 判断页面稳定,React 子树也要写:BoardUI 组件不带加载态,由 Peach 包装件补上。浏览器里发现的可判定问题(几何、computed style、状态切换),先在 `frontend/e2e/` 写出失败用例再修。页面迁到 React 时,旧源码断言按 ADR-0031 分三类再删:设计决定进 `frontend/e2e/design.test.ts` 或 lint,行为进 vitest,布局与运行期进冒烟。
+3. 桌面与 390×844 的通用不变量(无横向溢出、无越出视口的元素、等待态会结束、控制台无错误、无失败请求)由 `web` 域的 `tests/test_web_e2e.py` 执行,不再逐页手测;新路由加进 `frontend/e2e/smoke.test.ts` 的 `ROUTES`,分区 tab 由用例逐格切过去再测。用例靠 `aria-busy` 与 `data-skeleton` 判断页面稳定,React 子树也要写:BoardUI 组件不带加载态,由 Peach 包装件补上。浏览器里发现的可判定问题(几何、computed style、状态切换),先在 `frontend/e2e/` 写出失败用例再修。页面迁到 React 时,旧源码断言按 ADR-0031 分三类再删:设计决定进 `frontend/e2e/design-*.test.ts` 或 lint,行为进 vitest,布局与运行期进冒烟。
4. 浏览器取证只留给用例表达不了的:新布局首次成形、对齐外部参考、hover/focus 与观感判断。默认用 `agent-browser`(全局 CLI,装法 `npm i -g agent-browser`;
环境变量 `AGENT_BROWSER_EXECUTABLE_PATH` 指向本机 Chrome,`AGENT_BROWSER_SESSION=<任务名>` 隔离会话):`open <url>` → `wait <选择器>` → `snapshot -i -c -s <选择器>`/`get styles <选择器>`/`eval <js>`/`screenshot <文件>`,验完 `close`,一条命令 1~3 秒、不弹授权。
Bash 工具里每条命令加 `</dev/null` 或把输出重定向到文件:接管道时 CLI 会等 stdin 直到工具超时。残留守护进程用 `Get-Process -Name 'agent-browser-win32-x64' | Stop-Process -Force` 清掉。
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 7143e900f..0d20b92aa 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -196,8 +196,9 @@ jobs:
done
exit 1
- # 浏览器冒烟(`frontend/e2e/smoke.test.ts`)与设计决定断言(`design.test.ts`)。
- # `python` 矩阵的 Windows 行平时只跑 `core`,这两组用例靠这里执行;矩阵扩成全量
+ # 浏览器冒烟(`frontend/e2e/smoke.test.ts`)、设计决定断言(`design-*.test.ts`)与交互回归。
+ # runner 上 `GITHUB_ACTIONS=true`,浏览器用例按设计、交互、冒烟三批串行跑。
+ # `python` 矩阵的 Windows 行平时只跑 `core`,这几组用例靠这里执行;矩阵扩成全量
# (`plan` 的 `wide`)时 Windows 行已经把 `web` 域跑过一遍,这里就不再跑第二遍。
web-e2e:
name: 浏览器冒烟与设计决定断言
diff --git a/docs/FRONTEND.md b/docs/FRONTEND.md
index dd7a02266..a8f06fb79 100644
--- a/docs/FRONTEND.md
+++ b/docs/FRONTEND.md
@@ -154,7 +154,7 @@ Peach 按 [ADR-0031](adr/0031-frontend-react-boardui-tailwind.md) 逐页接入 R
- 内容由壳推:`paintSidebar(patch)` 合并 `content`、`filters`、`latest` 后调 `render`。目录与资料页的聚合在 `buildBars` 里换成 `{kind:'catalog'}`,关注页与关注详情的内容标签由 `renderFollowDrawer` 推 `{kind:'follow'}`;就地改筛选时 `applyFilterStateInPlace` 只推 `filters`,`refreshFacetCounts` 只推 `latest`。点下去的动作回到壳的 `navTo`、`commitContextFilter` 与关注页的筛选。`render` 与 `navChanged` 写组件模块里的 store 再 `flushSync`,返回时已经画好。
- 导航顺序读 `appSettings` 这一份 store 的 `sidebarOrder`:拖动排序先落 store 再写 `/api/settings`,设置面板改顺序也写同一份 store,侧栏按通知当场重排。按下态换了由壳的 `paintNav` 调 `navChanged`:它跑在 `route()` 的同步段里,玻璃拿到的是旧位置到新位置。
- 标题行 `[data-sidebar-head]` 是组件画的空槽,品牌与开合键是壳挪进去的节点;组件不往这个槽里画子节点,重画不碰它们。
-- 样式在 `sidebar/sidebar.css`,只认 `data-sidebar-*`;组件里不写 className。行为在 `test/react/sidebar.test.tsx`,量布局的玻璃滑动、拖动、各页计数与窄屏开合在 `e2e/sidebar.test.ts`;当前项玻璃、标题行间距、时长拉条与窄屏遮罩的外观在 `e2e/design.test.ts` 读计算值。
+- 样式在 `sidebar/sidebar.css`,只认 `data-sidebar-*`;组件里不写 className。行为在 `test/react/sidebar.test.tsx`,量布局的玻璃滑动、拖动、各页计数与窄屏开合在 `e2e/sidebar.test.ts`;当前项玻璃、标题行间距、时长拉条与窄屏遮罩的外观在 `e2e/design-detail.test.ts` 读计算值。
### 客户端导航
@@ -238,7 +238,7 @@ CI(`GITHUB_ACTIONS=true`)里缺这些就判失败,由工作流负责装齐
**改了 `frontend/src` 就必须重新构建并把 `web/dist/` 一起提交**,否则 CI 会红。
同一个域里还有真浏览器冒烟 `tests/test_web_e2e.py`:它在临时数据根上生成 12 条合成演示库、
-起回环 `peach serve --no-auth`,再跑 `npm --prefix frontend run e2e`。用例在
+起回环 `peach serve --no-auth`,再按批调起 `node --test` 跑 `frontend/e2e` 下全部用例(调度见 [docs/TESTING.md](TESTING.md))。冒烟用例在
`frontend/e2e/smoke.test.ts`,每条主路由在桌面与 390×844 下先等到目标页面主体出现(路由自己的标题,
加上内容区、索引条目或明确的空态),再断言:无页面异常与 `console.error`、无同源 4xx/5xx 与失败请求、
`aria-busy` 与 `data-skeleton` 会消失、无横向溢出、无越出视口的元素。主体一项不能省:页面完全没渲染时,
@@ -248,7 +248,7 @@ CI(`GITHUB_ACTIONS=true`)里缺这些就判失败,由工作流负责装齐
CI 由 `web-e2e` job 在 `windows-latest` 上执行 `web` 域,矩阵扩成全量时改由 Windows 全量行覆盖([docs/TESTING.md](TESTING.md))。界面验收里发现的同类问题,
先在这里补一条用例再修。
-设计决定另有 `frontend/e2e/design.test.ts`,读 `getComputedStyle` 断言用户定过的外观:React 输入框不带旧焦点环、
+设计决定另有 `frontend/e2e/design-*.test.ts`(按页面区域分文件,共用 `design-fixture.ts`),读 `getComputedStyle` 断言用户定过的外观:React 输入框不带旧焦点环、
React 子树读到 BoardUI 的 token 原值、持久警示是状态色块、一张卡底下只有写入那一颗是主按钮。页面迁到 React 时,旧的源码字符串断言按 ADR-0031
分三类再删:设计决定进这里或 lint,行为进 vitest,布局与运行期进冒烟。
@@ -459,7 +459,7 @@ BoardUI 的 `chart-*` 档。点一个内容标签是「回目录并按它筛选
断言结构、请求次数、轮询节律和失败时留下什么,用例之间 `queryClient.clear()`。
有写操作就再断言交上去的请求体、成功后页面上不再留着秘密输入、失败后输入原样还在;
有后台任务就用假时钟推到终态,看回执只发一次、卸载之后不再问。
- 外观决定进 `frontend/e2e/design.test.ts`:`page.route` 造出真实数据里凑不齐的状态,
+ 外观决定进对应区域的 `frontend/e2e/design-*.test.ts`:`page.route` 造出真实数据里凑不齐的状态,
断言读 `getComputedStyle`。
6. `web/app.js` 的挂载块不变;`web/css/` 与 `web/board.css` 里只服务这一页正文的规则删掉,
遗留骨架还要用的留着:骨架仍然用旧类名(`boardPageSkeleton`),它要的那几条不能一起删。
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 3abdb5ab2..a530a444f 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -68,7 +68,7 @@ Python 静态检查使用开发依赖 Ruff,随每个正式测试域扫描全
浏览器冒烟与设计决定断言(`tests/test_web_e2e.py`)由 `web-e2e` job 在 `windows-latest` 上执行 `web` 域。它装 Node 24、`frontend/node_modules`、ffmpeg,并经 `PEACH_E2E_CHROME` 指定 runner 自带的 Chrome。矩阵扩成全量(`plan` 输出的 `wide`)时,Windows 全量行本身就跑 `web` 域,这个 job 按条件跳过;`verified` 只在这种情况接受它的 skipped,别的 job 跳过照样算红。
-浏览器用例分为设计检查、交互回归和路由冒烟三批,每批限时 600 秒。各批及批内文件默认串行执行,覆盖 `frontend/e2e` 下全部 `*.test.ts`,包括子目录;任一批失败,整轮验证失败。完整 TAP 日志保存在 `build/agent-verification/browser/`,CI 在测试结束后上传该目录。
+浏览器用例覆盖 `frontend/e2e` 下全部 `*.test.ts`,包括子目录,按文件并发、文件内串行。并发数取 `PEACH_E2E_CONCURRENCY`;未设时本机取逻辑核数的四分之一、上限 4,CI(`GITHUB_ACTIONS=true`)为 1。并发时分两批:其余文件一次并发跑完,断言帧数或动画中途位置的文件(`tests/test_web_e2e.py` 的 `CPU_SENSITIVE_SUITES`)随后串行;并发为 1 时按设计决定、交互回归和路由冒烟分三批。每批限时 600 秒,任一批失败,整轮验证失败。并发的文件共用一个服务和演示库:用例触发的写请求只能落在别的用例不断言的状态上,否则用 `page.route` 拦下或归进串行批。完整 TAP 日志与服务访问日志 `serve.log` 保存在 `build/agent-verification/browser/`,CI 在测试结束后上传其中的 TAP 日志。
需要外部前置条件(Node、ffmpeg、Chrome 等)的用例,本机缺条件时跳过,在 CI(`GITHUB_ACTIONS=true`)里判失败,判定集中在 `tests/support/conditions.py` 的 `missing_prerequisite`。所以 `python` 矩阵里 `core` 以外的行也装 Node,Windows 行另装 ffmpeg 与 Chrome。
@@ -87,7 +87,7 @@ Windows 的路径、挂载、托盘、证书、进程编码、更新、认证及
按下面的分工写:
- 行为(点了发出什么请求、状态怎么变、算出什么值)写 vitest(`frontend/test/`)或 `tests/test_web_js.py`;后端调用真函数或真接口。
-- 用户定过的设计决定写 `frontend/e2e/design.test.ts`,读 `getComputedStyle`;布局与运行期不变量进 `smoke.test.ts`。
+- 用户定过的设计决定写进对应区域的 `frontend/e2e/design-*.test.ts`(共用 `design-fixture.ts`),读 `getComputedStyle`;布局与运行期不变量进 `smoke.test.ts`。
- 源码文本断言只减不增,由 `tests/test_source_assertion_ratchet.py` 按文件计数拦截。已有行为或浏览器验证的实现文本断言直接清退;确有行为缺口时才补用例,并同步降低基线。
- 先列失败模式再写用例。异步请求的中间态用手动放行的 Promise 验证;假 fetch 在同一个 `act` 里就回话,会掩盖请求未完成时的时序问题。
- 修缺陷先写一条会失败的用例,看它红了再修;修完按同一写法搜别处,有同类就收成共用实现。没有行为缺口的改动(文案、纯样式)不补回归用例。
diff --git a/docs/adr/0031-frontend-react-boardui-tailwind.md b/docs/adr/0031-frontend-react-boardui-tailwind.md
index 013008556..05cbd3bba 100644
--- a/docs/adr/0031-frontend-react-boardui-tailwind.md
+++ b/docs/adr/0031-frontend-react-boardui-tailwind.md
@@ -77,7 +77,7 @@ BoardUI 通过 shadcn 注册表发布 React + Tailwind v4 源码,表单与弹
- **沿用 ADR-0022**:`npm run build` 的产物提交进 `web/dist/`,运行时不需要 Node;`/dist/{path}` 路由不变;测试入口仍是 `scripts/test.ps1` / `scripts/test.sh` 的 `web` 域;依赖精确锁定,在 [docs/FRONTEND.md](../FRONTEND.md) 登记用途。
- **旧断言先分类再删**。页面迁走时,它在 `tests/test_web_ui.py` 等处的源码字符串断言逐条归入三类,去向写进提交说明:
- - 设计决定(用户定过的颜色、状态色块、焦点样式)写成 `frontend/e2e/design.test.ts` 里读 `getComputedStyle` 的断言,或由 lint 规则覆盖;
+ - 设计决定(用户定过的颜色、状态色块、焦点样式)写成 `frontend/e2e/design-*.test.ts` 里读 `getComputedStyle` 的断言,或由 lint 规则覆盖;
- 行为(提交什么、错误写回哪个字段、控件何时可用)写成 vitest;
- 布局与运行期问题(溢出、等待态、控制台报错)归 `frontend/e2e/smoke.test.ts`。
- 三类各管一件事:lint 查源码是否守约定,`getComputedStyle` 查浏览器实际应用的样式,vitest 与浏览器交互查点击和键盘行为,互不替代。
diff --git a/docs/reference-snapshots/fluid-functionalism.md b/docs/reference-snapshots/fluid-functionalism.md
index 81aec4fec..180a10a36 100644
--- a/docs/reference-snapshots/fluid-functionalism.md
+++ b/docs/reference-snapshots/fluid-functionalism.md
@@ -19,6 +19,6 @@
共用弹窗由 React Aria 的 entering/exiting 生命周期维持挂载,opacity 与 scale .98 在 200ms 内进入,120ms 退出。批量选择条沿底部 8px 路径进出,进入 160ms、退出 120ms;Motion AnimatePresence 保持退出阶段,退出内容立即 inert,数量更新不重播。上述数值是 Peach 的设计选择,不宣称是参考站的弹窗与操作条实测值。
-无障碍与生产边界:保留 React Aria 焦点管理,键盘与减少动态效果模式即时开合;不改变 API、账本写入、选择集合和提交时机。运行回归在 `frontend/e2e/design.test.ts`。
+无障碍与生产边界:保留 React Aria 焦点管理,键盘与减少动态效果模式即时开合;不改变 API、账本写入、选择集合和提交时机。运行回归在 `frontend/e2e/design-*.test.ts`。
局部滚动区通过共用 `attachOverlayScrollbar` 接入上下边缘提示:仍可滚动的一侧显示 16px 渐隐与 2px 背景模糊,到头即撤去,不影响滚轮与点击。整页不叠加此效果。此处根据复核卡截图设计;参考站“超出框范围的模糊”实时视觉证据未取得,不宣称是上游效果的复刻。
diff --git a/docs/reference-snapshots/vercel-geist-split-button.md b/docs/reference-snapshots/vercel-geist-split-button.md
index 5b39180b1..37cf4d8c9 100644
--- a/docs/reference-snapshots/vercel-geist-split-button.md
+++ b/docs/reference-snapshots/vercel-geist-split-button.md
@@ -77,5 +77,5 @@ deployment`),说明不参与和主动作的比对,第一行标签才是。
`--color-accent-400`,悬停时不变。
- 骨架里两半是原生 `disabled`,外圈 `--border-15` 画在整组上,中缝退成同一色。
-两半的悬停、中缝几何与骨架禁用面由 `frontend/e2e/design.test.ts` 量 computed style 守住,
+两半的悬停、中缝几何与骨架禁用面由 `frontend/e2e/design-controls.test.ts` 量 computed style 守住,
结构由 `tests/test_web_ui.py` 的 `test_history_actions_are_one_split_button_with_the_primary_mirrored` 守住。
diff --git a/frontend/e2e/design-cards.test.ts b/frontend/e2e/design-cards.test.ts
new file mode 100644
index 000000000..b6bebe5f5
--- /dev/null
+++ b/frontend/e2e/design-cards.test.ts
@@ -0,0 +1,1046 @@
+/* 设计决定:作品卡、管理页与复核。读 `getComputedStyle` 断言用户定过的外观;共用的桩与浏览器生命周期在 `design-fixture.ts`。 */
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import type { Browser, Locator } from 'playwright-core';
+import { expectBody, settle, visit } from './harness.ts';
+import {
+ DESKTOP, MOBILE, tokenColor, openReview, lightness, WIDE, JUNK_COUNT, openJunk, junkItem, openJunkWith,
+ openCatalog, openCatalogFixture, openFollowManage, stubFollowManage, holdApi, controlFaces, disabledTokens,
+ waitingActionFaces, assertDisabledFace, installDesignBrowser,
+} from './design-fixture.ts';
+
+describe('设计决定:作品卡、管理页与复核', () => {
+ let browser: Browser;
+ installDesignBrowser((next) => { browser = next; });
+
+ /* 骨架是列表回来之前那一屏的形状预告:JAV 默认大图,卡片是 3:4 的正封,骨架照 16:9
+ 铺的话,内容一到整屏卡片都被拉高一截。把列表请求扣住,只看骨架本身。 */
+ it('作品骨架的封面比例跟当前版式走:JAV 大图 3:4,首页小图 16:9', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', DESKTOP);
+ const { page } = opened;
+ await page.route(/\/api\/items\?/, () => {});
+ /* 骨架挂上的那一帧可能还没排版(宽高都是 0),量出来是 NaN。等它有了尺寸、且连续两帧
+ 比例不变再读:量的是这一屏落定后的形状,不是插进 DOM 的那一瞬。 */
+ const skeletonRatio = async (path: string) => {
+ await page.goto(new URL(path, page.url()).href, { waitUntil: 'load' });
+ const handle = await page.waitForFunction(() => {
+ const cover = document.querySelector('#grid .catalog-skeleton .skeletoncard i');
+ const box = cover?.getBoundingClientRect();
+ if (!box || !box.width || !box.height) return false;
+ const ratio = box.width / box.height;
+ const holder = window as unknown as { skeletonRatioSeen?: number };
+ const settled = holder.skeletonRatioSeen === ratio;
+ holder.skeletonRatioSeen = ratio;
+ return settled && ratio;
+ }, undefined, { polling: 'raf', timeout: 15_000 });
+ return Number(await handle.jsonValue());
+ };
+ try {
+ assert.ok(Math.abs(await skeletonRatio('/?jav=1') - 0.75) < 0.05, 'JAV 大图下骨架封面不是正封比例');
+ assert.ok(Math.abs(await skeletonRatio('/') - 16 / 9) < 0.05, '首页小图下骨架封面不是 16:9');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('卡片悬停反馈不在封面像素上描边', { timeout: 60_000 }, async () => {
+ const opened = await openCatalog(browser);
+ try {
+ const card = opened.page.locator('#grid [data-media-card]').first();
+ const picture = card.locator('[data-media-pic]');
+ await card.hover();
+ const overlay = await picture.evaluate((element) => {
+ const style = getComputedStyle(element, '::after');
+ return { content: style.content, borderWidth: style.borderTopWidth };
+ });
+ assert.equal(overlay.content, 'none', '悬停伪元素仍覆盖在封面像素上');
+ assert.equal(overlay.borderWidth, '0px', '悬停边线仍污染圆角边缘像素');
+ assert.match(await card.evaluate((element) => getComputedStyle(element).boxShadow),
+ /0px 0px 0px 8px/, '悬停底色没有在卡片四周向外多铺 8px');
+ assert.equal(await card.locator('[data-media-later]').evaluate(
+ (element) => getComputedStyle(element).opacity), '1', '移除描边后没有保留悬停反馈');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('馆藏卡片的字取页面正文那一档,角标、悬停控件、进度条、竖屏带、Mix 与回收站卡面按定下的样子画', { timeout: 90_000 }, async () => {
+ /* 演示库凑不出回收站里的非视频资源:回收站那一页把第二条换成一个压缩包。
+ 目录那一页给前三条挂半程观看进度,量进度条的颜色。 */
+ const opened = await openCatalogFixture(browser, (payload, url) => {
+ if (url.searchParams.get('state') !== 'trash') {
+ for (const item of payload.items.slice(0, 3)) Object.assign(item, { duration: 600, play_seconds: 300 });
+ return;
+ }
+ const item = payload.items[1];
+ if (!item) throw new Error('演示目录不够两条');
+ Object.assign(item, { medium: 'archive', name: '演示资料.zip', disposal: 'trash' });
+ payload.items[0].disposal = 'trash';
+ });
+ const { page } = opened;
+ /* 岛根是 `line-height:1.5`,卡里没写行高的格子会继承它;旧卡读的是页面正文 14px/20px。
+ 取值用同一个岛根下的空元素量 token,不在断言里抄像素。 */
+ const readStyles = (selectors: Record<string, string>) => page.evaluate((wanted) => {
+ const root = document.querySelector('#grid .peach-react')!;
+ const pick = (element: Element | null) => {
+ if (!element) return null;
+ const style = getComputedStyle(element);
+ return { fontSize: style.fontSize, lineHeight: style.lineHeight, fontFamily: style.fontFamily,
+ letterSpacing: style.letterSpacing, minHeight: style.minHeight, padding: style.padding,
+ display: style.display, place: `${style.alignItems} ${style.justifyItems}`, color: style.color,
+ background: style.backgroundColor, borderWidth: style.borderTopWidth, borderColor: style.borderTopColor,
+ leftRadius: style.borderTopLeftRadius, width: style.width, opacity: style.opacity };
+ };
+ const probe = (css: string) => {
+ const element = document.createElement('div');
+ element.style.cssText = css;
+ root.append(element);
+ const value = pick(element)!;
+ element.remove();
+ return value;
+ };
+ return {
+ body: probe('font: var(--board-body)'), caption: probe('font: var(--board-caption)'),
+ md: probe('font-size: var(--fs-md)'), muted: probe('color: var(--muted)'), text: probe(''),
+ ground: probe('background: var(--ground)'), tungsten: probe('background: var(--tungsten)'),
+ overlay: probe('background: var(--overlay-5); border: 1px solid var(--border-10)'),
+ ...Object.fromEntries(Object.entries(wanted).map(([key, selector]) => [key, pick(root.querySelector(selector))])),
+ };
+ }, selectors);
+ try {
+ await page.locator('#grid [data-shorts-strip]').first().waitFor({ timeout: 10_000 });
+ await page.locator('#grid [data-media-grid] > [data-media-card] [data-media-progress]').first().waitFor({ timeout: 10_000 });
+ const catalog = await readStyles({
+ card: '[data-media-grid] > [data-media-card]',
+ badge: '[data-media-grid] > [data-media-card] [data-media-badge]',
+ shorts: '[data-shorts-strip] > h2',
+ mix: '[data-media-grid] > [data-mix-card]',
+ mixTitle: '[data-media-grid] > [data-mix-card] [data-mix-title]',
+ mixGlyph: '[data-media-grid] > [data-mix-card] [data-mix-glyph]',
+ strip: '[data-shorts-strip]',
+ progress: '[data-media-grid] > [data-media-card] [data-media-progress] > i',
+ seekGlyph: '[data-media-grid] > [data-media-card] [data-media-seek] svg',
+ laterButton: '[data-media-grid] > [data-media-card] [data-media-later] button',
+ laterGlyph: '[data-media-grid] > [data-media-card] [data-media-later] svg',
+ });
+ const { body, caption, md, card, badge, shorts, mix, mixTitle } = catalog;
+ /* 竖屏带靠底色和网格区分,不描线;宽屏上往左铺过侧栏轨道,贴视口那一侧不留圆角。 */
+ assert.deepEqual([catalog.strip?.background, catalog.strip?.borderWidth], [catalog.ground.background, '0px'],
+ '竖屏带不是页面底色那一张面,或者描了一圈线');
+ assert.equal(catalog.strip?.leftRadius, '0px', '宽屏上竖屏带贴视口的那一侧还留着圆角');
+ const edges = await page.evaluate(() => ({
+ strip: document.querySelector('#grid [data-shorts-strip]')!.getBoundingClientRect().left,
+ grid: document.querySelector('#grid [data-media-grid]')!.getBoundingClientRect().left,
+ }));
+ assert.ok(edges.strip < edges.grid, `竖屏带左缘 ${edges.strip} 没有越过网格左缘 ${edges.grid} 铺到侧栏底下`);
+ /* 沉浸模式是一叠竖着翻的卡,入口用叠卡那一枚字形,不和别的动作共用。 */
+ assert.equal(await page.locator('#grid [data-shorts-enter] svg use').first().getAttribute('href'), '#i-gallery-vertical-end',
+ '竖屏带的「进入沉浸模式」换了字形');
+ assert.equal(catalog.progress?.background, catalog.tungsten.background, '观看进度条不是钨丝蓝');
+ assert.deepEqual([catalog.mixGlyph?.background, catalog.mixGlyph?.borderWidth, catalog.mixGlyph?.borderColor],
+ [catalog.overlay.background, '1px', catalog.overlay.borderColor], 'Mix 署名位那枚字形不是半透明底加细边');
+ /* 居中的快退快进和右下角「稍后看」是同一种控件,只是尺寸不同:58px 配 34px 图标,36px 配 21px。 */
+ assert.deepEqual([catalog.seekGlyph?.width, catalog.laterButton?.width, catalog.laterGlyph?.width], ['34px', '36px', '21px'],
+ '悬停控件的尺寸和图标比例变了');
+ const denseShort = await page.evaluate(() => {
+ document.body.dataset.density = 'dense';
+ const width = getComputedStyle(document.querySelector('#grid [data-shorts-strip] [data-media-card]')!).width;
+ delete document.body.dataset.density;
+ return width;
+ });
+ assert.equal(denseShort, '107px', '密集模式下竖屏带里的卡没有跟着缩到 214px 的一半');
+ assert.deepEqual([card?.fontSize, card?.lineHeight], ['14px', '20px'], '作品卡的字不是页面正文那一档,岛根的 1.5 行高漏了进来');
+ assert.deepEqual([badge?.fontSize, badge?.lineHeight], [caption.fontSize, caption.lineHeight], '来源角标的字不是 caption 那一档');
+ assert.equal(badge?.minHeight, '24px', '来源角标矮于 24px');
+ assert.deepEqual([shorts?.fontFamily, shorts?.lineHeight], [body.fontFamily, '20px'], '竖屏带标题的字体或行高不同页面正文');
+ assert.ok(mix && mixTitle, '夹具目录里没有插进 Mix');
+ assert.deepEqual([mix.fontSize, mix.lineHeight], ['14px', '20px'], '网格里的 Mix 卡没取页面正文那一档');
+ assert.equal(mixTitle.letterSpacing, 'normal', '网格里的 Mix 标题带着字距');
+ assert.ok(Math.abs(parseFloat(mixTitle.lineHeight) - parseFloat(md.fontSize) * 1.45) < .5,
+ `网格里的 Mix 标题行高 ${mixTitle.lineHeight},不是 --fs-md 的 1.45 倍`);
+
+ await page.goto(new URL('/trash', page.url()).href, { waitUntil: 'load' });
+ await page.locator('#grid [data-media-card][data-variant="resource"]').first().waitFor({ timeout: 15_000 });
+ await settle(page);
+ const trash = await readStyles({
+ meta: '[data-media-grid] > [data-media-card] [data-media-meta]',
+ glyph: '[data-variant="resource"] [data-media-glyph]',
+ kind: '[data-variant="resource"] [data-media-kind-glyph]',
+ });
+ /* 回收站卡有边框:量实际盒子,头像、标题与最后一行都要和框、封面隔开,一行文件名不留空行。 */
+ const inset = await page.locator('#grid [data-media-card][data-variant="resource"]').first().evaluate((card) => {
+ const box = (selector: string) => card.querySelector(selector)!.getBoundingClientRect();
+ const frame = card.getBoundingClientRect();
+ const [pic, avatar, title, byline] = ['[data-media-pic]', '[data-media-avatar]', '[data-media-title]', '[data-media-byline]'].map(box);
+ return { left: avatar.left - frame.left, top: title.top - pic.bottom, bottom: frame.bottom - byline.bottom,
+ title: title.height, lineHeight: parseFloat(getComputedStyle(card.querySelector('[data-media-title]')!).lineHeight),
+ skew: Math.abs((avatar.top + avatar.bottom) / 2 - (title.top + byline.bottom) / 2) };
+ });
+ assert.ok(inset.left >= 10 && inset.top >= 8 && inset.bottom >= 10,
+ `回收站卡的元信息区贴着边框或封面:左 ${inset.left}、上 ${inset.top}、下 ${inset.bottom}`);
+ assert.ok(inset.title < inset.lineHeight * 1.5, `一行文件名的标题仍占 ${inset.title}px,预留了第二行`);
+ assert.ok(inset.skew <= 3, `头像没有和标题加署名那一块居中对齐,偏 ${inset.skew}px`);
+ assert.deepEqual([trash.glyph?.display, trash.glyph?.place, trash.glyph?.color], ['grid', 'center center', trash.muted.color],
+ '回收站资源卡封面格里的字形没有居中或不是次要文字色');
+ assert.deepEqual([trash.kind?.display, trash.kind?.place, trash.kind?.color], ['grid', 'center center', trash.text.color],
+ '回收站资源卡头像位的字形没有居中或不是正文色');
+ /* 悬停扫视层是壳插进封面格的 `img.hvframes`:待删卡的灰化要连它一起,否则悬停时整卡「复活」成正常色。 */
+ const scan = await page.locator('#grid [data-media-card][data-pending-delete]:not([data-variant="resource"]) [data-media-pic]')
+ .first().evaluate((pic) => {
+ const layer = document.createElement('img');
+ layer.className = 'hvframes';
+ pic.append(layer);
+ const filter = getComputedStyle(layer).filter;
+ layer.remove();
+ return filter;
+ });
+ assert.match(scan, /grayscale\(0\.9\)/, '待删卡的悬停扫视层没有跟着灰化');
+ /* 待删卡整块压暗:元信息区降透明度,封面两侧那层模糊垫底也要重写一遍 blur 再灰化,
+ `filter` 不叠加,只写灰化会把模糊冲掉。 */
+ const pending = await page.locator('#grid [data-media-card][data-pending-delete]:not([data-variant="resource"])')
+ .first().evaluate((card) => ({
+ meta: getComputedStyle(card.querySelector('[data-media-meta]')!).opacity,
+ backdrop: getComputedStyle(card.querySelector('[data-media-pic]')!, '::before').filter,
+ }));
+ assert.equal(pending.meta, '0.58', '待删卡的元信息区没有压暗');
+ assert.match(pending.backdrop, /blur\(26px\) grayscale\(0\.9\) brightness\(0\.27\)/, '待删卡封面两侧的模糊垫底没有跟着灰化');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('回收站的骨架和落地同一副几何,计数栏在两种主题下都和页面底色分得开', { timeout: 90_000 }, async () => {
+ /* 回收站多是图片与压缩包,骨架照资源卡排:夹具把回收站那一页全换成图片。 */
+ const opened = await openCatalogFixture(browser, (payload, url) => {
+ if (url.searchParams.get('state') !== 'trash') return;
+ for (const [at, item] of payload.items.entries()) {
+ Object.assign(item, { medium: 'image', name: `演示图片-${at}.jpg`, disposal: 'trash' });
+ }
+ });
+ const { page } = opened;
+ const measure = () => page.evaluate(() => {
+ const box = (element: Element | null) => {
+ if (!element) return null;
+ const rect = element.getBoundingClientRect();
+ return [Math.round(rect.top), Math.round(rect.height)];
+ };
+ const lede = document.querySelector<HTMLElement>('[data-manage-lede]');
+ const card = document.querySelector('#grid .catalog-skeleton .skeletoncard')
+ || document.querySelector('#grid [data-media-card][data-variant="resource"]');
+ /* 读数与「清空回收站」各自的竖直中线:两者说的是同一批文件,同在说明行一行里。 */
+ const middle = (element: Element | null | undefined) => {
+ if (!element) return null;
+ const rect = element.getBoundingClientRect();
+ return Math.round(rect.top + rect.height / 2);
+ };
+ return { lede: box(lede), card: box(card),
+ cells: [...lede?.querySelectorAll<HTMLElement>('[data-trash-lede-skeleton]') ?? []].map((cell) => cell.dataset.trashLedeSkeleton),
+ text: lede?.querySelector('[data-lede-text]')?.textContent ?? null,
+ row: [middle(lede?.querySelector('[data-lede-text]')), middle(lede?.querySelector('[data-empty-trash]'))] };
+ });
+ try {
+ const release = await holdApi(page);
+ await page.goto(new URL('/trash', page.url()).href, { waitUntil: 'load' });
+ await page.locator('#grid .catalog-skeleton .skeletoncard').first().waitFor({ timeout: 15_000 });
+ const waiting = await measure();
+ release();
+ await page.locator('#grid [data-media-card][data-variant="resource"]').first().waitFor({ timeout: 15_000 });
+ await settle(page);
+ const landed = await measure();
+ assert.ok(waiting.lede, '回收站骨架期间没有计数栏,读数到了才冒出来把网格往下推');
+ assert.deepEqual([waiting.cells, waiting.text], [['text', 'action'], null], `骨架期间说明行不是两格占位:${JSON.stringify(waiting)}`);
+ assert.match(landed.text ?? '', /个符合 · 显示 \d+/, `读数没有落进说明行:${JSON.stringify(landed)}`);
+ assert.deepEqual(landed.cells, [], '读数落地后占位还在');
+ const [textMiddle, buttonMiddle] = landed.row;
+ assert.ok(textMiddle != null && buttonMiddle != null && Math.abs(textMiddle - buttonMiddle) <= 1,
+ `读数和清空键没并在说明行同一行:${JSON.stringify(landed.row)}`);
+ assert.deepEqual(waiting.lede, landed.lede, `计数栏落地时位置或高度跳了:${JSON.stringify({ waiting, landed })}`);
+ assert.deepEqual(waiting.card, landed.card, `回收站首张卡落地时位置或高度跳了:${JSON.stringify({ waiting, landed })}`);
+ /* 同一页重画(前进后退回到同一条 /trash):读数接口还在路上时说明行留着上一次的读数,不再铺占位。 */
+ await page.evaluate(() => {
+ const flags = window as unknown as { trashLedeFlashed?: boolean };
+ flags.trashLedeFlashed = false;
+ new MutationObserver(() => {
+ if (document.querySelector('[data-trash-lede-skeleton]')) flags.trashLedeFlashed = true;
+ }).observe(document.querySelector('[data-manage-header]')!, { childList: true, subtree: true });
+ });
+ const again = await holdApi(page);
+ const reread = page.waitForRequest((request) => {
+ const url = new URL(request.url());
+ return url.pathname === '/api/items' && url.searchParams.get('state') === 'trash';
+ }, { timeout: 15_000 });
+ await page.evaluate(() => dispatchEvent(new PopStateEvent('popstate')));
+ await reread;
+ const holding = await measure();
+ again();
+ await page.locator('#grid [data-media-card][data-variant="resource"]').first().waitFor({ timeout: 15_000 });
+ await settle(page);
+ assert.deepEqual([holding.cells, holding.text], [[], landed.text], `同页重画时说明行回到了占位:${JSON.stringify(holding)}`);
+ assert.equal(await page.evaluate(() => (window as unknown as { trashLedeFlashed?: boolean }).trashLedeFlashed), false,
+ '同页重画期间说明行闪回了占位');
+ const surfaces = await page.evaluate(() => {
+ const root = document.documentElement;
+ const before = root.dataset.theme;
+ const read = (theme: string) => {
+ root.dataset.theme = theme;
+ return [getComputedStyle(document.querySelector('[data-manage-lede]')!).backgroundColor,
+ getComputedStyle(document.body).backgroundColor];
+ };
+ const result = { light: read('light'), dark: read('dark') };
+ if (before === undefined) delete root.dataset.theme;
+ else root.dataset.theme = before;
+ return result;
+ });
+ for (const [theme, [lede, ground]] of Object.entries(surfaces)) {
+ assert.notEqual(lede, ground, `${theme} 主题下回收站计数栏和页面同一个底色:${lede}`);
+ }
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('批量条的键是 17px 字形、计数是 --ink-2;批量条与清空回收站两颗危险键读同一组红', { timeout: 90_000 }, async () => {
+ const opened = await openCatalogFixture(browser, (payload, url) => {
+ if (url.searchParams.get('state') !== 'trash') return;
+ for (const item of payload.items) Object.assign(item, { disposal: 'trash' });
+ });
+ const { page } = opened;
+ try {
+ await page.goto(new URL('/trash', page.url()).href, { waitUntil: 'load' });
+ const cards = page.locator('#grid [data-media-card][data-id]');
+ await cards.nth(1).waitFor({ timeout: 15_000 });
+ await page.locator('[data-manage-lede] [data-empty-trash]').waitFor({ timeout: 15_000 });
+ for (const at of [0, 1]) await cards.nth(at).click({ modifiers: ['Control'], position: { x: 20, y: 20 } });
+ await page.locator('[data-batch-dock] [data-selection-dock]').waitFor({ timeout: 10_000 });
+ await settle(page);
+ const read = await page.evaluate(() => {
+ const dock = document.querySelector('[data-batch-dock] [data-selection-dock]')!;
+ /* 两颗危险键的静止面与悬停层各自读出来,再与直接解析 token 的探针比:同一份定义才会三者一致。 */
+ const probe = (token: string) => {
+ const node = document.createElement('div');
+ node.style.background = `var(${token})`;
+ document.body.append(node);
+ const value = getComputedStyle(node).backgroundImage;
+ node.remove();
+ return value;
+ };
+ const paint = (key: Element) => [getComputedStyle(key).backgroundImage, getComputedStyle(key, '::before').backgroundImage];
+ return {
+ glyphs: [...dock.querySelectorAll('button svg')].map((svg) => {
+ const box = svg.getBoundingClientRect();
+ return [box.width, box.height];
+ }),
+ count: getComputedStyle(dock.querySelector('[role="status"]')!).color,
+ batch: paint(dock.querySelector('[data-batch-action="delete"]')!),
+ empty: paint(document.querySelector('[data-manage-lede] [data-empty-trash]')!),
+ tokens: [probe('--board-red'), probe('--board-red-hover')],
+ };
+ });
+ assert.deepEqual(read.glyphs, [[17, 17], [17, 17], [17, 17]], `批量条的字形不是 17px:${JSON.stringify(read.glyphs)}`);
+ assert.equal(read.count, await tokenColor(page, 'body', '--ink-2'), '批量条的计数不是次级墨色');
+ assert.match(read.tokens[0], /^linear-gradient/, `--board-red 没解析成渐变:${read.tokens[0]}`);
+ assert.deepEqual(read.batch, read.tokens, `批量条「彻底删除」的红不是 --board-red 那一组:${JSON.stringify(read)}`);
+ assert.deepEqual(read.empty, read.tokens, `「清空回收站」的红不是 --board-red 那一组:${JSON.stringify(read)}`);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('管理区页头:面包屑当前项升到 --ink、上一级与分隔符钉在 --muted,按下的页签蓝字配一条同宽蓝线', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/duplicates', DESKTOP);
+ try {
+ const { page } = opened;
+ await page.locator('[data-manage-crumb] [aria-current="true"]').waitFor({ timeout: 15_000 });
+ await page.locator('[data-manage-indicator][data-ready]').waitFor({ timeout: 15_000 });
+ await settle(page);
+ /* 指示线落位走一条弹簧过渡:等它停在按下那一枚底下再读;停不下来由下面的断言报出偏差。 */
+ await page.waitForFunction(() => {
+ const a = document.querySelector('[data-manage][aria-pressed="true"]')!.getBoundingClientRect();
+ const b = document.querySelector('[data-manage-indicator]')!.getBoundingClientRect();
+ return Math.abs(a.left - b.left) < 0.5 && Math.abs(a.width - b.width) < 0.5;
+ }, null, { timeout: 5_000 }).catch(() => undefined);
+ const [ink, muted, accent] = await Promise.all(['--ink', '--muted', '--tungsten'].map((token) => tokenColor(page, 'body', token)));
+ const read = await page.evaluate(() => {
+ const items = [...document.querySelectorAll<HTMLElement>('[data-manage-crumb] li')];
+ const pressed = document.querySelector<HTMLElement>('[data-manage][aria-pressed="true"]')!;
+ const line = document.querySelector<HTMLElement>('[data-manage-indicator]')!;
+ const [a, b] = [pressed.getBoundingClientRect(), line.getBoundingClientRect()];
+ return {
+ colors: items.map((item) => getComputedStyle(item).color),
+ separators: items.map((item) => item.querySelector('svg') ? getComputedStyle(item.querySelector('svg')!).stroke : null),
+ gap: getComputedStyle(document.querySelector('[data-manage-crumb] ol')!).columnGap,
+ tab: getComputedStyle(pressed).color,
+ line: getComputedStyle(line).backgroundColor,
+ under: [Math.round(b.left - a.left), Math.round(b.width - a.width), Math.round(a.bottom - b.bottom)],
+ };
+ });
+ assert.deepEqual(read.colors, [muted, ink], '上一级不是 --muted,或当前项没升到 --ink');
+ assert.deepEqual(read.separators, [muted, null], '分隔符跟着当前项提亮了,或最后一项也带了分隔符');
+ assert.equal(read.gap, '6px');
+ assert.deepEqual([read.tab, read.line], [accent, accent], '按下的页签不是蓝字配蓝线');
+ assert.deepEqual(read.under, [0, 0, 0], `指示线没压在按下那一枚底下、同宽:${JSON.stringify(read.under)}`);
+ assert.deepEqual(opened.problems.filter((line) => !line.includes('/api/links/check')), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('分卷卡不翻卡、悬停走分段预览,叠层纸边和封面同一档圆角', { timeout: 60_000 }, async () => {
+ /* 各卷共用同一个番号的封套,翻过去还是那张图。演示库没有分卷,给首张卡挂一个。 */
+ const opened = await openCatalogFixture(browser, (payload) => {
+ const [first, second] = payload.items;
+ payload.items[0] = { ...first, part_group: {
+ key: 'DEMO-PART', title: 'DEMO-PART', count: 2, seed_id: first.id,
+ item_ids: [first.id, second.id], total_duration: 120, total_size: 1 } };
+ });
+ try {
+ const shapeOf = (selector: string) => opened.page.locator(selector).first().evaluate((element) => {
+ const stack = element.querySelector('[data-media-stack],[data-mix-stack]')!;
+ const cover = element.querySelector('[data-media-pic],[data-mix-cover]')!;
+ return {
+ // 封面格的圆角由 clip-path 裁出来(media-card.css),格子本身不写 border-radius。
+ cover: getComputedStyle(cover).clipPath.match(/round (\S+)\)$/)?.[1] ?? '0px',
+ ground: getComputedStyle(cover).backgroundColor,
+ layers: ['::before', '::after'].map((pseudo) => getComputedStyle(stack, pseudo).borderTopLeftRadius),
+ faces: element.querySelectorAll('[data-mix-faces]').length,
+ preview: Boolean(element.querySelector('[data-media-preview]')),
+ };
+ });
+ await opened.page.locator('[data-media-card][data-part-seed]').first().waitFor({ timeout: 10_000 });
+ const part = await shapeOf('[data-media-card][data-part-seed]');
+ assert.notEqual(part.cover, '0px', '封面没有圆角,比对失去意义');
+ assert.deepEqual(part.layers, [part.cover, part.cover], '分卷卡的叠层纸边和封面不是同一档圆角');
+ // 封面格背后压着纸边:格子是空的,纸边线条就从封面没盖住的地方透出来。
+ assert.notEqual(part.ground, 'rgba(0, 0, 0, 0)', '叠层卡的封面格是透明的,纸边会透进封面');
+ assert.equal(part.faces, 0, '分卷卡仍挂着翻卡面板');
+ assert.ok(part.preview, '分卷卡悬停没有分段预览入口');
+ if (await opened.page.locator('#grid [data-mix-card]').count()) {
+ const mix = await shapeOf('#grid [data-mix-card]');
+ assert.deepEqual(mix.layers, [mix.cover, mix.cover], 'Mix 卡的叠层纸边和封面不是同一档圆角');
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('分卷计数在悬停与键盘聚焦时淡出,右上角让给倒计时圈', { timeout: 60_000 }, async () => {
+ const opened = await openCatalogFixture(browser, (payload) => {
+ const [first, second] = payload.items;
+ payload.items[0] = { ...first, part_group: {
+ key: 'DEMO-PART', title: 'DEMO-PART', count: 2, seed_id: first.id,
+ item_ids: [first.id, second.id], total_duration: 120, total_size: 1 } };
+ });
+ try {
+ const page = opened.page;
+ const card = page.locator('[data-media-card][data-part-seed]').first();
+ await card.waitFor({ timeout: 10_000 });
+ const read = () => card.evaluate(async (element) => {
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ const group = element.querySelector<HTMLElement>('[data-media-group]')!;
+ const box = group.getBoundingClientRect();
+ const hit = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2);
+ return {
+ group: [getComputedStyle(group).opacity, getComputedStyle(group).visibility],
+ later: getComputedStyle(element.querySelector('[data-media-later]')!).opacity,
+ hitGroup: hit?.closest('[data-media-group]') === group,
+ };
+ });
+ await page.mouse.move(0, 0);
+ assert.deepEqual(await read(), { group: ['1', 'visible'], later: '0', hitGroup: true }, '不悬停时分卷计数没有照常显示');
+
+ await card.locator('[data-media-pic]').hover();
+ assert.deepEqual(await read(), { group: ['0', 'hidden'], later: '1', hitGroup: false },
+ '悬停时分卷计数没有淡出,或仍压在右上角的悬停工具上');
+
+ await page.mouse.move(0, 0);
+ const opener = card.locator('[data-media-open]');
+ await opener.focus();
+ assert.equal(await opener.evaluate((element) => element.matches(':focus-visible')), true);
+ assert.deepEqual(await read(), { group: ['0', 'hidden'], later: '1', hitGroup: false }, '键盘聚焦时分卷计数没有淡出');
+ assert.equal(await card.locator('[data-media-preview]').evaluate((element) => getComputedStyle(element).opacity), '1',
+ '键盘聚焦时右上角没有打开预览的键');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('抬起与推开只属于作品卡的共演头像', { timeout: 60_000 }, async () => {
+ const opened = await openCatalog(browser);
+ try {
+ await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
+ for (const selector of ['[data-tier-performer]', '[data-tier-studio]']) {
+ const entry = opened.page.locator(selector).first();
+ if (!await entry.count()) continue;
+ await entry.hover();
+ await opened.page.waitForTimeout(320);
+ assert.equal(await entry.evaluate((element) => getComputedStyle(element).transform), 'none',
+ `${selector} 仍套用了作品共演头像的抬起效果`);
+ }
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('视频卡整块是入口且内部链接保持独立', { timeout: 60_000 }, async () => {
+ const opened = await openCatalogFixture(browser, (payload) => {
+ payload.items[0] = { ...payload.items[0], tags: ['演示标签'] };
+ });
+ try {
+ const card = opened.page.locator('#grid [data-media-card][data-id]').first();
+ const opener = card.locator('[data-media-open]');
+ const boxes = await Promise.all([card.boundingBox(), opener.boundingBox()]);
+ assert.deepEqual(boxes[1], boxes[0], '全卡入口没有覆盖图片、文字与卡内空白');
+ await card.hover();
+ assert.notEqual(await card.evaluate((element) => getComputedStyle(element).backgroundColor),
+ 'rgba(0, 0, 0, 0)', '悬停整卡没有灰色反馈');
+
+ await opened.page.setViewportSize({ width: 390, height: 844 });
+ const narrow = await Promise.all([card.boundingBox(), opener.boundingBox()]);
+ assert.deepEqual(narrow[1], narrow[0], '390px 下全卡入口没有覆盖完整卡片');
+ assert.ok((narrow[0]?.x || 0) >= 0 && (narrow[0]?.x || 0) + (narrow[0]?.width || 0) <= 390,
+ '390px 下视频卡越出视口');
+
+ const nested = card.locator('[data-media-tag]:not(:disabled)').first();
+ const tag = await nested.getAttribute('data-tag');
+ assert.ok(tag, '演示卡没有可操作的内部标签');
+ await nested.focus();
+ assert.equal(await nested.evaluate((element) => element.matches(':focus-visible')), true,
+ '卡内链接不能用键盘聚焦');
+ await nested.press('Enter');
+ await opened.page.waitForURL((url) => url.searchParams.get('tag') === tag, { timeout: 10_000 });
+ assert.doesNotMatch(opened.page.url(), /\/item\//, '卡内链接冒泡打开了视频');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ for (const [label, viewport, inset] of [['390px', MOBILE, 12], ['宽屏', DESKTOP, 24]] as const) {
+ it(`${label} 下教程浮窗贴着右下角,Toast 让到它上方,批量选择条盖在它上面`, { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', viewport);
+ try {
+ await opened.page.evaluate(() => {
+ localStorage.setItem('peach.post-setup-tutorial.v1', 'pending');
+ localStorage.removeItem('peach.post-setup-tutorial-collapsed.v1');
+ localStorage.removeItem('peach.post-setup-tutorial-skipped.v1');
+ });
+ await opened.page.reload({ waitUntil: 'load' });
+ /* 目录网格画出来时 paintSelection 已经按当前页收好批量条的按钮;教程卡取数期间的
+ 占位带 aria-busy,settle 等到的是最终那张卡。 */
+ await expectBody(opened.page, '/', [
+ opened.page.locator('#grid [data-media-card][data-id]').first(),
+ opened.page.locator('#postSetupTutorial .post-setup-notification'),
+ ]);
+ await settle(opened.page);
+ /* 批量条只在有选中项时才画:Ctrl 点两张卡进多选,再在浮条中心点取最上层元素。窄屏上它
+ 横跨整行,一定落在教程卡上;宽屏上两者不在同一处,这一条只在窄屏量。 */
+ const cards = opened.page.locator('#grid [data-media-card][data-id]');
+ for (const at of [0, 1]) await cards.nth(at).click({ modifiers: ['Control'], position: { x: 20, y: 20 } });
+ await opened.page.locator('[data-batch-dock] [data-selection-dock]').waitFor({ timeout: 10_000 });
+ await settle(opened.page);
+ const probe = await opened.page.evaluate(() => {
+ const dock = document.querySelector('[data-batch-dock] [data-selection-dock]')!;
+ const tutorial = document.querySelector('#postSetupTutorial .post-setup-notification')!;
+ const card = tutorial.getBoundingClientRect();
+ const box = dock.getBoundingClientRect();
+ const x = box.left + box.width / 2;
+ const y = box.top + box.height / 2;
+ const top = document.elementFromPoint(x, y);
+ return { top: card.top, bottom: card.bottom, left: card.left, right: card.right,
+ dock: { overlaps: x >= card.left && x <= card.right && y >= card.top && y <= card.bottom,
+ tutorialOnTop: !!top && tutorial.contains(top) } };
+ });
+ assert.ok(Math.abs(probe.bottom - (viewport.height - inset)) <= 1,
+ `教程浮窗没有贴着右下角:下沿 ${probe.bottom},应为 ${viewport.height - inset}`);
+ if (viewport.mobile) {
+ assert.ok(probe.dock.overlaps, '批量选择条的中心没落在教程浮窗上,这条判据没有量到重叠');
+ assert.ok(!probe.dock.tutorialOnTop, '教程浮窗盖住了批量选择条');
+ }
+ assert.ok(probe.top >= 0 && probe.left >= 0 && probe.right <= viewport.width,
+ `教程浮窗越出了 ${viewport.width}px 视口`);
+
+ /* 回执走真的入口发一条不会自己消失的,等栈里每一条都进场停稳再量。演示库刚跑完扫描,
+ 「扫描与资料采集已完成」随时可能也进栈,所以判据是栈里每一条都在卡上沿之上。 */
+ await opened.page.evaluate(async () => {
+ const entry = '/dist/peach-ui.js';
+ const ui = await import(entry);
+ ui.showToast(document.getElementById('toasts'), { success: '', error: '' }, 'e2e-tutorial-lift',
+ { html: '已保存配置', alert: false, timeout: 0, action: null });
+ });
+ await opened.page.locator('#toasts [data-sonner-toast]').first().waitFor();
+ await opened.page.waitForFunction(() => [...document.querySelectorAll('#toasts [data-sonner-toast]')]
+ .every((node) => node.getAttribute('data-mounted') === 'true' && node.getAnimations().length === 0));
+ const stack = await opened.page.evaluate(() => {
+ const card = document.querySelector('#postSetupTutorial .post-setup-notification')!.getBoundingClientRect();
+ const boxes = [...document.querySelectorAll('#toasts [data-sonner-toast]')].map((node) => node.getBoundingClientRect());
+ return { cardTop: card.top, lowest: Math.max(...boxes.map((box) => box.bottom)),
+ highest: Math.min(...boxes.map((box) => box.top)) };
+ });
+ assert.ok(stack.lowest <= stack.cardTop,
+ `Toast 压在教程浮窗上:Toast 下沿 ${stack.lowest},教程上沿 ${stack.cardTop}`);
+ assert.ok(stack.highest >= 0, `Toast 被顶出了视口:上沿 ${stack.highest}`);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+
+ it('复核筛选条上的下拉和按钮一样高', { timeout: 60_000 }, async () => {
+ const opened = await openReview(browser);
+ try {
+ /* BoardUI 的 Button 和 Input 都写死 h-8/h-9,Select 的 trigger 只有内边距,
+ 自己撑到 28px/38px。三颗并排时那 4px 一眼就看得见。量的是整条筛选条上每一颗
+ 控件,而不是点名某一颗:这一排以后加什么,都得落在同一档上。 */
+ const heights = await opened.page.locator('[data-review-filter]')
+ .evaluate((bar) => [...bar.querySelectorAll('button')]
+ .map((node) => Math.round(node.getBoundingClientRect().height)));
+ assert.ok(heights.length >= 2, `筛选条上只量到 ${heights.length} 颗控件`);
+ assert.deepEqual([...new Set(heights)], [heights[0]],
+ `筛选条上的控件高度不齐:${heights.join(' / ')}`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('复核卡的勾选框和标题共用一条中线', { timeout: 60_000 }, async () => {
+ const opened = await openReview(browser);
+ try {
+ /* 勾选框 16px、标题那行 24px(字段名是一枚 caption Chip)。两个高度不同的东西
+ 顶对顶排在一起,读的人看到的是勾选框比标题高出一截,而它们说的是同一张卡。 */
+ const offset = await opened.page.locator('section[data-review-key] header').first()
+ .evaluate((element) => {
+ const middle = (node: Element) => {
+ const box = node.getBoundingClientRect();
+ return box.top + box.height / 2;
+ };
+ return middle(element.querySelector('label > span')!) - middle(element.querySelector('h4')!);
+ });
+ assert.ok(Math.abs(offset) <= 1, `勾选框比标题偏了 ${offset.toFixed(1)}px,不在同一条中线上`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('复核滚动边缘按方向出现,当前信息在分隔线之间居中', { timeout: 60_000 }, async () => {
+ const opened = await openReview(browser);
+ try {
+ const card = opened.page.locator('section[data-review-key]').first();
+ const scroller = card.locator('div[data-overlay-scrollbar]').first();
+ // 增加候选内容,覆盖图片加载或队列更新后的溢出重算。
+ await scroller.evaluate((node) => {
+ const content = document.createElement('div');
+ content.style.cssText = 'height:1000px;flex-shrink:0';
+ content.dataset.scrollTest = '';
+ node.append(content);
+ });
+ const edges = scroller.locator('..').locator('.ov-edges');
+ await opened.page.waitForFunction(() => !!document.querySelector('[data-review-key] .can-scroll-bottom'));
+ assert.equal(await edges.evaluate((node) => node.classList.contains('can-scroll-top')), false);
+ await scroller.evaluate((node) => { node.scrollTop = 100 });
+ await opened.page.waitForFunction(() => !!document.querySelector('[data-review-key] .can-scroll-top.can-scroll-bottom'));
+ assert.equal(await edges.evaluate((node) => getComputedStyle(node).pointerEvents), 'none');
+ assert.equal(await edges.locator('.ov-edge-top').evaluate((node) => getComputedStyle(node).backdropFilter), 'blur(2px)');
+ const track = scroller.locator('..').locator('.ovtrack.ov-y');
+ for (const viewport of [DESKTOP, MOBILE]) {
+ await opened.page.setViewportSize({ width: viewport.width, height: viewport.height });
+ const bounds = await track.evaluate((node) => {
+ const scroll = node.parentElement!.querySelector('[data-overlay-scrollbar]')!.getBoundingClientRect();
+ const rail = node.getBoundingClientRect();
+ const card = node.closest('section')!.getBoundingClientRect();
+ return { gap: rail.left - scroll.right, inset: card.right - rail.right };
+ });
+ assert.ok(bounds.gap >= -1, `滚动条命中区覆盖正文:${JSON.stringify(bounds)}`);
+ assert.ok(bounds.inset >= 1, `滚动条越出卡片:${JSON.stringify(bounds)}`);
+ }
+ await opened.page.setViewportSize({ width: DESKTOP.width, height: DESKTOP.height });
+ const thumb = await track.locator('.ovthumb').boundingBox();
+ assert.ok(thumb);
+ await opened.page.mouse.move(thumb.x + thumb.width / 2, thumb.y + thumb.height / 2);
+ await opened.page.mouse.down();
+ await opened.page.mouse.move(thumb.x + thumb.width / 2, thumb.y + thumb.height / 2 + 30);
+ await opened.page.mouse.up();
+ assert.ok(await scroller.evaluate((node) => node.scrollTop > 100), '右侧轨道拖动没有滚动正文');
+ await scroller.evaluate((node) => { node.scrollTop = node.scrollHeight });
+ await opened.page.waitForFunction(() => !document.querySelector('[data-review-key] .can-scroll-bottom'));
+ await scroller.locator('[data-scroll-test]').evaluate((node) => node.remove());
+ await opened.page.waitForFunction(() => !document.querySelector('[data-review-key] [data-scroll-edges]'));
+ const spacing = await card.getByRole('region', { name: '当前信息' }).evaluate((node) => {
+ const style = getComputedStyle(node);
+ const footer = node.closest('section')!.querySelector('footer')!.getBoundingClientRect();
+ return { top: parseFloat(style.paddingTop), bottom: parseFloat(style.paddingBottom), gap: footer.top - node.getBoundingClientRect().bottom };
+ });
+ assert.equal(spacing.top, spacing.bottom);
+ assert.ok(Math.abs(spacing.gap) <= 1, `当前信息下方多出 ${spacing.gap}px`);
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close() }
+ });
+
+ it('暗色下没选中的勾选框边线不比浅色下更弱', { timeout: 60_000 }, async () => {
+ const opened = await openReview(browser);
+ try {
+ /* 这颗框的底和卡面同色,所以整个形状全靠那一圈 1px 的边说话。浅色下它是白底上的
+ 浅灰线,暗色下必须至少同样清楚——否则卡上看着就是「没有框」。 */
+ /* 计算值是 `oklch()` 原样,解析不出通道;画进 1×1 的画布再读回来就是 RGBA。 */
+ const edge = () => opened.page.locator('section[data-review-key] header label > span').first()
+ .evaluate((node) => {
+ const context = document.createElement('canvas').getContext('2d')!;
+ const paint = (color: string) => {
+ context.clearRect(0, 0, 1, 1);
+ context.fillStyle = color;
+ context.fillRect(0, 0, 1, 1);
+ return [...context.getImageData(0, 0, 1, 1).data];
+ };
+ const style = getComputedStyle(node);
+ return [paint(style.borderTopColor), paint(style.backgroundColor)] as const;
+ });
+ const [lightEdge, lightFace] = await edge();
+ // `web/app.js` 的 `applyTheme('dark')` 就是这两句;这里只借它换一次配色。
+ await opened.page.evaluate(() => {
+ document.documentElement.dataset.theme = 'dark';
+ document.documentElement.classList.add('dark');
+ });
+ const [darkEdge, darkFace] = await edge();
+ const light = Math.abs(lightness(lightEdge) - lightness(lightFace));
+ const dark = Math.abs(lightness(darkEdge) - lightness(darkFace));
+ assert.ok(dark >= light,
+ `暗色下边线与框内只差 ${dark.toFixed(1)} 个明度,浅色下有 ${light.toFixed(1)}`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('暗色下分隔线在两种卡面上都不比浅色更弱', { timeout: 60_000 }, async () => {
+ const opened = await openReview(browser);
+ try {
+ /* 量的是 token 对而不是某一条线:`separator-border` 画在哪种面上由各处自己决定,
+ 复核卡的外框和候选块之间那条线落在 `primary`,脚注带那条落在 `secondary`。逐条去点名,
+ 新加一处就得记得再补一条用例,而漏补和「这处本来就没线」在屏幕上看不出区别。
+ 末尾再核一次复核卡自己的框线确实取的就是这个 token,免得两档都合格却根本没落到现场。 */
+ const read = () => opened.page.locator('section[data-review-key]').first()
+ .evaluate((node) => {
+ const context = document.createElement('canvas').getContext('2d')!;
+ const paint = (color: string) => {
+ context.clearRect(0, 0, 1, 1);
+ context.fillStyle = color;
+ context.fillRect(0, 0, 1, 1);
+ return [...context.getImageData(0, 0, 1, 1).data];
+ };
+ const style = getComputedStyle(node);
+ const token = (name: string) => paint(style.getPropertyValue(name).trim());
+ return {
+ line: token('--color-separator-border'),
+ card: token('--color-background-primary-default'),
+ filled: token('--color-background-secondary-default'),
+ edge: paint(style.borderTopColor),
+ };
+ });
+ const before = await read();
+ // `web/app.js` 的 `applyTheme('dark')` 就是这两句;这里只借它换一次配色。
+ await opened.page.evaluate(() => {
+ document.documentElement.dataset.theme = 'dark';
+ document.documentElement.classList.add('dark');
+ });
+ const after = await read();
+ for (const [face, label] of [['card', '描边卡面'], ['filled', '填充卡面']] as const) {
+ const light = Math.abs(lightness(before.line) - lightness(before[face]));
+ const dark = Math.abs(lightness(after.line) - lightness(after[face]));
+ assert.ok(dark >= light,
+ `暗色下分隔线压在${label}上只差 ${dark.toFixed(1)} 个明度,浅色下有 ${light.toFixed(1)}`);
+ }
+ assert.deepEqual(after.edge, after.line, '复核卡的框线没走 separator-border');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('垃圾文件的计数行是两块看得见、跟标题同宽的面', { timeout: 60_000 }, async () => {
+ const opened = await openJunk(browser);
+ try {
+ /* 三件事一起量,它们是同一条:这一行装着摘要和分类切换两块整宽的面,横排时后者
+ 被挤成 0 宽;两块面和网格只要有一支不受 --board-content 约束,宽屏上标题就缩在
+ 中间、卡片顶着两边;浅色下 primary 就是页面底色,不换一档这两块面整个消失。 */
+ const box = await opened.page.evaluate(() => {
+ // 浅色是两块面最容易消失的那一档:深色下 primary 本来就比页面亮一级。
+ document.documentElement.dataset.theme = 'light';
+ document.documentElement.classList.remove('dark');
+ const span = (selector: string) => {
+ const rect = document.querySelector(selector)!.getBoundingClientRect();
+ return { left: Math.round(rect.left), width: Math.round(rect.width) };
+ };
+ const face = (selector: string) =>
+ getComputedStyle(document.querySelector(selector)!).backgroundColor;
+ return {
+ title: span('[data-manage-title]'),
+ summary: span('#count [data-collection-summary]'),
+ filters: span('#count [data-junk-filters-frame]'),
+ grid: span('#grid'),
+ summaryFace: face('#count [data-collection-summary]'),
+ filtersFace: face('#count [data-junk-filters-frame]'),
+ page: getComputedStyle(document.body).backgroundColor,
+ };
+ });
+ assert.ok(box.filters.width > 0, '分类切换被摘要挤成 0 宽,整条在宽屏上看不见');
+ for (const [label, measured] of [['摘要', box.summary], ['分类切换', box.filters],
+ ['网格', box.grid]] as const) {
+ assert.deepEqual(measured, box.title,
+ `${label}和标题不同宽:${measured.left}+${measured.width} 对 ${box.title.left}+${box.title.width}`);
+ }
+ assert.notEqual(box.summaryFace, box.page, '摘要那块面和页面底色同色,整块看不见');
+ assert.notEqual(box.filtersFace, box.page, '分类切换那块面和页面底色同色,整块看不见');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('垃圾文件等数据时画的仍是它自己那条计数行', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/junk-files', WIDE);
+ try {
+ /* 把等待态停在屏幕上:让这一页唯一那次取数挂着不回。等的只有读数,分类切换由
+ URL 决定、此刻就画得出最终样子;画成目录那条的话,等待期间摆着一排这一页根本
+ 没有的换批与排序键,数据到货整行再换成另一种东西。 */
+ await opened.page.route('**/api/ads?**', () => {});
+ await opened.page.reload({ waitUntil: 'load' });
+ // 等 island 接管:壳铺的骨架和它等数据时那一版相同,接管之后仍是这一版才算数。
+ await opened.page.locator(`${JUNK_COUNT} [data-junk-filters]`).waitFor({ timeout: 15_000 });
+ const row = await opened.page.locator('#count').evaluate((node) => ({
+ busy: node.getAttribute('aria-busy'),
+ filters: node.querySelectorAll('[data-junk-filters] a').length,
+ placeholder: node.querySelectorAll('[data-collection-summary] [data-skeleton="count"]').length,
+ sorts: node.querySelectorAll('.sorts').length,
+ }));
+ assert.equal(row.busy, 'true', '等待态没有对辅助技术公开');
+ assert.ok(row.filters > 0, '等待期间这一行没有分类切换');
+ assert.equal(row.placeholder, 1, '占位没有落在读数那一格');
+ assert.equal(row.sorts, 0, '等待期间摆着这一页没有的排序键');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('垃圾卡处置发出一条批量请求、卡随之离开;换分类不整页跳转', { timeout: 90_000 }, async () => {
+ const opened = await openJunkWith(browser, [
+ junkItem(9101, 'archive', '推广合集.zip'), junkItem(9102, 'url', '官网.url'), junkItem(9103, 'audio', '广告.mp3'),
+ ]);
+ try {
+ const page = opened.page;
+ const cards = page.locator('#grid [data-junk-card]');
+ assert.equal(await cards.count(), 3);
+ await cards.first().locator('[data-junk-action="dispose"]').click();
+ await page.waitForFunction(() => document.querySelectorAll('#grid [data-junk-card]').length === 2, null,
+ { timeout: 10_000 });
+ assert.deepEqual(opened.state.batches, [{ ids: [9101], operation: 'dispose' }]);
+ await page.getByText('已移入回收站', { exact: true }).first().waitFor({ timeout: 5_000 });
+
+ // 分类是 `<a href>`,普通左键由壳改地址重读:整页重载的话,页面上记的这个标记会丢。
+ await page.evaluate(() => { (window as { junkStay?: boolean }).junkStay = true });
+ await page.locator(`${JUNK_COUNT} [data-junk-kind-link="url"]`).click();
+ await page.waitForFunction(() => location.search === '?type=url'
+ && document.querySelectorAll('#grid [data-junk-card]').length === 1, null, { timeout: 10_000 });
+ assert.equal(await page.evaluate(() => (window as { junkStay?: boolean }).junkStay), true, '换分类整页重载了');
+ assert.match(opened.state.reads.at(-1)!, /kind=url/);
+ assert.equal(await page.locator(`${JUNK_COUNT} [data-junk-kind-link="url"]`).getAttribute('aria-current'), 'page');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('垃圾卡是一块有边的面:三颗键等宽居中,移入回收站静止就是实底红', { timeout: 90_000 }, async () => {
+ const opened = await openJunkWith(browser, [junkItem(9201, 'archive', '推广.zip'), junkItem(9202, 'url', '官网.url')]);
+ try {
+ const page = opened.page;
+ const read = () => page.evaluate(() => {
+ const card = document.querySelector('#grid [data-junk-card]')!;
+ const keys = [...card.querySelectorAll('[data-junk-action]')].map((button) => {
+ const style = getComputedStyle(button);
+ const rect = button.getBoundingClientRect();
+ return {
+ action: (button as HTMLElement).dataset.junkAction, width: Math.round(rect.width), height: Math.round(rect.height),
+ justify: style.justifyContent, border: style.borderTopWidth, face: style.backgroundColor, ink: style.color,
+ label: getComputedStyle(button.querySelector('[data-junk-label]')!).display,
+ };
+ });
+ const rect = (node: Element | null) => {
+ if (!node) return null;
+ const { left, top, width, height } = node.getBoundingClientRect();
+ return [left, top, width, height].map(Math.round);
+ };
+ const links = [...document.querySelectorAll('#count [data-junk-filters] a')].map((link) => ({
+ current: link.getAttribute('aria-current') === 'page', face: getComputedStyle(link).backgroundColor,
+ height: Math.round(link.getBoundingClientRect().height), box: rect(link),
+ }));
+ // 计数徽标到货时玻璃带动画重新落位:跑完再量,量的是它停下的地方。
+ document.querySelector('#count [data-view-glide]')?.getAnimations().forEach((one) => one.finish());
+ const glide = rect(document.querySelector('#count [data-view-glide]:not([hidden])'));
+ // 卡在 island 里取 oklch,页面底是 rgb:各画一个像素再比,字面不同不等于颜色不同。
+ const pixel = (color: string) => {
+ const context = document.createElement('canvas').getContext('2d')!;
+ context.fillStyle = color;
+ context.fillRect(0, 0, 1, 1);
+ return [...context.getImageData(0, 0, 1, 1).data].join(',');
+ };
+ const style = getComputedStyle(card);
+ const ground = [document.body, document.documentElement].map((el) => pixel(getComputedStyle(el).backgroundColor))
+ .find((value) => !value.endsWith(',0')) ?? '255,255,255,255';
+ return { edge: style.borderTopWidth, line: pixel(style.borderTopColor), page: ground, keys, links, glide };
+ });
+ const red = await tokenColor(page, 'body', '--board-red');
+ const wide = await read();
+ // 浅色下卡底与页面同为白,卡的轮廓全靠这圈边:边宽 1px、颜色不能跟页面底一样。
+ assert.equal(wide.edge, '1px', '垃圾卡没有描边');
+ assert.notEqual(wide.line, wide.page, '垃圾卡的边和页面底色同色');
+ assert.equal(new Set(wide.keys.map((key) => key.width)).size, 1, `三颗键不等宽:${wide.keys.map((key) => key.width)}`);
+ for (const key of wide.keys) {
+ assert.equal(key.justify, 'center', `${key.action} 的图标与标签没有居中`);
+ assert.equal(key.height, 36, `${key.action} 高 ${key.height}`);
+ }
+ const dispose = wide.keys.find((key) => key.action === 'dispose')!;
+ assert.equal(dispose.face, red, '移入回收站静止态不是实底红');
+ assert.equal(dispose.ink, 'rgb(255, 255, 255)');
+ for (const key of wide.keys.filter((one) => one.action !== 'dispose')) assert.equal(key.border, '1px', `${key.action} 没有描边`);
+ const current = wide.links.filter((link) => link.current);
+ assert.equal(current.length, 1);
+ // 分类条是首页筛选条那一副:键自己不铺底,当前那一类底下垫的是那块滑动玻璃。
+ assert.ok(wide.links.every((link) => link.face === 'rgba(0, 0, 0, 0)'), '分类键自己铺了底,不是首页那副滑动玻璃');
+ assert.deepEqual(wide.glide, current[0]!.box, '滑动玻璃没有落在当前那一类上');
+
+ // 紧凑密度下键上只剩图标。
+ await page.evaluate(() => { document.body.dataset.density = 'dense' });
+ assert.ok((await read()).keys.every((key) => key.label === 'none'), '紧凑密度下键上还有字');
+ await page.evaluate(() => { delete document.body.dataset.density });
+
+ // 手机上够手指点:分类与三颗键都到 44px。
+ await page.setViewportSize({ width: MOBILE.width, height: MOBILE.height });
+ const narrow = await read();
+ assert.ok(narrow.keys.every((key) => key.height >= 44), `手机上键高 ${narrow.keys.map((key) => key.height)}`);
+ assert.ok(narrow.links.every((link) => link.height >= 44), `手机上分类高 ${narrow.links.map((link) => link.height)}`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('关注列表工具行里的主动作、版式开关、排序框和方向键同高', { timeout: 60_000 }, async () => {
+ const opened = await openFollowManage(browser);
+ try {
+ const page = opened.page;
+ const controls = {
+ 检查全部: page.locator('button[aria-label="检查全部"]'),
+ // 两枚图标键拼成一组,对齐的是整组的外框,不是组里单个键。
+ 版式开关: page.locator('[aria-label="关注列表版式"]'),
+ 排序框: page.locator('button[aria-label="关注列表排序"]'),
+ 方向键: page.locator('button[aria-label^="按检查时间"]'),
+ };
+ const heights: Record<string, number> = {};
+ for (const [name, control] of Object.entries(controls)) {
+ heights[name] = (await control.boundingBox())!.height;
+ }
+ assert.equal(new Set(Object.values(heights)).size, 1, `同一排控件高度不一:${JSON.stringify(heights)}`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ for (const viewport of [DESKTOP, MOBILE]) {
+ it(`关注列表骨架的偏好控件和接管后同一副长相,等数据的操作键是禁用态(${viewport.name})`, { timeout: 60_000 }, async () => {
+ /* 骨架与真页面各量一遍。版式、排序和方向是这台浏览器的偏好,骨架里就是最终那一档;
+ 检查全部、全部收起和行尾的移除键要等名单,骨架里是禁用态,只有尺寸与接管后一致。
+ 窄屏上工具行收成纯图标,两边按同一条线收,尺寸也要对得上。 */
+ const opened = await visit(browser, '/follow-manage', viewport);
+ try {
+ const page = opened.page;
+ await stubFollowManage(page);
+ const release = await holdApi(page);
+ await page.reload({ waitUntil: 'load' });
+ await page.locator('[data-skeleton="board/follow-manage"] .follow-skeleton-toolbar').waitFor({ timeout: 15_000 });
+ const toolbar = '[data-skeleton] .follow-skeleton-toolbar';
+ const skeleton = await controlFaces(page, {
+ 检查全部: `${toolbar} > button:nth-of-type(1)`,
+ 默认视图: `${toolbar} > [data-button-group] > button:first-child`,
+ 表格视图: `${toolbar} > [data-button-group] > button:last-child`,
+ 排序框: `${toolbar} button[aria-haspopup="listbox"]`,
+ 方向键: `${toolbar} > button:nth-of-type(2)`,
+ 全部收起: `${toolbar} > button:nth-of-type(3)`,
+ 移除来源: '[data-skeleton] .follow-skeleton-source > span:last-child > button:last-child',
+ });
+ const expected = await disabledTokens(page);
+ const waiting = await waitingActionFaces(page, '[data-skeleton] [data-skeleton-action]');
+ assert.ok(waiting.length >= 3, '关注列表骨架里没有标出等数据的操作键');
+ for (const face of waiting) assertDisabledFace(face, expected);
+ release();
+ await page.locator('section[aria-label="kou 的关注来源"]').waitFor({ timeout: 15_000 });
+ await settle(page);
+ const final = await controlFaces(page, {
+ 检查全部: 'button[aria-label="检查全部"]',
+ 默认视图: '[aria-label="关注列表版式"] > button:first-child',
+ 表格视图: '[aria-label="关注列表版式"] > button:last-child',
+ 排序框: 'button[aria-label="关注列表排序"]',
+ 方向键: 'button[aria-label^="按检查时间"]',
+ 全部收起: 'button[aria-label="全部收起"]',
+ 移除来源: '[data-source-divider] > div > span:last-child > button:last-child',
+ });
+ const waitsForData = new Set(['检查全部', '全部收起', '移除来源']);
+ for (const name of Object.keys(final)) {
+ assert.ok(final[name], `接管后找不到 ${name}`);
+ if (waitsForData.has(name)) {
+ assert.equal(skeleton[name]!.size, final[name]!.size, `${name} 接管时尺寸跳了`);
+ continue;
+ }
+ assert.deepEqual(skeleton[name], final[name], `${name} 在骨架里和接管后长得不一样`);
+ }
+ assert.equal(final['默认视图']!.pressed, 'true', '默认版式下选中的不是网格那颗');
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+
+ /* 整行都能点选之后,指着哪一行得看得出来。卡片视图的来源行和表格行走同一条规则;选中行
+ 有自己的底色,指着它时不换。 */
+ it('关注列表指着哪一行哪一行换底色,两种视图都是,选中行的底色不被 hover 盖掉', { timeout: 60_000 }, async () => {
+ const opened = await openFollowManage(browser);
+ try {
+ const page = opened.page;
+ const background = (locator: Locator) => locator.evaluate((element) => {
+ for (const animation of element.getAnimations()) animation.finish();
+ return getComputedStyle(element).backgroundColor;
+ });
+ /* 勾选框的 input 视觉隐藏在画出来的方框底下,点它要 force,和上面选中底色那条用例一样。 */
+ const select = () => page.getByRole('checkbox', { name: '选择 kou · Kemono' })
+ .check({ force: true, timeout: 5_000 });
+ const card = page.locator('[data-source-divider] > div').first();
+ const cardRested = await background(card);
+ await card.hover();
+ assert.notEqual(await background(card), cardRested, '指着卡片视图的来源行时底色没换');
+ await select();
+ const cardSelectedHovered = await background(card);
+ await page.mouse.move(0, 0);
+ const cardSelectedRested = await background(card);
+ assert.equal(cardSelectedHovered, cardSelectedRested, '卡片视图选中行指着时换了底色,盖掉了选中态');
+ assert.notEqual(cardSelectedRested, cardRested, '卡片视图选中行没有自己的底色');
+
+ await page.locator('button[aria-label="表格视图"]').click({ timeout: 5_000 });
+ const row = page.locator('[data-board-data-table] tbody tr').first();
+ await row.waitFor({ timeout: 15_000 });
+ await page.mouse.move(0, 0);
+ const selectedRested = await background(row);
+ await row.hover();
+ assert.equal(await background(row), selectedRested, '表格视图选中行指着时换了底色,盖掉了选中态');
+ await page.getByRole('checkbox', { name: '选择 kou · Kemono' }).uncheck({ force: true, timeout: 5_000 });
+ await page.mouse.move(0, 0);
+ const rested = await background(row);
+ assert.notEqual(selectedRested, rested, '表格视图选中行没有自己的底色');
+ await row.hover();
+ assert.notEqual(await background(row), rested, '指着表格行时底色没换');
+ } finally {
+ await opened.close();
+ }
+ });
+});
diff --git a/frontend/e2e/design-controls.test.ts b/frontend/e2e/design-controls.test.ts
new file mode 100644
index 000000000..f75f527cc
--- /dev/null
+++ b/frontend/e2e/design-controls.test.ts
@@ -0,0 +1,758 @@
+/* 设计决定:控件、状态与首页顶部。读 `getComputedStyle` 断言用户定过的外观;共用的桩与浏览器生命周期在 `design-fixture.ts`。 */
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import type { Browser } from 'playwright-core';
+import { settle } from './harness.ts';
+import { ITEM, openItemPage } from './item-fixture.ts';
+import {
+ DESKTOP, MOBILE, tokenColor, openAccess, settledRun, openActivity, qualityGoal, openQualityGoals,
+ openScraping, openProcessing, openCatalog, openCatalogBars, openCatalogFixture, RUNNING_JOB, FAILED_JOB,
+ installDesignBrowser,
+} from './design-fixture.ts';
+
+describe('设计决定:控件、状态与首页顶部', () => {
+ let browser: Browser;
+ installDesignBrowser((next) => { browser = next; });
+
+ it('聚焦 React 输入框只画 BoardUI 外框,旧样式表的焦点环不进来', { timeout: 60_000 }, async () => {
+ const opened = await openAccess(browser);
+ try {
+ const input = opened.form.locator('#access-password');
+ await input.focus();
+ const style = await input.evaluate((element) => ({
+ outline: getComputedStyle(element).outlineStyle,
+ // TextField 经 GroupContext 把外框的 role 设成 presentation。
+ ring: getComputedStyle(element.closest('[role="presentation"]')!).boxShadow,
+ }));
+ assert.equal(style.outline, 'none', '输入框自己画了 outline:旧的全局 :focus-visible 进了 React 子树');
+ assert.notEqual(style.ring, 'none', '外框没有聚焦描边');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('详情舞台的焦点:骨架期间留在浮窗本身、不画焦点环,内容到了交给关闭键', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, '/', DESKTOP, { ready: `#grid [data-media-card][data-id="${ITEM.plain}"]` });
+ try {
+ const page = opened.page;
+ let release = () => {};
+ const held = new Promise<void>((resolve) => { release = resolve });
+ await page.route((url) => url.pathname === '/api/item', async (route) => { await held; await route.fallback() });
+ await page.locator(`#grid [data-media-card][data-id="${ITEM.plain}"] [data-media-title]`).first().press('Enter');
+ await page.locator('#stage[open] [data-skeleton="detail"]').waitFor();
+ /* 键盘打开也一样:骨架里没有可操作的东西,焦点环画在浮窗外沿上只是一圈噪声。 */
+ const waiting = await page.evaluate(() => {
+ const focused = document.activeElement as HTMLElement;
+ return { id: focused?.id, outline: getComputedStyle(focused).outlineStyle, visible: focused.matches(':focus-visible') };
+ });
+ assert.equal(waiting.id, 'stage', '骨架期间焦点不在浮窗上');
+ assert.equal(waiting.outline, 'none', `骨架期间浮窗画了焦点环(:focus-visible=${waiting.visible})`);
+ release();
+ await page.locator('#stage[open] [data-item-side]').waitFor();
+ await page.waitForFunction(() => document.activeElement?.id === 'closeStage', null, { timeout: 5_000 });
+ assert.deepEqual(opened.problems.filter((line) => !line.includes('VIDEOJS')), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('React 子树读 BoardUI 的 token 原值,不被 board.css 的同名定值盖掉', { timeout: 60_000 }, async () => {
+ const opened = await openAccess(browser);
+ try {
+ const shell = await opened.form.locator('#access-password').evaluate(
+ (element) => getComputedStyle(element.closest('[role="presentation"]')!).backgroundColor);
+ // BoardUI theme.css 浅色 neutral-200 是 #ebebeb;board.css 在 :root 上给的是 #e5e5e5。
+ assert.equal(shell, 'rgb(235, 235, 235)');
+ assert.equal(await tokenColor(opened.page, ':root', '--color-background-tertiary-default'), 'rgb(229, 229, 229)');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('持久警示是状态色块,不和字段说明共用灰色小字', { timeout: 60_000 }, async () => {
+ const opened = await openAccess(browser);
+ try {
+ await opened.form.getByText('关闭访问密码', { exact: true }).click({ timeout: 5_000 });
+ const note = opened.form.locator('[role="note"]');
+ await note.waitFor({ timeout: 5_000 });
+ const surface = await note.evaluate((element) => getComputedStyle(element).backgroundColor);
+ assert.notEqual(surface, 'rgba(0, 0, 0, 0)', '警示没有底色');
+ assert.equal(surface, await tokenColor(opened.page, '.peach-react', '--color-status-yellow-background'));
+ const ink = await note.evaluate((element) => getComputedStyle(element).color);
+ const hint = await opened.form.getByText('关闭访问密码时无需填写。').evaluate((element) => getComputedStyle(element).color);
+ assert.notEqual(ink, hint, '警示文字和字段说明同色');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('跑失败的那一轮整张卡框线换成 danger 色,结束原因还是正文色', { timeout: 60_000 }, async () => {
+ const opened = await openActivity(browser, [
+ settledRun(1, 'failed', '扫描与采集'), settledRun(2, 'succeeded', '追更检查'),
+ ]);
+ try {
+ const danger = await tokenColor(opened.page, '.peach-react', '--color-border-error-default');
+ const border = (status: string) => opened.page.locator(`li[data-status="${status}"]`)
+ .evaluate((element) => getComputedStyle(element).borderTopColor);
+ assert.equal(await border('failed'), danger, '失败卡的框线不是 danger 色');
+ assert.notEqual(await border('succeeded'), danger, '没失败的卡也用了 danger 框线');
+ // 一屏十几行里逐行读红字比看一眼哪张卡的框是红的慢:原因那行留正文色。
+ const reason = await opened.page.locator('li[data-status="failed"] p').last()
+ .evaluate((element) => getComputedStyle(element).color);
+ assert.notEqual(reason, danger, '结束原因那行字被涂成了 danger 色');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('状态徽章只有三档颜色:成功绿、失败红、被叫停黄,其余中性', { timeout: 60_000 }, async () => {
+ const opened = await openActivity(browser, [
+ settledRun(1, 'succeeded', '追更检查'), settledRun(2, 'failed', '扫描与采集'),
+ settledRun(3, 'cancelled', '批量操作'), settledRun(4, 'pending', '命令行批处理'),
+ ]);
+ try {
+ const badge = (status: string) => opened.page.locator(`li[data-status="${status}"] span`).first()
+ .evaluate((element) => getComputedStyle(element).backgroundColor);
+ const token = (name: string) => tokenColor(opened.page, '.peach-react', name);
+ assert.equal(await badge('succeeded'), await token('--color-status-lime-background'));
+ assert.equal(await badge('failed'), await token('--color-status-rose-background'));
+ assert.equal(await badge('cancelled'), await token('--color-status-yellow-background'));
+ // 第四种状态不另给颜色:三档之外都读同一个中性底,颜色才还说得出「成功/失败/被叫停」。
+ assert.equal(await badge('pending'), await token('--color-background-tertiary-default'));
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('高清版卡片的封面是 150px 宽的 16/10 方块,长标题从中间省略', { timeout: 60_000 }, async () => {
+ const long = '这是一个长到必须省略才放得下的文件名,用来盯住中间截断在 React 插进来的节点上也生效.mp4';
+ const opened = await openQualityGoals(browser, [
+ qualityGoal(1, long), qualityGoal(2, 'short.mp4'),
+ ]);
+ try {
+ const cover = opened.page.locator('li[data-goal-id="1"] button').first();
+ const box = await cover.evaluate((element) => ({
+ width: getComputedStyle(element).width,
+ ratio: getComputedStyle(element).aspectRatio,
+ }));
+ assert.equal(box.width, '150px');
+ assert.equal(box.ratio.replaceAll(' ', ''), '16/10');
+ // 中间截断由 `web/js/middle-truncate.js` 的 MutationObserver 接手:React 插进来的
+ // 节点不经过遗留层的渲染函数,观察器认不出它就只剩尾部省略。
+ const title = opened.page.locator('li[data-goal-id="1"] h3 button');
+ await title.waitFor({ timeout: 5_000 });
+ await opened.page.locator('li[data-goal-id="1"] h3 button.middle-truncated')
+ .waitFor({ timeout: 10_000 });
+ assert.ok((await title.textContent())!.includes('…'), '长标题没有被省略');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('一张来源卡底下只有写入那一颗是主按钮,其余次级', { timeout: 60_000 }, async () => {
+ const opened = await openScraping(browser);
+ try {
+ const card = opened.page.locator('form[aria-label="演示来源甲"]');
+ const fill = (name: string) => card.getByRole('button', { name, exact: true })
+ .evaluate((element) => getComputedStyle(element).backgroundColor);
+ // 收 Cookie 且已存了一份的来源,底下三颗:撤销、检查、保存;只有保存是写入。
+ assert.equal(await fill('保存'), await tokenColor(opened.page, '.peach-react', '--color-button-primary'));
+ const secondary = await tokenColor(opened.page, '.peach-react', '--color-background-primary-default');
+ assert.equal(await fill('检查连接'), secondary, '检查连接被画成了主按钮');
+ assert.equal(await fill('撤销 Cookie'), secondary, '撤销 Cookie 被画成了主按钮');
+ // 没存过 Cookie 的来源没有可撤的对象,那一颗不画。
+ const plain = opened.page.locator('form[aria-label="演示来源乙"]');
+ assert.equal(await plain.getByRole('button', { name: '撤销 Cookie', exact: true }).count(), 0);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('目录页那条处理横幅在跑的时候不占语气色,失败了才换成状态红并报警', { timeout: 60_000 }, async () => {
+ const running = await openProcessing(browser, '/', RUNNING_JOB);
+ try {
+ const banner = running.page.locator('#libraryProcessingNotice [role="status"]');
+ await banner.waitFor({ state: 'visible', timeout: 15_000 });
+ assert.match(await banner.innerText(), /采集缺失资料 · 38 \/ 100/);
+ // 一圈长度钉成 100,画出来的那一段就是百分比本身。
+ assert.equal(await banner.locator('[role="progressbar"]').getAttribute('aria-valuenow'), '38');
+ // 判据是「不是语气色」,不钉某一个具体的底:在跑那条走中性底,黄与红留给出事的时候。
+ const tint = await banner.evaluate((element) => getComputedStyle(element).backgroundColor);
+ for (const tone of ['--color-background-tertiary-error', '--color-status-yellow-background']) {
+ assert.notEqual(tint, await tokenColor(running.page, '.peach-react', tone),
+ '任务在跑是正在发生的事,配上状态底色就和「出事了」一个分量');
+ }
+ } finally {
+ await running.close();
+ }
+
+ const failed = await openProcessing(browser, '/', { status: 'failed', error: '来源离线' });
+ try {
+ const banner = failed.page.locator('#libraryProcessingNotice [role="alert"]');
+ await banner.waitFor({ state: 'visible', timeout: 15_000 });
+ /* 计算值现在是 `oklab()`/`oklch()`,两种记法之间没法直接比字符串,所以统一在
+ canvas 上取回 RGBA 再比。 */
+ const surface = await banner.evaluate((element) => {
+ const style = getComputedStyle(element);
+ const context = document.createElement('canvas').getContext('2d')!;
+ const paint = (color: string) => {
+ context.clearRect(0, 0, 1, 1);
+ context.fillStyle = color;
+ context.fillRect(0, 0, 1, 1);
+ return [...context.getImageData(0, 0, 1, 1).data];
+ };
+ return { tint: style.backgroundColor, line: paint(style.borderTopColor), ink: paint(style.color) };
+ });
+ assert.equal(surface.tint,
+ await tokenColor(failed.page, '.peach-react', '--color-background-tertiary-error'));
+ // 上下两条线取自己的文字色:红底上横一条中性灰线,读起来是把这一条切成了两半。
+ for (const at of [0, 1, 2]) {
+ assert.ok(Math.abs(surface.line[at]! - surface.ink[at]!) <= 2,
+ `横幅的线没跟着语气走:线 ${surface.line} 与字 ${surface.ink} 不是同一个色`);
+ }
+ assert.ok(surface.line[3]! < surface.ink[3]!,
+ '线和字一样实,整条读起来像三行字');
+ // 垃圾文件也是目录路径,但它是数据管理底下的一页:同一趟失败的任务,横幅不跟进去。
+ await failed.page.goto(new URL('/junk-files', failed.page.url()).href, { waitUntil: 'load' });
+ await failed.page.locator('[data-junk-filters]').waitFor({ state: 'visible', timeout: 15_000 });
+ await failed.page.waitForTimeout(1_000);
+ assert.equal(await failed.page.locator('#libraryProcessingNotice [role="alert"]').count(), 0,
+ '垃圾文件页顶上挂了目录页的处理横幅');
+ } finally {
+ await failed.close();
+ }
+ });
+
+ it('扫描卡的进度条走焦点环色,底槽是三级底,按下的那颗键转成忙态', { timeout: 60_000 }, async () => {
+ const opened = await openProcessing(browser, '/data-cleanup', RUNNING_JOB);
+ try {
+ const card = opened.page.locator('section[aria-label="扫描与采集"]');
+ await card.waitFor({ state: 'visible', timeout: 15_000 });
+ const bar = card.locator('[role="progressbar"]');
+ assert.equal(await bar.getAttribute('aria-valuenow'), '38');
+ assert.equal(await bar.getAttribute('aria-valuemax'), '100');
+ const fill = (at: number) =>
+ bar.locator('rect').nth(at).evaluate((element) => getComputedStyle(element).fill);
+ assert.equal(await fill(0),
+ await tokenColor(opened.page, '.peach-react', '--color-background-tertiary-default'));
+ assert.equal(await fill(1),
+ await tokenColor(opened.page, '.peach-react', '--color-border-focus-ring'));
+ // 忙态不改 `disabled`:控件仍可聚焦,重复触发由页面自己挡。
+ const scan = card.getByRole('button', { name: '扫描并补全资料', exact: true });
+ assert.equal(await scan.getAttribute('aria-busy'), 'true');
+ assert.equal(await scan.evaluate((element) => (element as HTMLButtonElement).disabled), false,
+ '用原生 disabled 挡的话按钮连焦点都拿不到');
+ const split = card.locator('[data-split-button]');
+ const parts = split.locator(':scope > button');
+ assert.equal(await parts.count(), 2, '拆分按钮没有保持主操作与菜单两区');
+ const boxes = await parts.evaluateAll((buttons) => buttons.map((button) => {
+ const rect = button.getBoundingClientRect();
+ return { left: rect.left, right: rect.right, height: rect.height };
+ }));
+ assert.ok(Math.abs(boxes[0]!.right - boxes[1]!.left) < 0.5,
+ '拆分按钮两区之间留了空隙');
+ assert.equal(boxes[0]!.height, boxes[1]!.height, '拆分按钮两区高度不一致');
+ const divider = await parts.nth(1).evaluate((element) => {
+ const style = getComputedStyle(element, '::after');
+ return { width: style.width, color: style.backgroundColor };
+ });
+ assert.equal(divider.width, '1px', '拆分按钮分隔线宽度不对');
+ assert.notEqual(divider.color, 'rgba(0, 0, 0, 0)', '拆分按钮分隔线没有颜色');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('拆分按钮两半各自抬填充:悬停哪半只有哪半变,中缝那条线不动', { timeout: 60_000 }, async () => {
+ // Geist 实测(`vercel-geist-split-button.md`「悬停」):两半各是一颗有自己底色的按钮,
+ // 悬停只抬指针下那一颗;分隔线是触发档 `::before`,`left:-1px` 盖在主动作最后一列上,
+ // 高度顶满、颜色不随悬停变。
+ const opened = await openProcessing(browser, '/data-cleanup', { status: 'idle' });
+ try {
+ // 骨架那张卡同名同结构,等到 React 接管、两半不再带骨架标记才量。
+ const split = opened.page.locator('section[aria-label="扫描与采集"] [data-split-button]:not(:has(> [data-skeleton-action]))');
+ await split.waitFor({ state: 'visible', timeout: 15_000 });
+ await settle(opened.page);
+ const parts = split.locator(':scope > button');
+ const faces = () => parts.evaluateAll((buttons) => buttons.map((button) => {
+ const style = getComputedStyle(button), lift = getComputedStyle(button, '::before');
+ return { fill: style.backgroundImage, lift: lift.opacity, ink: style.color };
+ }));
+ const seam = () => parts.nth(1).evaluate((element) => {
+ const line = getComputedStyle(element, '::after');
+ return { color: line.backgroundColor, width: line.width, left: line.left,
+ height: line.height, full: `${element.getBoundingClientRect().height}px`,
+ clip: getComputedStyle(element).overflowX };
+ });
+ assert.equal(await split.evaluate((element) => getComputedStyle(element).backgroundImage), 'none',
+ '底色画在整组上,两半就没法各自抬填充');
+ await opened.page.mouse.move(0, 0);
+ const rest = await faces();
+ assert.match(rest[0]!.fill, /gradient/, '主动作那半没有自己的蓝色填充');
+ assert.equal(rest[1]!.fill, rest[0]!.fill, '两半静止时不是同一档填充');
+ assert.deepEqual(rest.map((face) => face.lift), ['0', '0'], '没悬停就抬了填充');
+ const line = await seam();
+ assert.equal(line.width, '1px');
+ assert.equal(line.left, '-1px', '分隔线该盖在主动作最后一列上,不占触发档的宽度');
+ assert.equal(line.height, line.full, '分隔线没有上下顶满');
+ assert.equal(line.clip, 'visible', '触发档把伸到左邻上的分隔线裁掉了,屏幕上看不见');
+ assert.notEqual(line.color, 'rgba(0, 0, 0, 0)');
+ for (const [at, other] of [[0, 1], [1, 0]] as const) {
+ await parts.nth(at).hover();
+ // 悬停层按 150ms 淡入淡出,直接读会落在半路;走到终点再比。
+ await opened.page.evaluate(() => document.getAnimations().forEach((animation) => animation.finish()));
+ const hovered = await faces();
+ assert.equal(hovered[at]!.lift, '1', `悬停第 ${at + 1} 半没有抬填充`);
+ assert.equal(hovered[other]!.lift, '0', `悬停第 ${at + 1} 半时另一半也跟着变了`);
+ assert.deepEqual(hovered.map((face) => face.ink), rest.map((face) => face.ink), '悬停改了字色');
+ assert.deepEqual(await seam(), line, '悬停时分隔线变了');
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('失败提示里重试键靠右,问题清单铺满提示并走覆盖式滚动条', { timeout: 60_000 }, async () => {
+ const opened = await openProcessing(browser, '/data-cleanup', FAILED_JOB);
+ try {
+ const alert = opened.page.locator('#libraryProcessing [role="alert"]');
+ await alert.waitFor({ state: 'visible', timeout: 15_000 });
+ await alert.locator('summary').click();
+ const list = alert.locator('ul');
+ await list.waitFor({ state: 'visible', timeout: 5_000 });
+ const geometry = await alert.evaluate((element) => {
+ const note = element.getBoundingClientRect();
+ const button = element.querySelector('button')!.getBoundingClientRect();
+ const items = element.querySelector('ul')!;
+ return {
+ padding: parseFloat(getComputedStyle(element).paddingRight),
+ noteRight: note.right, buttonRight: button.right,
+ listRight: items.getBoundingClientRect().right,
+ client: items.clientWidth, offset: items.offsetWidth,
+ track: !!element.querySelector('.ovtrack'),
+ };
+ });
+ assert.ok(geometry.noteRight - geometry.buttonRight - geometry.padding < 1,
+ '重试键没有贴着提示的右内边,读起来就不是这条提示的主动作');
+ assert.ok(geometry.noteRight - geometry.listRight - geometry.padding < 1,
+ '问题清单没有铺满提示的宽度');
+ assert.equal(geometry.client, geometry.offset, '原生滚动条还占着清单右边一列');
+ assert.ok(geometry.track, '清单没有挂上全站那条覆盖式滚动条');
+ /* 同一块红底上叠着三段:结论、清单、完整记录。条与条之间要看得见界,完整记录
+ 要退回灰字——它不是这条提示在说的事,是出事之后自己去翻的东西。 */
+ const layering = await alert.evaluate((element) => {
+ const context = document.createElement('canvas').getContext('2d')!;
+ const paint = (color: string) => {
+ context.clearRect(0, 0, 1, 1);
+ context.fillStyle = color;
+ context.fillRect(0, 0, 1, 1);
+ return [...context.getImageData(0, 0, 1, 1).data];
+ };
+ // `divide-y` 把线画在每条的下缘(末条除外),所以量的是第一条的下边。
+ const first = element.querySelectorAll('li')[0]!;
+ const log = element.querySelector('details p')!;
+ return {
+ divider: parseFloat(getComputedStyle(first).borderBottomWidth),
+ dividerInk: paint(getComputedStyle(first).borderBottomColor),
+ logInk: paint(getComputedStyle(log).color),
+ bodyInk: paint(getComputedStyle(element).color),
+ };
+ });
+ assert.ok(layering.divider > 0, '两条明细之间没有界,几十条连成一片');
+ assert.ok(layering.dividerInk[3]! < layering.bodyInk[3]!, '条间的线和正文一样实');
+ assert.ok([0, 1, 2].some((at) => Math.abs(layering.logInk[at]! - layering.bodyInk[at]!) > 8),
+ '完整记录还跟着提示是红的,读起来像又出了一件事');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('新窗口打开的来源地址两项 rel 都写:不带走会话,也不带走来处', { timeout: 60_000 }, async () => {
+ const opened = await openScraping(browser);
+ try {
+ const link = opened.page.locator('form[aria-label="演示来源甲"] a[target="_blank"]');
+ assert.equal(await link.getAttribute('href'), 'https://demoa.example/login');
+ assert.equal((await link.getAttribute('rel'))!.split(/\s+/).sort().join(' '), 'noopener noreferrer');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('顶栏版式键保留两枚字形并原地换态', { timeout: 60_000 }, async () => {
+ const opened = await openCatalog(browser);
+ try {
+ await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
+ const button = opened.page.locator('#density');
+ const swap = button.locator('[data-icon-swap]');
+ await swap.waitFor({ timeout: 5_000 });
+ assert.equal(await swap.locator('[data-icon]').count(), 2);
+ const before = await swap.getAttribute('data-icon-state');
+ await swap.evaluate((element) => { element.setAttribute('data-test-identity', 'density-swap'); });
+ await button.click();
+ assert.notEqual(await swap.getAttribute('data-icon-state'), before,
+ '按下后仍停在同一枚字形');
+ assert.equal(await swap.locator('[data-icon]').count(), 2,
+ '换态不应销毁其中一枚字形');
+ await button.click();
+ assert.equal(await swap.getAttribute('data-icon-state'), before, '第二次按下没有回到原字形');
+ assert.equal(await button.locator('[data-icon-swap][data-test-identity="density-swap"]').count(), 1,
+ '两次换态之间重建了字形容器');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('读数首次静态落笔,变值时每一位都有有效动画', { timeout: 60_000 }, async () => {
+ const opened = await openCatalogFixture(browser, (payload, url) => {
+ payload.total = url.searchParams.has('q') ? 34 : 12;
+ });
+ try {
+ await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
+ const result = await opened.page.evaluate(async () => {
+ const { popCount } = await import('/js/ui-components.js');
+ const host = document.createElement('span');
+ document.body.append(host);
+ popCount(host, '12');
+ const firstWasStatic = !host.firstElementChild?.classList.contains('popping');
+ popCount(host, '34');
+ const digit = host.querySelector<HTMLElement>('.digits.popping > span');
+ const style = digit && getComputedStyle(digit);
+ const answer = {
+ firstWasStatic,
+ animationName: style?.animationName || '',
+ duration: style?.animationDuration || '',
+ };
+ host.remove();
+ return answer;
+ });
+ assert.equal(result.firstWasStatic, true, '首次写入不应弹动');
+ assert.equal(result.animationName, 'digit-pop-in');
+ assert.equal(result.duration, '0.25s');
+
+ const input = opened.page.locator('#q');
+ await opened.page.evaluate(() => {
+ document.documentElement.removeAttribute('data-count-animation');
+ const count = document.querySelector('[data-catalog-filter]');
+ const observer = new MutationObserver(() => {
+ const digit = count?.querySelector<HTMLElement>('[data-count-readout] .digits.popping > span');
+ if (!digit) return;
+ const style = getComputedStyle(digit);
+ document.documentElement.dataset.countAnimation = JSON.stringify({
+ animationName: style.animationName,
+ duration: style.animationDuration,
+ });
+ observer.disconnect();
+ });
+ observer.observe(count!, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });
+ });
+ await input.fill('读数变值');
+ await input.press('Enter');
+ await opened.page.waitForFunction(() =>
+ document.querySelector('[data-catalog-filter] [data-count-readout]')?.textContent?.includes('34 个符合'));
+ /* 读数更新后还可能因自动续页再重画。在触发前观察真实节点,既能验收
+ 动画的计算值,也不把断言绑在之后某一次采样恰好撞上短暂节点。 */
+ await opened.page.waitForFunction(() =>
+ document.documentElement.hasAttribute('data-count-animation'), undefined, { timeout: 5_000 });
+ const liveAnimation = await opened.page.evaluate(() =>
+ JSON.parse(document.documentElement.dataset.countAnimation || '{}') as {
+ animationName?: string; duration?: string;
+ });
+ assert.equal(liveAnimation.animationName, 'digit-pop-in', '真实读数节点变值后没有播放动画');
+ assert.equal(liveAnimation.duration, '0.25s');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('五枚叠放头像只朝标题方向展开,左缘和窄卡边界不动', { timeout: 60_000 }, async () => {
+ const names = Array.from({ length: 7 }, (_, index) => `演示演员 ${index + 1}`);
+ const opened = await openCatalogFixture(browser, (payload) => {
+ const item = payload.items[0];
+ if (!item) throw new Error('演示目录没有可替换的卡片');
+ item.creator = '';
+ item.performers = names;
+ item.performer_total = names.length;
+ item.performer_entities = names.map((name, index) => ({ id: 90_000 + index, name, has_image: false }));
+ });
+ try {
+ await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
+ const stack = opened.page.locator('[data-media-card][data-id] [data-media-avatars]').first();
+ await stack.waitFor({ timeout: 5_000 });
+ const avatars = stack.locator('[data-media-avatar]');
+ assert.equal(await avatars.count(), 5, 'API 给七位表演者时卡片没有收在五枚以内');
+ const before = await avatars.evaluateAll((items) => items.map((item) => item.getBoundingClientRect().x));
+ const left = (await stack.boundingBox())!.x;
+ const waitForAvatarMotion = () => stack.evaluate(async (element) => {
+ const animations = element.getAnimations({ subtree: true });
+ await Promise.all(animations.map((animation) => animation.finished.catch(() => undefined)));
+ });
+
+ await avatars.first().hover();
+ await waitForAvatarMotion();
+ const firstSpread = await avatars.evaluateAll((items) => items.map((item) => item.getBoundingClientRect().x));
+ for (let index = 1; index < firstSpread.length; index += 1) {
+ assert.ok(firstSpread[index] > before[index], `首枚悬停时第 ${index + 1} 枚没有向标题方向展开`);
+ }
+
+ await avatars.nth(2).hover();
+ await waitForAvatarMotion();
+ const after = await avatars.evaluateAll((items) => items.map((item) => item.getBoundingClientRect().x));
+ const card = stack.locator('xpath=ancestor::article[@data-media-card]').first();
+ const bounds = await card.evaluate((cardElement) => {
+ const stackRect = cardElement.querySelector('[data-media-avatars]')!.getBoundingClientRect();
+ const lastRect = cardElement.querySelector('[data-media-avatar]:last-child')!.getBoundingClientRect();
+ const firstRect = cardElement.querySelector('[data-media-avatar]')!.getBoundingClientRect();
+ const cardRect = cardElement.getBoundingClientRect();
+ return {
+ stackLeft: stackRect.left,
+ firstRingLeft: firstRect.left - 2,
+ lastRingRight: lastRect.right + 2,
+ cardLeft: cardRect.left,
+ cardRight: cardRect.right,
+ };
+ });
+ assert.equal(bounds.stackLeft, left, '展开时左缘发生位移');
+ // Chrome 合成层结束 transition 时会留下远小于一个物理像素的浮点残差;这里守的是
+ // 头像没有发生可见位移,不把 303 与 302.9933 这种同一像素内的取整差判成布局回退。
+ assert.ok(Math.abs(after[0] - before[0]) <= .5, '指向第三枚时第一枚被往左推');
+ assert.ok(Math.abs(after[1] - before[1]) <= .5, '指向第三枚时第二枚被往左推');
+ assert.ok(after[3] > before[3] && after[4] > before[4], '右侧邻座没有朝标题方向让开');
+ assert.ok(bounds.firstRingLeft >= bounds.cardLeft - .5, '首枚放大加描边后被卡片左缘裁切');
+ assert.ok(bounds.lastRingRight <= bounds.cardRight + .5, '头像展开越出卡片右缘');
+
+ await opened.page.mouse.move(0, 0);
+ await avatars.nth(2).focus();
+ await waitForAvatarMotion();
+ const layers = await avatars.evaluateAll((items) => items.map((item) => Number(getComputedStyle(item).zIndex)));
+ assert.equal(layers[2], Math.max(...layers), '键盘焦点所在头像没有升到最高层');
+
+ await opened.page.setViewportSize({ width: 390, height: 844 });
+ const drawer = opened.page.locator('#drawer');
+ if (await drawer.evaluate((element) => element.classList.contains('open'))) {
+ await opened.page.locator('#scrim').evaluate((element) => (element as HTMLElement).click());
+ await opened.page.waitForFunction(() => !document.querySelector('#drawer')?.classList.contains('open'));
+ }
+ await avatars.first().hover();
+ await waitForAvatarMotion();
+ const narrow = await card.evaluate((cardElement) => {
+ const cardRect = cardElement.getBoundingClientRect();
+ const firstRect = cardElement.querySelector('[data-media-avatar]')!.getBoundingClientRect();
+ const lastRect = cardElement.querySelector('[data-media-avatar]:last-child')!.getBoundingClientRect();
+ let clip: Element | null = cardElement.parentElement;
+ while (clip && clip !== document.documentElement) {
+ const style = getComputedStyle(clip);
+ if (style.overflowX !== 'visible' || style.overflowY !== 'visible') break;
+ clip = clip.parentElement;
+ }
+ const clipRect = (clip || document.documentElement).getBoundingClientRect();
+ return {
+ firstRingLeft: firstRect.left - 2,
+ lastRingRight: lastRect.right + 2,
+ cardLeft: cardRect.left,
+ cardRight: cardRect.right,
+ clipLeft: clipRect.left,
+ clipRight: clipRect.right,
+ viewport: document.documentElement.clientWidth,
+ };
+ });
+ assert.ok(narrow.firstRingLeft >= Math.max(narrow.cardLeft, narrow.clipLeft) - .5,
+ '390px 视口下首枚头像或描边被最近的裁切祖先截掉');
+ assert.ok(narrow.lastRingRight <= Math.min(narrow.cardRight, narrow.clipRight, narrow.viewport) + .5,
+ '390px 视口下展开头像越出卡片、裁切祖先或视口');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('搜索框从非空变空时立即清值并溶解原内容', { timeout: 60_000 }, async () => {
+ const opened = await openCatalog(browser);
+ try {
+ await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
+ const input = opened.page.locator('#q');
+ const text = '一段长到会在搜索框里横向滚动的内容 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ '.repeat(4).trim();
+ await input.fill(text);
+ await input.evaluate((element) => {
+ const field = element as HTMLInputElement;
+ field.setSelectionRange(field.value.length, field.value.length);
+ field.scrollLeft = field.scrollWidth;
+ field.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }));
+ });
+ assert.ok(await input.evaluate((element) => (element as HTMLInputElement).scrollLeft) > 0,
+ '测试内容没有真正让搜索框横向滚动');
+ await input.fill('');
+ const ghost = opened.page.locator('.search > .cleardissolve');
+ await ghost.waitFor({ timeout: 1_000 });
+ assert.equal(await input.inputValue(), '', '动画阻塞了真实输入框清空');
+ assert.equal(await ghost.locator('[data-dissolve-value]').textContent(), text);
+ // 残影节点先挂载,placeholder 再经 CSS transition 淡出;慢速 Windows runner 上
+ // 两件事可能跨帧。等待过渡的最终状态,仍然守住 placeholder 必须完全不可见。
+ await opened.page.waitForFunction(() => {
+ const field = document.querySelector('#q');
+ return field !== null && getComputedStyle(field, '::placeholder').opacity === '0';
+ }, undefined, { timeout: 1_000 });
+ assert.match(await ghost.locator('[data-dissolve-value]').getAttribute('style') || '', /translateX\(-\d+px\)/);
+ await ghost.waitFor({ state: 'detached', timeout: 2_000 });
+ assert.equal(await input.evaluate((element) => element.classList.contains('dissolving')), false,
+ '动画结束后仍压着输入框的溶解状态');
+
+ await input.fill(text);
+ await input.fill('');
+ await opened.page.locator('.search > .cleardissolve').waitFor({ timeout: 1_000 });
+ await input.type('新输入');
+ assert.equal(await opened.page.locator('.search > .cleardissolve').count(), 0,
+ '清空后继续输入仍被旧残影覆盖');
+ assert.equal(await input.inputValue(), '新输入');
+
+ await input.fill('输入法候选');
+ await input.fill('');
+ await opened.page.locator('.search > .cleardissolve').waitFor({ timeout: 1_000 });
+ await input.evaluate((element) => element.dispatchEvent(new CompositionEvent('compositionstart', {
+ bubbles: true,
+ data: '候',
+ })));
+ assert.equal(await opened.page.locator('.search > .cleardissolve').count(), 0,
+ '输入法开始组字后旧残影仍覆盖候选字');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ /* 搜索框住在粘性顶栏里,永远在视口上沿;可 `html` 的 `scroll-padding-top` 把那一条
+ 划成「被顶栏盖住」的区域,浏览器每敲一个字就把光标往下滚一次,页面一路往回退。
+ 点击走鼠标坐标:定位器的 click 会先替元素滚进视口,那一下不是页面自己的行为。 */
+ it('往下翻过之后在搜索框里打字,页面停在原处', { timeout: 60_000 }, async () => {
+ const opened = await openCatalog(browser);
+ try {
+ const { page } = opened;
+ await page.setViewportSize({ width: DESKTOP.width, height: 480 });
+ await page.mouse.move(DESKTOP.width / 2, 300);
+ await page.mouse.wheel(0, 600);
+ await page.waitForFunction(() => scrollY > 300, undefined, { timeout: 5_000 });
+ const before = await page.evaluate(() => scrollY);
+ const box = await page.locator('#q').boundingBox();
+ if (!box) throw new Error('搜索框不可见');
+ await page.mouse.click(box.x + 40, box.y + box.height / 2);
+ await page.keyboard.type('演示abc', { delay: 60 });
+ await page.waitForTimeout(300);
+ assert.equal(await page.evaluate(() => scrollY), before, '打字时页面跟着滚动了');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('首页版式默认小图,大图统一作品画面框,选择单独记住', { timeout: 60_000 }, async () => {
+ /* 首张卡使用番号封面,第二张使用普通预览图。 */
+ const opened = await openCatalogFixture(browser, (payload) => {
+ Object.assign(payload.items[0], { is_jav: true, code: 'ABC-123', display_code: 'ABC-123', has_cover: true });
+ });
+ const { page } = opened;
+ const ratio = (index: number) => page.locator('#grid [data-media-grid] > [data-media-card][data-id]').nth(index).locator('[data-media-pic]')
+ .evaluate((element) => element.getBoundingClientRect().width / element.getBoundingClientRect().height);
+ const choice = (value: string) => page.locator(`[data-catalog-filter] input[name="home-layout"][value="${value}"]`);
+ try {
+ assert.equal(await choice('small').isChecked(), true, '首页版式默认不是小图');
+ assert.ok(Math.abs(await ratio(0) - 16 / 9) < 0.05, '小图下番号卡不是 16:9');
+ await choice('big').check({ force: true });
+ assert.ok(Math.abs(await ratio(0) - 0.75) < 0.05, '大图下番号卡没有拉成正封比例');
+ assert.ok(Math.abs(await ratio(1) - 0.75) < 0.05, '大图下普通作品画面框不是 3:4');
+ const box = (index: number) => page.locator('#grid [data-media-grid] > [data-media-card][data-id]').nth(index).locator('[data-media-pic]')
+ .evaluate((element) => ({ top: element.getBoundingClientRect().top, height: element.getBoundingClientRect().height }));
+ const [jav, plain] = [await box(0), await box(1)];
+ assert.ok(Math.abs(jav.top - plain.top) < 1, '前两张卡不在同一行,量不到撑高');
+ assert.ok(Math.abs(plain.height - jav.height) < 1, '同行作品画面框不等高');
+ // `visit()` 的初始化脚本每次导航都重写设置,刷新验不了;直接读存下来的那份。
+ const saved = await page.evaluate(() => JSON.parse(localStorage.getItem('peach.settings.v1') || '{}'));
+ assert.equal(saved.homeLayout, 'big', '首页版式没有存下来');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('首页标签:没加上去是 --field-ring-hover 的虚线,加上去是玻璃上那圈实线,视图不画虚线;触屏上排 52、视图与标签 36', { timeout: 60_000 }, async () => {
+ /* 虚线只说「这条筛选可加、此刻没加」,取 Vercel 筛选令牌未生效那一档;四枚视图恒有一枚生效,不画。
+ 圆角同卡片、详情与交集条那一颗(`--tag-radius`)。触屏上 30px 不够一枚指尖。 */
+ const opened = await openCatalogBars(browser);
+ try {
+ const { page } = opened;
+ const scope = '[data-catalog-filter]';
+ const ring = await tokenColor(page, scope, '--field-ring-hover');
+ const low = await tokenColor(page, scope, '--glass-low');
+ const edge = (selector: string) => page.locator(`${scope} ${selector}`).first().evaluate((element) => {
+ const style = getComputedStyle(element);
+ const probe = document.createElement('div');
+ probe.style.borderRadius = 'var(--tag-radius)';
+ element.append(probe);
+ const radius = getComputedStyle(probe).borderTopLeftRadius;
+ probe.remove();
+ return { style: style.borderTopStyle, color: style.borderTopColor, radius: style.borderTopLeftRadius === radius };
+ });
+ assert.deepEqual(await edge('[data-catalog-tag][aria-pressed="false"]'), { style: 'dashed', color: ring, radius: true },
+ '没加上去的标签不是 --field-ring-hover 的虚线,或圆角不是 --tag-radius');
+ assert.notEqual((await edge('[data-catalog-view]')).style, 'dashed', '视图恒有一枚生效,不画虚线');
+ await page.locator(`${scope} [data-catalog-tag][aria-pressed="false"]`).first().click();
+ await page.locator(`${scope} [data-catalog-tag][aria-pressed="true"]`).waitFor({ timeout: 5_000 });
+ assert.deepEqual(await edge('[data-catalog-tag][aria-pressed="true"]'), { style: 'solid', color: low, radius: true },
+ '加上去的标签那圈线不是玻璃上的 --glass-low');
+ } finally {
+ await opened.close();
+ }
+ const phone = await openCatalogBars(browser, MOBILE);
+ try {
+ const { page } = phone;
+ const heights = await page.evaluate(() => {
+ const height = (selector: string) => {
+ const element = document.querySelector(`[data-catalog-filter] ${selector}`);
+ return element ? Math.round(element.getBoundingClientRect().height) : null;
+ };
+ return { coarse: matchMedia('(pointer: coarse)').matches, row: height('[data-filter-row="top"]'),
+ view: height('[data-catalog-view]'), tag: height('[data-catalog-tag]') };
+ });
+ assert.deepEqual(heights, { coarse: true, row: 52, view: 36, tag: 36 }, '触屏上筛选条上排没有放大到指尖尺寸');
+ } finally {
+ await phone.close();
+ }
+ });
+
+ it('首页换一批:头像、厂牌与标签原地藏起来只露一层微光,名字条收成 52px,四枚视图不盖', { timeout: 60_000 }, async () => {
+ /* 框就是它们自己的框,零位移;`visibility:hidden` 的控件也不可聚焦。视图由 state 决定,这一趟不改它们。 */
+ const opened = await openCatalogBars(browser);
+ let release = () => {};
+ try {
+ const { page } = opened;
+ const held = new Promise<void>((resolve) => { release = resolve; });
+ // 后注册的先拦:拖住这一趟,放行后交回夹具那一份。
+ await page.route((url) => url.pathname === '/api/tops', async (route) => { await held; await route.fallback(); });
+ await page.locator('[data-catalog-filter] [data-entity-batch]').click();
+ await page.locator('[data-catalog-filter] [data-catalog-root][data-refreshing]').waitFor({ timeout: 5_000 });
+ const shown = await page.evaluate(() => {
+ const read = (selector: string) => {
+ const element = document.querySelector(`[data-catalog-filter] ${selector}`);
+ if (!element) return null;
+ return { hidden: getComputedStyle(element).visibility, sheen: getComputedStyle(element, '::after').visibility,
+ width: Math.round(element.getBoundingClientRect().width) };
+ };
+ return { tag: read('[data-catalog-tag]'), ring: read('[data-tier-ring]'), name: read('[data-tier-name]'),
+ studio: read('[data-tier-studio]'), view: read('[data-catalog-view]') };
+ });
+ for (const key of ['tag', 'ring', 'name', 'studio'] as const) {
+ assert.equal(shown[key]?.hidden, 'hidden', `换一批时${key}没有藏起来:${JSON.stringify(shown[key])}`);
+ assert.equal(shown[key]?.sheen, 'visible', `换一批时${key}上没有那层微光:${JSON.stringify(shown[key])}`);
+ }
+ assert.equal(shown.name?.width, 52, '名字条没有收成首屏骨架那一宽');
+ assert.equal(shown.view?.hidden, 'visible', '视图不随这一趟变,不该盖');
+ } finally {
+ release();
+ await opened.close();
+ }
+ });
+});
diff --git a/frontend/e2e/design-detail.test.ts b/frontend/e2e/design-detail.test.ts
new file mode 100644
index 000000000..ab6655a11
--- /dev/null
+++ b/frontend/e2e/design-detail.test.ts
@@ -0,0 +1,904 @@
+/* 设计决定:关注详情、作品详情、播放器与侧栏。读 `getComputedStyle` 断言用户定过的外观;共用的桩与浏览器生命周期在 `design-fixture.ts`。 */
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import type { Browser, Page } from 'playwright-core';
+import { DETAIL, openFollowFeed } from './follow-fixture.ts';
+import { settle, visit, VIEWPORTS, type Viewport, type Visit } from './harness.ts';
+import { muteVideos, openImmerse, pickClips, pinQueue, settledClip } from './immerse-fixture.ts';
+import { ITEM, openItemPage } from './item-fixture.ts';
+import { DESKTOP, MOBILE, tokenColor, installDesignBrowser } from './design-fixture.ts';
+
+describe('设计决定:关注详情、作品详情、播放器与侧栏', () => {
+ let browser: Browser;
+ installDesignBrowser((next) => { browser = next; });
+
+ it('关注详情的翻页圆钮:48px 玻璃底、窄屏 44px;落在图片黑边的视觉中心,太窄才退回 16/10 的安全内距;圆点离底 18/12', { timeout: 90_000 }, async () => {
+ const read = (page: Page) => page.evaluate(() => {
+ const frame = document.querySelector<HTMLElement>('#stage [data-follow-detail-media="image"]')!;
+ const next = frame.querySelector('[data-follow-image-arrow="next"]')!, style = getComputedStyle(next);
+ const outer = frame.getBoundingClientRect(), box = next.getBoundingClientRect();
+ const dots = frame.querySelector('[data-follow-image-dots]')!.getBoundingClientRect();
+ // 桩里的图都是 600×800:object-fit:contain 之后左右各留一道黑边。
+ const rendered = Math.min(outer.width, outer.height * 600 / 800);
+ const gutter = (outer.width - rendered) / 2;
+ return {
+ size: [box.width, box.height], background: style.backgroundColor, blur: style.backdropFilter,
+ inset: outer.right - box.right, gutter, dotsBottom: outer.bottom - dots.bottom,
+ framed: frame.hasAttribute('data-framed'),
+ ratio: getComputedStyle(frame.querySelector('[data-follow-detail-poster]')!).aspectRatio,
+ };
+ });
+ const centered = (shown: { gutter: number; size: number[] }, safe: number) =>
+ shown.gutter >= shown.size[0]! + safe * 2 ? (shown.gutter - shown.size[0]!) / 2 : safe;
+ const wide = await openFollowFeed(browser, `/follow/item/${DETAIL.gallery}`, DESKTOP,
+ { ready: '#stage [data-follow-image-arrow="next"]' });
+ try {
+ await wide.page.waitForFunction(() => (document.querySelector('#stage [data-follow-detail-poster]') as HTMLImageElement)?.complete);
+ const shown = await read(wide.page);
+ assert.deepEqual(shown.size, [48, 48]);
+ assert.equal(shown.background, 'rgba(0, 0, 0, 0.6)');
+ assert.equal(shown.blur, 'blur(16px)');
+ assert.ok(Math.abs(shown.inset - centered(shown, 16)) <= 1, `箭头没落在黑边中心:${JSON.stringify(shown)}`);
+ assert.ok(Math.abs(shown.dotsBottom - 18) <= .5, `圆点离底 ${shown.dotsBottom}px`);
+ // 画框比例跟整组图走:换图时详情不忽高忽低。
+ assert.equal(shown.framed, true);
+ assert.match(shown.ratio, /^0\.75\b/);
+ assert.deepEqual(wide.problems, []);
+ } finally {
+ await wide.close();
+ }
+ const narrow = await openFollowFeed(browser, `/follow/item/${DETAIL.gallery}`, MOBILE,
+ { ready: '#stage [data-follow-image-arrow="next"]' });
+ try {
+ await narrow.page.waitForFunction(() => (document.querySelector('#stage [data-follow-detail-poster]') as HTMLImageElement)?.complete);
+ const shown = await read(narrow.page);
+ assert.deepEqual(shown.size, [44, 44]);
+ assert.ok(Math.abs(shown.inset - centered(shown, 10)) <= 1, `窄屏箭头内距不对:${JSON.stringify(shown)}`);
+ assert.ok(Math.abs(shown.dotsBottom - 12) <= .5, `窄屏圆点离底 ${shown.dotsBottom}px`);
+ assert.deepEqual(narrow.problems, []);
+ } finally {
+ await narrow.close();
+ }
+ });
+
+ it('关注详情:没有预览的那一格占 16:9;标签按来源记下的类型取 r34 色板,未知类型取中性灰', { timeout: 60_000 }, async () => {
+ const opened = await openFollowFeed(browser, `/follow/item/${DETAIL.bare}`, DESKTOP,
+ { ready: '#stage [data-follow-detail-tags]' });
+ try {
+ const page = opened.page;
+ const shown = await page.evaluate(() => ({
+ placeholder: getComputedStyle(document.querySelector('#stage [data-follow-detail-placeholder]')!).aspectRatio,
+ tags: Object.fromEntries([...document.querySelectorAll<HTMLElement>('#stage [data-follow-tag]')].map((tag) =>
+ [tag.dataset.followTag, getComputedStyle(tag).getPropertyValue('--tag-color').trim()])),
+ }));
+ assert.equal(shown.placeholder, '16 / 9');
+ const muted = await tokenColor(page, '#stage [data-follow-detail]', '--muted');
+ const unknown = await page.evaluate(() => {
+ const tag = document.querySelector<HTMLElement>('#stage [data-follow-tag="odd"]')!;
+ const probe = document.createElement('div');
+ probe.style.backgroundColor = 'var(--tag-color)';
+ tag.append(probe);
+ const value = getComputedStyle(probe).backgroundColor;
+ probe.remove();
+ return value;
+ });
+ assert.deepEqual({ ...shown.tags, odd: unknown }, {
+ ow: '#d675d6', tracer: '#68c76f', kou: '#e36c6c', solo: '#55a7ff', animated: '#f5a24a', odd: muted,
+ });
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ /* 作品详情(`item-detail` 岛)。桩数据见 `item-fixture.ts`:普通那一条评了 3 星、两位出演、
+ 一个厂牌一个系列,都带实体 id。桩里的片源没有正片,播放器那一条 VIDEOJS 错误不算。 */
+ const withoutPlayer = (problems: string[]) => problems.filter((line) => !line.includes('VIDEOJS'));
+
+ it('作品详情标题与评分:来源徽标站在标题第一行开头;整排星一种琥珀、评没评只看填不填,悬停预演到指针那一颗', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
+ try {
+ const page = opened.page;
+ const title = await page.evaluate(() => {
+ const text = document.querySelector('#stage [data-detail-title]')!;
+ const badge = text.querySelector('[class~="srcbig"]')!;
+ const style = getComputedStyle(badge);
+ return {
+ clamp: getComputedStyle(text).webkitLineClamp,
+ first: text.firstElementChild === badge,
+ badge: { display: style.display, width: style.width, height: style.height, gap: style.marginRight },
+ tools: document.querySelector('#stage [data-title-tools]')!.getBoundingClientRect().top
+ >= text.getBoundingClientRect().bottom - 0.5,
+ };
+ });
+ assert.deepEqual(title, {
+ clamp: '2', first: true, badge: { display: 'inline-grid', width: '17px', height: '28px', gap: '8px' }, tools: true,
+ }, '徽标是行内块、随文字一起被两行折叠裁住;那排键自成一行排在标题下面');
+
+ const stars = page.locator('#stage [data-rate]');
+ const read = () => stars.evaluateAll((nodes) => nodes.map((node) => ({
+ color: getComputedStyle(node).color, filled: getComputedStyle(node.querySelector('svg')!).fill !== 'none',
+ })));
+ const amber = await tokenColor(page, '#stage [data-item-detail]', '--rating');
+ await page.mouse.move(0, 0);
+ const rest = await read();
+ assert.deepEqual(rest.map((star) => star.color), Array(5).fill(amber), '换色那一档在浅色主题下凑不出两级都成立的灰');
+ assert.deepEqual(rest.map((star) => star.filled), [true, true, true, false, false]);
+ await stars.nth(1).hover();
+ const preview = await read();
+ assert.deepEqual(preview.map((star) => star.color), Array(5).fill(amber));
+ assert.deepEqual(preview.map((star) => star.filled), [true, true, false, false, false]);
+ const edges = await page.evaluate(() => {
+ const box = (selector: string) => document.querySelector(`#stage ${selector}`)!.getBoundingClientRect();
+ return { stars: box('[data-rating-stars]').left, title: box('[data-detail-title]').left };
+ });
+ assert.equal(edges.stars, edges.title - 4, '26px 命中区里的星形靠右约 4px 起笔,这一排往左让回来');
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('作品详情身份区:各组按内容宽并排换行,名字行框容得下下伸部;系列是整行宽的图标链接,不是标签胶囊', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
+ try {
+ const page = opened.page;
+ const shown = await page.evaluate(() => {
+ const stage = document.querySelector('#stage')!;
+ const primary = stage.querySelector('[data-identity-primary]')!;
+ const width = primary.getBoundingClientRect().width;
+ const name = getComputedStyle(stage.querySelector('[data-id-group="performer"] [data-id-name]')!);
+ const series = stage.querySelector('[data-series-link]')!;
+ const link = getComputedStyle(series);
+ return {
+ primary: [getComputedStyle(primary).display, getComputedStyle(primary).flexWrap],
+ narrower: [...primary.querySelectorAll('[data-id-group]')].every((group) => group.getBoundingClientRect().width < width),
+ name: { ratio: parseFloat(name.lineHeight) / parseFloat(name.fontSize), overflow: name.textOverflow, align: name.textAlign },
+ cursor: getComputedStyle(stage.querySelector('[data-id-group="performer"] [data-id-cell]')!).cursor,
+ face: getComputedStyle(stage.querySelector('[data-id-group="performer"] [data-id-face]')!).backgroundColor,
+ series: {
+ display: link.display, wrap: link.overflowWrap, border: link.borderTopWidth,
+ full: Math.abs(series.getBoundingClientRect().width - series.parentElement!.getBoundingClientRect().width) < 0.5,
+ },
+ };
+ });
+ assert.deepEqual(shown.primary, ['flex', 'wrap']);
+ assert.equal(shown.narrower, true, '组按内容宽,共演作品不会一组占满一行');
+ assert.ok(shown.name.ratio >= 1.5, `名字行高 ${shown.name.ratio} 倍字号,拉丁字母的下伸部会被省略号那层 overflow 裁掉`);
+ assert.deepEqual([shown.name.overflow, shown.name.align], ['ellipsis', 'left']);
+ assert.equal(shown.cursor, 'pointer');
+ assert.notEqual(shown.face, 'rgba(0, 0, 0, 0)', '没图的头像画首字盘');
+ assert.deepEqual(shown.series, { display: 'flex', wrap: 'anywhere', border: '0px', full: true });
+ await page.locator('#stage [data-series-link]').hover();
+ const hovered = await page.locator('#stage [data-series-link]').evaluate((node) =>
+ [getComputedStyle(node).color, getComputedStyle(node).textDecorationLine]);
+ assert.deepEqual(hovered, [await tokenColor(page, '#stage [data-item-detail]', '--tungsten'), 'none']);
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ for (const viewport of VIEWPORTS) {
+ it(`作品详情头像按有尺寸的圆框取景并显示(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, viewport);
+ try {
+ const page = opened.page;
+ const base = await page.evaluate(() => fetch('/api/item?id=14').then((response) => response.json()));
+ const payload = { ...base, performers: ['取景艺人', '无图艺人'],
+ entity_refs: { ...base.entity_refs, performer: [
+ { id: 3, name: '取景艺人', has_image: true, image_version: 'face-version',
+ avatar_focus: { box: { cx: 0.58, cy: 0.49, faceW: 344, imgW: 1000, imgH: 1000 } } },
+ { id: 4, name: '无图艺人', has_image: false },
+ ] } };
+ await page.route((url) => url.pathname === '/api/item', (route) => route.fulfill({ json: payload }));
+ await page.route('**/entity-image**', (route) => route.fulfill({ contentType: 'image/svg+xml',
+ body: '<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000"><rect width="1000" height="1000" fill="#ddd"/></svg>' }));
+ await page.goto(new URL('/item/14', page.url()).href, { waitUntil: 'load' });
+ const face = page.locator('#stage [data-entity-name="取景艺人"] [data-id-face]');
+ await face.scrollIntoViewIfNeeded();
+ await page.waitForFunction(() => {
+ const image = document.querySelector<HTMLImageElement>('#stage [data-id-cell="performer"] img');
+ return image?.complete && image.naturalWidth > 0;
+ });
+ const geometry = await face.evaluate((ring) => {
+ const image = ring.querySelector('img')!, frame = ring.getBoundingClientRect(), pixels = image.getBoundingClientRect();
+ return { visible: getComputedStyle(image).visibility, framed: image.hasAttribute('data-face-framed'),
+ direct: image.parentElement === ring, zoomed: pixels.width > frame.width,
+ covers: pixels.left <= frame.left + 0.5 && pixels.right >= frame.right - 0.5
+ && pixels.top <= frame.top + 0.5 && pixels.bottom >= frame.bottom - 0.5 };
+ });
+ assert.deepEqual(geometry, { visible: 'visible', framed: true, direct: true, zoomed: true, covers: true });
+ assert.equal(await page.locator('#stage [data-entity-name="无图艺人"] img').count(), 0);
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally { await opened.close(); }
+ });
+ }
+
+ it('作品详情身份区:没实体 id 的格子不给手形,厂牌标识铺满方框', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
+ try {
+ const page = opened.page;
+ // 先经桩取到原样的那一条;`route.fetch()` 会绕过桩直接打到服务器。
+ const base = await page.evaluate(() => fetch('/api/item?id=14').then((response) => response.json()));
+ const payload = {
+ ...base, performers: ['无名氏'], performer_total: 1, performer_entities: [{ id: 0, has_image: false }], has_studio_logo: true,
+ entity_refs: { ...base.entity_refs,
+ performer: [{ id: 0, name: '无名氏', has_image: false, avatar_focus: null }],
+ studio: [{ id: 50, name: 'Peach Studio', has_image: false, has_logo: true }] },
+ };
+ await page.route((url) => url.pathname === '/api/item', (route) => route.fulfill({ json: payload }));
+ await page.goto(new URL('/item/14', page.url()).href, { waitUntil: 'load' });
+ await page.locator('#stage [data-id-cell="studio"] img').waitFor({ timeout: 15_000 });
+ await settle(page);
+ const shown = await page.evaluate(() => {
+ const cell = (kind: string) => document.querySelector(`#stage [data-id-cell="${kind}"]`)!;
+ const face = cell('studio').querySelector('[data-id-face]')!.getBoundingClientRect();
+ const img = cell('studio').querySelector('img')!;
+ const box = img.getBoundingClientRect();
+ return {
+ performer: [cell('performer').tagName, getComputedStyle(cell('performer')).cursor],
+ studio: getComputedStyle(cell('studio')).cursor,
+ fit: getComputedStyle(img).objectFit,
+ filled: [box.left - face.left, box.top - face.top, box.width - face.width, box.height - face.height]
+ .every((delta) => Math.abs(delta) < 0.5),
+ };
+ });
+ assert.deepEqual(shown, { performer: ['SPAN', 'default'], studio: 'pointer', fit: 'cover', filled: true },
+ '标识文件自带边距,页面再补 inset 或换成 contain 就多围出一圈框');
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('作品详情标签与反馈键:标签和卡片同一张脸,筛选那半边悬停抬填充;反馈条每一枚悬停都换色', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
+ try {
+ const page = opened.page;
+ const face = await page.evaluate(() => {
+ const tag = document.querySelector('#stage [data-detail-tag]')!;
+ const probe = document.createElement('div');
+ probe.style.cssText = 'border:1px solid var(--line);border-radius:var(--tag-radius);background:var(--tag-fill);color:var(--ink-2)';
+ tag.parentElement!.append(probe);
+ const want = getComputedStyle(probe);
+ const expected = { radius: want.borderTopLeftRadius, line: want.borderTopColor, fill: want.backgroundColor, ink: want.color };
+ probe.remove();
+ const style = getComputedStyle(tag);
+ return { expected, actual: { radius: style.borderTopLeftRadius, line: style.borderTopColor,
+ fill: style.backgroundColor, ink: getComputedStyle(tag.querySelector('[data-tag]')!).color } };
+ });
+ assert.deepEqual(face.actual, face.expected, '圆角、线、填充与字色都走卡片那颗 `.tg` 的同一组 token');
+ const filter = page.locator('#stage [data-detail-tag] [data-tag]').first();
+ await filter.hover();
+ assert.equal(await filter.evaluate((node) => getComputedStyle(node).backgroundColor),
+ await tokenColor(page, '#stage [data-item-detail]', '--hover'));
+
+ const buttons = ['[data-fb="like"]', '[data-fb="reason"]', '[data-stage-action="dislike"]', '[data-stage-action="seen"]', '[data-stage-action="later"]', '[data-fb="playlist"]',
+ '[data-fb="quality"]', '[data-fb="dispose"]'];
+ const unchanged: string[] = [];
+ for (const selector of buttons) {
+ const button = page.locator(`#stage [data-stage-actions] ${selector}`);
+ const color = () => button.evaluate((node) => {
+ node.getAnimations({ subtree: true }).forEach((animation) => animation.finish());
+ return getComputedStyle(node).color;
+ });
+ await page.mouse.move(0, 0);
+ const rest = await color();
+ await button.hover();
+ if (await color() === rest) unchanged.push(selector);
+ }
+ assert.deepEqual(unchanged, [], '漏写配色的那一枚全程停在 --muted,看着像不能点');
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('作品详情喜爱理由框与「接着看」:输入框聚焦画 BoardUI 那枚 2px 内环;接着看和侧栏同底、顶上一条细线', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
+ try {
+ const page = opened.page;
+ await page.locator('#stage [data-media-card]').first().waitFor({ timeout: 15_000 });
+ await page.locator('#preferenceToggle').click();
+ const field = page.locator('#stage [data-item-preference] textarea');
+ await field.focus();
+ const ring = await field.evaluate((node) => {
+ node.getAnimations().forEach((animation) => animation.finish());
+ return getComputedStyle(node).boxShadow;
+ });
+ const active = await tokenColor(page, '#stage [data-item-detail]', '--color-border-button-active');
+ assert.equal(ring, `${active} 0px 0px 0px 2px inset`);
+
+ const related = await page.evaluate(() => {
+ const block = document.querySelector('#stage [data-item-related]')!;
+ const style = getComputedStyle(block);
+ const row = getComputedStyle(block.querySelector('[data-related-row]')!);
+ return {
+ fill: style.backgroundColor, side: getComputedStyle(document.querySelector('#stage [data-item-side]')!).backgroundColor,
+ line: [style.borderTopWidth, style.borderTopStyle, style.borderTopColor],
+ heading: getComputedStyle(block.querySelector('h3')!).fontWeight,
+ row: [row.display, row.overflowX, row.scrollbarWidth],
+ };
+ });
+ assert.equal(related.fill, related.side, '同一格详情的两块,底色同源,不然整幅宽度上留一道色差');
+ assert.deepEqual(related.line, ['1px', 'solid', await tokenColor(page, '#stage', '--line-soft')]);
+ assert.equal(related.heading, '600');
+ assert.deepEqual(related.row, ['flex', 'auto', 'none'], '那一排横滚,不露系统滚动条');
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('作品详情队列与说明块:版次徽章和标题同一行、不斜体;脱盘说明块铺满播放器格', { timeout: 60_000 }, async () => {
+ const editions = await openItemPage(browser, `/editions/${ITEM.edition}/${ITEM.edition}`, DESKTOP,
+ { ready: '#stage [data-queue-edition]' });
+ try {
+ const shown = await editions.page.evaluate(() => {
+ const badge = document.querySelector('#stage [data-queue-edition]')!;
+ const head = badge.parentElement!;
+ const name = head.querySelector('b')!.getBoundingClientRect();
+ const box = badge.getBoundingClientRect();
+ return {
+ head: [getComputedStyle(head).display, getComputedStyle(head).flexDirection],
+ badge: [getComputedStyle(badge).fontStyle, getComputedStyle(badge).flexShrink],
+ sameRow: box.top < name.bottom && box.bottom > name.top,
+ heading: getComputedStyle(document.querySelector('#stage [data-mix-queue-head] h2')!).fontWeight,
+ };
+ });
+ assert.deepEqual(shown, { head: ['flex', 'row'], badge: ['normal', '0'], sameRow: true, heading: '600' },
+ '`<i>` 默认斜体,徽章不是强调语气');
+ /* 队列头的按钮是关闭一类的操作,走控件圆角,不是圆形标签。 */
+ const head = await editions.page.evaluate(() => {
+ const button = document.querySelector('#stage [data-mix-queue-head] button')!;
+ return [getComputedStyle(button).borderTopLeftRadius, getComputedStyle(button).getPropertyValue('--control-radius').trim()];
+ });
+ assert.equal(head[0], head[1]);
+ assert.deepEqual(withoutPlayer(editions.problems), []);
+ } finally {
+ await editions.close();
+ }
+ const offline = await openItemPage(browser, `/item/${ITEM.offline}`, DESKTOP, { ready: '#stage #offlineGate' });
+ try {
+ const fit = await offline.page.evaluate(() => {
+ const gate = document.querySelector('#stage #offlineGate')!;
+ const cell = gate.parentElement!;
+ const a = gate.getBoundingClientRect(), b = cell.getBoundingClientRect();
+ return {
+ filled: [a.left - b.left, a.top - b.top, a.width - b.width, a.height - b.height].every((delta) => Math.abs(delta) < 0.5),
+ radius: [getComputedStyle(gate).borderTopLeftRadius, getComputedStyle(cell).borderTopLeftRadius],
+ };
+ });
+ assert.equal(fit.filled, true, '说明块铺满播放器格,不上下留黑');
+ assert.equal(fit.radius[0], fit.radius[1], '圆角跟着格走');
+ assert.notEqual(fit.radius[0], '0px');
+ assert.deepEqual(offline.problems, []);
+ } finally {
+ await offline.close();
+ }
+ });
+
+ it('作品详情标签选择器用全站下拉面板那一对开合动效,减少动态效果时当场开合', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
+ try {
+ const page = opened.page;
+ const picker = page.locator('#stage [data-tag-picker]');
+ const motion = () => page.evaluate(() => {
+ const node = document.querySelector<HTMLElement>('#stage [data-tag-picker]');
+ return node && !node.hidden ? getComputedStyle(node).animationName : 'closed';
+ });
+ const cycle = async () => {
+ await page.locator('#tagPlus').click();
+ await page.locator('#tagPickSearch').waitFor();
+ const opening = await motion();
+ await page.locator('#stage [data-rating-value]').click();
+ const closing = await motion();
+ await picker.waitFor({ state: 'hidden' });
+ return [opening, closing];
+ };
+ assert.deepEqual(await cycle(), ['none', 'closed']);
+ await page.emulateMedia({ reducedMotion: 'no-preference' });
+ assert.deepEqual(await cycle(), ['board-menu-in', 'board-menu-out']);
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ /* 舞台与播放器的外观:数值照 YouTube 桌面版 delhi-modern 的播放器与 ytd-miniplayer 实测定下。
+ 桩里的片源放不出来,Video.js 停在错误态,控件照样挂着,读的是计算值。 */
+ const PLAYER_BAR = '#stage .video-js .vjs-control-bar';
+ const PLAYER_BLACK = 'rgba(0, 0, 0, 0.6)';
+ const styleOf = (page: Page, selector: string, properties: string[], pseudo = '') => page.evaluate(
+ ([target, names, element]) => {
+ const node = document.querySelector(target);
+ if (!node) return null;
+ const style = getComputedStyle(node, element || null);
+ return Object.fromEntries(names.map((name) => [name, style.getPropertyValue(name)]));
+ }, [selector, properties, pseudo] as const);
+ const tokenOf = (page: Page, selector: string, token: string) => page.evaluate(([target, name]) =>
+ getComputedStyle(document.querySelector(target)!).getPropertyValue(name).trim(), [selector, token] as const);
+
+ it('详情浮窗:遮罩同一档 --scrim、不带模糊,进出场同设置弹层;关闭键是压在画面上的 40px 黑圆;媒体格只圆左上角,剧场模式圆上面两角、排成单列', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP, { settings: { theme: 'light' } });
+ try {
+ const page = opened.page;
+ const scrim = await tokenColor(page, 'body', '--scrim');
+ assert.equal(scrim, 'rgba(0, 0, 0, 0.7)');
+ await page.emulateMedia({ reducedMotion: 'no-preference' });
+ assert.deepEqual(await styleOf(page, '#stage', ['background-color', 'backdrop-filter', 'animation-name'], '::backdrop'),
+ { 'background-color': scrim, 'backdrop-filter': 'none', 'animation-name': 'settings-backdrop-in' });
+ assert.equal((await styleOf(page, '#stage', ['animation-name']))!['animation-name'], 'board-dialog-in');
+ /* 亮色主题下白底白晕看不出悬停,用户以 YouTube 为参照:播放器上的键在亮色下也是黑底。 */
+ assert.deepEqual(await styleOf(page, '#closeStage', ['width', 'height', 'border-top-left-radius', 'background-color', 'color']),
+ { width: '40px', height: '40px', 'border-top-left-radius': '50%', 'background-color': PLAYER_BLACK, color: 'rgb(255, 255, 255)' });
+
+ const corners = () => styleOf(page, '#stage [data-stage-media]',
+ ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-left-radius']);
+ const wide = (await corners())!;
+ assert.notEqual(wide['border-top-left-radius'], '0px', '媒体格左上角没圆');
+ assert.deepEqual([wide['border-top-right-radius'], wide['border-bottom-left-radius']], ['0px', '0px'],
+ '媒体格右边贴着侧栏、下面接着「接着看」,只圆左上角');
+ /* `overflow-y:auto` 会把 overflow-x 算成 auto,内容宽出 1px 就冒横向滚动条;侧栏撑满所在那一行,不露半截底色。 */
+ assert.deepEqual(await styleOf(page, '#stage [data-stage-side-content]', ['overflow-x', 'overflow-y']),
+ { 'overflow-x': 'hidden', 'overflow-y': 'auto' });
+ assert.equal((await styleOf(page, '#stage [data-stage-side]', ['align-self']))!['align-self'], 'stretch');
+ await page.locator('#stage [data-player-theater]').dispatchEvent('click');
+ await page.locator('#stage[data-theater]').waitFor();
+ const theater = (await corners())!;
+ assert.deepEqual([theater['border-top-right-radius'], theater['border-bottom-left-radius']],
+ [wide['border-top-left-radius'], '0px'], '剧场模式下媒体格圆上面两角');
+ const columns = (await styleOf(page, '#stage [data-stage-grid]', ['grid-template-columns']))!['grid-template-columns']!;
+ assert.equal(columns.split(' ').length, 1, `剧场模式没排成单列:${columns}`);
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('手机上详情浮窗离屏幕边 8px,滚的是里面那一层,视频格吸在它顶上', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, MOBILE);
+ try {
+ const page = opened.page;
+ await page.locator(PLAYER_BAR).waitFor({ state: 'attached' });
+ const box = (await page.locator('#stage').boundingBox())!;
+ assert.deepEqual([box.x, box.y, box.width], [8, 8, MOBILE.width - 16]);
+ assert.equal((await styleOf(page, '#stage > [data-stage-scroll]', ['overflow-y']))!['overflow-y'], 'auto');
+ assert.deepEqual(await styleOf(page, '#stage [data-stage-media]', ['position', 'top']), { position: 'sticky', top: '0px' });
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('播放器控件:40px 黑圆播放键、同一档黑的右侧胶囊与提示、钨丝色进度、页面字体;统计键与加载速度角标压在左上;报错是一张盖在统计上面的卡', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
+ try {
+ const page = opened.page;
+ await page.locator(PLAYER_BAR).waitFor({ state: 'attached' });
+ assert.deepEqual(await styleOf(page, `${PLAYER_BAR} > .vjs-play-control`, ['width', 'height', 'border-top-left-radius', 'background-color']),
+ { width: '40px', height: '40px', 'border-top-left-radius': '50%', 'background-color': PLAYER_BLACK });
+ assert.equal((await styleOf(page, '#stage .vjs-peach-right-controls', ['background-color']))!['background-color'], PLAYER_BLACK);
+ /* 错误态下控件条收起、量不到盒子,读它离播放器四边的计算值。 */
+ assert.deepEqual(await styleOf(page, PLAYER_BAR, ['left', 'right', 'bottom', 'height']),
+ { left: '12px', right: '12px', bottom: '8px', height: '59px' });
+ /* 彩条 6px,抓取区 18px,多出来的 12px 全在条上方:往下扩会盖住按钮那一排的顶边。 */
+ assert.deepEqual(await styleOf(page, '#stage .vjs-progress-control', ['height', 'top']), { height: '18px', top: '-12px' });
+ assert.equal((await styleOf(page, '#stage .vjs-progress-holder', ['height']))!.height, '6px', '彩条本身不变粗');
+ assert.equal((await styleOf(page, '#stage .vjs-play-progress', ['background-color']))!['background-color'],
+ await tokenColor(page, '#stage', '--tungsten'));
+ assert.deepEqual(await styleOf(page, '#stage .vjs-big-play-button', ['width', 'height']), { width: '56px', height: '56px' });
+ assert.equal((await styleOf(page, '#stage .video-js', ['font-family']))!['font-family'],
+ (await styleOf(page, 'body', ['font-family']))!['font-family'], '播放器里的字用页面字体,不是 Video.js 的 Arial');
+ assert.deepEqual(await styleOf(page, '#stage [data-player-theater] > .vjs-peach-tooltip',
+ ['background-color', 'color', 'padding-top', 'padding-left', 'backdrop-filter', 'white-space']),
+ { 'background-color': PLAYER_BLACK, color: 'rgb(255, 255, 255)', 'padding-top': '5px', 'padding-left': '9px',
+ 'backdrop-filter': 'blur(16px)', 'white-space': 'nowrap' });
+ assert.deepEqual(await styleOf(page, '#stage #playerStatsBtn', ['left', 'top', 'width', 'height', 'border-top-left-radius', 'background-color']),
+ { left: '11px', top: '11px', width: '40px', height: '40px', 'border-top-left-radius': '50%', 'background-color': PLAYER_BLACK });
+ /* 音量胶囊和右边那枚同一排,毛玻璃同一档:只有一边磨砂,展开后它就比邻居更透。 */
+ assert.equal((await styleOf(page, `${PLAYER_BAR} > .vjs-volume-panel`, ['backdrop-filter']))!['backdrop-filter'], 'blur(16px)');
+ assert.deepEqual(await styleOf(page, '#stage #playerNet', ['left', 'top', 'height', 'white-space']),
+ { left: '58px', top: '11px', height: '40px', 'white-space': 'nowrap' }, '速率断成两行会顶破 40px 的胶囊');
+ /* sprite 里的仪表盘是描边图形,容器不声明就按 SVG 默认填成黑块,压在黑底上等于没有图标。
+ 演示库的片子放不出来、角标没有速率可写,量的是临时塞进去的一枚 svg。 */
+ const gauge = await page.evaluate(() => {
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ document.querySelector('#stage #playerNet')!.append(svg);
+ const style = getComputedStyle(svg);
+ const shown = { fill: style.fill, stroke: style.stroke };
+ svg.remove();
+ return shown;
+ });
+ assert.deepEqual(gauge, { fill: 'none', stroke: 'rgb(255, 255, 255)' });
+ await page.locator('#stage .video-js.vjs-error').waitFor({ timeout: 10_000 });
+ const error = (await styleOf(page, '#stage .vjs-error-display .vjs-modal-dialog-content', ['background-color', 'z-index']))!;
+ const stats = (await styleOf(page, '#stage #playerStats', ['z-index']))!;
+ assert.equal(error['background-color'], 'rgba(2, 4, 8, 0.86)');
+ assert.ok(Number(error['z-index']) > Number(stats['z-index']), `报错卡压在统计面板底下:${error['z-index']} / ${stats['z-index']}`);
+ const card = (await page.locator('#stage .vjs-error-display .vjs-modal-dialog-content').boundingBox())!;
+ const frame = (await page.locator('#stage .video-js').boundingBox())!;
+ assert.ok(Math.abs(card.x + card.width / 2 - (frame.x + frame.width / 2)) < 1
+ && Math.abs(card.y + card.height / 2 - (frame.y + frame.height / 2)) < 1, '报错卡居中在画面里,躲开左上角的速率角标');
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('播放器的设置面板与右键菜单:同一档黑、浮层圆角、48px 的行;右键菜单悬停抬一层白', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
+ try {
+ const page = opened.page;
+ await page.locator('#stage #playerStatsBtn').waitFor();
+ const menu = '#stage .vjs-peach-settings-menu';
+ /* 关闭态不能是 display:none:它没有可过渡的中间态,面板只会瞬间消失。 */
+ assert.deepEqual(await styleOf(page, menu, ['display', 'opacity', 'visibility']),
+ { display: 'block', opacity: '0', visibility: 'hidden' });
+ await page.locator('#stage .vjs-peach-settings-toggle').dispatchEvent('click');
+ const floating = await tokenOf(page, menu, '--floating-radius');
+ const settings = (await styleOf(page, menu, ['background-color', 'border-top-left-radius', 'width', 'backdrop-filter']))!;
+ assert.equal(settings['background-color'], PLAYER_BLACK);
+ assert.equal(settings['backdrop-filter'], 'blur(16px)', '设置面板的毛玻璃没生效');
+ assert.equal(settings['border-top-left-radius'], floating);
+ assert.ok(parseFloat(settings.width!) <= 274, `设置面板宽 ${settings.width}`);
+ assert.equal((await styleOf(page, `${menu} .vjs-peach-menu-row`, ['min-height']))!['min-height'], '48px');
+ await page.locator('#stage .vjs-peach-settings-toggle').dispatchEvent('click');
+
+ await page.locator('#stage .video-js').click({ button: 'right' });
+ await page.locator('#playerMenu:popover-open').waitFor();
+ assert.deepEqual(await styleOf(page, '#playerMenu', ['padding-top', 'background-color', 'border-top-left-radius', 'backdrop-filter']),
+ { 'padding-top': '8px', 'background-color': PLAYER_BLACK, 'border-top-left-radius': await tokenOf(page, '#playerMenu', '--floating-radius'),
+ 'backdrop-filter': 'blur(16px)' });
+ const row = (await styleOf(page, '#playerMenu [data-player-menu]', ['min-height', 'grid-template-columns']))!;
+ assert.equal(row['min-height'], '48px');
+ const tracks = row['grid-template-columns']!.split(' ');
+ assert.deepEqual([tracks[0], tracks.at(-1)], ['56px', '32px'], `右键菜单行的列:${row['grid-template-columns']}`);
+ await page.locator('#playerMenu [data-player-menu]').first().hover();
+ assert.equal((await styleOf(page, '#playerMenu [data-player-menu]', ['background-color']))!['background-color'],
+ 'rgba(255, 255, 255, 0.1)');
+ await page.keyboard.press('Escape');
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('统计图 20px 高,缓冲那条按健康度换色;小窗照 ytd-miniplayer:固定在右下角 16px、宽 400px、层级在弹层之下,快退快进键 36px', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
+ try {
+ const page = opened.page;
+ await page.locator('#stage #playerStatsBtn').click();
+ const plot = '#stage [data-player-stats-plot="buffer"]';
+ assert.equal((await styleOf(page, plot, ['height']))!.height, '20px');
+ const colors = await page.evaluate((selector) => ['low', 'mid'].map((state) => {
+ const bar = document.createElement('i');
+ bar.dataset.bar = state;
+ document.querySelector(selector)!.append(bar);
+ const color = getComputedStyle(bar).backgroundColor;
+ bar.remove();
+ return color;
+ }), plot);
+ assert.deepEqual(colors, ['rgb(225, 105, 98)', 'rgb(239, 181, 95)']);
+
+ await page.locator('#closeStage').focus();
+ await page.keyboard.press('i');
+ await page.locator('#miniplayer:not([hidden]) .video-js').waitFor({ timeout: 10_000 });
+ assert.deepEqual(await styleOf(page, '#miniplayer', ['position', 'z-index']), { position: 'fixed', 'z-index': '900' });
+ const box = (await page.locator('#miniplayer').boundingBox())!;
+ assert.deepEqual([box.width, box.x + box.width, box.y + box.height], [400, DESKTOP.width - 16, DESKTOP.height - 16]);
+ assert.deepEqual(await styleOf(page, '#miniplayerBack', ['width', 'height']), { width: '36px', height: '36px' });
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ /** 一组元素的外框,取到小数点后一位。 */
+ const rectsOf = (page: Page, selectors: Record<string, string>) => page.evaluate((entries) => Object.fromEntries(
+ Object.entries(entries).map(([name, selector]) => {
+ const box = document.querySelector(selector)!.getBoundingClientRect();
+ const round = (value: number) => Math.round(value * 10) / 10;
+ return [name, { left: round(box.left), top: round(box.top), right: round(box.right), bottom: round(box.bottom), width: round(box.width), height: round(box.height) }];
+ })), selectors);
+ const IMMERSE = {
+ root: '[data-immerse]', stage: '[data-immerse-stage]', actions: '[data-immerse-actions]', ui: '[data-immerse-ui]',
+ bar: '[data-immerse-bar]', close: '[data-immerse-close]',
+ };
+
+ it('沉浸模式桌面照 Shorts 三段:9:16 舞台居中、动作列贴舞台右侧 12px、作者标题在左下;横片换成 16:9,动作列收进框里;浅色主题下仍是深色层', { timeout: 90_000 }, async () => {
+ const opened = await visit(browser, '/', DESKTOP);
+ try {
+ const { page } = opened;
+ const { wide, tall } = await pickClips(page);
+ await pinQueue(page, [tall, wide]);
+ await muteVideos(page);
+ await openImmerse(page, tall.id);
+ const portrait = await rectsOf(page, IMMERSE);
+ assert.deepEqual(portrait.stage, { left: 415, top: 0, right: 865, bottom: 800, width: 450, height: 800 });
+ assert.deepEqual([portrait.actions.left, portrait.actions.width, portrait.actions.bottom], [877, 72, 792]);
+ assert.deepEqual([portrait.ui.left, portrait.ui.bottom], [20, 780]);
+ assert.deepEqual(portrait.bar, { left: 0, top: 780, right: 1280, bottom: 800, width: 1280, height: 20 });
+ assert.deepEqual([portrait.close.top, portrait.close.right, portrait.close.width], [15, 1265, 42]);
+ const faces = await page.evaluate(() => {
+ const read = (selector: string, names: string[]) => {
+ const style = getComputedStyle(document.querySelector(selector)!);
+ return Object.fromEntries(names.map((name) => [name, style.getPropertyValue(name)]));
+ };
+ return {
+ root: read('[data-immerse]', ['background-color']),
+ track: read('[data-immerse-track]', ['border-radius', 'background-color']),
+ floating: (() => {
+ const probe = document.createElement('div');
+ probe.style.borderRadius = 'var(--floating-radius)';
+ document.querySelector('[data-immerse]')!.append(probe);
+ const value = getComputedStyle(probe).borderRadius;
+ probe.remove();
+ return value;
+ })(),
+ circle: read('[data-immerse-circle]', ['width', 'height', 'border-radius', 'background-color', 'color']),
+ glyph: read('[data-immerse-circle] svg', ['width', 'height', 'fill', 'stroke']),
+ author: read('[data-immerse-author]>a', ['color', 'font-weight']),
+ title: read('[data-immerse-title]', ['font-size', 'font-weight', 'text-overflow', 'white-space', 'pointer-events']),
+ caption: read('[data-immerse-ui]', ['pointer-events']),
+ progress: read('[data-immerse-bar] i', ['height']),
+ };
+ });
+ const { floating, ...face } = faces;
+ assert.notEqual(floating, '0px');
+ assert.deepEqual(face, {
+ root: { 'background-color': 'rgb(15, 15, 15)' },
+ track: { 'border-radius': floating, 'background-color': 'rgb(0, 0, 0)' },
+ circle: { width: '48px', height: '48px', 'border-radius': '50%', 'background-color': 'rgba(255, 255, 255, 0.1)', color: 'rgb(241, 241, 241)' },
+ glyph: { width: '24px', height: '24px', fill: 'none', stroke: 'rgb(241, 241, 241)' },
+ author: { color: 'rgb(241, 241, 241)', 'font-weight': '600' },
+ title: { 'font-size': '20px', 'font-weight': '600', 'text-overflow': 'ellipsis', 'white-space': 'nowrap', 'pointer-events': 'auto' },
+ caption: { 'pointer-events': 'none' },
+ progress: { height: '4px' },
+ });
+
+ // 进度:4px 的线贴着 20px 热区的底,走钨丝蓝;指针靠近才变粗。
+ assert.equal(await page.evaluate(() => getComputedStyle(document.querySelector('[data-immerse-bar] i')!).backgroundColor),
+ await tokenColor(page, '[data-immerse]', '--tungsten'));
+ await page.hover('[data-immerse-bar]');
+ await page.waitForFunction(() => getComputedStyle(document.querySelector('[data-immerse-bar] i')!).height === '9px');
+
+ // 动作键:悬停放大 1.05、按住缩到 .96;选中反相成浅底深字(压在画面上,抬一档的面会被画面吃掉)。
+ await page.route('**/api/feedback', (route) => route.fulfill({ json: { feedback: 'seen', o_count: 0 } }));
+ const seen = '[data-immerse-actions] button[aria-label="标为看过"]';
+ await page.hover(seen);
+ const scale = (value: string) => page.waitForFunction(([selector, want]) =>
+ getComputedStyle(document.querySelector(selector!)!).scale === want, [seen, value] as const);
+ await scale('1.05');
+ await page.mouse.down();
+ await scale('0.96');
+ await page.mouse.up();
+ await page.locator(`${seen}[aria-pressed="true"]`).waitFor({ timeout: 5_000 });
+ await page.mouse.move(0, 0);
+ assert.deepEqual(await page.evaluate((selector) => {
+ const style = getComputedStyle(document.querySelector(selector)!);
+ return [style.backgroundColor, style.color];
+ }, seen), ['rgb(241, 241, 241)', 'rgb(15, 15, 15)']);
+
+ await page.keyboard.press('ArrowDown');
+ await page.waitForFunction((id) => location.search === `?id=${id}`, wide.id);
+ await settledClip(page);
+ const landscape = await rectsOf(page, IMMERSE);
+ assert.deepEqual(landscape.stage, { left: 230.4, top: 169.6, right: 1049.6, bottom: 630.4, width: 819.2, height: 460.8 });
+ assert.deepEqual([landscape.actions.right, landscape.actions.bottom], [1037.6, 612.4]);
+ assert.equal(landscape.ui.width, 404.8);
+
+ await page.evaluate(() => { document.documentElement.dataset.theme = 'light' });
+ assert.deepEqual(await page.evaluate(() => [
+ getComputedStyle(document.querySelector('[data-immerse]')!).backgroundColor,
+ getComputedStyle(document.querySelector('[data-immerse-author]>a')!).color,
+ ]), ['rgb(15, 15, 15)', 'rgb(241, 241, 241)']);
+ assert.deepEqual(opened.problems.filter((line) => !line.includes('VIDEOJS')), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('沉浸模式手机铺满视口:舞台不留圆角,动作列贴右、作者标题贴左下,作者那行的时长与序号收起', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', MOBILE);
+ try {
+ const { page } = opened;
+ const { wide, tall } = await pickClips(page);
+ await pinQueue(page, [tall, wide]);
+ await muteVideos(page);
+ await openImmerse(page, tall.id);
+ const rects = await rectsOf(page, { ...IMMERSE, avatar: '[data-immerse-avatar]' });
+ assert.deepEqual(rects.stage, { left: 0, top: 0, right: 390, bottom: 844, width: 390, height: 844 });
+ assert.deepEqual([rects.actions.right, rects.actions.bottom, rects.actions.width], [382, 752, 56]);
+ assert.deepEqual([rects.ui.left, rects.ui.right, rects.ui.bottom], [14, 308, 816]);
+ assert.deepEqual([rects.avatar.width, rects.avatar.height], [36, 36]);
+ assert.deepEqual([rects.close.top, rects.close.right], [10, 380]);
+ assert.deepEqual(await page.evaluate(() => ({
+ radius: getComputedStyle(document.querySelector('[data-immerse-track]')!).borderRadius,
+ meta: getComputedStyle(document.querySelector('[data-immerse-author]>span')!).display,
+ title: getComputedStyle(document.querySelector('[data-immerse-title]')!).fontSize,
+ })), { radius: '0px', meta: 'none', title: '14px' });
+ assert.deepEqual(opened.problems.filter((line) => !line.includes('VIDEOJS')), []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ /* ── 侧栏岛(`frontend/src/react/sidebar/sidebar.css`) ── */
+
+ /** 打开首页等侧栏的分组画出来。聚合照演示库真取,只保证时长那一组在(演示库的短片可能凑不出总时长)。 */
+ async function openSidebar(viewport: Viewport): Promise<Visit> {
+ const opened = await visit(browser, '/', viewport);
+ await opened.page.route((url) => url.pathname === '/api/facets', async (route) => {
+ const real = await (await route.fetch()).json() as { stats?: Record<string, unknown> };
+ await route.fulfill({ json: { ...real, stats: { ...real.stats, duration: real.stats?.duration || 540 } } });
+ });
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('#drawer [data-sidebar-group="时长"]').waitFor({ state: 'attached', timeout: 15_000 });
+ await settle(opened.page);
+ return { ...opened, close: async () => {
+ await opened.page.unrouteAll({ behavior: 'ignoreErrors' });
+ await opened.close();
+ } };
+ }
+
+ it('侧栏当前项自己不铺底,由挂在抽屉上的那块玻璃标出;悬停时玻璃跟过去,离开这一列回到当前项', { timeout: 60_000 }, async () => {
+ const opened = await openSidebar(DESKTOP);
+ try {
+ const { page } = opened;
+ const read = (key: string) => page.evaluate((target) => {
+ const glide = document.querySelector<HTMLElement>('[data-sidebar-glide]')!;
+ const button = document.querySelector<HTMLElement>(`#drawer [data-sidebar-nav] [data-nav="${target}"]`)!;
+ const box = (node: Element) => {
+ const rect = node.getBoundingClientRect();
+ return [rect.left, rect.top, rect.width, rect.height].map(Math.round);
+ };
+ const style = getComputedStyle(button);
+ return {
+ glide: box(glide), button: box(button), parent: glide.parentElement?.id,
+ layer: getComputedStyle(glide).zIndex, radius: getComputedStyle(glide).borderRadius,
+ fill: [style.backgroundColor, style.backgroundImage, style.boxShadow], color: style.color,
+ };
+ }, key);
+ const current = await read('');
+ assert.equal(current.parent, 'drawer', '玻璃没有挂在抽屉上,纵滚时会被滚动层切掉');
+ assert.deepEqual([current.layer, current.radius], ['-1', '10px'], '玻璃要压在字底下、圆角照按钮的 10px');
+ assert.deepEqual(current.glide, current.button, '玻璃没有垫在当前项下面');
+ assert.deepEqual(current.fill, ['rgba(0, 0, 0, 0)', 'none', 'none'], '当前项自己铺了底,静止时就是两层底叠着');
+ assert.equal(current.color, await tokenColor(page, '#drawer', '--glass-text'), '当前项的字色不是玻璃上的字色');
+ const idle = await read('studios');
+ assert.equal(idle.color, await tokenColor(page, '#drawer', '--color-text-secondary'), '未选中项的字色不是次要文字色');
+
+ await page.locator('#drawer [data-sidebar-nav] [data-nav="studios"]').hover();
+ const hovered = await read('studios');
+ assert.deepEqual(hovered.glide, hovered.button, '悬停时玻璃没有跟到指着的那一项');
+ assert.deepEqual(hovered.fill, ['rgba(0, 0, 0, 0)', 'none', 'none'], '悬停的那一项自己铺了底');
+ await page.mouse.move(900, 420);
+ const back = await read('');
+ assert.deepEqual(back.glide, back.button, '指针离开这一列之后玻璃没有回到当前项');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('侧栏标题行:切换器 32px 圆标识、收起键 20px 高,与导航首项相隔 12px;分组箭头展开时转 90°;收起后只剩 60px 宽的图标列', { timeout: 60_000 }, async () => {
+ const opened = await openSidebar(DESKTOP);
+ try {
+ const { page } = opened;
+ const head = await page.evaluate(() => {
+ const drawer = document.querySelector('#drawer')!;
+ const rect = (selector: string) => drawer.querySelector(selector)!.getBoundingClientRect();
+ const mark = drawer.querySelector('#brandHome .mark')!;
+ const rotation = (group: Element) => {
+ const matrix = new DOMMatrix(getComputedStyle(group.querySelector(':scope > [data-sidebar-toggle] svg')!).transform);
+ return Math.round(Math.atan2(matrix.b, matrix.a) * 180 / Math.PI);
+ };
+ const groups = [...drawer.querySelectorAll<HTMLDetailsElement>('[data-sidebar-group]')];
+ return {
+ gap: Math.round(rect('[data-sidebar-nav]').top - rect('[data-sidebar-head]').bottom),
+ mark: [Math.round(rect('#brandHome .mark').width), Math.round(rect('#brandHome .mark').height), getComputedStyle(mark).borderRadius],
+ toggle: Math.round(rect('#filterBtn').height),
+ open: groups.filter((group) => group.open).map(rotation),
+ closed: groups.filter((group) => !group.open).map(rotation),
+ };
+ });
+ assert.equal(head.gap, 12, '切换器与导航首项挨得太近,两块底色读起来像压在一起');
+ assert.deepEqual(head.mark, [32, 32, '50%'], '切换器的标识不是 32px 的圆');
+ assert.equal(head.toggle, 20, '收起键不是 20px 高');
+ assert.ok(head.open.length && head.closed.length, `首页的分组没有一开一合可比:${JSON.stringify(head)}`);
+ assert.ok(head.open.every((angle) => angle === 90), `展开的分组箭头没有转到 90°:${head.open}`);
+ assert.ok(head.closed.every((angle) => angle === 0), `收着的分组箭头没有回到 0°:${head.closed}`);
+
+ await page.locator('#filterBtn').click();
+ await page.waitForFunction(() => Math.round(document.querySelector('#drawer')!.getBoundingClientRect().width) === 60,
+ undefined, { timeout: 5_000 });
+ const rail = await page.evaluate(() => {
+ const drawer = document.querySelector('#drawer')!;
+ const toggle = drawer.querySelector('#filterBtn')!.getBoundingClientRect();
+ return {
+ toggle: [Math.round(toggle.width), Math.round(toggle.height)],
+ groups: [...new Set([...drawer.querySelectorAll('[data-sidebar-group]')].map((group) => getComputedStyle(group).display))],
+ labels: [...new Set([...drawer.querySelectorAll('[data-sidebar-nav] button span')].map((span) => getComputedStyle(span).maxWidth))],
+ };
+ });
+ assert.deepEqual(rail, { toggle: [36, 20], groups: ['none'], labels: ['0px'] }, '收起的窄栏不是一列图标');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('时长拉条:已选段是 accent 渐变,两端读数常显、推到端点也不越出轨道,刚动过的那枚压在上面', { timeout: 60_000 }, async () => {
+ const opened = await openSidebar(DESKTOP);
+ try {
+ const { page } = opened;
+ await page.locator('#drawer [data-sidebar-group="时长"] > [data-sidebar-toggle]').click();
+ await page.locator('#drawer [data-sidebar-group="时长"] [data-sidebar-collapse]:not([inert])').waitFor({ timeout: 5_000 });
+ const read = () => page.evaluate(() => {
+ const range = document.querySelector('#durationRange')!;
+ const bounds = range.getBoundingClientRect();
+ return {
+ fill: getComputedStyle(range.querySelector('[data-sidebar-range-fill]')!).backgroundImage,
+ tips: [...range.querySelectorAll<HTMLElement>('[data-sidebar-range-tip]')].map((tip) => {
+ const box = tip.getBoundingClientRect();
+ return {
+ end: tip.dataset.rangeEnd, text: tip.textContent, layer: getComputedStyle(tip).zIndex,
+ visible: getComputedStyle(tip).visibility === 'visible' && box.width > 0,
+ inside: box.left >= bounds.left - 1 && box.right <= bounds.right + 1,
+ };
+ }),
+ };
+ });
+ const resting = await read();
+ const accent = await tokenColor(page, '#drawer', '--color-accent-400');
+ assert.ok(resting.fill.startsWith('linear-gradient(90deg') && resting.fill.includes(accent),
+ `已选段不是从 accent-400 起的横向渐变:${resting.fill}`);
+ assert.deepEqual(resting.tips, [
+ { end: 'min', text: '0 分钟', layer: '1', visible: true, inside: true },
+ { end: 'max', text: '不限', layer: '2', visible: true, inside: true },
+ ], '两端读数要常显、贴着轨道两端不越界,没动过时右端那枚在上');
+
+ await page.locator('#durMin').focus();
+ await page.keyboard.press('ArrowRight');
+ await page.waitForFunction(() => document.querySelector('[data-sidebar-range-tip][data-range-end="min"]')?.hasAttribute('data-range-active'),
+ undefined, { timeout: 5_000 });
+ const moved = await read();
+ assert.deepEqual(moved.tips.map((tip) => [tip.end, tip.layer, tip.inside]), [['min', '2', true], ['max', '1', true]],
+ '刚动过的那一端没有压到上面');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('手机侧栏:抽屉开着时遮罩外壳隐形、暗色画在 ::before 上,层级低于抽屉;收起时遮罩退出渲染树', { timeout: 60_000 }, async () => {
+ const opened = await openSidebar(MOBILE);
+ try {
+ const { page } = opened;
+ const scrim = () => page.evaluate(() => {
+ const node = document.querySelector('#scrim')!, drawer = document.querySelector('#drawer')!;
+ const before = getComputedStyle(node, '::before');
+ return {
+ display: getComputedStyle(node).display, visibility: getComputedStyle(node).visibility,
+ dim: [before.visibility, before.backgroundColor],
+ layers: [Number(getComputedStyle(node).zIndex), Number(getComputedStyle(drawer).zIndex)],
+ fill: getComputedStyle(drawer).getPropertyValue('--glass-fill'),
+ };
+ });
+ assert.equal((await scrim()).display, 'none', '抽屉收着时遮罩还在渲染树里,iOS 的 Safari 会拿它给状态栏取色');
+ await page.locator('#filterBtn').tap();
+ await page.waitForFunction(() => document.querySelector('#drawer')?.classList.contains('open'));
+ const shown = await scrim();
+ assert.deepEqual([shown.display, shown.visibility], ['block', 'hidden'], '遮罩外壳没有隐形,iOS 的 Safari 会拿它给状态栏取色');
+ assert.equal(shown.dim[0], 'visible', '遮罩的暗色没有画在 ::before 上');
+ assert.notEqual(shown.dim[1], 'rgba(0, 0, 0, 0)', '遮罩的 ::before 是透明的,压不暗身后的页面');
+ assert.ok(shown.layers[0] < shown.layers[1], `遮罩压在抽屉上面,抽屉里就点不动了:${shown.layers}`);
+ assert.ok(shown.fill.replace(/\s/g, '').includes('86%'), `窄屏抽屉的填充没有加厚到 86%:${shown.fill}`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+});
diff --git a/frontend/e2e/design-fixture.ts b/frontend/e2e/design-fixture.ts
new file mode 100644
index 000000000..dad508ed8
--- /dev/null
+++ b/frontend/e2e/design-fixture.ts
@@ -0,0 +1,802 @@
+/* 设计决定用例(`design-*.test.ts`)共用的桩数据、打开页面的入口与浏览器生命周期。
+ *
+ * 设计决定按浏览器里的计算值断言,不绑定 CSS 源码的写法。页面迁到 React 时,旧的源码字符串
+ * 断言按 ADR-0031 分三类:设计决定落在 `design-*.test.ts` 或 lint 规则,行为落在 vitest,
+ * 布局与运行期问题归 `smoke.test.ts`。每条用例守一个决定,读的是 `getComputedStyle`,
+ * 类名或样式写法换了照样成立。 */
+import assert from 'node:assert/strict';
+import { after, before, beforeEach } from 'node:test';
+import type { Browser, Locator, Page } from 'playwright-core';
+import {
+ configurationBody, expectBody, launch, settle, visit, VIEWPORTS, type Viewport, type Visit,
+} from './harness.ts';
+
+export const DESKTOP = VIEWPORTS.find((viewport) => !viewport.mobile)!;
+export const MOBILE = VIEWPORTS.find((viewport) => viewport.mobile)!;
+
+/** 在 `scope` 里解析一个颜色 token:临时挂一个元素读背景色,读完就移除。 */
+export async function tokenColor(page: Page, scope: string, token: string): Promise<string> {
+ return page.evaluate(([selector, name]) => {
+ const probe = document.createElement('div');
+ probe.style.backgroundColor = `var(${name})`;
+ document.querySelector(selector)!.append(probe);
+ const value = getComputedStyle(probe).backgroundColor;
+ probe.remove();
+ return value;
+ }, [scope, token] as const);
+}
+
+/** 配置页「网络与访问」下的访问密码分区。演示库没有 access.json,分区处于系统口令状态。
+ * 与冒烟同一口径:先等配置页主体,再 settle、再切分区。 */
+export async function openAccess(browser: Browser): Promise<Visit & { form: Locator }> {
+ const opened = await visit(browser, '/configuration', DESKTOP);
+ await expectBody(opened.page, '/configuration', configurationBody(opened.page));
+ await settle(opened.page);
+ await opened.page.getByRole('tab', { name: '网络与访问' }).click({ timeout: 5_000 });
+ await settle(opened.page);
+ const form = opened.page.locator('form[aria-label="访问密码"]');
+ await form.waitFor({ timeout: 10_000 });
+ return { ...opened, form };
+}
+
+/** 一轮跑完的任务。字段以 `/api/tasks`(`src/peach/routes_tasks.py`)为准。 */
+export const settledRun = (id: number, status: string, label: string) => ({
+ id, task_key: `task-${id}`, task_label: label, trigger: 'manual', status, host: 'desk',
+ started_at: '2026-09-11T10:00:00Z', finished_at: '2026-09-11T10:01:00Z', elapsed_seconds: 60,
+ progress_current: null, progress_total: null, progress_label: '',
+ result_summary: {}, error: status === 'failed' ? 'RuntimeError: 上游挡回来了' : '',
+});
+
+/** 活动页按给定的一份 `/api/tasks` 打开:演示库里凑不齐失败、被挡下和成功三种状态。 */
+export async function openActivity(browser: Browser, runs: unknown[]): Promise<Visit> {
+ const opened = await visit(browser, '/activity', DESKTOP);
+ await opened.page.route('**/api/tasks', (route) => route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ available: true, running: [], skipped: [], finished: runs }),
+ }));
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('li[data-status]').first().waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return opened;
+}
+
+/** 一条待升级的目标。字段以 `/api/quality-goals`(`src/peach/web_contract.py`)为准。 */
+export const qualityGoal = (id: number, name: string) => ({
+ id, name, code: null, location: 'local', size: 2147483648, duration: 3725,
+ reason: '只有 720p', cost: 'free', has_thumb: true, has_cover: false,
+});
+
+/** 1×1 的透明 PNG,够让 `<img>` 走完一次加载。 */
+export const PIXEL = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
+
+/** 口味页浏览器画像的五个维度:头一个是其余的十倍,和真实馆藏的分布一样。 */
+export const TASTE_CATEGORIES = [['剧情', 657], ['写真', 68], ['素人', 56], ['偶像', 4], ['企划', 1]]
+ .map(([name, score]) => ({ name, score }));
+
+/** 一张全身站姿照的人脸框:脸落在画面上半截的一小块里,小圆框要放大好几倍才看得清。 */
+export const TASTE_FACE = { cx: .439, cy: .224, faceW: 67, imgW: 640, imgH: 960 };
+
+/** 口味页按改写过的 `/api/taste` 打开:演示库没有浏览记录,也没有带人脸框的实体图。
+ * 字段以 `src/peach/taste_history.py` 与 `src/peach/web_stats.py` 为准;实体图换成与人脸框同尺寸的纯色图。 */
+export async function openTaste(browser: Browser, viewport: typeof DESKTOP): Promise<Visit> {
+ const opened = await visit(browser, '/taste', viewport);
+ const face = (id: number, name: string) => ({
+ name, peach_items: 3, peach_score: 5, entity_id: id, has_image: true, avatar_focus: { box: TASTE_FACE },
+ });
+ await opened.page.route(/\/api\/taste\?/, async (route) => {
+ const json = await (await route.fetch()).json();
+ await route.fulfill({ json: { ...json, rankings: { ...json.rankings,
+ browser_categories: TASTE_CATEGORIES,
+ peach_performers: [face(901, '演示女优')],
+ peach_creators: [face(902, '演示创作者')],
+ } } });
+ });
+ await opened.page.route(/\/entity-image\?/, (route) => route.fulfill({
+ contentType: 'image/svg+xml',
+ body: `<svg xmlns="http://www.w3.org/2000/svg" width="${TASTE_FACE.imgW}" height="${TASTE_FACE.imgH}">`
+ + `<rect width="${TASTE_FACE.imgW}" height="${TASTE_FACE.imgH}" fill="#888"/></svg>`,
+ }));
+ await opened.page.reload({ waitUntil: 'load' });
+ await expectBody(opened.page, '/taste', [
+ opened.page.locator('#stats').getByRole('tab', { name: '浏览器记录', exact: true }),
+ ]);
+ return opened;
+}
+
+/** 高清版目标页按给定的一份 `/api/quality-goals` 打开:演示库里凑不齐很长的标题。 */
+export async function openQualityGoals(browser: Browser, items: unknown[]): Promise<Visit> {
+ const opened = await visit(browser, '/quality-goals', DESKTOP);
+ await opened.page.route('**/api/quality-goals?limit=200', (route) => route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ total: items.length, items, offset: 0, has_more: false }),
+ }));
+ /* 这几条目标是造出来的,演示库里没有对应的抽帧,预览图会 404——而失败请求本身是另一
+ 条判据。这一条量的是封面那块的几何,给它一张能加载完的图就够。 */
+ await opened.page.route('**/poster**', (route) => route.fulfill({
+ status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
+ }));
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('li[data-goal-id]').first().waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return opened;
+}
+
+/** 一个采集来源。字段以 `/api/scraping`(`src/peach/web_scraping.py`)为准。 */
+export const scrapingSource = (source: string, label: string, cookie: boolean) => ({
+ source, label, login: `https://${source}.example/login`,
+ accepts_cookie: cookie, network: 'peach', cookie_saved: cookie,
+});
+
+/** 来源和凭证页按给定的一份 `/api/scraping` 打开:演示库里未必同时有收 Cookie 和不收的来源。
+ *
+ * 站标走服务端的 `/site-mark`,而这几个来源是造出来的,那一趟必然取不到;那是另一条判据,
+ * 这里给它一张能加载完的图,免得运行期问题名单里混进与本条无关的失败。 */
+export async function openScraping(browser: Browser): Promise<Visit> {
+ const opened = await visit(browser, '/scraping', DESKTOP);
+ await opened.page.route('**/api/scraping', (route) => route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ sources: [scrapingSource('demoa', '演示来源甲', true), scrapingSource('demob', '演示来源乙', false)],
+ }),
+ }));
+ await opened.page.route('**/site-mark**', (route) => route.fulfill({
+ status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
+ }));
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('form[aria-label="演示来源甲"]').waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return opened;
+}
+
+/** 一行等人判的元数据候选。字段以 `src/peach/web_review.py` 的 `_review_rows` 为准。 */
+export const REVIEW_ROW = {
+ item_key: 'metadata_fields:ABC-123:studio',
+ field: 'studio',
+ field_label: '厂牌',
+ code: 'ABC-123',
+ query: 'ABC-123',
+ evidence: '当前值:尚无;1 个匹配资产;2 个来源候选',
+ candidates: [{ candidate_key: 'javdb:studio', source: 'javdb', display_value: '示例厂牌' }],
+};
+
+/** 人工复核页按一行造出来的队列打开:演示库里这一格未必正好有候选,而队列空了就没有卡。 */
+export async function openReview(browser: Browser): Promise<Visit> {
+ const opened = await visit(browser, '/review', DESKTOP);
+ await opened.page.route('**/api/review', (route) => route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ sections: { metadata_fields: [REVIEW_ROW] }, counts: { metadata_fields: 1 }, genre_tags: [],
+ }),
+ }));
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('section[data-review-key]').first().waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return opened;
+}
+
+/** CIE L*。一条 1px 的线看不看得见跟的是明度差,不是对比度比值:同样 1.48:1,浅色底上
+ * 是一条灰线,深色底上两头的绝对亮度都贴着 0,什么都看不出来。 */
+export function lightness([red, green, blue]: number[]): number {
+ const linear = (channel: number) => {
+ const value = channel / 255;
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
+ };
+ const y = 0.2126 * linear(red!) + 0.7152 * linear(green!) + 0.0722 * linear(blue!);
+ return y > 0.008856 ? 116 * Math.cbrt(y) - 16 : 903.3 * y;
+}
+
+/** 按给定的一份 `/api/library-processing` 打开某一页:演示库里那趟任务早就跑完了,
+ * 而运行态和失败态正是这两条要看的东西。字段以 `src/peach/web_library_processing.py` 为准。 */
+export async function openProcessing(
+ browser: Browser, path: string, job: Record<string, unknown>,
+): Promise<Visit> {
+ const opened = await visit(browser, path, DESKTOP);
+ await opened.page.route('**/api/library-processing', (route) => route.fulfill({
+ status: 200, contentType: 'application/json', body: JSON.stringify(job),
+ }));
+ await opened.page.reload({ waitUntil: 'load' });
+ return opened;
+}
+
+/** 1280 的桌面视口比 `--board-content` 还窄,量不出「网格铺满、标题居中」这类差别。 */
+export const WIDE = { name: 'wide', width: 1600, height: 900, mobile: false };
+
+/** 垃圾文件页。计数行由垃圾队列那一页画,演示库里一条候选都没有时它照样在;壳铺的
+ * 骨架(`[data-junk-count-skeleton]`)也有这两块,等的是页面接管之后的那一版。 */
+export const JUNK_COUNT = '#count > .peach-react:not([data-junk-count-skeleton])';
+export async function openJunk(browser: Browser): Promise<Visit> {
+ const opened = await visit(browser, '/junk-files', WIDE);
+ await expectBody(opened.page, '/junk-files', [
+ opened.page.locator(`${JUNK_COUNT} [data-collection-summary]`),
+ opened.page.locator(`${JUNK_COUNT} [data-junk-filters]`),
+ ]);
+ await settle(opened.page);
+ return opened;
+}
+
+/** 一条垃圾候选。字段以 `/api/ads`(`src/peach/web_batch.py` 的 `q_ads`)为准;类型都挑没有预览
+ * 的,造出来的 id 取不到缩略图。 */
+export const junkItem = (id: number, kind: string, name: string) => ({
+ id, name, junk_kind: kind, why: '文件名像推广', size: 1048576 * id, location: 'local', cost: '',
+});
+
+/** 垃圾文件页按给定的候选打开:演示库里没有垃圾候选。`/api/ads` 每次都按当前名单回话,
+ * `/api/batch` 记下请求体、把处置掉的那条从名单里拿掉。 */
+export async function openJunkWith(browser: Browser, items: ReturnType<typeof junkItem>[], viewport = WIDE) {
+ const opened = await visit(browser, '/junk-files', viewport);
+ const state = { items: [...items], batches: [] as { ids: number[]; operation: string }[], reads: [] as string[] };
+ await opened.page.route('**/api/ads?**', (route) => {
+ const url = new URL(route.request().url());
+ state.reads.push(url.search);
+ const kind = url.searchParams.get('kind');
+ const shown = state.items.filter((item) => !kind || item.junk_kind === kind);
+ const counts: Record<string, number> = {};
+ for (const item of state.items) counts[item.junk_kind] = (counts[item.junk_kind] || 0) + 1;
+ return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({
+ items: shown, total: shown.length, all_total: state.items.length, pending_total: state.items.length,
+ dismissed_total: 0, counts,
+ }) });
+ });
+ await opened.page.route('**/api/batch', (route) => {
+ const body = JSON.parse(route.request().postData() || '{}');
+ state.batches.push(body);
+ state.items = state.items.filter((item) => !body.ids.includes(item.id));
+ return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true, updated: body.ids.length }) });
+ });
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('#grid [data-junk-card]').first().waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return { ...opened, state };
+}
+
+/** 一个重复文件。字段以 `/api/duplicates`(`src/peach/web_contract.py`)为准。 */
+export const duplicateFile = (id: number, location: string, patch: Record<string, unknown> = {}) => ({
+ id, name: `DUPE-${id}.mp4`, path: `R:\\media\\DUPE-${id}.mp4`, location, drive: location === '115' ? 'B:' : 'R:',
+ size: 1073741824, duration: 3600, is_largest: false, is_longest: false, ...patch,
+});
+
+/** 重复文件页按给定的两组打开:演示库里没有重复组。一组字节一致,一组本地与 115 混着。
+ * 文件是造出来的,抽帧那一趟必然取不到,给它一张能加载完的图。 */
+export async function openDuplicates(browser: Browser): Promise<Visit> {
+ const opened = await visit(browser, '/duplicates', DESKTOP);
+ const groups = [
+ { code: 'DUPE-001', count: 2, identical: true, drives: ['R:'], cross_drive: false, reclaimable: 1073741824,
+ files: [duplicateFile(9001, 'local', { is_largest: true }), duplicateFile(9002, 'local', { is_longest: true })] },
+ { code: 'DUPE-002', count: 2, identical: false, drives: ['R:', 'B:'], cross_drive: true, reclaimable: 1073741824,
+ files: [duplicateFile(9003, 'local', { is_largest: true, is_longest: true }), duplicateFile(9004, '115')] },
+ ];
+ await opened.page.route('**/api/duplicates?**', (route) => route.fulfill({
+ status: 200, contentType: 'application/json',
+ body: JSON.stringify({ total: 2, files: 4, reclaimable: 2147483648, groups }),
+ }));
+ await opened.page.route('**/thumb?**', (route) => route.fulfill({
+ status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
+ }));
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('#stats section[aria-label="DUPE-002"] .duplicate-row').first().waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return opened;
+}
+
+/** 打开一张索引页,名册与词表都换成桩:演示库的索引在一轮里会从空变成有,不桩的话
+ * 这一条量到的可能是空态。名册第一格带一张桩图,其余只落首字母。 */
+export async function openIndexPage(browser: Browser, path: string): Promise<Visit> {
+ const opened = await visit(browser, path, DESKTOP);
+ const json = (body: unknown) => ({ status: 200, contentType: 'application/json', body: JSON.stringify(body) });
+ await opened.page.route('**/api/index?**', (route) => {
+ const kind = new URL(route.request().url()).searchParams.get('kind');
+ return route.fulfill(json(kind === 'tags'
+ ? { items: [{ k: '痴女', n: 4, cat: 'role' }, { k: '秘书OL', n: 2, cat: 'scene' }], has_more: false,
+ categories: { role: 1, scene: 1 } }
+ : { items: [{ k: '甲', n: 3, members: 2, entity_id: 90_101, has_image: true }, { k: '乙', n: 1, members: 1 }],
+ has_more: false }));
+ });
+ // 桩图要比框大:比框小的图按原尺寸摆,走的是另一条规则。
+ await opened.page.route('**/entity-image?**', (route) => route.fulfill({
+ status: 200, contentType: 'image/svg+xml',
+ body: '<svg xmlns="http://www.w3.org/2000/svg" width="600" height="800"><rect width="600" height="800" fill="#888"/></svg>',
+ }));
+ await opened.page.route('**/api/follow/tags?**', (route) => route.fulfill(json({
+ items: [{ k: 'some_artist', n: 5, cat: 'artist' }, { k: 'long_hair', n: 9, cat: 'general' }], has_more: false,
+ categories: { artist: 1, general: 1 } })));
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('#index [data-index-cell], #index [data-alpha-tag], #index [data-tag-chip]').first()
+ .waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return opened;
+}
+
+/** 一串 `box-shadow`(计算值或 token 原文)里最大的那个像素数:落影三层里最远那层的模糊半径。 */
+export const farthestShadow = (shadow: string) =>
+ Math.max(0, ...[...shadow.matchAll(/(\d+(?:\.\d+)?)px/g)].map((match) => Number(match[1])));
+
+/** 播放列表页按一份造出来的 `/api/playlists`(`src/peach/web_playlists.py`)打开:演示库里
+ * 没有播放列表。第一份带三位署名,第二份没人(画标题首字),第三份是空列表(写「无预览」)。
+ * 封面是造出来的编号,给一张能加载完的图。 */
+export async function openPlaylistsPage(browser: Browser, viewport = DESKTOP): Promise<Visit> {
+ const opened = await visit(browser, '/playlists', viewport);
+ const face = (id: number, name: string, kind = 'performer') => ({ kind, id, name, has_image: false });
+ const row = (id: number, patch: Record<string, unknown> = {}) => ({
+ id, name: `列表${id}`, source_kind: 'manual', source_seed_asset_id: null, current_asset_id: null,
+ created_at: '2026-09-01 10:00:00', updated_at: '2026-09-01 10:00:00', item_count: 2,
+ preview_asset_id: 11, preview_ids: [11, 12], faces: [], ...patch,
+ });
+ await opened.page.route((url) => url.pathname === '/api/playlists', (route) => route.fulfill({ json: { items: [
+ row(1, { source_kind: 'mix', faces: [face(901, '甲'), face(902, '乙'), face(903, '丙', 'creator')] }),
+ row(2),
+ row(3, { item_count: 0, preview_asset_id: null, preview_ids: [] }),
+ ] } }));
+ await opened.page.route('**/poster**', (route) => route.fulfill({
+ status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
+ }));
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('#stats [data-playlist-card]').first().waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return opened;
+}
+
+/** 打开目录并等到读数与卡片一起替下首屏骨架。 */
+export async function openCatalog(browser: Browser): Promise<Visit> {
+ const opened = await visit(browser, '/', DESKTOP);
+ await opened.page.locator('[data-catalog-filter] [data-count-readout]').waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return opened;
+}
+
+/** 打开目录,两排头像与标签条用桩数据铺满:演示库那十几部作品凑不出一排标签。 */
+export async function openCatalogBars(browser: Browser, viewport: Viewport = DESKTOP): Promise<Visit> {
+ const opened = await visit(browser, '/', viewport);
+ const performers = Array.from({ length: 6 }, (_, at) => ({
+ id: 96_000 + at, k: `演示女优${at + 1}`, n: 30 - at, has_image: false, has_avatar: false, avatar_focus: null, rep: null,
+ }));
+ const studios = Array.from({ length: 3 }, (_, at) => ({ k: `演示厂牌${at + 1}`, n: 20 - at, has_logo: false }));
+ const tags = Array.from({ length: 8 }, (_, at) => ({ k: `演示标签${at + 1}`, n: 90 - at }));
+ await opened.page.route((url) => url.pathname === '/api/tops', (route) =>
+ route.fulfill({ json: Number(new URL(route.request().url()).searchParams.get('page') || 0)
+ ? { performers: [], studios: [] } : { performers, studios } }));
+ await opened.page.route((url) => url.pathname === '/api/facets', async (route) => {
+ const response = await route.fetch();
+ await route.fulfill({ json: { ...await response.json(), tags } });
+ });
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('[data-catalog-filter] [data-catalog-tag]').first().waitFor({ timeout: 15_000 });
+ await opened.page.locator('[data-catalog-filter] [data-tier-studio]').first().waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ // 关页时还在路上的那一趟桩请求不算失败。
+ return { ...opened, close: async () => {
+ await opened.page.unrouteAll({ behavior: 'ignoreErrors' });
+ await opened.close();
+ } };
+}
+
+export interface CatalogFixture {
+ total: number;
+ items: Array<Record<string, unknown>>;
+ [key: string]: unknown;
+}
+
+/** 从演示库取一份能完整渲染的真实目录响应,只替换当前判据需要的字段。 */
+export async function openCatalogFixture(
+ browser: Browser,
+ change: (payload: CatalogFixture, url: URL) => void,
+): Promise<Visit> {
+ const opened = await visit(browser, '/', DESKTOP);
+ let baseline: CatalogFixture | undefined;
+ await opened.page.route(/\/api\/items\?/, async (route) => {
+ const url = new URL(route.request().url());
+ /* `visit()` 返回时,首屏还可能在后台续取下一页。路由接管之后若先撞上 offset>0,
+ 那份响应本来就可能没有卡片,不能拿它当首屏基线;让旧请求原样完成,reload 后
+ 再以 offset=0 的响应建立夹具。 */
+ if (url.searchParams.get('offset') !== '0') {
+ await route.continue();
+ return;
+ }
+ if (!baseline) {
+ const response = await route.fetch();
+ baseline = await response.json() as CatalogFixture;
+ }
+ const payload = structuredClone(baseline);
+ change(payload, url);
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(payload),
+ });
+ });
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('[data-catalog-filter] [data-count-readout]').waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return opened;
+}
+
+/** 一趟跑到一半的扫描与采集。 */
+export const RUNNING_JOB = { status: 'running', stage: '采集缺失资料', checked: 38, total: 100 };
+
+/** 一趟断在半路、攒下一份长问题清单的扫描与采集:演示库里这两样都凑不出来。 */
+export const FAILED_JOB = {
+ status: 'failed', job_id: 'one', error: '处理被中断,请检查媒体目录后重试。',
+ issue_count: 347, issues_truncated: true, retryable_asset_ids: [1, 2],
+ issues_log: 'C:\\peach-data\\state\\library-processing-demo.issues.jsonl',
+ issue_preview: Array.from({ length: 20 }, (_, at) => ({
+ asset_id: at + 1, title: `示例-${at + 1}.mp4`, path: `B:\\番号\\示例-${at + 1}.mp4`,
+ message: '封面未取得:javdb:本趟采集次数已用完,再跑一次接着采;已有图片保留',
+ })),
+};
+
+/** 一条关注来源。字段以 `_source_payload`(`src/peach/web_follow.py`)为准。 */
+export const followSource = (id: number, author: string, provider: string, label: string, status = 'ok') => ({
+ id, provider: provider.toLowerCase(), provider_label: provider, ref: `ref/${id}`, label,
+ url: `https://example.com/${id}`, enabled: true, last_status: status,
+ last_checked_at: '2026-09-01T00:00:00Z', created_at: '2026-08-01T00:00:00Z',
+ author_key: `name:${author}`, author_name: author,
+});
+
+/** 一个站的凭据状态。字段以 `/api/follow/credentials` 为准。 */
+export const followCredential = (provider: string, requirement: string, present: boolean, missing: string[]) => ({
+ provider: provider.toLowerCase(), provider_label: provider, followable: true, requirement,
+ needs: missing, fields: present ? ['cookie'] : [], missing, present,
+});
+
+/** 关注管理页按一份造好的来源与凭据打开:演示库没有关注来源,也凑不齐四种凭据处境。
+ * 站标同 `openScraping`:造出来的来源取不到图标,给一张能加载完的图。 */
+export async function openFollowManage(browser: Browser, viewport = DESKTOP): Promise<Visit> {
+ const opened = await visit(browser, '/follow-manage', viewport);
+ await stubFollowManage(opened.page);
+ await opened.page.reload({ waitUntil: 'load' });
+ await opened.page.locator('section[aria-label="kou 的关注来源"]').waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ return opened;
+}
+
+export async function stubFollowManage(page: Page): Promise<void> {
+ const json = (body: unknown) => ({ status: 200, contentType: 'application/json', body: JSON.stringify(body) });
+ await page.route('**/api/follow?summary=1', (route) => route.fulfill(json({
+ sources: [
+ followSource(1, 'kou', 'Kemono', 'kou · Kemono'),
+ followSource(2, 'kou', 'Pawchive', 'kou · Pawchive'),
+ followSource(3, 'mira', 'Kemono', 'mira · Kemono', 'error'),
+ ],
+ counts: { new: 0, seen: 0, saved: 0, ignored: 0 },
+ author_aliases: [{ canonical_key: 'kou', canonical_name: 'kou', aliases: [{ key: 'kou_art', name: 'kou_art' }] }],
+ alias_suggestions: [],
+ suggestions: [],
+ })));
+ await page.route('**/api/follow/credentials', (route) => route.fulfill(json({
+ root: 'C:\\peach\\creds',
+ providers: [
+ followCredential('Fanbox', 'required', false, ['FANBOXSESSID']),
+ followCredential('Patreon', 'optional', true, []),
+ followCredential('OnlyFans', 'blocked', false, []),
+ followCredential('Kemono', 'none', false, []),
+ ],
+ })));
+ await page.route('**/source-icon**', (route) => route.fulfill({
+ status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
+ }));
+ /* 服务端的定时检查可能正在跑,那一趟会让每颗检查键挂着 aria-busy,settle 等不到头。 */
+ await page.route('**/api/follow/check', (route) => (route.request().method() === 'GET'
+ ? route.fulfill(json({ status: 'idle' })) : route.fallback()));
+}
+
+/** 把 `/api/` 请求挂住,直到调用返回的 `release()`:首屏骨架停在屏幕上,量完再放行。
+ * 先注册的桩照常生效:放行走 `fallback()`,交给它们或真实服务端。 */
+export async function holdApi(page: Page): Promise<() => void> {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ await page.route((url) => url.pathname.startsWith('/api/') && url.pathname !== '/api/settings', async (route) => {
+ await gate;
+ await route.fallback().catch(() => {});
+ });
+ return release;
+}
+
+/** 一组控件此刻的长相:面色、字色、边线、圆角与外框尺寸,以及按钮组的选中标记。 */
+export async function controlFaces(page: Page, selectors: Record<string, string>) {
+ return page.evaluate((map) => Object.fromEntries(Object.entries(map).map(([name, selector]) => {
+ const node = document.querySelector(selector);
+ if (!node) return [name, null];
+ const style = getComputedStyle(node);
+ const box = node.getBoundingClientRect();
+ return [name, {
+ face: `${style.backgroundColor} ${style.backgroundImage}`, ink: style.color,
+ edge: `${style.borderTopWidth} ${style.borderTopColor}`, radius: style.borderTopLeftRadius,
+ size: `${Math.round(box.width)}x${Math.round(box.height)}`, pressed: node.getAttribute('aria-pressed'),
+ }];
+ })), selectors);
+}
+
+/** 打开一位订了新作、有一排同台艺人的人物页。演示库里没有人物实体,资料照服务端下发的形状写。 */
+export async function openPerformer(browser: Browser, viewport = DESKTOP): Promise<Visit> {
+ const name = '七沢みあ';
+ const opened = await visit(browser, '/', viewport);
+ const costar = (id: number, k: string) => ({ id, k, n: 1, rep: null, has_image: false, has_avatar: false, avatar_focus: null });
+ await opened.page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
+ id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],
+ user_aliases: [], asset_count: 0, tags: [],
+ related_performers: ['本田愛华', '枢木葵', '美谷朱音', '高杉麻里', '高桥圣子', '今井夏帆'].map((k, at) => costar(90_002 + at, k)),
+ links: [], metadata: {}, has_image: false, has_avatar: false, avatar_focus: null, representative_asset_id: null,
+ entry_links: [
+ { site: 'javdb', label: 'JavDB', ordinal: '', slot: 'mark', mark: 'mark-javdb', url: 'https://javdb.com/actors/NPD3' },
+ { site: 'missav', label: 'MISSAV', ordinal: '', slot: 'mark', mark: '', url: 'https://missav.ai/actresses/x' },
+ ],
+ feed: { following: true },
+ } }));
+ await opened.page.goto(new URL(`/performers/${encodeURIComponent(name)}`, opened.page.url()).href, { waitUntil: 'load' });
+ await opened.page.locator('[data-entry-feed]').waitFor({ timeout: 15_000 });
+ await opened.page.locator('[data-entity-foot] [data-related-performer]').first().waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ await opened.page.evaluate(() => {
+ document.documentElement.dataset.theme = 'light';
+ document.documentElement.classList.remove('dark');
+ });
+ return opened;
+}
+
+/** 照片档:一部作品的两张官方样张加六张本地图片,缩略图都是 1×1 的图,量的是墙的几何。 */
+export async function openPhotoWall(browser: Browser, viewport = DESKTOP): Promise<Visit> {
+ const name = '七沢みあ';
+ const opened = await visit(browser, '/', viewport);
+ const { page } = opened;
+ await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
+ id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [], user_aliases: [],
+ asset_count: 0, tags: [], related_performers: [], links: [], metadata: {}, has_image: false, has_avatar: false,
+ avatar_focus: null, representative_asset_id: null, entry_links: [], feed: { following: false },
+ } }));
+ // 下一页一直不回:「载入更多」停在忙态,墙不再变,量得到那枚键的几何。
+ await page.route(/\/api\/photos\?/, (route) => Number(new URL(route.request().url()).searchParams.get('offset') || 0) ? undefined : route.fulfill({ json: {
+ kind: 'performer', name, entity_id: 90_001, total: 12, seed: '', has_more: true, sample_total: 2,
+ items: Array.from({ length: 6 }, (_, i) => ({ id: 200 + i, name: `${200 + i}.jpg`, size: 1, location: 'media' })),
+ sets: [{ id: 'code:SSIS-057', kind: 'code', code: 'SSIS-057', name: '雨の日', title: 'SSIS-057 雨の日', n: 2,
+ release_date: '2021-05-18', site: 'dmm', site_label: 'DMM', has_cover: true }],
+ } }));
+ await page.route(/\/(?:photo-thumb|sample-thumb)\?/, (route) => route.fulfill({
+ status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
+ }));
+ await page.goto(new URL(`/performers/${encodeURIComponent(name)}?media=photos`, page.url()).href, { waitUntil: 'load' });
+ await page.locator('[data-local-wall] [data-photo-cell] img').first().waitFor({ timeout: 15_000 });
+ await settle(page);
+ return opened;
+}
+
+/** 本地图片那面墙的排法:网格数列宽,瀑布流数 column-count。 */
+export const photoWallFaces = (page: Page) => page.evaluate(() => {
+ const wall = document.querySelector<HTMLElement>('[data-local-wall]')!;
+ const style = getComputedStyle(wall);
+ const cell = wall.querySelector<HTMLElement>('[data-photo-cell]')!;
+ const box = cell.getBoundingClientRect();
+ return {
+ display: style.display,
+ columns: style.display === 'grid' ? style.gridTemplateColumns.split(' ').length : Number(style.columnCount),
+ gap: style.columnGap,
+ square: Math.abs(box.width - box.height) <= 1,
+ };
+});
+
+/** 照片档里 `count` 张本地图,点开第一张的灯箱。大图是 `width`×`height` 的 SVG;取图口全部回桩图,
+ * `/photo` 原图走计费来源,设计用例也不碰真的。 */
+export async function openLightbox(browser: Browser, { count, width, height }: { count: number; width: number; height: number }):
+ Promise<Visit & { box: Locator }> {
+ const name = '七沢みあ';
+ const opened = await visit(browser, '/', DESKTOP);
+ const { page } = opened;
+ const svg = (w: number, h: number) => ({ status: 200, contentType: 'image/svg+xml',
+ body: `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="100%" height="100%" fill="#3a4a5a"/></svg>` });
+ await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
+ id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [], user_aliases: [],
+ asset_count: 0, tags: [], related_performers: [], links: [], metadata: {}, has_image: false, has_avatar: false,
+ avatar_focus: null, representative_asset_id: null, entry_links: [], feed: { following: false },
+ } }));
+ await page.route(/\/api\/photos\?/, (route) => route.fulfill({ json: {
+ kind: 'performer', name, entity_id: 90_001, total: count, seed: '', has_more: false, sample_total: 0, sets: [],
+ items: Array.from({ length: count }, (_, i) => ({ id: 300 + i, name: `${300 + i}.jpg`, size: 1, location: 'media' })),
+ } }));
+ await page.route(/\/photo\?/, (route) => route.fulfill(svg(width, height)));
+ await page.route(/\/photo-thumb\?/, (route) => route.fulfill(svg(160, 120)));
+ await page.goto(new URL(`/performers/${encodeURIComponent(name)}?media=photos`, page.url()).href, { waitUntil: 'load' });
+ await page.locator('[data-photo-cell] img').first().waitFor({ timeout: 15_000 });
+ await settle(page);
+ await page.locator('[data-photo-cell]').first().click();
+ const box = page.locator('dialog[data-photo-lightbox][open]');
+ await box.waitFor();
+ await page.waitForFunction(() => document.querySelector<HTMLImageElement>('[data-photo-main] .swiper-slide-active img')!
+ .naturalWidth > 0, undefined, { timeout: 10_000 });
+ return { ...opened, box };
+}
+
+/** 有 minnano-av 资料的女优。`profile` 与 `name_groups` 照 `peach.entity_profile.header` 的形状写,
+ * 出道片名故意很长:资料表那一格要单行截断。 */
+export const PROFILED = {
+ name: '篠田ゆう',
+ profile: {
+ birth_date: '1991-07-21', age: 35, height: 155, bust: 86, waist: 60, hip: 87, cup: 'F',
+ debut_date: '2010-12-02', debut_title: 'セキララ 〜今どき世代のゆるい性事情〜 03 はじめての撮影でとまどう素人娘の記録',
+ active: { from: '2010', to: '2023' },
+ tags: ['美乳', '美臀', '百合', '肛交', '巨乳', '高颜值', '苗条', '高个', '剛毛'],
+ },
+ name_groups: {
+ reading: 'しのだゆう', shown: ['篠崎ゆう子', '高木早希', '橋本真紀'], total: 7,
+ groups: [
+ { label: '旧名义', names: [{ name: '篠崎ゆう子', reading: 'しのざきゆうこ' }] },
+ { label: '舞ワイフ', names: [{ name: '橋本真紀' }, { name: '桧山彩音' }, { name: '篠田杏奈' }] },
+ { label: 'ラグジュTV', names: [{ name: '高木早希' }] },
+ { label: '其它', names: [{ name: '城田優子' }] },
+ ],
+ },
+};
+
+/** 打开一位有资料的女优:资料表、名字行和外链照服务端下发的形状写,主题按参数切好。
+ * `extra` 覆盖资料里的字段:默认没有看片那一行(`entry_links` 只有 minnano-av 那枚 pill、没有 `feed`),
+ * 要验两行都在的几何就从这里补。 */
+export async function openProfiledPerformer(browser: Browser, viewport = DESKTOP, theme: 'light' | 'dark' = 'light',
+ extra: Record<string, unknown> = {}): Promise<Visit> {
+ const opened = await visit(browser, '/', viewport);
+ await opened.page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
+ id: 90_101, kind: 'performer', canonical_name: PROFILED.name, aliases: ['篠崎ゆう子'], display_aliases: ['篠崎ゆう子'],
+ user_aliases: [], asset_count: 42, tags: [], related_performers: [], metadata: {},
+ has_image: false, has_avatar: false, avatar_focus: null, representative_asset_id: null,
+ agency: { id: 90_102, canonical_name: 'New Actor eXperience', source: 'test', checked_at: '' },
+ links: [
+ { link_id: 90_201, link_kind: 'official', clickable: true, label: 'New Actor eXperience',
+ url: 'https://official.nax-pro.com/actress/shinoda' },
+ { link_id: 90_202, link_kind: 'social', clickable: true, label: 'X @shinoda_yu', url: 'https://x.com/shinoda_yu' },
+ ],
+ entry_links: [{ site: 'minnano-av', label: 'みんなのAV', ordinal: '', slot: 'pill', mark: 'brand-minnano',
+ url: 'https://www.minnano-av.com/actress12345.html' }],
+ profile: PROFILED.profile, name_groups: PROFILED.name_groups,
+ ...extra,
+ } }));
+ // 这几条链接是造出来的,服务端的圆标取不到;那是另一条判据,这里给一张能加载完的图。
+ await opened.page.route('**/link-mark**', (route) => route.fulfill({
+ status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
+ }));
+ await opened.page.goto(new URL(`/performers/${encodeURIComponent(PROFILED.name)}`, opened.page.url()).href, { waitUntil: 'load' });
+ await opened.page.locator('[data-entity-card] [data-entity-links]').waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ await opened.page.evaluate((dark) => {
+ document.documentElement.dataset.theme = dark ? 'dark' : 'light';
+ document.documentElement.classList.toggle('dark', dark);
+ }, theme === 'dark');
+ return opened;
+}
+
+/** 资料卡浮层的落影要和遗留 `.popmenu` 同一副:在同一页造一个空 `.popmenu` 取它的计算值。 */
+export async function popmenuShadow(page: Page): Promise<string> {
+ return page.evaluate(() => {
+ const menu = document.body.appendChild(Object.assign(document.createElement('div'), { className: 'popmenu' }));
+ const shadow = getComputedStyle(menu).boxShadow;
+ menu.remove();
+ return shadow;
+ });
+}
+
+/** 下拉栏里一部作品的小图。字段以 `_suggest_work_card`(`src/peach/web_entity.py`)为准。 */
+export const suggestCard = (id: number) => ({ id, code: `ABW-${id % 1000}`, has_cover: true, has_thumb: false, cover_frame: null, poster_box: null });
+
+/** 一段输入命中女优、厂牌与视频三类的补全,字段以 `q_suggest` 为准。演示库里没有女优实体。 */
+export const SUGGEST = {
+ q: '涼森',
+ groups: [
+ { kind: 'performer', label: '女优', total: 2, items: [
+ { value: '涼森れむ', n: 128, matched: '', id: null, entity_id: 90_301, has_image: true, avatar_focus: null, rep: null,
+ agency: 'Capsule Agency', works: [1, 2, 3, 4].map((at) => suggestCard(90_400 + at)) },
+ { value: '涼森ひより', n: 3, matched: 'すずもりひより', id: null, entity_id: 90_302, has_image: false, rep: null,
+ agency: '', works: [] },
+ ] },
+ { kind: 'studio', label: '厂牌', total: 1, items: [
+ { value: 'Prestige', n: 900, matched: '', id: null, entity_id: 90_303, has_image: false, has_logo: true },
+ ] },
+ { kind: 'asset', label: '视频', total: 12, items: [1, 2, 3, 4, 5].map((at) => ({
+ value: `ABW-${500 + at}`, n: 0, matched: '', id: 90_500 + at, code: `ABW-${500 + at}`,
+ title: '出演作', who: '涼森れむ', card: suggestCard(90_500 + at),
+ })) },
+ ],
+};
+
+/** 补全、下拉里的图和点进去的资料页都按上面那份造好的数据答。返回每次补全请求问的种类。
+ * 图是造出来的实体和番号,服务端取不到;那是另一条判据,这里给一张能加载完的图。 */
+export async function stubSuggest(page: Page): Promise<string[]> {
+ const kinds: string[] = [];
+ await page.route(/\/api\/suggest\?/, (route) => {
+ const kind = new URL(route.request().url()).searchParams.get('kind') || '';
+ kinds.push(kind);
+ return route.fulfill({ json: { q: SUGGEST.q, groups: SUGGEST.groups.filter((group) => !kind || group.kind === kind) } });
+ });
+ await page.route(/\/(?:cover|entity-image|avatar|logo)\?/, (route) => route.fulfill({
+ status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
+ }));
+ await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
+ id: 90_301, kind: 'performer', canonical_name: '涼森れむ', aliases: [], display_aliases: [], user_aliases: [],
+ asset_count: 0, tags: [], related_performers: [], links: [], metadata: {}, entry_links: [],
+ has_image: false, has_avatar: false, avatar_focus: null, representative_asset_id: null,
+ } }));
+ return kinds;
+}
+
+/** 资料卡此刻的几何:身份列、资料表与卡本身的外框,以及资料表那道分隔线落在哪一边。 */
+export async function heroGeometry(page: Page) {
+ return page.evaluate(() => {
+ const rect = (selector: string) => {
+ const box = document.querySelector(selector)?.getBoundingClientRect();
+ return box ? { left: box.left, right: box.right, top: box.top, bottom: box.bottom } : null;
+ };
+ const hero = document.querySelector('[data-entity-card]')!;
+ const facts = document.querySelector('[data-entity-facts]');
+ const style = facts ? getComputedStyle(facts) : null;
+ return {
+ hero: rect('[data-entity-card]'), identity: rect('[data-entity-identity]'), facts: rect('[data-entity-facts]'),
+ heroScrolls: hero.scrollWidth > hero.clientWidth + 1,
+ rule: style ? { left: style.borderLeftWidth, top: style.borderTopWidth } : null,
+ labels: [...document.querySelectorAll('[data-entity-facts] dt')].map((dt) => dt.textContent!.trim()),
+ };
+ });
+}
+
+/** 禁用档的三样颜色(peach-web-ui「按钮悬停只抬填充」那条):`--surface` 底、`--border-15` 边、`--muted` 字。 */
+export async function disabledTokens(page: Page) {
+ return {
+ face: await tokenColor(page, '#main', '--surface'),
+ ink: await tokenColor(page, '#main', '--muted'),
+ ring: await tokenColor(page, '#main', '--border-15'),
+ };
+}
+
+/** 骨架里等数据的操作键此刻的长相与状态,按文档顺序。 */
+export async function waitingActionFaces(page: Page, selector: string) {
+ return page.locator(selector).evaluateAll((buttons) => buttons.map((button) => {
+ const style = getComputedStyle(button);
+ return {
+ name: (button.getAttribute('aria-label') || button.textContent || '').trim(),
+ disabled: (button as HTMLButtonElement).disabled, cursor: style.cursor, opacity: style.opacity,
+ face: style.backgroundColor, image: style.backgroundImage, ink: style.color, ring: style.boxShadow,
+ split: !!button.closest('[data-split-button]'),
+ };
+ }));
+}
+
+export function assertDisabledFace(face: Awaited<ReturnType<typeof waitingActionFaces>>[number],
+ expected: Awaited<ReturnType<typeof disabledTokens>>): void {
+ assert.equal(face.disabled, true, `${face.name} 在骨架里没有禁用`);
+ assert.equal(face.cursor, 'not-allowed', `${face.name} 在骨架里的光标不是禁用那一种`);
+ assert.equal(face.opacity, '1', `${face.name} 的禁用态靠透明度,而不是换颜色`);
+ assert.equal(face.face, expected.face, `${face.name} 在骨架里不是禁用底色`);
+ assert.equal(face.image, 'none', `${face.name} 在骨架里还铺着渐变`);
+ assert.equal(face.ink, expected.ink, `${face.name} 在骨架里不是禁用字色`);
+ // 分体键的外圈画在整组上,两半各画一圈的话中缝会出现两道线。
+ if (!face.split) assert.ok(face.ring.includes(expected.ring), `${face.name} 在骨架里没有禁用描边:${face.ring}`);
+}
+
+/** 切到关注管理页的另一栏。栏名后面可能挂着待配置的数目,按开头认。 */
+export async function followTab(opened: Visit, name: string): Promise<void> {
+ await opened.page.locator('#stats').getByRole('tab', { name: new RegExp(`^${name}`) }).click({ timeout: 5_000 });
+ await settle(opened.page);
+}
+
+/** 每个设计决定文件一个浏览器,至多运行 8 项就换一个,页面与图像缓存的累积占用受限。
+ * `assign` 在每次换上新浏览器时收到它,文件里的用例照旧读同一个 `browser` 变量。 */
+export function installDesignBrowser(assign: (browser: Browser) => void): void {
+ let browser: Browser;
+ let browserTests = 0;
+
+ before(async () => {
+ browser = await launch();
+ assign(browser);
+ });
+
+ beforeEach(async () => {
+ if (browserTests === 8) {
+ await browser.close();
+ browser = await launch();
+ assign(browser);
+ browserTests = 0;
+ }
+ browserTests += 1;
+ });
+
+ after(async () => {
+ await browser.close();
+ });
+}
diff --git a/frontend/e2e/design-manage.test.ts b/frontend/e2e/design-manage.test.ts
new file mode 100644
index 000000000..07717b4c0
--- /dev/null
+++ b/frontend/e2e/design-manage.test.ts
@@ -0,0 +1,1013 @@
+/* 设计决定:数据管理、索引页与资料页头。读 `getComputedStyle` 断言用户定过的外观;共用的桩与浏览器生命周期在 `design-fixture.ts`。 */
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import type { Browser, Page } from 'playwright-core';
+import { layout, settle, visit } from './harness.ts';
+import {
+ DESKTOP, MOBILE, tokenColor, openDuplicates, openIndexPage, openPlaylistsPage, openFollowManage, holdApi,
+ controlFaces, openPerformer, PROFILED, openProfiledPerformer, popmenuShadow, heroGeometry, disabledTokens,
+ waitingActionFaces, assertDisabledFace, followTab, installDesignBrowser,
+} from './design-fixture.ts';
+
+describe('设计决定:数据管理、索引页与资料页头', () => {
+ let browser: Browser;
+ installDesignBrowser((next) => { browser = next; });
+
+ it('数据管理骨架里等数据的操作键是禁用态,数据到了才换回蓝色主按钮', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/data-cleanup', DESKTOP);
+ try {
+ const page = opened.page;
+ // 没有任务在跑:跑着的那一档会把扫描键压成忙碌态,那是数据不是骨架。
+ await page.route('**/api/library-processing', (route) => route.fulfill({
+ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'idle' }),
+ }));
+ const release = await holdApi(page);
+ await page.reload({ waitUntil: 'load' });
+ await page.locator('[data-skeleton="cleanup"] .cleanupscraping [data-split-button]').waitFor({ timeout: 15_000 });
+ const expected = await disabledTokens(page);
+ const waiting = await waitingActionFaces(page, '[data-skeleton="cleanup"] [data-skeleton-action]');
+ assert.deepEqual(waiting.map((face) => face.name),
+ ['扫描并补全资料', '更多扫描与采集方式', '开始修复', '预览', '检查死链', '检查文件']);
+ for (const face of waiting) assertDisabledFace(face, expected);
+ const ring = await page.locator('[data-skeleton="cleanup"] [data-split-button]')
+ .evaluate((element) => getComputedStyle(element).boxShadow);
+ assert.ok(ring.includes(expected.ring), `骨架里的分体键外圈不是禁用那一档描边:${ring}`);
+ const sizes = await controlFaces(page, {
+ 扫描并补全资料: '.cleanupscraping [data-split-button] > button:first-child',
+ 更多方式: '.cleanupscraping [data-split-button] > button:last-child',
+ 开始修复: '.cleanupmediarepair footer > button',
+ });
+ release();
+ await page.locator('[data-skeleton="cleanup"]').waitFor({ state: 'detached', timeout: 15_000 });
+ // 正式页面先摆一份同样的骨架卡,等 React 岛接管;键上没了 `data-skeleton-action` 才算接管完。
+ await page.locator('section[aria-label="扫描与采集"] [data-split-button] > button:first-child:not([data-skeleton-action])')
+ .waitFor({ timeout: 15_000 });
+ await page.locator('section[aria-label="媒体修复"] footer > button:not([data-skeleton-action])')
+ .waitFor({ timeout: 15_000 });
+ await settle(page);
+ const final = await controlFaces(page, {
+ 扫描并补全资料: 'section[aria-label="扫描与采集"] [data-split-button] > button:first-child',
+ 更多方式: 'section[aria-label="扫描与采集"] [data-split-button] > button:last-child',
+ 开始修复: 'section[aria-label="媒体修复"] footer > button',
+ });
+ for (const name of Object.keys(sizes)) {
+ assert.equal(sizes[name]!.size, final[name]!.size, `${name} 接管时尺寸跳了`);
+ assert.match(final[name]!.face, /gradient/, `${name} 接管后没换回蓝色主按钮`);
+ }
+ const enabled = await page.locator('section[aria-label="扫描与采集"] [data-split-button] > button')
+ .evaluateAll((buttons) => buttons.map((button) => (button as HTMLButtonElement).disabled));
+ assert.deepEqual(enabled, [false, false], '数据到了扫描键还是禁用的');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('数据管理卡外的分区标题是 20px 的 Title 2,链接读数照旧版字号与行高', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/data-cleanup', DESKTOP);
+ try {
+ const page = opened.page;
+ await page.locator('#link-manager .link-stat-grid b').first().waitFor({ timeout: 15_000 });
+ await page.locator('#resource-sync-title').waitFor({ timeout: 15_000 });
+ await settle(page);
+ const faces = await page.evaluate(() => {
+ const style = (selector: string) => {
+ const computed = getComputedStyle(document.querySelector(selector)!);
+ return {
+ size: computed.fontSize, weight: computed.fontWeight, line: computed.lineHeight,
+ top: computed.marginTop, bottom: computed.marginBottom,
+ };
+ };
+ return {
+ links: style('#link-manager-title'),
+ sync: style('#resource-sync-title'),
+ label: style('#link-manager .link-stat-grid span'),
+ figure: style('#link-manager .link-stat-grid b'),
+ };
+ });
+ /* 这一页挂在 `#stats` 里,遗留样式表给那里的二级标题定了 24px 与 4px 底距。 */
+ for (const [name, heading] of [['链接管理', faces.links], ['资源同步', faces.sync]] as const) {
+ assert.equal(heading.size, '20px', `${name}标题字号不是 Title 2`);
+ assert.equal(heading.bottom, '0px', `${name}标题带着遗留那 4px 底距`);
+ }
+ assert.deepEqual([faces.label.size, faces.label.line], ['12px', '20px'], '链接读数的标签不是 12/20');
+ assert.deepEqual([faces.figure.size, faces.figure.weight, faces.figure.line], ['20px', '700', '20px'],
+ '链接读数的数字不是 20px 粗体、20px 行高');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('可点的卡悬停时铺卡面掺 5% 主文字色的那一档面,不是透明', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/data-cleanup', DESKTOP);
+ try {
+ const page = opened.page;
+ const selector = '.peach-react [data-cleanup-go]';
+ const card = page.locator(selector).first();
+ await card.waitFor({ timeout: 15_000 });
+ await settle(page);
+ const rest = await card.evaluate((element) => getComputedStyle(element).backgroundColor);
+ await card.hover();
+ // 过渡跑完才读:等到底色变了,或三秒后照实读出没变的那个值。
+ await page.waitForFunction(([target, before]) =>
+ getComputedStyle(document.querySelector(target)!).backgroundColor !== before,
+ [selector, rest] as const, { timeout: 3_000 }).catch(() => undefined);
+ const hovered = await card.evaluate((element) => getComputedStyle(element).backgroundColor);
+ assert.notEqual(hovered, 'rgba(0, 0, 0, 0)', '悬停底色落成了透明:token 在根上就折掉了');
+ assert.notEqual(hovered, rest, '悬停没有换面');
+ assert.equal(hovered, await tokenColor(page, '.peach-react', '--card-hover'), '悬停底色不是卡面掺 5% 主文字色');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('索引页名册格用遗留卡面那一套:格底 --ground、头像框 --sunk、首字与读数 --muted 配 Bahnschrift,悬停掺 6% 主文字色;页头过滤框与版式切换同为 36px 高,切换两枚共 66px 宽', { timeout: 60_000 }, async () => {
+ const opened = await openIndexPage(browser, '/performers');
+ try {
+ const page = opened.page;
+ const selector = '#index [data-index-cell]';
+ const cell = page.locator(selector).first();
+ const rest = await cell.evaluate((element) => getComputedStyle(element).backgroundColor);
+ const face = await page.evaluate(() => {
+ const ring = document.querySelector('#index [data-person-ring]')!;
+ const initial = document.querySelector('#index [data-person-ring] .ini')!;
+ const readout = document.querySelector('#index [data-index-readout]')!;
+ return { ring: getComputedStyle(ring).backgroundColor, initial: getComputedStyle(initial).color,
+ font: getComputedStyle(initial).fontFamily, readout: getComputedStyle(readout).color };
+ });
+ assert.equal(rest, await tokenColor(page, 'html', '--ground'), '名册格底不是 --ground');
+ assert.equal(face.ring, await tokenColor(page, 'html', '--sunk'), '头像框底不是 --sunk');
+ const muted = await page.evaluate(() => {
+ const probe = document.createElement('div');
+ probe.style.color = 'var(--muted)';
+ document.documentElement.append(probe);
+ const value = getComputedStyle(probe).color;
+ probe.remove();
+ return value;
+ });
+ assert.deepEqual([face.initial, face.readout], [muted, muted], '首字与读数不是 --muted');
+ assert.match(face.font, /^Bahnschrift/, '首字不是 Bahnschrift');
+ await cell.hover();
+ await page.waitForFunction(([target, before]) =>
+ getComputedStyle(document.querySelector(target)!).backgroundColor !== before,
+ [selector, rest] as const, { timeout: 3_000 }).catch(() => undefined);
+ const hovered = await cell.evaluate((element) => getComputedStyle(element).backgroundColor);
+ const lifted = await page.evaluate(() => {
+ const probe = document.createElement('div');
+ probe.style.backgroundColor = 'color-mix(in srgb, var(--ink) 6%, var(--ground))';
+ document.documentElement.append(probe);
+ const value = getComputedStyle(probe).backgroundColor;
+ probe.remove();
+ return value;
+ });
+ assert.equal(hovered, lifted, '名册格悬停不是格底掺 6% 主文字色');
+ const head = await page.evaluate(() => {
+ const input = document.querySelector('#index [data-index-search] input')!;
+ const shell = input.closest('[role="presentation"]')!;
+ const toggle = document.querySelector('#index [data-index-layout]')!;
+ return { search: getComputedStyle(shell).height, toggle: getComputedStyle(toggle).height,
+ width: getComputedStyle(toggle).width };
+ });
+ assert.deepEqual(head, { search: '36px', toggle: '36px', width: '66px' });
+ // 人脸放大把 img 撑得比框还宽再负偏移;Preflight 的 `max-width:100%` 会把它压回框宽。
+ const photo = page.locator('#index [data-person-ring] img').first();
+ await photo.waitFor({ state: 'attached', timeout: 5_000 });
+ await page.waitForFunction(() => document.querySelector('#index [data-person-ring]')?.hasAttribute('data-native-small'),
+ undefined, { timeout: 5_000 });
+ assert.equal(await photo.evaluate((element) => getComputedStyle(element).maxWidth), 'none');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('索引页换一档 Tabs 时那条蓝线沿弹簧滑过去,不是一跳', { timeout: 60_000 }, async () => {
+ const opened = await openIndexPage(browser, '/studios');
+ try {
+ const page = opened.page;
+ await page.emulateMedia({ reducedMotion: 'no-preference' });
+ const indicator = page.locator('#index [data-tab-indicator]');
+ await page.waitForFunction(() => document.querySelector('#index [data-tab-indicator]')?.hasAttribute('data-ready'),
+ undefined, { timeout: 5_000 });
+ const motion = await indicator.evaluate((element) => {
+ const style = getComputedStyle(element);
+ return { property: style.transitionProperty, duration: style.transitionDuration, height: style.height };
+ });
+ assert.equal(motion.property, 'transform, width');
+ assert.notEqual(motion.duration.split(',')[0]!.trim(), '0s', '蓝线没有过渡时长');
+ assert.equal(motion.height, '2px');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('播放列表卡:封面后压两层纸边、黑底封面、玻璃徽标、38px 头像叠 22px;标题 32/44,菜单键静止透明', { timeout: 60_000 }, async () => {
+ const opened = await openPlaylistsPage(browser);
+ try {
+ const page = opened.page;
+ const look = await page.evaluate(() => {
+ const card = document.querySelector('#stats [data-playlist-card="1"]')!;
+ const css = (selector: string) => getComputedStyle(card.querySelector(selector)!);
+ const stack = card.querySelector('[data-mix-stack]')!;
+ const back = getComputedStyle(stack, '::before');
+ const mid = getComputedStyle(stack, '::after');
+ const title = getComputedStyle(document.querySelector('#stats header h2')!);
+ const cover = css('[data-mix-cover]');
+ const badge = css('[data-mix-badge]');
+ const menu = css('[data-playlist-menu]');
+ const blank = getComputedStyle(document.querySelector('#stats [data-playlist-card="3"] [data-mix-cover] > span')!);
+ return {
+ title: [title.fontSize, title.lineHeight, title.fontWeight],
+ gap: getComputedStyle(document.querySelector('#stats [data-playlist-grid]')!).gap,
+ back: [back.borderTopWidth, back.inset, back.transform, back.opacity],
+ mid: [mid.borderTopWidth, mid.inset, mid.transform, mid.opacity],
+ cover: [cover.backgroundColor, cover.clipPath],
+ badge: [badge.backgroundColor, badge.backdropFilter, badge.minHeight, badge.borderRadius, badge.right, badge.bottom],
+ avatars: [...card.querySelectorAll('[data-mix-avatars] button')].map((button) => {
+ const style = getComputedStyle(button);
+ return [style.width, style.marginLeft, style.zIndex];
+ }),
+ menu: [menu.width, menu.height, menu.borderRadius, menu.backgroundColor],
+ blank: [blank.letterSpacing, blank.textTransform],
+ };
+ });
+ assert.deepEqual(look, {
+ title: ['32px', '44px', '500'],
+ gap: '18px',
+ back: ['1px', '0px 12px 8px', 'matrix(1, 0, 0, 1, 0, -7)', '0.54'],
+ mid: ['1px', '0px 6px 4px', 'matrix(1, 0, 0, 1, 0, -4)', '0.78'],
+ cover: ['rgb(0, 0, 0)', 'inset(0px round 14px)'],
+ badge: ['rgba(12, 8, 8, 0.72)', 'blur(10px)', '28px', '10px', '9px', '9px'],
+ avatars: [['38px', '0px', '5'], ['38px', '-22px', '4'], ['38px', '-22px', '3']],
+ menu: ['30px', '30px', '10px', 'rgba(0, 0, 0, 0)'],
+ blank: ['1.44px', 'uppercase'],
+ });
+ // 指到的头像抬起 4px、放大到 1.05,右边那位朝标题让开 10px。
+ await page.locator('#stats [data-playlist-card="1"] [data-mix-avatars] button').first().hover();
+ const lifted = await page.evaluate(() => {
+ document.getAnimations().forEach((animation) => animation.finish());
+ return [...document.querySelectorAll('#stats [data-playlist-card="1"] [data-mix-avatars] button')]
+ .slice(0, 2).map((button) => getComputedStyle(button).transform);
+ });
+ assert.deepEqual(lifted, ['matrix(1.05, 0, 0, 1.05, 0, -4)', 'matrix(1, 0, 0, 1, 10, -1.8)']);
+ // 点点点菜单外宽 172px,同旧卡片菜单。
+ await page.locator('#stats [data-playlist-card="1"] [data-playlist-menu]').click();
+ const panel = page.locator(':has(> [role="dialog"][aria-label="播放列表操作:列表1"])');
+ await panel.waitFor({ timeout: 5_000 });
+ assert.equal(await panel.evaluate((element) => getComputedStyle(element).width), '172px');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('播放列表页窄屏:页头改竖排,新建框字号 16px 免得 iOS 聚焦时放大', { timeout: 60_000 }, async () => {
+ const opened = await openPlaylistsPage(browser, MOBILE);
+ try {
+ const narrow = await opened.page.evaluate(() => ({
+ header: getComputedStyle(document.querySelector('#stats header')!).flexDirection,
+ input: getComputedStyle(document.querySelector('#stats [data-playlist-create] input')!).fontSize,
+ title: getComputedStyle(document.querySelector('#stats header h2')!).fontSize,
+ }));
+ assert.deepEqual(narrow, { header: 'column', input: '16px', title: '32px' });
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('分段底板支持鼠标反向、键盘即时切换与减少动态效果', { timeout: 60_000 }, async () => {
+ const opened = await openIndexPage(browser, '/performers');
+ const { page } = opened;
+ try {
+ await page.emulateMedia({ reducedMotion: 'no-preference' });
+ const track = page.locator('[data-index-layout]');
+ const choices = track.locator('label');
+ const pane = track.locator('[data-moving-surface]');
+ await pane.waitFor();
+ const aligned = async () => {
+ await page.waitForFunction(() => {
+ const host = document.querySelector('[data-index-layout]')!;
+ const pane = host.querySelector('[data-moving-surface]')!.getBoundingClientRect();
+ const selected = host.querySelector('label[data-selected]')!.getBoundingClientRect();
+ return Math.abs(pane.x - selected.x) < 1 && Math.abs(pane.width - selected.width) < 1;
+ });
+ };
+ const assertInstant = async () => {
+ const offset = await pane.evaluate((node) => {
+ const selected = node.parentElement!.querySelector('label[data-selected]')!.getBoundingClientRect();
+ const box = node.getBoundingClientRect();
+ return { x: box.x - selected.x, width: box.width - selected.width };
+ });
+ assert.ok(Math.abs(offset.x) < 1 && Math.abs(offset.width) < 1,
+ `即时切换的底板位置:${JSON.stringify(offset)}`);
+ };
+ await choices.nth(0).click();
+ await aligned();
+ const endpoints = await choices.evaluateAll((nodes) => nodes.slice(0, 2).map((node) => node.getBoundingClientRect().x));
+ await pane.evaluate((node) => {
+ const samples: number[] = [];
+ const sample = () => {
+ samples.push(node.getBoundingClientRect().x);
+ if (samples.length < 24) requestAnimationFrame(sample);
+ else (node as HTMLElement).dataset.motionSamples = JSON.stringify(samples);
+ };
+ requestAnimationFrame(sample);
+ });
+ await choices.nth(1).click();
+ await page.waitForFunction(() => document.querySelector('[data-index-layout] [data-motion-samples]'));
+ const samples = JSON.parse((await pane.getAttribute('data-motion-samples'))!) as number[];
+ assert.ok(samples.some((x) => x > Math.min(...endpoints) + 1 && x < Math.max(...endpoints) - 1),
+ `鼠标切换应经过两项之间的位置:${JSON.stringify(samples)}`);
+ await choices.nth(0).click();
+ await choices.nth(1).click();
+ await choices.nth(0).click();
+ await aligned();
+ assert.equal(await pane.count(), 1);
+ assert.equal(await pane.getAttribute('aria-hidden'), 'true');
+ await track.getByRole('radio').nth(0).focus();
+ await page.keyboard.press('ArrowRight');
+ await assertInstant();
+ assert.equal(await track.getByRole('radio').nth(1).isChecked(), true);
+ assert.equal(await pane.evaluate((node) => node.getAnimations().length), 0);
+ assert.match(await choices.nth(1).evaluate((node) => getComputedStyle(node).getPropertyValue('--tw-ring-shadow')), /2px/,
+ '选中底板不能抹掉键盘焦点环');
+ await page.emulateMedia({ reducedMotion: 'reduce' });
+ await choices.nth(0).click();
+ await assertInstant();
+ assert.equal(await pane.evaluate((node) => node.getAnimations().length), 0);
+ await page.setViewportSize({ width: 390, height: 844 });
+ await aligned();
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close(); }
+ });
+
+ it('短菜单共享悬停面,弹窗关闭释放焦点与遮罩', { timeout: 60_000 }, async () => {
+ const opened = await openPlaylistsPage(browser);
+ const { page } = opened;
+ try {
+ await page.emulateMedia({ reducedMotion: 'no-preference' });
+ const trigger = page.locator('[data-playlist-card="1"] [data-playlist-menu]');
+ await trigger.click();
+ const menu = page.getByRole('dialog', { name: '播放列表操作:列表1' });
+ await menu.getByRole('button', { name: '编辑名称' }).hover();
+ const pane = menu.locator('[data-moving-surface]');
+ await pane.waitFor();
+ await menu.getByRole('button', { name: '删除播放列表' }).hover();
+ await page.waitForFunction(() => {
+ const host = document.querySelector('[data-surface-host="hover"]')!;
+ const pane = host.querySelector('[data-moving-surface]')!.getBoundingClientRect();
+ const button = [...host.querySelectorAll('button')].at(-1)!.getBoundingClientRect();
+ return Math.abs(pane.y - button.y) < 1;
+ });
+ await page.keyboard.press('Tab');
+ assert.equal(await pane.isVisible(), false);
+ await menu.getByRole('button', { name: '编辑名称' }).click();
+ const modal = page.locator('[data-modal-motion]');
+ await modal.waitFor();
+ await modal.getByRole('textbox', { name: '名称' }).waitFor();
+ assert.equal(await modal.locator('[data-modal-surface]').evaluate((node) =>
+ getComputedStyle(node).transitionProperty.includes('transform')), true);
+ await modal.locator('form').getByRole('button', { name: '取消', exact: true }).click();
+ await modal.waitFor({ state: 'detached' });
+ await trigger.click();
+ await menu.getByRole('button', { name: '编辑名称' }).focus();
+ await page.keyboard.press('Enter');
+ await modal.waitFor();
+ assert.equal(await modal.getAttribute('data-motion-instant'), 'true');
+ await page.waitForFunction(() => Boolean(document.activeElement?.closest('[data-modal-motion]')),
+ null, { timeout: 5_000 });
+ await page.keyboard.press('Escape');
+ await modal.waitFor({ state: 'detached' });
+ assert.equal(await page.evaluate(() => document.activeElement?.closest('[data-modal-motion]') !== null), false);
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close(); }
+ });
+
+ it('批量选择条更新计数保持节点,清空后退出且不保留可操作控件', { timeout: 60_000 }, async () => {
+ const opened = await openIndexPage(browser, '/tags');
+ const { page } = opened;
+ try {
+ await page.emulateMedia({ reducedMotion: 'no-preference' });
+ await page.locator('#selectMode').click();
+ const tags = page.locator('#index [data-alpha-tag]');
+ await tags.nth(0).click();
+ const dock = page.locator('[data-selection-dock]');
+ await dock.waitFor();
+ await dock.evaluate((node) => node.setAttribute('data-test-identity', 'retained'));
+ await tags.nth(1).click();
+ assert.equal(await dock.getAttribute('data-test-identity'), 'retained');
+ assert.match(await dock.textContent() ?? '', /已选 2 个标签/);
+ await dock.getByRole('button', { name: '清空', exact: true }).click();
+ await page.waitForFunction(() => {
+ const dock = document.querySelector<HTMLElement>('[data-selection-dock]');
+ return !dock || (dock.inert && dock.getAttribute('aria-hidden') === 'true');
+ });
+ await dock.waitFor({ state: 'detached' });
+ await tags.nth(0).click();
+ await dock.waitFor();
+ await page.emulateMedia({ reducedMotion: 'reduce' });
+ await dock.getByRole('button', { name: '清空', exact: true }).click();
+ await dock.waitFor({ state: 'detached' });
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close(); }
+ });
+
+ it('标签多选坞出现时页底让出 96px;在线词表的类型色走上游 tag_type 那一套', { timeout: 60_000 }, async () => {
+ const opened = await openIndexPage(browser, '/tags');
+ try {
+ const page = opened.page;
+ await page.locator('#selectMode').click({ timeout: 5_000 });
+ await page.locator('#index [data-alpha-tag]').nth(0).click({ timeout: 5_000 });
+ await page.locator('#index [data-alpha-tag]').nth(1).click({ timeout: 5_000 });
+ const dock = page.locator('[data-selection-dock]');
+ await dock.waitFor({ timeout: 5_000 });
+ const padding = await page.evaluate(() =>
+ getComputedStyle(document.querySelector('#index .peach-react')!).paddingBottom);
+ assert.equal(padding, '96px', '选择坞盖住了最后一行标签');
+ await page.locator('#index [role="tab"][data-tab="online"]').click({ timeout: 5_000 });
+ const dot = page.locator('#index [data-alpha-tag][data-tag-cat="r34-artist"] [data-tag-dot]');
+ await dot.waitFor({ timeout: 5_000 });
+ assert.equal(await dot.evaluate((element) => getComputedStyle(element).backgroundColor), 'rgb(227, 108, 108)');
+ assert.equal(await dock.count(), 0, '在线词表不给多选坞');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('标签云一枚里名字与计数只隔一个空格宽;筛选浮层的 Aa 字形摆进 16×16 的框', { timeout: 60_000 }, async () => {
+ const opened = await openIndexPage(browser, '/tags?view=cloud');
+ try {
+ const page = opened.page;
+ const spacing = await page.locator('#index [data-tag-chip]').first().evaluate((chip) => {
+ // 名字那段文字按字符切开量:字的右缘到计数左缘,与末尾那个空格自己画出来的宽度相比。
+ const name = chip.firstChild!;
+ const end = name.textContent!.trimEnd().length;
+ const box = (from: number, to: number) => {
+ const part = document.createRange();
+ part.setStart(name, from);
+ part.setEnd(name, to);
+ return part.getBoundingClientRect();
+ };
+ const count = chip.querySelector('[data-tag-n]')!.getBoundingClientRect();
+ return { gap: count.left - box(0, end).right, space: box(end, name.textContent!.length).width,
+ columnGap: getComputedStyle(chip).columnGap };
+ });
+ assert.equal(spacing.columnGap, 'normal', '名字与计数之间不另加 flex 间距');
+ assert.ok(spacing.space > 2 && Math.abs(spacing.gap - spacing.space) < 0.5,
+ `名字与计数隔了 ${spacing.gap}px,一个空格是 ${spacing.space}px`);
+ const glyph = page.locator('#index svg:has(use[href="#i-text-aa"])');
+ assert.deepEqual(await glyph.evaluate((element) => {
+ const style = getComputedStyle(element);
+ return [style.width, style.height];
+ }), ['16px', '16px']);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('重复文件的汇总条是玻璃面,组卡 14px 圆角、组头 20px 内边距,每行上方一条 1px 分隔线', { timeout: 60_000 }, async () => {
+ const opened = await openDuplicates(browser);
+ try {
+ const faces = await opened.page.evaluate(() => {
+ const glass = getComputedStyle(document.querySelector('[data-filter-glass]')!);
+ const group = document.querySelector('#stats section[aria-label="DUPE-002"]')!;
+ const head = group.firstElementChild!;
+ const card = getComputedStyle(group);
+ const header = getComputedStyle(head);
+ const code = getComputedStyle(head.querySelector('b')!);
+ return {
+ glass: { filter: glass.backdropFilter, padding: glass.padding, height: glass.height },
+ card: { radius: card.borderRadius, overflow: card.overflow, face: card.backgroundColor },
+ head: { padding: header.padding, face: header.backgroundColor, size: code.fontSize, weight: code.fontWeight },
+ rows: [...group.querySelectorAll('.duplicate-row')].map((row) => {
+ const computed = getComputedStyle(row);
+ return [computed.borderTopWidth, computed.padding];
+ }),
+ };
+ });
+ assert.match(faces.glass.filter, /blur\(/, '汇总条没有背景模糊,不是玻璃面');
+ assert.deepEqual([faces.glass.padding, faces.glass.height], ['10px 16px', '50px']);
+ assert.deepEqual([faces.card.radius, faces.card.overflow], ['14px', 'hidden'], '组卡圆角或裁切不对');
+ assert.notEqual(faces.head.face, faces.card.face, '组头和组卡同色,番号那一行分不出来');
+ assert.deepEqual([faces.head.padding, faces.head.size, faces.head.weight], ['20px', '20px', '500']);
+ assert.deepEqual(faces.rows, [['1px', '16px 20px'], ['1px', '16px 20px']],
+ '组内每一行上方不是 1px 分隔线,或内边距不是 16/20');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('整页空态沉一档底色、20px 圆角、至少 320px 高,图标装进 54px 描边方框;卡里的空态不带方框', { timeout: 60_000 }, async () => {
+ // 演示库在一轮里凑得出重复组,桩成空的才一定落到整页空态上。
+ const opened = await visit(browser, '/duplicates', DESKTOP);
+ try {
+ const page = opened.page;
+ await page.route('**/api/duplicates?**', (route) => route.fulfill({
+ status: 200, contentType: 'application/json',
+ body: JSON.stringify({ total: 0, files: 0, reclaimable: 0, groups: [] }),
+ }));
+ await page.reload({ waitUntil: 'load' });
+ await page.locator('#stats [data-empty-state]').waitFor({ timeout: 15_000 });
+ await settle(page);
+ const face = await page.evaluate(() => {
+ const root = document.querySelector('#stats [data-empty-state]')!;
+ const glyph = root.querySelector('svg')!;
+ const box = glyph.parentElement!;
+ const shell = getComputedStyle(root);
+ const frame = getComputedStyle(box);
+ const title = getComputedStyle(root.querySelector('h3')!);
+ const copy = getComputedStyle(root.querySelector('p')!);
+ return {
+ shell: { face: shell.backgroundColor, line: shell.borderTopColor, width: shell.borderTopWidth,
+ radius: shell.borderTopLeftRadius, minHeight: shell.minHeight },
+ boxed: box !== root,
+ frame: { width: frame.width, height: frame.height, radius: frame.borderTopLeftRadius,
+ line: frame.borderTopWidth, glyph: getComputedStyle(glyph).width },
+ title: [title.fontSize, title.fontWeight], copy: [copy.maxWidth, copy.lineHeight],
+ };
+ });
+ assert.equal(face.shell.face, await tokenColor(page, '.peach-react', '--color-background-secondary-default'),
+ '整页空态没有沉一档底色');
+ assert.equal(face.shell.line, await tokenColor(page, '.peach-react', '--color-separator-border'), '外框不是分隔线色');
+ assert.deepEqual([face.shell.width, face.shell.radius, face.shell.minHeight], ['1px', '20px', '320px']);
+ assert.ok(face.boxed, '整页空态的图标没有装进方框');
+ assert.deepEqual(face.frame, { width: '54px', height: '54px', radius: '20px', line: '1px', glyph: '32px' });
+ assert.deepEqual(face.title, ['14px', '600']);
+ assert.deepEqual(face.copy, ['340px', '20.15px']);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ // 卡里那一档(活动页没有任务记录)图标直接挂在空态上,外面没有方框。
+ const activity = await visit(browser, '/activity', DESKTOP);
+ try {
+ await activity.page.route('**/api/tasks', (route) => route.fulfill({
+ status: 200, contentType: 'application/json',
+ body: JSON.stringify({ available: true, running: [], skipped: [], finished: [] }),
+ }));
+ await activity.page.reload({ waitUntil: 'load' });
+ const empty = activity.page.locator('[data-empty-state]');
+ await empty.waitFor({ timeout: 15_000 });
+ await settle(activity.page);
+ assert.equal(await empty.evaluate((root) => root.querySelector('svg')!.parentElement === root), true,
+ '卡里的空态也套了图标方框');
+ assert.deepEqual(activity.problems, []);
+ } finally {
+ await activity.close();
+ }
+ });
+
+ it('骨架里的占位和按键悬停不给任何反馈,也点不中', { timeout: 120_000 }, async () => {
+ const name = '七沢みあ';
+ const pages: { path: string; ready: string; targets: string[]; prepare?: (page: Page) => Promise<void> }[] = [
+ { path: `/performers/${encodeURIComponent(name)}`, ready: '[data-skeleton="entity/performer"] .entityfoot .avskeleton',
+ targets: ['[data-skeleton] .entityfoot .avskeleton'],
+ prepare: (page) => page.route(/\/api\/entity\/shapes/, (route) => route.fulfill({ json: {
+ ok: true, entities: [{ id: 90_001, kind: 'performer', names: [name], parts: ['costars'] }] } })) },
+ { path: '/data-cleanup', ready: '[data-skeleton="cleanup"] [data-skeleton-action]',
+ targets: ['[data-skeleton] .board-plain-stat', '[data-skeleton] a[href="/scraping"]',
+ '[data-skeleton] [data-skeleton-action]', '[data-skeleton] .cleanupfieldset [data-skeleton-action]'] },
+ { path: '/review', ready: '[data-skeleton="review"] .reviewtabs button',
+ targets: ['[data-skeleton] .reviewtabs button', '[data-skeleton] .skeletoncard'] },
+ { path: '/follow', ready: '.followauthors .avskeleton',
+ targets: ['.followauthors .avskeleton', '.followworks .brandskeleton', '[data-skeleton^="cards/"] > div > *'] },
+ { path: '/follow-manage', ready: '[data-skeleton="board/follow-manage"] .follow-skeleton-toolbar',
+ targets: ['[data-skeleton] .follow-skeleton-toolbar > button:nth-of-type(2)',
+ '[data-skeleton] .follow-skeleton-toolbar > button:nth-of-type(1)'] },
+ ];
+ for (const { path, ready, targets, prepare } of pages) {
+ const opened = await visit(browser, '/', DESKTOP);
+ try {
+ const page = opened.page;
+ // 后登记的路由先拿到请求:桩要排在挂住 /api/ 那条之后,不然它也被挂住。
+ await holdApi(page);
+ await prepare?.(page);
+ await page.goto(new URL(path, page.url()).href, { waitUntil: 'load' });
+ await page.locator(ready).first().waitFor({ state: 'visible', timeout: 15_000 });
+ for (const target of targets) {
+ const node = page.locator(target).first();
+ await node.waitFor({ state: 'visible', timeout: 5_000 });
+ // 落在首屏以下的目标(数据管理的整理卡)先滚进视口:`elementFromPoint` 只认视口里的点。
+ await node.scrollIntoViewIfNeeded();
+ const box = (await node.boundingBox())!;
+ const look = () => node.evaluate((element) => [element, ...element.querySelectorAll('*')].slice(0, 6).map((part) => {
+ const style = getComputedStyle(part);
+ return [style.borderColor, style.boxShadow, style.backgroundColor, style.backgroundImage,
+ style.outlineStyle, style.color, style.scale, style.transform].join(' | ');
+ }));
+ await page.mouse.move(0, 0);
+ const rest = await look();
+ const [x, y] = [box.x + box.width / 2, box.y + box.height / 2];
+ await page.mouse.move(x, y);
+ assert.deepEqual(await look(), rest, `${path} ${target} 悬停时变了样子`);
+ // 分层骨架那一排(`data-skeleton-tier`)是最终那条轨道本身,点中它等于点在页面底上;
+ // 要问的是指针有没有落在某一枚占位或整块骨架里。
+ const hit = await page.evaluate(([px, py]) => {
+ const at = document.elementFromPoint(px!, py!);
+ return { cursor: at ? getComputedStyle(at).cursor : '',
+ inside: !!at?.closest('[data-skeleton],.avskeleton,.brandskeleton,.tagskeleton,.skeletoncard'),
+ disabled: !!at?.closest('button:disabled') };
+ }, [x, y]);
+ assert.ok(['auto', 'default', 'not-allowed'].includes(hit.cursor), `${path} ${target} 悬停换了光标:${hit.cursor}`);
+ assert.ok(!hit.inside || hit.disabled, `${path} ${target} 在骨架里还能点中`);
+ }
+ } finally {
+ await opened.close();
+ }
+ }
+ });
+
+ it('勾中的来源在卡片和表格里都铺 BoardUI 数据表那一档选中底色', { timeout: 60_000 }, async () => {
+ const opened = await openFollowManage(browser);
+ try {
+ const page = opened.page;
+ const selected = await tokenColor(page, '.peach-react', '--color-background-secondary-default');
+ await page.getByRole('checkbox', { name: '选择 kou · Kemono' }).check({ force: true, timeout: 5_000 });
+ const cardRow = page.locator('[data-source-divider] > [data-selected]');
+ assert.equal(await cardRow.count(), 1);
+ assert.equal(await cardRow.evaluate((row) => getComputedStyle(row).backgroundColor), selected,
+ '卡片里的选中行没有铺选中底色');
+
+ await page.locator('button[aria-label="表格视图"]').click({ timeout: 5_000 });
+ const tableRow = page.locator('[data-follow-selected]');
+ await tableRow.waitFor({ timeout: 5_000 });
+ assert.equal(await tableRow.evaluate((row) => getComputedStyle(row).backgroundColor), selected,
+ '表格里的选中行和卡片里的不是同一档');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('别名的组数是次要字色的读数,不借提醒或主按钮的颜色', { timeout: 60_000 }, async () => {
+ const opened = await openFollowManage(browser);
+ try {
+ await followTab(opened, '添加关注');
+ const count = opened.page.getByText('1 组', { exact: true });
+ const look = await count.evaluate((node) => ({
+ ink: getComputedStyle(node).color, face: getComputedStyle(node).backgroundColor,
+ }));
+ assert.equal(look.ink, await tokenColor(opened.page, '.peach-react', '--color-text-secondary'));
+ assert.equal(look.face, 'rgba(0, 0, 0, 0)', '组数画成了带底色的徽章');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ /* 建议由这里给,两组共 30 条,两个视口下字段下方都装不下。桌面取 1280×1000,
+ 字段下缘在视口中段偏下,正是只能往下开、又放不全的那种处境。 */
+ for (const viewport of [{ ...DESKTOP, height: 1000 }, MOBILE]) {
+ it(`添加关注的建议下拉压在字段下方剩下的空间里,装不下在菜单内滚,选中行滚进可见区(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openFollowManage(browser, viewport);
+ try {
+ const { page } = opened;
+ await page.route(/\/api\/follow\/suggest\?/, (route) => route.fulfill({ json: {
+ q: 'bulging',
+ groups: [['归档站', 18], ['站方分类', 12]].map(([label, count]) => ({
+ kind: String(label), label,
+ items: Array.from({ length: Number(count) }, (_, at) => ({
+ value: `bulging ${label} ${at + 1}`, matched: 'Kemono', n: 120 - at,
+ })),
+ })),
+ } }));
+ await followTab(opened, '添加关注');
+ const before = await page.evaluate(() => document.documentElement.scrollHeight);
+ const input = page.getByRole('textbox', { name: '来源链接、名字或 id' });
+ await input.click({ timeout: 5_000 });
+ await input.fill('bulging');
+ const menu = page.locator('[aria-label="来源建议"]');
+ await menu.locator('button').nth(29).waitFor({ state: 'attached', timeout: 10_000 });
+ const measure = () => menu.evaluate((element) => {
+ for (const animation of element.getAnimations({ subtree: true })) animation.finish();
+ const box = element.getBoundingClientRect();
+ const field = element.ownerDocument.querySelector('input[aria-label="来源链接、名字或 id"]')!
+ .getBoundingClientRect();
+ const row = element.querySelector('[aria-current="true"]')?.getBoundingClientRect();
+ return {
+ top: box.top, bottom: box.bottom, fieldBottom: field.bottom, viewport: innerHeight,
+ overflowing: element.scrollHeight > element.clientHeight,
+ overscroll: getComputedStyle(element).overscrollBehaviorY,
+ page: document.documentElement.scrollHeight, pageWidth: document.documentElement.scrollWidth,
+ width: innerWidth, y: scrollY,
+ row: row ? { top: row.top, bottom: row.bottom } : null,
+ };
+ });
+ const open = await measure();
+ assert.ok(open.bottom <= open.viewport + .5, `下拉底边 ${open.bottom} 越出视口 ${open.viewport}`);
+ assert.ok(open.top >= open.fieldBottom, `下拉上沿 ${open.top} 盖住了字段(下缘 ${open.fieldBottom})`);
+ assert.ok(open.overflowing, '30 条建议没有让下拉溢出,这条用例没练到内滚');
+ assert.equal(open.overscroll, 'contain', '下拉滚到头会带着页面一起滚');
+ assert.ok(open.page <= before, `下拉把页面从 ${before} 撑到 ${open.page}`);
+ assert.ok(open.pageWidth <= open.width, `页面被撑出横向滚动:${open.pageWidth} > ${open.width}`);
+
+ // 走到最后一条:它在初始可见区外面,得被滚进来,页面本身不动。
+ for (let step = 0; step < 30; step++) await input.press('ArrowDown');
+ const last = await measure();
+ assert.ok(last.row, '上下键没有选中任何一行');
+ assert.ok(last.row.top >= last.top - .5 && last.row.bottom <= last.bottom + .5,
+ `选中行 ${last.row.top}–${last.row.bottom} 不在下拉可见区 ${last.top}–${last.bottom} 内`);
+ assert.equal(last.y, open.y, '选中行滚进可见区时把页面也滚了');
+ await input.press('ArrowDown');
+ const first = await measure();
+ assert.ok(first.row && first.row.top >= first.top - .5, '绕回第一条后它没有滚回可见区');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+
+ it('凭据的四种处境四副底色:待办和完成一眼分得开', { timeout: 60_000 }, async () => {
+ const opened = await openFollowManage(browser);
+ try {
+ await followTab(opened, '来源和凭证');
+ const faces: Record<string, string> = {};
+ for (const state of ['需要', '已配置', '接不进来', '不需要']) {
+ faces[state] = await opened.page.getByText(state, { exact: true }).first()
+ .evaluate((chip) => getComputedStyle(chip).backgroundColor);
+ }
+ assert.equal(new Set(Object.values(faces)).size, 4, `有两种处境同色:${JSON.stringify(faces)}`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('浅色下看片那两枚标识悬停时有底,资料卡上带订阅新作开关', { timeout: 60_000 }, async () => {
+ // 演示库里没有人物实体:资料由这里给,入口与开关字段照服务端拼好下发的形状写。
+ const name = '七沢みあ';
+ const opened = await visit(browser, '/', DESKTOP);
+ try {
+ await opened.page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
+ id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],
+ user_aliases: [], asset_count: 0, tags: [], related_performers: [], links: [],
+ metadata: {}, has_image: false, has_avatar: false, avatar_focus: null,
+ representative_asset_id: null,
+ entry_links: [{ site: 'javdb', label: 'JavDB', ordinal: '', slot: 'mark',
+ mark: 'mark-javdb', url: 'https://javdb.com/actors/NPD3' }],
+ feed: { following: false },
+ } }));
+ await opened.page.goto(new URL(`/performers/${encodeURIComponent(name)}`,
+ opened.page.url()).href, { waitUntil: 'load' });
+ const mark = opened.page.locator('[data-entry-marks] a[data-entry-mark]').first();
+ await mark.waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ // 浅色下 `--hover` 与资料卡的 `--ground` 同是 #f5f5f5,垫上去等于没垫。
+ await opened.page.evaluate(() => {
+ document.documentElement.dataset.theme = 'light';
+ document.documentElement.classList.remove('dark');
+ });
+ await mark.hover();
+ const faces = await mark.evaluate((element) => ({
+ mark: getComputedStyle(element).backgroundColor,
+ card: getComputedStyle(element.closest('[data-entity-card]')!).backgroundColor,
+ }));
+ assert.notEqual(faces.mark, 'rgba(0, 0, 0, 0)', '悬停没有垫底');
+ assert.notEqual(faces.mark, faces.card, '悬停底色和资料卡同色,看不出来');
+ const toggle = opened.page.getByRole('switch', { name: '订阅新作' });
+ assert.equal(await toggle.count(), 1, '资料卡上没有订阅新作开关');
+ assert.equal(await toggle.isChecked(), false);
+ const feed = opened.page.locator('[data-entry-feed]');
+ await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
+ assert.equal(await feed.evaluate((element) => getComputedStyle(element).animationName),
+ 'entryfeed-breathe', '没订的那枚图标不呼吸,一枚墨色小图标没人注意到');
+ const tip = opened.page.locator('#entityFeedTip');
+ assert.equal(await tip.isVisible(), false);
+ await feed.hover();
+ assert.equal(await tip.isVisible(), true, '悬停没有说明这枚图标是干嘛的');
+ assert.equal(await tip.innerText(), '订阅新作');
+ const placed = await tip.evaluate((element) => {
+ const box = element.getBoundingClientRect();
+ return box.left >= 0 && box.right <= innerWidth && box.bottom <= innerHeight;
+ });
+ assert.ok(placed, '说明浮层越出了视口');
+ await toggle.focus();
+ await opened.page.keyboard.press('Escape');
+ assert.equal(await tip.isVisible(), false, 'Escape 收不起说明浮层');
+ } finally {
+ await opened.close();
+ }
+ });
+
+ for (const viewport of [DESKTOP, MOBILE]) {
+ it(`订阅新作的说明浮层整块露在外面:不被资料卡裁掉,也不被同台艺人那条盖住(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openPerformer(browser, viewport);
+ try {
+ const page = opened.page;
+ const feed = page.locator('[data-entry-feed]');
+ await feed.hover();
+ const tip = page.locator('#entityFeedTip');
+ await tip.waitFor({ state: 'visible', timeout: 5_000 });
+ const placement = await tip.evaluate((element) => {
+ const box = element.getBoundingClientRect();
+ const clippedBy: string[] = [];
+ // 顶层里的元素不受祖先 overflow 裁切,只有写在文档流里的浮层才要逐层量。
+ const topLayer = element.matches(':popover-open');
+ for (let node = topLayer ? null : element.parentElement; node; node = node.parentElement) {
+ const style = getComputedStyle(node);
+ if (style.overflowX === 'visible' && style.overflowY === 'visible') continue;
+ const clip = node.getBoundingClientRect();
+ if (box.left < clip.left - 0.5 || box.right > clip.right + 0.5
+ || box.top < clip.top - 0.5 || box.bottom > clip.bottom + 0.5) clippedBy.push(node.className || node.tagName);
+ }
+ // 浮层本身不接指针;临时放开再问四条边和正中最上面是谁,盖在它上面的东西就现形了。
+ // 取样点离角 16px:圆角外那一小块本来就不属于它。
+ element.style.pointerEvents = 'auto';
+ const [midX, midY] = [box.left + box.width / 2, box.top + box.height / 2];
+ const covered = [[box.left + 16, box.top + 2], [box.right - 16, box.top + 2], [box.left + 16, box.bottom - 2],
+ [box.right - 16, box.bottom - 2], [box.left + 2, midY], [box.right - 2, midY], [midX, midY]]
+ .map(([x, y]) => document.elementFromPoint(x!, y!))
+ .filter((hit) => !hit || !element.contains(hit)).map((hit) => hit?.className || 'null');
+ element.style.pointerEvents = '';
+ return { inView: box.left >= 0 && box.right <= innerWidth && box.top >= 0 && box.bottom <= innerHeight,
+ clippedBy, covered, below: box.top >= document.querySelector('[data-entry-feed]')!.getBoundingClientRect().bottom };
+ });
+ assert.ok(placement.inView, '说明浮层越出了视口');
+ assert.deepEqual(placement.clippedBy, [], '说明浮层被外层容器裁掉了一截');
+ assert.deepEqual(placement.covered, [], '说明浮层被别的东西盖住了');
+ assert.ok(placement.below, '视口下方放得下时说明浮层应该在图标下面');
+ const page_ = await layout(page);
+ assert.ok(page_.scrollWidth <= page_.viewportWidth, '说明浮层把页面撑出了横向滚动');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+
+ // 1000px 窗口侧栏展开时内容区只剩七百来像素:三栏的判据量的是内容区,这一档要排成两层,
+ // 身份那一栏不能被资料表挤到只剩一个字宽。
+ for (const [viewport, stacked] of [[DESKTOP, false], [{ name: 'wide', width: 1440, height: 900, mobile: false }, false],
+ [{ name: 'mid', width: 1000, height: 900, mobile: false }, true], [MOBILE, true]] as const) {
+ it(`女优页头:宽屏资料表在身份信息右侧隔一道竖线,窄屏排到下面隔一道横线,整张卡不横向溢出(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openProfiledPerformer(browser, viewport);
+ try {
+ const geometry = await heroGeometry(opened.page);
+ assert.deepEqual(geometry.labels, ['生日', '身材', '出道', '生涯', '标签'], '资料表不是那五项');
+ assert.ok(geometry.facts && geometry.identity && geometry.hero, '页头缺了资料表');
+ assert.ok(geometry.identity.right - geometry.identity.left >= 240, '身份那一栏被挤窄了');
+ if (stacked) {
+ assert.ok(geometry.facts.top >= geometry.identity.bottom - 0.5, '窄屏下资料表没有排到身份信息下面');
+ assert.deepEqual(geometry.rule, { left: '0px', top: '1px' }, '窄屏下资料表该用横线和身份信息隔开');
+ } else {
+ assert.ok(geometry.facts.left >= geometry.identity.right - 0.5, '宽屏下资料表没有排在身份信息右侧');
+ assert.deepEqual(geometry.rule, { left: '1px', top: '0px' }, '宽屏下资料表该用竖线和身份信息隔开');
+ }
+ assert.ok(geometry.facts.right <= geometry.hero.right + 0.5, '资料表越出了资料卡');
+ assert.equal(geometry.heroScrolls, false, '资料卡里有东西被横向裁掉');
+ const debut = await opened.page.locator('[data-entity-facts] dd[title]').evaluate((dd) => ({
+ title: dd.getAttribute('title'), wrap: getComputedStyle(dd).whiteSpace,
+ cut: getComputedStyle(dd).textOverflow, clipped: dd.scrollWidth > dd.clientWidth,
+ lines: Math.round(dd.getBoundingClientRect().height / parseFloat(getComputedStyle(dd).lineHeight)),
+ }));
+ assert.equal(debut.title, PROFILED.profile.debut_title, '出道那一格的 title 没给全名');
+ assert.deepEqual([debut.wrap, debut.cut, debut.lines], ['nowrap', 'ellipsis', 1], '出道片名没有单行截断');
+ const page_ = await layout(opened.page);
+ assert.ok(page_.scrollWidth <= page_.viewportWidth, `页头把页面撑出了横向滚动:${page_.offenders.join(',')}`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+
+ for (const viewport of [DESKTOP, MOBILE]) {
+ it(`公司资料页显示公司与品牌事实且长地址可折行(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const fact = (value: string) => ({ value, source_url: 'https://company.example/about' });
+ const opened = await openProfiledPerformer(browser, viewport, 'light', {
+ kind: 'studio', canonical_name: 'Company', profile: undefined, agency: undefined,
+ company_profile: { legal_name: fact('Example Company, LLC'), founded: fact('2002-05'),
+ launched: fact('2016'), operator: fact('General Media Systems, LLC'),
+ location: fact('LongOfficeAddressWithoutSpaces'.repeat(5)) },
+ });
+ try {
+ await opened.page.goto(new URL('/studios/Company', opened.page.url()).href, { waitUntil: 'load' });
+ await opened.page.locator('[data-entity-facts]').waitFor();
+ await settle(opened.page);
+ const geometry = await heroGeometry(opened.page);
+ assert.deepEqual(geometry.labels, ['公司名称', '公司成立', '品牌启动', '所在地', '运营公司']);
+ assert.equal(geometry.heroScrolls, false);
+ assert.ok(geometry.hero && geometry.facts && geometry.facts.right <= geometry.hero.right + 1);
+ assert.equal(await opened.page.locator('[data-entity-facts] [title]').count(), 0);
+ const page_ = await layout(opened.page);
+ assert.ok(page_.scrollWidth <= page_.viewportWidth);
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close(); }
+ });
+ }
+
+ it('女优页头名字下面一行:视频数、事务所与读音加前三个别名,外链一律 36px 纯图标方块', { timeout: 60_000 }, async () => {
+ const opened = await openProfiledPerformer(browser, DESKTOP);
+ try {
+ const page = opened.page;
+ const line = await page.locator('[data-entity-alias]').evaluate((alias) => ({
+ glyphs: [...alias.querySelectorAll(':scope > [data-meta-item] > svg use')].map((use) => use.getAttribute('href')),
+ names: [...alias.querySelectorAll('[data-alias-names] > span')].map((span) => span.textContent!.trim()),
+ more: alias.querySelector('[data-hero-more="alias"]')?.textContent?.trim() ?? '',
+ agency: alias.querySelector('a[data-agency]')?.textContent?.trim() ?? '',
+ }));
+ assert.deepEqual(line.glyphs, ['#i-film', '#i-briefcase', '#i-id-card'], '名字那一行的三项不是视频、事务所、别名');
+ assert.deepEqual(line.names, ['しのだゆう', '篠崎ゆう子', '高木早希', '橋本真紀'], '读音没有排在别名最前,或别名不是前三个');
+ assert.equal(line.more, '+4', '「+N」数的不是剩下那几个别名');
+ assert.equal(line.agency, 'New Actor eXperience');
+ const links = await page.locator('[data-entity-links] a').evaluateAll((anchors) => anchors.map((a) => {
+ const box = a.getBoundingClientRect();
+ return { size: `${Math.round(box.width)}x${Math.round(box.height)}`, kind: a.getAttribute('data-link'), title: a.getAttribute('title'),
+ name: a.getAttribute('aria-label') ?? '', visibleText: a.querySelector('[data-link-label]') !== null };
+ }));
+ assert.equal(links.length, 3);
+ for (const link of links) {
+ assert.deepEqual([link.size, link.kind, link.visibleText], ['36x36', 'icon', false], `${link.title} 不是纯图标方块`);
+ assert.equal(link.name, link.title, `${link.title} 给读屏的名字和悬停提示不一致`);
+ }
+ assert.deepEqual(links.map((link) => link.title), ['みんなのAV', 'New Actor eXperience 官方资料', 'X @shinoda_yu']);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ for (const viewport of [DESKTOP, MOBILE]) {
+ it(`别名的「+N」浮层进顶层按名义分组:悬停、聚焦都出,不被资料卡裁掉,Escape 收起(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openProfiledPerformer(browser, viewport);
+ try {
+ const page = opened.page;
+ const more = page.locator('[data-hero-more="alias"]');
+ const pop = page.locator('#entityAliasPop');
+ assert.equal(await pop.isVisible(), false);
+ await more.hover();
+ await pop.waitFor({ state: 'visible', timeout: 5_000 });
+ assert.equal(await more.getAttribute('aria-expanded'), 'true');
+ const shown = await pop.evaluate((element) => {
+ const box = element.getBoundingClientRect();
+ return {
+ topLayer: element.matches(':popover-open'),
+ inView: box.left >= 0 && box.right <= innerWidth && box.top >= 0 && box.bottom <= innerHeight,
+ title: element.querySelector('[data-hero-pop-head]')?.textContent?.trim(),
+ groups: [...element.querySelectorAll('dt')].map((dt) => dt.textContent!.trim()),
+ face: getComputedStyle(element).backgroundColor,
+ shadow: getComputedStyle(element).boxShadow,
+ };
+ });
+ assert.equal(shown.shadow, await popmenuShadow(page), '别名浮层的落影和 .popmenu 不是同一副');
+ assert.equal(shown.topLayer, true, '别名浮层没进顶层,会被资料卡的 overflow:hidden 裁掉');
+ assert.ok(shown.inView, '别名浮层越出了视口');
+ assert.equal(shown.title, '7 个别名');
+ assert.deepEqual(shown.groups, ['旧名义', '舞ワイフ', 'ラグジュTV', '其它']);
+ assert.notEqual(shown.face, 'rgba(0, 0, 0, 0)', '别名浮层没有底色');
+ // 指针从按钮挪到浮层上读名字,浮层不能在半路收起。
+ const box = (await pop.boundingBox())!;
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 4 });
+ await page.waitForTimeout(300);
+ assert.equal(await pop.isVisible(), true, '指针移到浮层上它就收起了');
+ await page.mouse.move(1, 1);
+ await pop.waitFor({ state: 'hidden', timeout: 5_000 });
+ await more.focus();
+ await page.keyboard.press('Tab');
+ await page.keyboard.press('Shift+Tab');
+ await pop.waitFor({ state: 'visible', timeout: 5_000 });
+ await page.keyboard.press('Escape');
+ assert.equal(await pop.isVisible(), false, 'Escape 收不起别名浮层');
+ const page_ = await layout(page);
+ assert.ok(page_.scrollWidth <= page_.viewportWidth, '别名浮层把页面撑出了横向滚动');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+
+ // 名字右边那枚按钮往左开的话,260px 的菜单越过名字压在头像上(用户报过)。
+ for (const viewport of [DESKTOP, MOBILE]) {
+ it(`名字与别名菜单从按钮左缘往右开,不盖住页头头像(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openProfiledPerformer(browser, viewport);
+ try {
+ const page = opened.page;
+ await page.locator('[data-namepick-toggle]').click();
+ await page.locator('[data-namepick-menu]').waitFor({ state: 'visible', timeout: 5_000 });
+ const box = await page.evaluate(() => {
+ const rect = (selector: string) => {
+ const b = document.querySelector(selector)!.getBoundingClientRect();
+ return { left: b.left, right: b.right, top: b.top, bottom: b.bottom };
+ };
+ return { menu: rect('[data-namepick-menu]'), portrait: rect('[data-entity-portrait]'), toggle: rect('[data-namepick-toggle]') };
+ });
+ const overlaps = box.menu.left < box.portrait.right && box.menu.right > box.portrait.left
+ && box.menu.top < box.portrait.bottom && box.menu.bottom > box.portrait.top;
+ assert.equal(overlaps, false, `名字菜单盖住了头像:${JSON.stringify(box)}`);
+ assert.ok(box.menu.left >= 0 && box.menu.right <= viewport.width, '名字菜单越出了视口');
+ if (!viewport.mobile) assert.ok(Math.abs(box.menu.left - box.toggle.left) < 1, '宽屏下菜单没有对齐按钮左缘');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+});
diff --git a/frontend/e2e/design-people.test.ts b/frontend/e2e/design-people.test.ts
new file mode 100644
index 000000000..7c9e4fc93
--- /dev/null
+++ b/frontend/e2e/design-people.test.ts
@@ -0,0 +1,1095 @@
+/* 设计决定:人物与厂牌资料页。读 `getComputedStyle` 断言用户定过的外观;共用的桩与浏览器生命周期在 `design-fixture.ts`。 */
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import type { Browser } from 'playwright-core';
+import { expectBody, layout, requiredEnv, settle, visit, VIEWPORTS } from './harness.ts';
+import {
+ DESKTOP, MOBILE, tokenColor, PIXEL, TASTE_FACE, WIDE, openCatalog, openCatalogFixture, openFollowManage,
+ openPerformer, openPhotoWall, photoWallFaces, PROFILED, openProfiledPerformer, popmenuShadow, SUGGEST,
+ stubSuggest, installDesignBrowser,
+} from './design-fixture.ts';
+
+describe('设计决定:人物与厂牌资料页', () => {
+ let browser: Browser;
+ installDesignBrowser((next) => { browser = next; });
+
+ for (const [viewport, split] of [[WIDE, true], [MOBILE, false]] as const) {
+ it(`搜索下拉按种类分页签;宽屏分两栏、人名带头像与近作、视频排成封面格,窄屏一栏(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', viewport);
+ try {
+ const page = opened.page;
+ const kinds = await stubSuggest(page);
+ await expectBody(page, '/', [page.locator('#grid [data-media-card][data-id]').first()]);
+ await settle(page);
+ if (viewport.mobile) await page.locator('#searchBtn').click();
+ await page.locator('#q').fill(SUGGEST.q);
+ const menu = page.locator('#searchMenu');
+ await menu.locator('[data-search-option="person"]').first().waitFor({ state: 'visible', timeout: 5_000 });
+ const shown = await page.evaluate(() => {
+ const menuBox = document.querySelector('#searchMenu')!.getBoundingClientRect();
+ const results = document.querySelector<HTMLElement>('#searchMenu [data-search-results]')!;
+ const columns = [...results.querySelectorAll(':scope > [data-search-col]')];
+ const person = document.querySelector('#searchMenu [data-search-option="person"]')!;
+ /* 命中的别名与作品数是这一行的注脚:字号小一档、字色退一档,作品数靠右。 */
+ const footnote = (selector: string) => {
+ const note = document.querySelector<HTMLElement>(`#searchMenu ${selector}`)!;
+ const row = note.closest('[data-search-option]')!;
+ const name = note.previousElementSibling!;
+ const [noteStyle, nameStyle] = [getComputedStyle(note), getComputedStyle(name)];
+ return {
+ smaller: parseFloat(noteStyle.fontSize) < parseFloat(nameStyle.fontSize),
+ quieter: noteStyle.color !== nameStyle.color,
+ trailing: Math.round(row.getBoundingClientRect().right - note.getBoundingClientRect().right),
+ };
+ };
+ return {
+ matched: footnote('[data-search-matched]'),
+ count: footnote('[data-search-n]'),
+ radius: getComputedStyle(person).borderRadius === getComputedStyle(document.documentElement).getPropertyValue('--control-radius').trim(),
+ tabs: [...document.querySelectorAll('#searchMenu [role="tab"]')].map((tab) => tab.textContent!.trim()),
+ tracks: getComputedStyle(results).gridTemplateColumns.split(' ').filter((track) => track !== 'none').length,
+ divider: getComputedStyle(results, '::before').content,
+ dividerHeight: parseFloat(getComputedStyle(results, '::before').height),
+ resultsHeight: results.getBoundingClientRect().height,
+ right: columns.at(-1)!.querySelector('[data-search-group]')?.getAttribute('data-kind'),
+ videoGrid: getComputedStyle(document.querySelector('#searchMenu [data-search-group][data-kind="asset"] [data-search-items]')!).display,
+ peeks: getComputedStyle(person.querySelector('[data-search-peeks]')!).display,
+ peekCount: person.querySelectorAll('[data-open-work]').length,
+ sub: person.querySelector('[data-search-sub]')!.textContent,
+ face: person.querySelector('[data-search-face] img')?.getAttribute('src'),
+ inView: menuBox.left >= 0 && menuBox.right <= innerWidth,
+ edges: [Math.round(menuBox.left), Math.round(innerWidth - menuBox.right)],
+ };
+ });
+ assert.deepEqual(shown.tabs, ['全部', '女优2', '厂牌1', '视频12'], '页签不是「全部」加各类命中数');
+ assert.equal(shown.tracks, split ? 2 : 0, split ? '宽屏下拉没有分两栏' : '窄屏下拉不该分栏');
+ assert.equal(shown.divider, split ? '""' : 'none', split ? '宽屏两栏之间没有分隔线' : '窄屏一栏不该有分隔线');
+ if (split) {
+ assert.ok(Math.abs(shown.dividerHeight - shown.resultsHeight) <= 1,
+ `分隔线高 ${shown.dividerHeight}px,两栏高 ${shown.resultsHeight}px`);
+ }
+ assert.equal(shown.right, 'asset', '视频不在最后一栏');
+ assert.equal(shown.videoGrid, split ? 'grid' : 'block', split ? '宽屏视频没排成封面格' : '窄屏视频该一行一部');
+ assert.equal(shown.peeks, split ? 'flex' : 'none', split ? '宽屏人名一行没摆近作' : '窄屏人名一行不摆近作');
+ assert.equal(shown.peekCount, 4);
+ assert.equal(shown.sub, '128 个视频 · Capsule Agency');
+ assert.equal(shown.face, '/entity-image?kind=performer&id=90301&thumb=1');
+ for (const [name, note] of [['别名', shown.matched], ['作品数', shown.count]] as const) {
+ assert.ok(note.smaller && note.quieter, `${name}没有退成注脚:${JSON.stringify(note)}`);
+ }
+ assert.equal(shown.count.trailing, 10, '作品数没有靠右贴着行的内边距');
+ assert.ok(shown.radius, '补全行的圆角不是 --control-radius');
+ assert.ok(shown.inView, '下拉栏越出了视口');
+ // 窄屏下拉栏盖过返回键那一列,和顶栏两侧一样各留 8,不缩进到搜索框底下。
+ if (viewport.mobile) assert.deepEqual(shown.edges, [8, 8], '窄屏下拉栏两侧留白不是 8');
+ const page_ = await layout(page);
+ assert.ok(page_.scrollWidth <= page_.viewportWidth, `下拉把页面撑出了横向滚动:${page_.offenders.join(',')}`);
+
+ await menu.getByRole('tab', { name: /^女优/ }).click();
+ await page.waitForFunction(() => document.querySelectorAll('#searchMenu [data-search-group][data-kind]').length === 1);
+ assert.equal(await menu.isVisible(), true, '点页签把下拉栏收掉了');
+ assert.ok(kinds.includes('performer'), '选了一类没有按这一类去拉满');
+ assert.equal(await menu.getByRole('tab', { name: /^女优/ }).getAttribute('aria-selected'), 'true');
+
+ // 人名那一行点开的是资料页,不是按名字再搜一遍。
+ await page.keyboard.press('ArrowDown');
+ await page.keyboard.press('Enter');
+ await page.waitForURL(/\/performers\//, { timeout: 5_000 });
+ assert.equal(decodeURIComponent(new URL(page.url()).pathname), '/performers/涼森れむ');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+
+ it('只看视频时封面格按列均分铺满整栏,每格有宽度上限', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', WIDE);
+ try {
+ const page = opened.page;
+ await stubSuggest(page);
+ await expectBody(page, '/', [page.locator('article[data-media-card][data-id]').first()]);
+ await settle(page);
+ await page.locator('#q').fill(SUGGEST.q);
+ const menu = page.locator('#searchMenu');
+ await menu.locator('[data-search-option="person"]').first().waitFor({ state: 'visible', timeout: 5_000 });
+ await menu.getByRole('tab', { name: /^视频/ }).click();
+ await page.waitForFunction(() => document.querySelectorAll('#searchMenu [data-search-group][data-kind]').length === 1);
+ const grid = await page.evaluate(() => {
+ const items = document.querySelector('#searchMenu [data-search-group][data-kind="asset"] [data-search-items]')!;
+ const box = items.getBoundingClientRect();
+ const cards = [...items.querySelectorAll('[data-search-option="work"]')].map((card) => card.getBoundingClientRect());
+ return {
+ rows: new Set(cards.map((card) => Math.round(card.top))).size,
+ widths: cards.map((card) => Math.round(card.width)),
+ slack: Math.round(box.right - cards.at(-1)!.right),
+ };
+ });
+ assert.equal(grid.rows, 1, '五部视频没排在同一行');
+ assert.ok(grid.slack <= 1, `封面格右侧空出 ${grid.slack}px`);
+ assert.ok(grid.widths.every((width) => width >= 96 && width <= 242), `封面宽度越出 96~242:${grid.widths.join('、')}`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('资料页照片墙:1280 宽小图 4 列、大图 2 列,手机 2 列;固定版式是方格,瀑布流按列填;格子是一块等图的空底', { timeout: 90_000 }, async () => {
+ const opened = await openPhotoWall(browser);
+ try {
+ const { page } = opened;
+ // 默认瀑布流、小图。
+ assert.deepEqual(await photoWallFaces(page), { display: 'block', columns: 4, gap: '10px', square: true });
+ const cell = await page.evaluate(() => {
+ const node = document.querySelector<HTMLElement>('[data-local-wall] [data-photo-cell]')!;
+ const style = getComputedStyle(node);
+ const head = document.querySelector('[data-photo-group]')!;
+ return {
+ radius: style.borderRadius, cursor: style.cursor, sunk: style.backgroundColor,
+ token: getComputedStyle(document.documentElement).getPropertyValue('--surface-radius').trim(),
+ alt: getComputedStyle(node.querySelector('img')!).color,
+ headTop: getComputedStyle(head).marginTop,
+ rows: [head, head.querySelector('b')!].map((node) => getComputedStyle(node).lineHeight),
+ code: getComputedStyle(head.querySelector('b')!).fontFamily,
+ meta: getComputedStyle(head.querySelector('[data-photo-group-meta]')!).marginLeft !== '0px',
+ };
+ });
+ assert.equal(cell.radius, cell.token, '照片格的圆角是 --surface-radius');
+ assert.equal(cell.cursor, 'zoom-in');
+ assert.equal(cell.alt, 'rgba(0, 0, 0, 0)', '等图时 alt 文件名不画出来');
+ assert.notEqual(cell.sunk, 'rgba(0, 0, 0, 0)', '格子自带一块沉底色');
+ assert.equal(cell.headTop, '28px', '每段上方留出段距');
+ assert.deepEqual(cell.rows, ['20px', '20px'], '段头一行 20px,番号不按自己的字号撑高');
+ assert.match(cell.code, /Cascadia Mono/, '段头番号是等宽字');
+ assert.ok(cell.meta, '来源与张数靠右');
+ assert.equal(await page.locator('#index [data-entity-more]').evaluate((node) => {
+ const style = getComputedStyle(node);
+ return `${style.height} ${style.borderRadius} ${style.fontSize} ${style.fontWeight}`;
+ }), '36px 10px 14px 500', '载入更多是 36px 高、10px 圆角的 secondary 按钮');
+ await page.locator('[data-entity-layout][aria-label="图片布局"] label:has(input[value="fixed"])').click();
+ await page.waitForFunction(() => document.querySelector('[data-local-wall]')?.getAttribute('data-layout') === 'fixed');
+ assert.deepEqual(await photoWallFaces(page), { display: 'grid', columns: 4, gap: '10px', square: true });
+ // 顶栏那枚大小键在照片档里换的是照片的大小档,一次请求都不发。
+ await page.locator('#density').click();
+ await page.waitForFunction(() => document.querySelector('[data-local-wall]')?.getAttribute('data-size') === 'big');
+ assert.deepEqual(await photoWallFaces(page), { display: 'grid', columns: 2, gap: '10px', square: true });
+ assert.equal(await page.locator('#density').getAttribute('title'), '当前:大图');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ const phone = await openPhotoWall(browser, MOBILE);
+ try {
+ const { page } = phone;
+ assert.deepEqual(await photoWallFaces(page), { display: 'block', columns: 2, gap: '10px', square: true });
+ await page.locator('[data-entity-layout][aria-label="图片布局"] label:has(input[value="fixed"])').click();
+ await page.waitForFunction(() => document.querySelector('[data-local-wall]')?.getAttribute('data-layout') === 'fixed');
+ assert.deepEqual(await photoWallFaces(page), { display: 'grid', columns: 2, gap: '8px', square: true });
+ assert.deepEqual(phone.problems, []);
+ } finally {
+ await phone.close();
+ }
+ });
+
+ it('空输入时搜索记录与推荐并排,两栏之间的分隔线从顶画到底', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', WIDE);
+ try {
+ const page = opened.page;
+ const history = Array.from({ length: 10 }, (_, at) => `搜索记录 ${at + 1}`);
+ await page.route(/\/api\/search-history\?/, (route) => route.fulfill({ json: { items: history } }));
+ await page.reload({ waitUntil: 'load' });
+ await expectBody(page, '/', [page.locator('article[data-media-card][data-id]').first()]);
+ await settle(page);
+ await page.locator('#q').click();
+ await page.locator('#searchMenu [data-search-results][data-split]').waitFor({ state: 'visible', timeout: 5_000 });
+ const split = await page.evaluate(() => {
+ const results = document.querySelector('#searchMenu [data-search-results]')!;
+ const [left, right] = [...results.querySelectorAll(':scope > [data-search-col]')].map((col) => col.getBoundingClientRect());
+ const box = results.getBoundingClientRect();
+ const line = getComputedStyle(results, '::before');
+ return {
+ box: box.height, left: left.height, right: right.height, line: parseFloat(line.height),
+ offset: parseFloat(line.left) + parseFloat(line.width) / 2 - ((left.right + right.left) / 2 - box.left),
+ };
+ });
+ assert.ok(split.right < split.left, `推荐一栏(${split.right}px)应比十条搜索记录(${split.left}px)短`);
+ assert.ok(Math.abs(split.line - split.box) <= 1, `分隔线高 ${split.line}px,两栏高 ${split.box}px`);
+ assert.ok(Math.abs(split.offset) <= 1, `分隔线偏离两栏之间的缝 ${split.offset}px`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('资料表的标签只列前四个,余下的收进「+N」,浮层进顶层列全部标签', { timeout: 60_000 }, async () => {
+ const opened = await openProfiledPerformer(browser, DESKTOP);
+ try {
+ const page = opened.page;
+ const cell = await page.locator('[data-entity-facts] dd[data-fact="tags"]').evaluate((dd) => ({
+ shown: [...dd.querySelectorAll(':scope > [data-fact-tag]')].map((tag) => tag.textContent!.trim()),
+ more: dd.querySelector(':scope > [data-hero-more="fact"]')?.textContent?.trim() ?? '',
+ }));
+ assert.deepEqual(cell.shown, PROFILED.profile.tags.slice(0, 4), '标签那一格不是前四个');
+ assert.equal(cell.more, '+5', '「+N」数的不是剩下那几个标签');
+ const pop = page.locator('#entityTagPop');
+ assert.equal(await pop.isVisible(), false);
+ await page.locator('[data-hero-more="fact"]').hover();
+ await pop.waitFor({ state: 'visible', timeout: 5_000 });
+ const shown = await pop.evaluate((element) => {
+ const box = element.getBoundingClientRect();
+ return {
+ topLayer: element.matches(':popover-open'),
+ inView: box.left >= 0 && box.right <= innerWidth && box.top >= 0 && box.bottom <= innerHeight,
+ title: element.querySelector('[data-hero-pop-head]')?.textContent?.trim(),
+ tags: [...element.querySelectorAll('[data-fact-tag]')].map((tag) => tag.textContent!.trim()),
+ };
+ });
+ assert.equal(shown.topLayer, true, '标签浮层没进顶层,会被资料卡的 overflow:hidden 裁掉');
+ assert.ok(shown.inView, '标签浮层越出了视口');
+ assert.equal(shown.title, '9 个标签');
+ assert.deepEqual(shown.tags, PROFILED.profile.tags);
+ await page.mouse.move(1, 1);
+ await pop.waitFor({ state: 'hidden', timeout: 5_000 });
+ // 点一下钉住:指针离开也不收,Escape 才收。
+ await page.locator('[data-hero-more="fact"]').click();
+ await page.mouse.move(1, 1);
+ await page.waitForTimeout(300);
+ assert.equal(await pop.isVisible(), true, '点按钉住的标签浮层指针一走就收了');
+ await page.keyboard.press('Escape');
+ assert.equal(await pop.isVisible(), false, 'Escape 收不起标签浮层');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('换头像的加号量在圆框上:整行比圆框高时也贴着圆框右下角', { timeout: 60_000 }, async () => {
+ const opened = await openProfiledPerformer(browser, { name: 'wide', width: 1440, height: 900, mobile: false });
+ try {
+ const page = opened.page;
+ const button = page.locator('[data-entity-portrait-wrap] [data-avatar-picker] button');
+ await button.waitFor({ timeout: 15_000 });
+ // 行有多高看她有多少资料、别名那一行折不折;这里直接把身份列撑高,量的是加号跟不跟圆框。
+ await page.addStyleTag({ content: '[data-entity-identity]{padding-block:40px}' });
+ const box = await page.evaluate(() => {
+ const rect = (element: Element) => element.getBoundingClientRect();
+ const wrap = rect(document.querySelector('[data-entity-portrait-wrap]')!);
+ const circle = rect(document.querySelector('[data-entity-portrait]')!);
+ const plus = rect(document.querySelector('[data-entity-portrait-wrap] [data-avatar-picker] button')!);
+ return { wrap: wrap.height, circle: { right: circle.right, bottom: circle.bottom, height: circle.height },
+ plus: { right: plus.right, bottom: plus.bottom } };
+ });
+ assert.ok(box.wrap > box.circle.height + 8, `这一行没有比圆框高,用例量不出偏移(行 ${box.wrap},圆框 ${box.circle.height})`);
+ // Tailwind 的 `right-1 bottom-1`:按钮离圆框外框右、下各 4px。
+ assert.ok(Math.abs(box.circle.bottom - box.plus.bottom - 4) < 1, `加号没有贴着圆框底边:${JSON.stringify(box)}`);
+ assert.ok(Math.abs(box.circle.right - box.plus.right - 4) < 1, `加号没有贴着圆框右边:${JSON.stringify(box)}`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('女优页头深色主题:资料表与别名浮层跟着主题取墨色和浮层底', { timeout: 60_000 }, async () => {
+ const opened = await openProfiledPerformer(browser, DESKTOP, 'dark');
+ try {
+ const page = opened.page;
+ const ink = await tokenColor(page, '#main', '--ink');
+ const muted = await tokenColor(page, '#main', '--muted');
+ const ground = await tokenColor(page, '#main', '--ground');
+ const facts = await page.locator('[data-entity-facts]').evaluate((dl) => ({
+ dd: getComputedStyle(dl.querySelector('dd')!).color, dt: getComputedStyle(dl.querySelector('dt')!).color,
+ }));
+ assert.equal(facts.dd, ink, '深色下资料表的值不是墨色');
+ assert.equal(facts.dt, muted, '深色下资料表的项名不是次级字色');
+ await page.locator('[data-hero-more="alias"]').hover();
+ const pop = page.locator('#entityAliasPop');
+ await pop.waitFor({ state: 'visible', timeout: 5_000 });
+ const { face, shadow } = await pop.evaluate((element) => {
+ const style = getComputedStyle(element);
+ return { face: style.backgroundColor, shadow: style.boxShadow };
+ });
+ assert.notEqual(face, 'rgba(0, 0, 0, 0)');
+ assert.notEqual(face, 'rgb(255, 255, 255)', '深色下别名浮层还是白底');
+ assert.equal(shadow, await popmenuShadow(page), '深色下别名浮层的落影和 .popmenu 不是同一副');
+ assert.notEqual(ground, 'rgb(255, 255, 255)', '主题没有切到深色');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('详情出演区每一组的标题、头像和名字共用一条左边缘', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', DESKTOP);
+ try {
+ const page = opened.page;
+ /* 演示库的作品没有女优与厂牌,身份数据按 `/api/item` 的 `entity_refs` 形状换进去;
+ 名字比头像宽的那种最容易看出错位,所以女优名取四个字。 */
+ await page.route(/\/api\/item\?/, async (route) => {
+ const payload = await (await route.fetch()).json();
+ Object.assign(payload, {
+ is_jav: true, performers: ['凉森玲梦'], studio: 'Prestige', creator: '',
+ entity_refs: {
+ creator: [], series: [],
+ performer: [{ id: 90_101, name: '凉森玲梦', has_image: true }],
+ studio: [{ id: 90_102, name: 'Prestige', has_image: false, has_logo: true }],
+ },
+ });
+ await route.fulfill({ json: payload });
+ });
+ const square = { contentType: 'image/svg+xml',
+ body: '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect width="200" height="200" fill="#888"/></svg>' };
+ await page.route(/\/entity-image\?/, (route) => route.fulfill(square));
+ await page.route(/\/logo\?/, (route) => route.fulfill(square));
+ await page.goto(new URL(`/item/${requiredEnv('PEACH_E2E_ITEM')}`, page.url()).href, { waitUntil: 'load' });
+ await page.locator('[data-item-identity] [data-id-group="studio"] [data-id-name]').waitFor({ timeout: 15_000 });
+ const edges = await page.evaluate(() => Object.fromEntries(
+ ['performer', 'studio'].map((kind) => {
+ const group = document.querySelector(`[data-item-identity] [data-id-group="${kind}"]`)!;
+ const name = document.createRange();
+ name.selectNodeContents(group.querySelector('[data-id-name]')!);
+ return [kind, {
+ label: group.querySelector('[data-id-label]')!.getBoundingClientRect().left,
+ face: group.querySelector('[data-id-face]')!.getBoundingClientRect().left,
+ name: name.getBoundingClientRect().left,
+ }];
+ })));
+ for (const [kind, edge] of Object.entries(edges)) {
+ assert.ok(Math.abs(edge.face - edge.label) < 0.5, `${kind} 组头像左缘 ${edge.face} 不在标题左缘 ${edge.label}`);
+ assert.ok(Math.abs(edge.name - edge.label) < 0.5, `${kind} 组名字左缘 ${edge.name} 不在标题左缘 ${edge.label}`);
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('人物页同台艺人的头像悬停和首页顶栏女优头像同一副:抬整格填充、不描圈', { timeout: 60_000 }, async () => {
+ const opened = await openPerformer(browser, DESKTOP);
+ try {
+ const page = opened.page;
+ const person = page.locator('[data-entity-foot] [data-related-performer]').first();
+ const face = () => person.evaluate((element) => {
+ const style = getComputedStyle(element), ring = getComputedStyle(element.querySelector('[data-hero-ring]')!);
+ return { fill: style.backgroundColor, ink: style.color, radius: style.borderRadius, padding: style.padding,
+ width: style.width, ring: ring.boxShadow, size: ring.width };
+ });
+ await page.mouse.move(0, 0);
+ const rest = await face();
+ await person.hover();
+ const hovered = await face();
+ // 首页那一格(board.css「首页顶部两排」):76px 宽、6/4px 内边距、12px 圆角,悬停铺
+ // primary-hover、字换主文字色,48px 圆头像不另描圈。
+ const home = {
+ fill: await tokenColor(page, '#main', '--color-background-primary-hover'),
+ ink: await tokenColor(page, '#main', '--color-text-primary'),
+ };
+ assert.equal(rest.fill, 'rgba(0, 0, 0, 0)', '没悬停就垫了底');
+ assert.deepEqual({ radius: hovered.radius, padding: hovered.padding, width: hovered.width, size: hovered.size },
+ { radius: '12px', padding: '6px 4px', width: '76px', size: '48px' }, '同台艺人那一格和首页头像格不是同一副几何');
+ assert.equal(hovered.fill, home.fill, '悬停没有铺首页那一档填充');
+ assert.equal(hovered.ink.replace(/\s/g, ''), home.ink.replace(/\s/g, ''), '悬停没有换成主文字色');
+ assert.equal(hovered.ring, 'none', '悬停还在给圆头像描圈');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('资料卡大位与同台艺人的头像按人脸框放大:图保持原比例、盖满圆框,不被预检的 max-width 夹住', { timeout: 60_000 }, async () => {
+ const name = '七沢みあ';
+ const opened = await visit(browser, '/', DESKTOP);
+ try {
+ const page = opened.page;
+ const focus = { box: TASTE_FACE };
+ await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
+ id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],
+ user_aliases: [], asset_count: 0, tags: [], links: [], metadata: {}, entry_links: [],
+ related_performers: [{ id: 90_002, k: '共演者', n: 1, rep: null, has_image: true, has_avatar: false,
+ avatar_focus: focus }],
+ has_image: true, has_avatar: false, avatar_focus: focus, representative_asset_id: null,
+ } }));
+ await page.route(/\/entity-image\?/, (route) => route.fulfill({
+ contentType: 'image/svg+xml',
+ body: `<svg xmlns="http://www.w3.org/2000/svg" width="${TASTE_FACE.imgW}" height="${TASTE_FACE.imgH}">`
+ + `<rect width="${TASTE_FACE.imgW}" height="${TASTE_FACE.imgH}" fill="#888"/></svg>`,
+ }));
+ await page.goto(new URL(`/performers/${encodeURIComponent(name)}`, page.url()).href, { waitUntil: 'load' });
+ for (const [where, selector] of [['大位', '[data-entity-portrait] > img[data-facebox]'],
+ ['同台艺人', '[data-hero-ring] > img[data-facebox]']] as const) {
+ const img = page.locator(selector).first();
+ await img.waitFor({ state: 'attached', timeout: 15_000 });
+ // 放大是图加载后 `avatarFrame` 写进内联 style 的;等到那一步落地再量。
+ await page.waitForFunction((element) => element instanceof HTMLImageElement
+ && element.complete && element.naturalWidth > 0 && element.style.width !== '',
+ await img.elementHandle(), { timeout: 15_000 });
+ const frame = await img.evaluate((element) => {
+ const ring = element.parentElement!.getBoundingClientRect();
+ const box = element.getBoundingClientRect();
+ return {
+ maxWidth: getComputedStyle(element).maxWidth, maxHeight: getComputedStyle(element).maxHeight,
+ ring: ring.width, width: box.width, aspect: box.width / box.height,
+ gaps: [box.left - ring.left, ring.right - box.right, box.top - ring.top, ring.bottom - box.bottom],
+ initial: getComputedStyle(element.parentElement!.querySelector('span')!).display,
+ };
+ });
+ assert.deepEqual([frame.maxWidth, frame.maxHeight], ['none', 'none'], `${where}的图被预检的 max-width 夹住`);
+ assert.ok(frame.width > frame.ring, `${where}没有按人脸框放大:图宽 ${frame.width}px,圆框 ${frame.ring}px`);
+ assert.ok(Math.abs(frame.aspect - TASTE_FACE.imgW / TASTE_FACE.imgH) < .02, `${where}的图宽高比 ${frame.aspect},被压扁了`);
+ assert.ok(frame.gaps.every((gap) => gap <= .5), `${where}的图没盖满圆框:${frame.gaps.join('、')}`);
+ if (where === '大位') assert.equal(frame.initial, 'none', '大位有图时首字母没有让位');
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ for (const viewport of [DESKTOP, MOBILE]) {
+ it(`资料卡外链的圆盘不垫底、社媒字形铺满圆盘;手机上那一排不换行、横滑,滚动层顶到卡沿(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openProfiledPerformer(browser, viewport);
+ try {
+ const row = await opened.page.locator('[data-entity-links]').evaluate((element) => {
+ const style = getComputedStyle(element);
+ const card = element.closest('[data-entity-card]')!.getBoundingClientRect();
+ const box = element.getBoundingClientRect();
+ const brand = element.querySelector('[data-link-icon="brand"]')!;
+ const glyph = brand.querySelector('svg')!.getBoundingClientRect(), plate = brand.getBoundingClientRect();
+ return {
+ wrap: style.flexWrap, overflowX: style.overflowX, justify: style.justifyContent,
+ edges: [box.left - card.left, card.right - box.right],
+ discs: [...element.querySelectorAll('[data-link-icon]')].map((disc) => getComputedStyle(disc).backgroundColor),
+ glyph: [Math.round(glyph.width), Math.round(glyph.height)], plate: [Math.round(plate.width), Math.round(plate.height)],
+ };
+ });
+ // 垫一层底会让圆盘比周围暗一档,看着像这条链接被禁用了。
+ assert.ok(row.discs.every((fill) => fill === 'rgba(0, 0, 0, 0)'), `外链圆盘垫了底色:${row.discs.join('、')}`);
+ assert.deepEqual(row.glyph, row.plate, '社媒字形没有铺满圆盘,场色的角露出底');
+ if (viewport.mobile) {
+ // 普通 `center` 在溢出时把前半排推到滚动起点之前,那几条滑不到。
+ assert.deepEqual([row.wrap, row.overflowX, row.justify], ['nowrap', 'auto', 'safe center'], '窄屏外链不是一行横滑');
+ assert.ok(row.edges.every((gap) => Math.abs(gap) < 0.5), `窄屏外链的滚动层没有顶到卡沿:${row.edges.join('、')}`);
+ } else {
+ assert.equal(row.wrap, 'wrap', '宽屏外链该换行,不横滑');
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it(`名字菜单:当前统称抬一档底色并打勾,其余行的勾位空着;手机上开关画 32px、命中区 44px,菜单行 44px(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openProfiledPerformer(browser, viewport);
+ try {
+ const page = opened.page;
+ const toggle = page.locator('[data-namepick-toggle]');
+ const hit = await toggle.evaluate((element) => {
+ const box = element.getBoundingClientRect(), after = getComputedStyle(element, '::after');
+ return { drawn: [Math.round(box.width), Math.round(box.height)], hit: [after.width, after.height] };
+ });
+ assert.deepEqual(hit.drawn, [32, 32], '名字旁那枚开关画出来不是 32px');
+ if (viewport.mobile) assert.deepEqual(hit.hit, ['44px', '44px'], '手机上开关的命中区不到 44px');
+ await toggle.click();
+ await page.locator('[data-namepick-menu]').waitFor({ state: 'visible', timeout: 5_000 });
+ const rows = await page.locator('[data-namepick-menu] [role="menuitemradio"]').evaluateAll((items) => items.map((item) => ({
+ checked: item.getAttribute('aria-checked') === 'true', fill: getComputedStyle(item).backgroundColor,
+ tick: getComputedStyle(item.querySelector('svg')!).visibility, height: item.getBoundingClientRect().height,
+ menu: getComputedStyle(item.closest('[data-namepick-menu]')!).backgroundColor,
+ })));
+ assert.deepEqual(rows.map((row) => row.checked), [true, false], '菜单里当前统称不是第一行,或不止一行被选中');
+ const [current, other] = rows;
+ assert.notEqual(current!.fill, 'rgba(0, 0, 0, 0)', '当前统称那一行没有抬底');
+ assert.notEqual(current!.fill, current!.menu, '当前统称那一行的底色和菜单面同色,看不出来');
+ assert.deepEqual([current!.tick, other!.tick], ['visible', 'hidden'], '勾没有只给当前统称,或未选中那行不留勾位');
+ assert.equal(other!.fill, 'rgba(0, 0, 0, 0)', '未选中那一行也抬了底');
+ const least = viewport.mobile ? 44 : 36;
+ const alias = await page.locator('[data-namepick-alias]').evaluate((item) => item.getBoundingClientRect().height);
+ assert.ok([...rows.map((row) => row.height), alias].every((height) => height >= least - 0.5), `菜单行矮于 ${least}px`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+
+ /* 尺寸按身份列有哪几行定:外链与看片那一行都在是 160px,缺一行是 120px。取行高百分比的话
+ 圆框宽、列宽、别名折行、行高绕成一个圈,折行多出的那截压进卡底内边距。
+ 有资料的女优默认只有外链那一行,两行都在的那位要补上看片标识与订阅开关;七沢みあ只有看片那一行。 */
+ for (const viewport of VIEWPORTS) {
+ it(`分类图标与视频数量同排,分类位于身份行最左侧(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openProfiledPerformer(browser, viewport, 'light', { identity_labels: ['女优','西方'] });
+ try {
+ const geometry = await opened.page.locator('[data-entity-alias="meta"]').evaluate((element) => {
+ const classification = element.querySelector('[data-identity-classification]')!;
+ const count = classification.nextElementSibling!;
+ const label = classification.getBoundingClientRect(), video = count.getBoundingClientRect();
+ const glyph = classification.querySelector('svg')!.getBoundingClientRect();
+ return { first: element.firstElementChild === classification, top: [label.top, video.top],
+ edges: [label.right, video.left], glyph: [glyph.width, glyph.height] };
+ });
+ assert.equal(geometry.first, true);
+ assert.ok(Math.abs(geometry.top[0]! - geometry.top[1]!) < 1, '分类与视频数量另起了行');
+ assert.ok(geometry.edges[0]! <= geometry.edges[1]!, '分类没有排在视频数量左侧');
+ assert.deepEqual(geometry.glyph, [16, 16]);
+ const measured = await layout(opened.page);
+ assert.ok(measured.scrollWidth <= measured.viewportWidth + 1);
+ assert.deepEqual(measured.offenders, []);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+ const openBothRows = (browser: Browser, viewport: typeof DESKTOP) => openProfiledPerformer(browser, viewport, 'light', {
+ entry_links: [
+ { site: 'minnano-av', label: 'みんなのAV', ordinal: '', slot: 'pill', mark: 'brand-minnano',
+ url: 'https://www.minnano-av.com/actress12345.html' },
+ { site: 'javdb', label: 'JavDB', ordinal: '', slot: 'mark', mark: 'mark-javdb', url: 'https://javdb.com/actors/NPD3' },
+ ],
+ feed: { following: false },
+ });
+ for (const [label, open, size] of [
+ ['外链与看片那一行都在', openBothRows, 160],
+ ['只有看片那一行', openPerformer, 120],
+ ['只有外链那一行', openProfiledPerformer, 120],
+ ] as const) {
+ it(`资料卡大位按身份列的行数定尺寸:${label}是 ${size}px 正圆,身份列不压进卡底内边距`, { timeout: 60_000 }, async () => {
+ const opened = await open(browser, DESKTOP);
+ try {
+ const box = await opened.page.locator('[data-entity-portrait]').evaluate((element) => {
+ const portrait = element.getBoundingClientRect();
+ const profile = element.closest('[data-entity-profile]')!.getBoundingClientRect();
+ const identity = element.closest('[data-entity-profile]')!.querySelector('[data-entity-identity]')!.getBoundingClientRect();
+ return { width: portrait.width, height: portrait.height, room: profile.bottom - identity.bottom };
+ });
+ assert.ok(Math.abs(box.height - size) < 1, `头像 ${box.height}px,应是 ${size}px`);
+ assert.ok(Math.abs(box.width - box.height) < 1, '头像不是正圆');
+ assert.ok(box.room >= 19.5, `身份列离卡底只剩 ${box.room}px,压进了 20px 的内边距`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+
+ it('看片那一行:两枚标识隔 32px、按 22px 字高对齐;MISSAV 按它站上的排字,AV 用它的粉;第二枚带序号', { timeout: 60_000 }, async () => {
+ const name = '七沢みあ';
+ const opened = await visit(browser, '/', DESKTOP);
+ try {
+ const page = opened.page;
+ await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
+ id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],
+ user_aliases: [], asset_count: 0, tags: [], related_performers: [], links: [], metadata: {},
+ has_image: false, has_avatar: false, avatar_focus: null, representative_asset_id: null,
+ entry_links: [
+ { site: 'javdb', label: 'JavDB', ordinal: '', slot: 'mark', mark: 'mark-javdb', url: 'https://javdb.com/actors/NPD3' },
+ { site: 'missav', label: 'MISSAV', ordinal: '2', slot: 'mark', mark: '', url: 'https://missav.ws/actresses/x' },
+ ],
+ } }));
+ await page.goto(new URL(`/performers/${encodeURIComponent(name)}`, page.url()).href, { waitUntil: 'load' });
+ await page.locator('[data-missav-mark]').waitFor({ timeout: 15_000 });
+ const marks = await page.locator('[data-entry-marks]').evaluate((row) => {
+ const wordmark = row.querySelector('[data-missav-mark]')!;
+ const [miss, av] = [...wordmark.children].map((part) => getComputedStyle(part).color);
+ return {
+ gap: getComputedStyle(row).columnGap,
+ javdb: row.querySelector('[data-entry-mark] svg')!.getBoundingClientRect().height,
+ family: getComputedStyle(wordmark).fontFamily, weight: getComputedStyle(wordmark).fontWeight,
+ miss, av, ink: getComputedStyle(wordmark.closest('a')!).color,
+ ordinal: row.querySelector('[data-entry-ordinal]')?.textContent ?? '',
+ hrefs: [...row.querySelectorAll('a[data-entry-mark]')].map((a) => a.getAttribute('href')),
+ };
+ });
+ assert.equal(marks.gap, '32px', '两枚标识的间距不是 32px');
+ assert.equal(Math.round(marks.javdb), 22, 'JavDB 标识的字高不是 22px');
+ assert.match(marks.family, /^Halant/, 'MISSAV 没有用 Halant 排字');
+ assert.equal(marks.weight, '500');
+ assert.equal(marks.miss, marks.ink, 'MISS 那半没有跟页面墨色');
+ assert.equal(marks.av, 'rgb(254, 98, 142)', 'AV 那半不是 MISSAV 的粉');
+ assert.equal(marks.ordinal, '2', '第二枚没带服务端编好的序号');
+ assert.deepEqual(marks.hrefs, ['https://javdb.com/actors/NPD3', 'https://missav.ws/actresses/x'], '入口地址不是服务端下发的那个');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('厂牌页资料卡:标识铺满方框;指回自家站的官网写「官方网站」,带站点圆标、字距 .02em', { timeout: 60_000 }, async () => {
+ const name = 'S1 NO.1 STYLE';
+ const opened = await visit(browser, '/', DESKTOP);
+ try {
+ const page = opened.page;
+ await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
+ id: 90_601, kind: 'studio', canonical_name: name, aliases: [], display_aliases: [], user_aliases: [],
+ asset_count: 3, tags: [], related_performers: [], labels: [], metadata: {}, entry_links: [],
+ has_image: false, has_avatar: false, has_logo: true, avatar_focus: null, representative_asset_id: null,
+ links: [{ link_id: 90_602, link_kind: 'official', clickable: true, label: 'S1', url: 'https://www.s1s1s1.com/' }],
+ } }));
+ // 标识比方框大,走铺满那条;比框小的走原尺寸居中,是另一条判据。
+ await page.route(/\/logo\?/, (route) => route.fulfill({
+ contentType: 'image/svg+xml',
+ body: '<svg xmlns="http://www.w3.org/2000/svg" width="600" height="600"><rect width="600" height="600" fill="#888"/></svg>',
+ }));
+ await page.route('**/link-mark**', (route) => route.fulfill({
+ status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
+ }));
+ await page.goto(new URL(`/studios/${encodeURIComponent(name)}`, page.url()).href, { waitUntil: 'load' });
+ const logo = page.locator('[data-entity-portrait] > img');
+ await logo.waitFor({ state: 'attached', timeout: 15_000 });
+ await page.waitForFunction((element) => element instanceof HTMLImageElement && element.complete && element.naturalWidth > 0,
+ await logo.elementHandle(), { timeout: 15_000 });
+ const face = await logo.evaluate((element) => {
+ const frame = element.parentElement!, box = element.getBoundingClientRect(), outer = frame.getBoundingClientRect();
+ return { shape: frame.getAttribute('data-entity-portrait'), radius: getComputedStyle(frame).borderTopLeftRadius,
+ fit: getComputedStyle(element).objectFit,
+ gaps: [box.left - outer.left, outer.right - box.right, box.top - outer.top, outer.bottom - box.bottom] };
+ });
+ assert.equal(face.shape, 'square');
+ assert.notEqual(face.radius, '50%', '厂牌的标识框画成了圆');
+ // 标识走「图比框小就别放大」那组:contain 不裁字标,比框大的按框收,所以照样铺满。
+ assert.equal(face.fit, 'contain', '厂牌标识被裁成了铺满');
+ assert.ok(face.gaps.every((gap) => Math.abs(gap) < 0.5), `标识没盖满方框:${face.gaps.join('、')}`);
+ const site = await page.locator('[data-entity-links] a[data-link="url"]').evaluate((a) => ({
+ text: a.querySelector('[data-link-label]')?.textContent ?? '',
+ spacing: parseFloat(getComputedStyle(a).letterSpacing) / parseFloat(getComputedStyle(a).fontSize),
+ mark: a.querySelector('[data-link-icon] img')?.getAttribute('src') ?? '',
+ referrer: a.querySelector('[data-link-icon] img')?.getAttribute('referrerpolicy') ?? '',
+ }));
+ assert.equal(site.text, '官方网站');
+ assert.ok(Math.abs(site.spacing - 0.02) < 0.001, `官网那一格的字距是 ${site.spacing}em`);
+ assert.deepEqual([site.mark, site.referrer], ['/link-mark?id=90602', 'no-referrer'], '官网没带本机合成的站点圆标');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('人物页骨架第一帧就带着这一位有的新作行与同台艺人,数据到了一次换齐、高度不变、封面不再等第二遍', { timeout: 60_000 }, async () => {
+ const name = '七沢みあ';
+ const opened = await visit(browser, '/', DESKTOP);
+ try {
+ await opened.page.route(/\/api\/entity\/shapes/, (route) => route.fulfill({ json: {
+ ok: true, entities: [{ id: 90_001, kind: 'performer', names: [name], parts: ['feed', 'costars'] }] } }));
+ // 骨架插进页面的那一刻就记下它带着哪几块:之后才补进去的,就是在骨架里跳了一下。
+ await opened.page.addInitScript(() => {
+ const first = { feed: null as boolean | null, foot: null as boolean | null, sheen: '' };
+ (window as unknown as { skeletonFirst: typeof first }).skeletonFirst = first;
+ new MutationObserver(() => {
+ const skeleton = document.querySelector('[data-skeleton="entity/performer"]');
+ if (!skeleton || first.feed !== null) return;
+ first.feed = !!skeleton.querySelector('.feednew');
+ first.foot = !!skeleton.querySelector('.entityfoot');
+ // 骨架卡的微光和骨架同一帧就在:晚一步的话,那一步里露出来的是封面格的黑底。
+ const pic = skeleton.querySelector('.feednewskeleton .pic.imgwait');
+ first.sheen = pic ? getComputedStyle(pic, '::after').opacity : '';
+ }).observe(document, { childList: true, subtree: true });
+ // 真实库上启动脚本发出名单请求后还要连续跑四五百毫秒,名单的响应就在这段时间里到、
+ // 排在队里。这里在发请求的同一个任务末尾占住主线程 700ms,把那一段复现出来。
+ const fetch = window.fetch;
+ let blocked = false;
+ window.fetch = (...args) => {
+ if (!blocked && String(args[0]).includes('/api/entity/shapes')) {
+ blocked = true;
+ queueMicrotask(() => { const end = performance.now() + 700; while (performance.now() < end); });
+ }
+ return fetch(...args);
+ };
+ });
+ let release = () => {};
+ const held = new Promise<void>((resolve) => { release = resolve; });
+ await opened.page.route(/\/api\/entity\?/, async (route) => {
+ await held;
+ await route.fulfill({ json: {
+ id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],
+ user_aliases: [], asset_count: 0, tags: [],
+ related_performers: [{ id: 90_002, k: '共演者', n: 1, rep: null, has_image: false,
+ has_avatar: false, avatar_focus: null }],
+ links: [], metadata: {}, has_image: false, has_avatar: false, avatar_focus: null,
+ representative_asset_id: null, entry_links: [], feed: { following: true },
+ } });
+ });
+ await opened.page.route(/\/api\/feeds\/discoveries\?/, (route) => route.fulfill({ json: {
+ ok: true, more: false, items: [{
+ id: 1, code: 'ABC-001', title: '标题', link: 'https://javdb.com/v/x', cover_url: null,
+ has_cover: true, cover_frame: null, poster_box: null, release_date: '2026-09-01',
+ studio: '厂牌', performers: name, source_name: '', read: false, ignored: false,
+ scrape_error: null }] } }));
+ // 封面比数据晚到一截:整页要等它,而不是先换上真卡、再在封面格里微光一遍。
+ await opened.page.route(/\/cover\?code=ABC-001/, async (route) => {
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ await route.fulfill({ contentType: 'image/png', body: Buffer.from(PIXEL, 'base64') });
+ });
+ await opened.page.goto(new URL(`/performers/${encodeURIComponent(name)}`,
+ opened.page.url()).href, { waitUntil: 'load' });
+ const skeleton = opened.page.locator('[data-skeleton="entity/performer"]');
+ await skeleton.locator('.feednew .feednewskeleton').first().waitFor({ timeout: 15_000 });
+ const before = await skeleton.evaluate((element) => {
+ const row = element.querySelector('.feednew')!;
+ const foot = element.querySelector('.entityhero > .entityfoot');
+ // 同一个 `.pic.imgwait` 放在新作那一行外面,它的微光就是全站等待态那一种。
+ const probe = document.createElement('div');
+ probe.className = 'pic imgwait';
+ document.querySelector('#main')!.append(probe);
+ const plain = getComputedStyle(probe, '::after').backgroundImage;
+ probe.remove();
+ return { height: row.getBoundingClientRect().height,
+ footHeight: foot?.getBoundingClientRect().height ?? 0,
+ between: !!row.previousElementSibling?.matches('[data-filter-frame]')
+ && !!row.nextElementSibling?.matches('.entitysection'),
+ sheen: getComputedStyle(row.querySelector('.pic.imgwait')!, '::after').backgroundImage, plain,
+ first: (window as unknown as { skeletonFirst: { feed: boolean; foot: boolean; sheen: string } }).skeletonFirst };
+ });
+ assert.ok(before.between, '骨架里的新作那一行不在筛选框和作品之间');
+ const { sheen, ...parts } = before.first;
+ assert.deepEqual(parts, { feed: true, foot: true }, '骨架先画了一版,新作行或同台艺人是后来才补进去的');
+ assert.equal(sheen, '1', '新作骨架卡的微光晚于骨架出现,中间露出封面格的黑底');
+ assert.ok(before.footHeight > 0, '骨架的资料卡底没有同台艺人那一条');
+ assert.equal(before.sheen, before.plain, '新作骨架的微光另起了一种颜色');
+ // 画好的页面上那一行一出现就得是真卡:再露一回它自己的骨架,就是同一行等了两遍。
+ await opened.page.evaluate(() => {
+ const seen = { second: false };
+ (window as unknown as { feedSeen: typeof seen }).feedSeen = seen;
+ new MutationObserver(() => {
+ if (document.querySelector('[data-feed-new] .feednewskeleton')) seen.second = true;
+ }).observe(document.querySelector('#index')!, { childList: true, subtree: true });
+ });
+ release();
+ const row = opened.page.locator('[data-feed-new]');
+ await row.locator('[data-feed-id]').waitFor({ timeout: 15_000 });
+ const after = await row.evaluate((element) => ({
+ height: element.getBoundingClientRect().height, busy: element.getAttribute('aria-busy'),
+ waiting: element.querySelectorAll('[data-feed-id] .pic.imgwait').length,
+ footHeight: document.querySelector('[data-entity-card] > [data-entity-foot]')?.getBoundingClientRect().height ?? 0,
+ second: (window as unknown as { feedSeen: { second: boolean } }).feedSeen.second }));
+ assert.equal(after.height, before.height, '占位行和到货的那一行不一样高,下面的作品网格会跳');
+ assert.equal(after.footHeight, before.footHeight, '同台艺人那一条占位和真的不一样高,资料卡会伸缩');
+ assert.equal(after.busy, null);
+ assert.equal(after.second, false, '整页画出来之后新作那一行又单独骨架了一轮');
+ assert.equal(after.waiting, 0, '骨架退场后封面格里又微光了一遍');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('卡片悬停面不顶到邻卡,三处卡片网格同一副列距', { timeout: 60_000 }, async () => {
+ const opened = await openCatalog(browser);
+ try {
+ const card = opened.page.locator('#grid [data-media-grid] > [data-media-card]').first();
+ await card.hover();
+ const geometry = await card.evaluate((element) => {
+ const box = element.getBoundingClientRect();
+ const neighbor = [...element.parentElement!.children].find((other) => other !== element
+ && Math.abs(other.getBoundingClientRect().top - box.top) < 1)!;
+ const spread = Number(/0px 0px 0px (\d+(?:\.\d+)?)px/.exec(getComputedStyle(element).boxShadow)?.[1]);
+ // 壳画的骨架网格和关注页岛的视频列表不在首页这叠卡里:各挂一个同形的空壳读列距。
+ const columnGap = (build: (probe: HTMLElement) => HTMLElement) => {
+ const probe = document.createElement('div');
+ const host = build(probe);
+ document.querySelector('#main')!.append(host);
+ const gap = parseFloat(getComputedStyle(probe).columnGap);
+ host.remove();
+ return gap;
+ };
+ return {
+ spread, clearance: neighbor.getBoundingClientRect().left - (box.right + spread),
+ home: parseFloat(getComputedStyle(element.parentElement!).columnGap),
+ skeleton: columnGap((probe) => { probe.className = 'grid'; return probe }),
+ follow: columnGap((probe) => {
+ const island = document.createElement('div');
+ island.className = 'peach-react';
+ probe.setAttribute('data-follow-list', '');
+ island.append(probe);
+ return island;
+ }),
+ };
+ });
+ assert.ok(geometry.spread > 0, '卡片悬停面没有往盒外铺');
+ assert.ok(geometry.clearance >= geometry.spread,
+ `悬停面离邻卡只剩 ${geometry.clearance}px,比它自己往外铺的 ${geometry.spread}px 还窄`);
+ assert.equal(geometry.skeleton, geometry.home, '壳画的骨架网格的列距和首页不一样,真卡换上来时整排挪位');
+ assert.equal(geometry.follow, geometry.home, '关注页视频列表的列距和首页不一样');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('跳过渲染的元信息区不裁掉贴着边的头像悬停描边和焦点环', { timeout: 60_000 }, async () => {
+ /* 演示库的作品都未归属,头像是不可聚焦的 `<span>`;首张卡归给一位女优,头像才是按钮。 */
+ const opened = await openCatalogFixture(browser, (payload) => {
+ const item = payload.items[0];
+ if (!item) throw new Error('演示目录没有可替换的卡片');
+ item.creator = '';
+ item.performers = ['演示演员'];
+ item.performer_total = 1;
+ item.performer_entities = [{ id: 90_000, name: '演示演员', has_image: false }];
+ });
+ try {
+ /* 视口外跳过渲染连带 paint containment,元信息区里画出 padding box 的像素一律裁掉;
+ 几何照算,所以这里比的是描边外沿与 padding box,不是与内容盒。头像贴着内容盒的
+ 左缘和上缘。这条不读 `overflow-clip-margin`:Safari 不认它,裁切边只能靠盒子本身。 */
+ const { page } = opened;
+ const avatar = page.locator('#grid [data-media-grid] > [data-media-card] [data-media-meta] > button[data-media-avatar]').first();
+ const edges = () => avatar.evaluate((element) => {
+ const meta = element.closest('[data-media-meta]')!;
+ const style = getComputedStyle(element);
+ const shadow = Number(/0px 0px 0px (\d+(?:\.\d+)?)px/.exec(style.boxShadow)?.[1] ?? 0);
+ const outline = style.outlineStyle === 'none' ? 0
+ : parseFloat(style.outlineWidth) + parseFloat(style.outlineOffset);
+ const ring = Math.max(shadow, outline);
+ const box = element.getBoundingClientRect();
+ const clip = meta.getBoundingClientRect();
+ const left = clip.left + meta.clientLeft, top = clip.top + meta.clientTop;
+ return {
+ contained: getComputedStyle(meta).contentVisibility === 'auto',
+ focused: element.matches(':focus-visible'), ring,
+ // 描边外沿到裁切边还剩多少,四边取最小的那一边。
+ room: Math.min(box.left - ring - left, box.top - ring - top,
+ left + meta.clientWidth - (box.right + ring), top + meta.clientHeight - (box.bottom + ring)),
+ };
+ });
+ await avatar.hover();
+ const hovered = await edges();
+ assert.ok(hovered.contained, '首页卡片的元信息区不再跳过渲染:这条用例守的裁切前提变了,改用例');
+ assert.ok(hovered.ring > 0, '头像悬停没有描边');
+ assert.ok(hovered.room >= -.5, `头像悬停描边越过了元信息区的裁切边 ${-hovered.room}px,那一截会被裁掉`);
+ await page.mouse.move(0, 0);
+ await page.keyboard.press('Tab');
+ await avatar.focus();
+ const focused = await edges();
+ assert.ok(focused.focused && focused.ring > 0, '键盘聚焦的头像没有焦点环');
+ assert.ok(focused.room >= -.5, `头像焦点环越过了元信息区的裁切边 ${-focused.room}px,那一截会被裁掉`);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('头像圆框里的图按人脸框写进的内联尺寸不被岛里的预检夹回框宽', { timeout: 60_000 }, async () => {
+ /* 演示库没有实体图,往首张卡的头像框里塞一张按人脸框放大的图:宽超过框宽时图就该那么宽,
+ 由圆框的 overflow 裁;被夹回框宽的话脸偏到左边,右侧露出底下的首字母。 */
+ const opened = await openCatalogFixture(browser, (payload) => {
+ const item = payload.items[0];
+ if (!item) throw new Error('演示目录没有可替换的卡片');
+ item.creator = '';
+ item.performers = ['演示演员'];
+ item.performer_total = 1;
+ item.performer_entities = [{ id: 90_000, name: '演示演员', has_image: false }];
+ });
+ try {
+ const avatar = opened.page.locator('#grid [data-media-grid] > [data-media-card] [data-media-meta] > button[data-media-avatar]').first();
+ const framed = await avatar.evaluate((element) => {
+ const img = document.createElement('img');
+ img.setAttribute('style', 'position:absolute;inset:-25% auto auto 0;width:150%;height:195%');
+ element.appendChild(img);
+ const frame = element.getBoundingClientRect();
+ const box = img.getBoundingClientRect();
+ const style = getComputedStyle(img);
+ return { maxWidth: style.maxWidth, maxHeight: style.maxHeight,
+ width: box.width / frame.width, height: box.height / frame.height };
+ });
+ assert.equal(framed.maxWidth, 'none', '头像图还带着预检的 max-width');
+ assert.equal(framed.maxHeight, 'none', '头像图还带着 max-height');
+ assert.ok(Math.abs(framed.width - 1.5) <= .02, `按人脸框放大到 1.5 倍框宽的图被夹成了 ${framed.width} 倍`);
+ assert.ok(Math.abs(framed.height - 1.95) <= .02, `按人脸框放大到 1.95 倍框高的图被夹成了 ${framed.height} 倍`);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('亮暗按钮保持尺寸与悬停面色,卡片和回执保持接触阴影', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/stats', DESKTOP);
+ try {
+ // 选中的那张页签按基线收掉接触阴影,读旁边没选中的一张。
+ const card = opened.page.locator('#main [class~="shadow-card"]:not([data-selected])').first();
+ await card.waitFor({ timeout: 15_000 });
+ await settle(opened.page);
+ const checkSecondaryButton = async () => {
+ await opened.page.mouse.move(0, 0);
+ const dimensions = await opened.page.evaluate(() => {
+ const holder = document.createElement('div');
+ holder.style.cssText = 'position:fixed;right:16px;bottom:16px;z-index:10000';
+ const button = document.createElement('button');
+ button.className = 'geist-button';
+ button.dataset.buttonProbe = '';
+ button.textContent = '操作';
+ holder.append(button);
+ document.body.append(holder);
+ const style = getComputedStyle(button);
+ return [style.boxSizing, style.height, style.paddingTop, style.paddingRight,
+ style.borderTopWidth, style.display];
+ });
+ assert.deepEqual(dimensions, ['border-box', '36px', '8px', '12px', '1px', 'inline-flex']);
+ const button = opened.page.locator('[data-button-probe]');
+ try {
+ const idle = await button.evaluate(element => getComputedStyle(element).backgroundColor);
+ assert.equal(idle, await tokenColor(opened.page, 'body', '--color-background-primary-default'));
+ const border = await button.evaluate(element => getComputedStyle(element).borderTopColor);
+ await button.hover();
+ await settle(opened.page);
+ const hovered = await button.evaluate(element => getComputedStyle(element).backgroundColor);
+ assert.equal(hovered, await tokenColor(opened.page, 'body', '--control-hover'));
+ assert.equal(await button.evaluate(element => getComputedStyle(element).borderTopColor), border);
+ } finally {
+ await button.evaluate(element => element.parentElement!.remove());
+ }
+ };
+ /* Tailwind 把阴影 token 的字面值抄进工具类,`.dark` 里改 `--shadow-*` 够不着它;
+ 旧样式表里写死的浅色阴影同样不跟主题走。读三类来源各一处的计算值。 */
+ const alphas = () => opened.page.evaluate(() => {
+ const strongest = (shadow: string) => Math.max(0, ...[...shadow.matchAll(
+ /rgba\(0, 0, 0, ([\d.]+)\)|rgb\(0, 0, 0\)/g)].map((match) => (match[1] ? Number(match[1]) : 1)));
+ const probe = (html: string, parent: Element = document.body) => {
+ const holder = document.createElement('div');
+ holder.innerHTML = html;
+ const element = holder.firstElementChild!;
+ // 挂在 React 岛外面:岛里的重置会把旧样式表的按钮阴影清掉。
+ parent.append(element);
+ const shadow = getComputedStyle(element).boxShadow;
+ element.remove();
+ return strongest(shadow);
+ };
+ return {
+ card: strongest(getComputedStyle(document.querySelector('#main [class~="shadow-card"]:not([data-selected])')!).boxShadow),
+ button: probe('<button class="geist-button" type="button">键</button>'),
+ // Toast 的面只在 #toasts 里成立:阴影写在 Sonner 那一条的属性选择器上。
+ toast: probe('<li data-sonner-toast data-styled="true">回执</li>', document.getElementById('toasts')!),
+ };
+ });
+ await opened.page.evaluate(() => {
+ document.documentElement.dataset.theme = 'light';
+ document.documentElement.classList.remove('dark');
+ });
+ const light = await alphas();
+ await checkSecondaryButton();
+ // `web/app.js` 的 `applyTheme('dark')` 就是这两句;这里只借它换一次配色。
+ await opened.page.evaluate(() => {
+ document.documentElement.dataset.theme = 'dark';
+ document.documentElement.classList.add('dark');
+ });
+ const dark = await alphas();
+ await checkSecondaryButton();
+ for (const key of Object.keys(light) as Array<keyof typeof light>) {
+ assert.ok(light[key] > 0 && light[key] < .2, `浅色下 ${key} 的阴影 ${light[key]} 不在浅色那一档`);
+ assert.ok(dark[key] > light[key] && dark[key] <= .2,
+ `暗色 ${key} 阴影应保留接触感而不形成重边:${dark[key]}`);
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ for (const viewport of [DESKTOP, MOBILE]) {
+ it(`JAV 订阅卡片包含分页与贴边底栏(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openFollowManage(browser, viewport);
+ try {
+ const page = opened.page;
+ await page.route('**/api/feeds', route => route.fulfill({ json: {
+ unread: 81, sources: Array.from({ length: 25 }, (_, i) => ({
+ id: i + 1, kind: 'javdb-actor', kind_label: 'JAV 订阅', name: `测试订阅 ${i + 1}`,
+ url: `https://example.com/actors/${i + 1}`, entity_id: null, entity_name: null,
+ has_image: false, enabled: true, interval_minutes: 360, last_fetched_at: null,
+ last_error: null, last_new_count: 0, seen: 0,
+ })),
+ } }));
+ await page.reload({ waitUntil: 'load' });
+ await page.getByRole('tab', { name: 'JAV 订阅源', exact: true }).click();
+ const card = page.getByRole('region', { name: 'JAV 订阅列表', exact: true });
+ await card.getByText('1–20 / 25 个订阅源', { exact: true }).waitFor();
+ assert.equal(await card.locator('[role="row"][data-key]').count(), 20);
+ await card.getByRole('button', { name: '下一页', exact: true }).click();
+ await card.getByText('21–25 / 25 个订阅源', { exact: true }).waitFor();
+ assert.equal(await card.locator('[role="row"][data-key]').count(), 5);
+ for (const theme of ['light', 'dark']) {
+ await page.evaluate(value => {
+ document.documentElement.dataset.theme = value;
+ document.documentElement.classList.toggle('dark', value === 'dark');
+ }, theme);
+ const surface = await card.evaluate(element => {
+ const footer = element.querySelector('footer')!;
+ const box = element.getBoundingClientRect();
+ const bottom = footer.getBoundingClientRect();
+ return { background: getComputedStyle(element).backgroundColor,
+ footerBackground: getComputedStyle(footer).backgroundColor,
+ left: bottom.left - box.left, right: box.right - bottom.right,
+ bottom: box.bottom - bottom.bottom };
+ });
+ assert.notEqual(surface.background, 'rgba(0, 0, 0, 0)');
+ assert.notEqual(surface.background, surface.footerBackground);
+ for (const edge of ['left', 'right', 'bottom'] as const) assert.ok(Math.abs(surface[edge]) <= 1);
+ const dimensions = await layout(page);
+ assert.ok(dimensions.scrollWidth <= dimensions.viewportWidth + 1, JSON.stringify(dimensions));
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close(); }
+ });
+ it(`关注分类使用 Pills,凭据按要求分组并带描边(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openFollowManage(browser, viewport);
+ try {
+ const page = opened.page;
+ const tabs = page.getByRole('tablist', { name: '关注管理区域' });
+ for (const theme of ['light', 'dark']) {
+ await page.evaluate((value) => {
+ document.documentElement.dataset.theme = value;
+ document.documentElement.classList.toggle('dark', value === 'dark');
+ }, theme);
+ await tabs.getByRole('tab', { name: /来源和凭证/ }).click();
+ const face = await tabs.evaluate((element) => {
+ const selected = element.querySelector('[aria-selected=true]')!;
+ return { track: getComputedStyle(element).backgroundColor,
+ selected: getComputedStyle(selected).backgroundColor,
+ shadow: getComputedStyle(selected).boxShadow };
+ });
+ assert.equal(face.track, 'rgba(0, 0, 0, 0)', 'Pills 容器应透明');
+ assert.notEqual(face.selected, face.track, '当前分类应有独立底色');
+ assert.equal(face.shadow, 'none', 'Pills 不使用浮起滑块');
+ for (const name of ['可配置凭据', '不需要凭据', '暂不支持']) {
+ const group = page.getByRole('region', { name, exact: true });
+ const rows = await group.evaluate((element) => {
+ const style = getComputedStyle(element.lastElementChild!);
+ return { shadow: style.boxShadow, width: style.borderTopWidth,
+ border: style.borderTopColor, background: style.backgroundColor };
+ });
+ assert.equal(rows.shadow, 'none');
+ assert.equal(rows.width, '1px');
+ assert.notEqual(rows.border, rows.background);
+ }
+ assert.match(await page.getByRole('region', { name: '不需要凭据', exact: true }).innerText(), /Kemono/);
+ assert.match(await page.getByRole('region', { name: '暂不支持', exact: true }).innerText(), /OnlyFans/);
+ await tabs.getByRole('tab', { name: /来源和凭证/ }).focus();
+ await page.keyboard.press('Home');
+ await page.keyboard.press('Enter');
+ assert.equal(await tabs.getByRole('tab', { name: '关注列表', exact: true }).getAttribute('aria-selected'), 'true');
+ const dimensions = await layout(page);
+ assert.ok(dimensions.scrollWidth <= dimensions.viewportWidth + 1, JSON.stringify(dimensions));
+ }
+ await page.route('**/api/follow/resolve', (route) => route.fulfill({
+ status: 200, contentType: 'application/json', body: JSON.stringify({
+ status: 'done', results: [{ line: '主题测试来源', candidates: [{
+ provider: 'kemono', provider_label: 'Kemono', label: '主题测试候选', url: 'https://example.com/creator',
+ }] }],
+ }),
+ }));
+ await tabs.getByRole('tab', { name: '添加关注', exact: true }).click();
+ await page.getByRole('textbox', { name: '来源链接、名字或 id' }).fill('主题测试来源');
+ await page.getByRole('button', { name: '查找', exact: true }).click();
+ const result = page.getByText('主题测试来源', { exact: true }).locator('..');
+ await result.waitFor();
+ for (const theme of ['light', 'dark']) {
+ await page.evaluate((value) => {
+ document.documentElement.dataset.theme = value;
+ document.documentElement.classList.toggle('dark', value === 'dark');
+ }, theme);
+ const surface = await result.evaluate((element) => {
+ const s = getComputedStyle(element);
+ return { shadow: s.boxShadow, width: s.borderTopWidth, border: s.borderTopColor, bg: s.backgroundColor };
+ });
+ assert.equal(surface.shadow, 'none');
+ assert.equal(surface.width, '1px');
+ assert.notEqual(surface.border, surface.bg, '结果分组必须有可辨认边界');
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close(); }
+ });
+ }
+});
diff --git a/frontend/e2e/design-settings.test.ts b/frontend/e2e/design-settings.test.ts
new file mode 100644
index 000000000..75480e7b1
--- /dev/null
+++ b/frontend/e2e/design-settings.test.ts
@@ -0,0 +1,871 @@
+/* 设计决定:设置、口味、统计与筛选玻璃。读 `getComputedStyle` 断言用户定过的外观;共用的桩与浏览器生命周期在 `design-fixture.ts`。 */
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import type { Browser, Page } from 'playwright-core';
+import { openFollowFeed } from './follow-fixture.ts';
+import { configurationBody, expectBody, requiredEnv, settle, visit, VIEWPORTS } from './harness.ts';
+import { openHome, openPanel, ORDER, PANEL, stubServer } from './settings-fixture.ts';
+import {
+ DESKTOP, MOBILE, tokenColor, settledRun, openActivity, TASTE_CATEGORIES, TASTE_FACE, openTaste, openIndexPage,
+ farthestShadow, holdApi, openLightbox, installDesignBrowser,
+} from './design-fixture.ts';
+
+describe('设计决定:设置、口味、统计与筛选玻璃', () => {
+ let browser: Browser;
+ installDesignBrowser((next) => { browser = next; });
+
+ it('使用空间按字节量级的真实容量画出已用那一段,每个卷一行、不越出卡片', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/stats', DESKTOP);
+ try {
+ const page = opened.page;
+ const TB = 1024 ** 4;
+ const volumes = [
+ { kind: 'system', label: '系统盘', root: 'C:\\', online: true, total: 2 * TB, used: 1.8 * TB, free: .2 * TB },
+ { kind: 'media', label: '资源盘', root: 'R:\\media', online: false, total: null, used: null, free: null },
+ { kind: 'media', label: 'PikPak 网盘', root: 'A:\\', online: true, total: 10240 * TB, used: 0, free: 10240 * TB },
+ ];
+ await page.route(/\/api\/stats(?:\?|$)/, async (route) => {
+ const json = await (await route.fetch()).json();
+ await route.fulfill({ json: { ...json, storage_volumes: volumes, storage_summary: {
+ volumes: 3, online: 2, measured: 2, free: 10240.2 * TB, used: 1.8 * TB, total: 10242 * TB,
+ } } });
+ });
+ await page.reload({ waitUntil: 'load' });
+ await page.getByRole('tab', { name: /使用空间/ }).click();
+ const panel = page.locator('[role="tabpanel"]').first();
+ await panel.locator('[role="progressbar"]').first().waitFor({ state: 'visible', timeout: 15_000 });
+ await settle(page);
+ const shown = await panel.evaluate((element) => {
+ const card = element.firstElementChild!;
+ const cardBox = card.getBoundingClientRect();
+ const detail = card.lastElementChild!.getBoundingClientRect();
+ return {
+ filled: [...element.querySelectorAll('[role="progressbar"]')].map((bar) =>
+ Math.round(bar.querySelectorAll('rect')[1]!.getBoundingClientRect().width / bar.getBoundingClientRect().width * 100)),
+ rows: [...element.querySelectorAll('article')].map((row) => getComputedStyle(row).borderBottomWidth),
+ overflow: detail.right - (cardBox.right - parseFloat(getComputedStyle(card).paddingRight)),
+ text: element.textContent ?? '',
+ };
+ });
+ assert.deepEqual(shown.filled, [90, 0], '进度条画出来的已用比例不对');
+ assert.deepEqual(shown.rows, ['1px', '1px', '0px'], '卷与卷之间没有覆盖率那样的分隔线');
+ assert.ok(shown.overflow <= .5, `使用空间的详情越出卡片内边距 ${shown.overflow}px`);
+ assert.ok(shown.text.includes('10.00 PB'), '网盘容量没按 PB 写');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ for (const viewport of VIEWPORTS) {
+ it(`口味维度排名宽屏跟雷达那一栏等高、窄屏按条数给高度,图拉高时条不变粗(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openTaste(browser, viewport);
+ try {
+ const page = opened.page;
+ const bars = page.locator('section[aria-label="口味维度排名"]');
+ await bars.locator('.recharts-bar-rectangle').first().waitFor({ state: 'visible', timeout: 15_000 });
+ await settle(page);
+ const shown = await page.locator('section[aria-label="浏览器画像"]').evaluate((section) => {
+ const radar = section.firstElementChild!.getBoundingClientRect();
+ const ranked = section.querySelector('section[aria-label="口味维度排名"]')!.getBoundingClientRect();
+ return {
+ radar: radar.height,
+ ranked: ranked.height,
+ thickness: [...section.querySelectorAll('.recharts-bar-rectangle')]
+ .map((bar) => bar.getBoundingClientRect().height),
+ };
+ });
+ assert.equal(shown.thickness.length, TASTE_CATEGORIES.length);
+ if (viewport.mobile) {
+ assert.ok(shown.ranked >= 32 * TASTE_CATEGORIES.length,
+ `窄屏排行条只有 ${shown.ranked}px,${TASTE_CATEGORIES.length} 条挤不下`);
+ } else {
+ assert.ok(Math.abs(shown.ranked - shown.radar) < 2,
+ `排行条 ${shown.ranked}px,雷达那一栏 ${shown.radar}px,两栏不等高`);
+ }
+ // 26 是一格 32 里默认留出的粗细;图被拉高时多出来的高度拉开条距,不进条本身。
+ assert.ok(shown.thickness.every((height) => height <= 26.5), `条粗 ${shown.thickness.join('、')}px`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+
+ it('口味榜的女优与创作者头像按人脸框放大:图保持原比例、盖满圆框,不露出底下的首字母', { timeout: 60_000 }, async () => {
+ const opened = await openTaste(browser, DESKTOP);
+ try {
+ const page = opened.page;
+ await page.getByRole('tablist', { name: '口味证据来源' }).getByRole('tab', { name: 'Peach 内部' }).click();
+ for (const name of ['女优', '创作者']) {
+ await page.getByRole('tablist', { name: 'Peach 口味维度' }).getByRole('tab', { name }).click();
+ const img = page.getByRole('tabpanel', { name }).locator('img[data-facebox]').first();
+ await img.scrollIntoViewIfNeeded();
+ // 放大是图加载后 `avatarFrame` 写进内联 style 的;等到那一步落地再量。
+ await page.waitForFunction((element) => element instanceof HTMLImageElement
+ && element.complete && element.naturalWidth > 0 && element.style.width !== '',
+ await img.elementHandle(), { timeout: 15_000 });
+ const frame = await img.evaluate((element) => {
+ const ring = element.parentElement!.getBoundingClientRect();
+ const box = element.getBoundingClientRect();
+ return {
+ maxWidth: getComputedStyle(element).maxWidth, ring: ring.width,
+ width: box.width, aspect: box.width / box.height,
+ gaps: [box.left - ring.left, ring.right - box.right, box.top - ring.top, ring.bottom - box.bottom],
+ };
+ });
+ assert.equal(frame.maxWidth, 'none', `${name}头像的图被预检的 max-width 夹住`);
+ assert.ok(frame.width > frame.ring, `${name}头像没有按人脸框放大:图宽 ${frame.width}px,圆框 ${frame.ring}px`);
+ assert.ok(Math.abs(frame.aspect - TASTE_FACE.imgW / TASTE_FACE.imgH) < .02,
+ `${name}头像的图宽高比 ${frame.aspect},被压扁了`);
+ assert.ok(frame.gaps.every((gap) => gap <= .5), `${name}头像的图没盖满圆框:${frame.gaps.join('、')}`);
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('被打断的那一轮只有结束原因,卡片正文下面不留空行', { timeout: 60_000 }, async () => {
+ const opened = await openActivity(browser, [
+ { ...settledRun(1, 'interrupted', '追更检查'), error: '服务重启,这一轮没有跑完' },
+ ]);
+ try {
+ const body = await opened.page.locator('li[data-status="interrupted"] > div').first()
+ .evaluate((element) => ({
+ trailing: element.getBoundingClientRect().bottom - element.lastElementChild!.getBoundingClientRect().bottom,
+ padding: parseFloat(getComputedStyle(element).paddingBottom),
+ }));
+ assert.ok(Math.abs(body.trailing - body.padding) <= .5,
+ `正文最后一行下面空出 ${body.trailing}px,底边距只有 ${body.padding}px`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ /* 首页「未入库的新作」那一排会自己横着走,每一帧都发一次 scroll。手机上侧栏是抽屉,
+ 两枚弹层一打开就碰上它;演示库没有订阅,这一排由拦下的 `/api/feeds/discoveries`
+ 画出来(字段以 `src/peach/web_feeds.py` 为准)。夹具关了动效,自动滚动不起步,
+ 所以这里亲手滚它,发出的是同一种 scroll。 */
+ it('390px 下侧栏两枚弹层不随别处那一排横滚收起,整页滚动才收', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', MOBILE);
+ try {
+ const items = Array.from({ length: 12 }, (_, index) => ({
+ id: index + 1, code: `DEMO-${String(index + 1).padStart(3, '0')}`, title: `演示新作 ${index + 1}`,
+ studio: '演示厂牌', release_date: '2026-09-01', has_cover: false, cover_url: '', link: '', read: false,
+ }));
+ await opened.page.route((url) => url.pathname === '/api/feeds/discoveries', (route) => route.fulfill({
+ status: 200, contentType: 'application/json', body: JSON.stringify({ items }),
+ }));
+ await opened.page.reload({ waitUntil: 'load' });
+ const row = opened.page.locator('#feedNew .feednewrow');
+ await row.waitFor({ state: 'visible', timeout: 15_000 });
+ await settle(opened.page);
+ assert.ok(await row.evaluate((element) => element.scrollWidth > element.clientWidth + 120),
+ '新作那一排在 390px 下没有可横滚的余量,这条用例量不到东西');
+ await opened.page.locator('#filterBtn').tap();
+ await opened.page.waitForFunction(() => document.querySelector('#drawer')?.classList.contains('open'));
+ for (const [trigger, menuId] of [['#brandHome', 'boardLibraryMenu'], ['#boardGlowBtn', 'boardGlowMenu']] as const) {
+ const menu = opened.page.locator(`#${menuId}`);
+ await opened.page.locator(trigger).tap();
+ await menu.waitFor({ state: 'visible', timeout: 5_000 });
+ for (let step = 0; step < 4; step += 1) {
+ await row.evaluate((element) => { element.scrollLeft += 30; });
+ await opened.page.waitForTimeout(100);
+ }
+ assert.ok(await menu.isVisible(), `${trigger} 打开的弹层随新作那一排横滚收起了`);
+ // 菜单装不下时本来就要在内部滚;捕获阶段的 scroll 连它自己的也收得到。
+ await menu.evaluate((element) => element.dispatchEvent(new Event('scroll')));
+ await opened.page.waitForTimeout(100);
+ assert.ok(await menu.isVisible(), `${trigger} 打开的弹层随它自己的内部滚动收起了`);
+ assert.equal(await opened.page.locator(trigger).getAttribute('aria-expanded'), 'true');
+ await opened.page.evaluate(() => document.dispatchEvent(new Event('scroll')));
+ await menu.waitFor({ state: 'hidden', timeout: 5_000 });
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('设置里的光晕配色和侧栏配色卡是同一组预设色块,键盘选一档两处一起换', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', DESKTOP);
+ try {
+ await settle(opened.page);
+ await opened.page.locator('#settingsBtn').click();
+ const grid = opened.page.locator('#homeGlowControls [data-glow-grid]');
+ await grid.waitFor({ state: 'visible', timeout: 10_000 });
+ const chips = (root: string) => opened.page.locator(`${root} [data-glow-preset]`).evaluateAll((nodes) =>
+ nodes.map((node) => ({
+ key: (node as HTMLElement).dataset.glowPreset,
+ label: node.getAttribute('aria-label'),
+ pressed: node.getAttribute('aria-pressed'),
+ ball: getComputedStyle(node.querySelector('[data-glow-ball]')!).backgroundImage,
+ })));
+ const inSettings = await chips('#homeGlowControls');
+ assert.ok(inSettings.length >= 2, '设置里没有预设色块');
+ assert.deepEqual(inSettings, await chips('#boardGlowMenu'), '设置里的预设色块和侧栏配色卡不是同一组');
+ const size = await grid.locator('[data-glow-ball]').first().evaluate((node) => node.getBoundingClientRect().width);
+ assert.equal(size, 28, '设置里的色块和侧栏那一枚不是同一副尺寸');
+ /* 设置这一行有整块设置那么宽:列数跟着可用宽度走,每格就是一枚球,挨着排满再换行,
+ 间距与侧栏那条 `[data-glow-grid]` 同一个值;侧栏那张卡仍是六列。 */
+ const gridStyle = (root: string) => opened.page.locator(`${root} [data-glow-grid]`).evaluate((node) => {
+ const style = getComputedStyle(node);
+ return { tracks: style.gridTemplateColumns, gap: style.columnGap, inline: style.paddingLeft };
+ });
+ const swatchLayout = () => grid.evaluate((node) => {
+ const box = node.getBoundingClientRect();
+ const chips = [...node.querySelectorAll('[data-glow-preset]')].map((chip) => chip.getBoundingClientRect());
+ const firstTop = chips[0]!.top;
+ return {
+ count: chips.length,
+ firstRow: chips.filter((chip) => chip.top === firstTop).length,
+ rows: new Set(chips.map((chip) => chip.top)).size,
+ steps: chips.slice(1).filter((chip) => chip.top === firstTop).map((chip, index) => chip.left - chips[index]!.left),
+ startsAt: chips[0]!.left - box.left,
+ overflow: node.scrollWidth > node.clientWidth || chips.some((chip) => chip.right > box.right + 0.5),
+ viewportOverflow: document.documentElement.scrollWidth > document.documentElement.clientWidth,
+ };
+ });
+ const settingsGrid = await gridStyle('#homeGlowControls');
+ const sidebarGrid = await gridStyle('#boardGlowMenu');
+ assert.ok(settingsGrid.tracks.split(' ').every((track) => track === '28px'), '设置里的色块每格不是一枚球的宽度');
+ assert.equal(settingsGrid.gap, sidebarGrid.gap, '设置里的色块间距和侧栏配色卡不同');
+ assert.equal(settingsGrid.inline, '0px', '设置里的色块没有从这一行的内容左缘起');
+ // 侧栏配色卡此刻收着,计算值停在声明式 `repeat(6, 1fr)`;展开时是六个解析后的宽度。
+ assert.ok(sidebarGrid.tracks === 'repeat(6, 1fr)' || sidebarGrid.tracks.split(' ').length === 6,
+ `侧栏配色卡不再是每行六枚:${sidebarGrid.tracks}`);
+ const wide = await swatchLayout();
+ assert.ok(wide.firstRow > 6, `桌面宽度下第一行只排了 ${wide.firstRow} 枚,右边的空间没用上`);
+ assert.ok(wide.steps.every((step) => step === 34), `设置里的色块没有挨着排:步长 ${wide.steps.join('/')}`);
+ assert.equal(wide.startsAt, 0, '设置里的第一枚色块没有从这一行的内容左缘起');
+ assert.equal(wide.overflow, false, '桌面宽度下色块越出了这一行');
+ assert.equal(await grid.getAttribute('role'), 'group');
+ assert.ok(await grid.getAttribute('aria-label'), '预设色块那一组没有无障碍名称');
+
+ const target = inSettings.find((chip) => chip.pressed === 'false')!;
+ const chip = grid.locator(`[data-glow-preset="${target.key}"]`);
+ await chip.focus();
+ await opened.page.keyboard.press('Space');
+ await opened.page.waitForFunction((key) => document.querySelector(
+ `#homeGlowControls [data-glow-preset="${key}"]`)?.getAttribute('aria-pressed') === 'true', target.key);
+ assert.equal(await grid.locator('[aria-pressed="true"]').count(), 1);
+ assert.equal(await opened.page.evaluate(() => (document.activeElement as HTMLElement | null)?.dataset.glowPreset
+ && document.activeElement!.closest('#homeGlowControls [data-glow-grid]') ? (document.activeElement as HTMLElement).dataset.glowPreset : null),
+ target.key, '选完之后焦点离开了刚选的那一枚色块');
+ assert.equal(await opened.page.locator(`#boardGlowMenu [data-glow-preset="${target.key}"]`)
+ .getAttribute('aria-pressed'), 'true', '侧栏配色卡没有跟着换到同一档');
+ assert.equal(await opened.page.locator('#homeGlowControls [data-glow-preset-name]').textContent(), target.label);
+ assert.equal(await opened.page.evaluate(() => JSON.parse(localStorage.getItem('peach.settings.v1')!).homeGlow.preset),
+ target.key, '选中的那一档没有写进设置');
+
+ await opened.page.setViewportSize({ width: MOBILE.width, height: MOBILE.height });
+ await grid.waitFor({ state: 'visible', timeout: 10_000 });
+ const narrow = await swatchLayout();
+ assert.ok(narrow.firstRow < narrow.count && narrow.rows > 1, `${MOBILE.width}px 下色块没有换行`);
+ assert.ok(narrow.steps.every((step) => step === 34), `${MOBILE.width}px 下色块没有挨着排`);
+ assert.equal(narrow.startsAt, 0, `${MOBILE.width}px 下第一枚色块没有从内容左缘起`);
+ assert.equal(narrow.overflow, false, `${MOBILE.width}px 下色块越出了这一行`);
+ assert.equal(narrow.viewportOverflow, false, `${MOBILE.width}px 下页面出现横向溢出`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ /* ADR-0050:设置弹层只放一行一个值、改完就生效的控件;带「保存配置」的表单在配置页,
+ 要确认、要看进度的长任务在数据管理页,订阅源在关注管理页。 */
+ it('设置弹层「这台电脑」只有摘要卡,按钮直达配置页;媒体修复与订阅源都不在设置和配置页里', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', DESKTOP);
+ try {
+ const { page } = opened;
+ await settle(page);
+ await page.locator('#settingsBtn').click();
+ const panel = page.locator('#settingsPanel');
+ await panel.getByRole('tab', { name: '这台电脑' }).click({ timeout: 10_000 });
+ const machine = panel.locator('#machineSettings');
+ const go = machine.getByRole('button', { name: '打开配置页', exact: true });
+ await go.waitFor({ state: 'visible', timeout: 10_000 });
+ assert.deepEqual(await machine.locator('dt').allTextContents(), ['媒体库', '端口', '更新']);
+ assert.equal(await machine.locator('input, textarea, select, form, [role="switch"], [aria-haspopup="listbox"]').count(), 0,
+ '摘要卡里出现了可编辑的控件');
+ assert.equal(await panel.locator('.configpage').count(), 0, '设置弹层里又挂了一份配置页');
+ for (const text of ['媒体修复', '订阅源', '保持登录时间']) {
+ assert.equal(await panel.getByText(text, { exact: true }).count(), 0, `设置弹层里还有「${text}」`);
+ }
+
+ await go.click();
+ await expectBody(page, '/configuration', configurationBody(page));
+ assert.equal(new URL(page.url()).pathname, '/configuration');
+ assert.equal(await panel.isHidden(), true, '去配置页之后设置弹层没有关');
+ await settle(page);
+ for (const text of ['媒体修复', '订阅源']) {
+ assert.equal(await page.locator('#stats').getByText(text, { exact: true }).count(), 0, `配置页上还有「${text}」`);
+ }
+ const entry = page.locator('[data-manage-bar] [data-manage="configuration"]');
+ await entry.waitFor({ state: 'attached', timeout: 10_000 });
+ assert.equal(await entry.getAttribute('aria-pressed'), 'true', '管理菜单里的「配置」没有标成当前页');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ /* 设置面板:盖住整页的弹层与作品详情浮窗同一档遮罩、同一组进出场;遮罩不带模糊,值只来自 `--scrim`。
+ 动效要真跑起来才读得到关键帧名,这一条自建不减动态的上下文。 */
+ it('设置面板的遮罩取 --scrim、不带模糊、压在最顶层,卡片用弹层那一组关键帧进出', { timeout: 60_000 }, async () => {
+ const context = await browser.newContext({ viewport: { width: DESKTOP.width, height: DESKTOP.height } });
+ await context.addInitScript(() => localStorage.setItem('peach.settings.v1', JSON.stringify({ detailAutoplay: false })));
+ try {
+ const page = await context.newPage();
+ await stubServer(page);
+ await page.goto(`${requiredEnv('PEACH_E2E_ORIGIN')}/`, { waitUntil: 'load' });
+ await settle(page);
+ await openPanel(page);
+ const scrim = await tokenColor(page, 'body', '--scrim');
+ const shown = await page.locator(PANEL).evaluate((panel) => {
+ const style = getComputedStyle(panel);
+ const card = getComputedStyle(panel.querySelector('[data-settings-card]')!);
+ return {
+ position: style.position, z: style.zIndex, inset: [style.top, style.right, style.bottom, style.left],
+ layer: getComputedStyle(document.documentElement).getPropertyValue('--layer-dialog').trim(),
+ face: style.backgroundColor, blur: [style.backdropFilter, card.backdropFilter],
+ backdrop: [style.animationName, style.animationFillMode], card: [card.animationName, card.animationFillMode],
+ padding: [style.paddingTop, style.paddingBottom],
+ };
+ });
+ assert.equal(shown.position, 'fixed');
+ assert.equal(shown.z, shown.layer, '设置遮罩不在 --layer-dialog 那一层');
+ assert.deepEqual(shown.inset, ['0px', '0px', '0px', '0px'], '设置遮罩没有铺满视口');
+ assert.equal(shown.face, scrim, '设置遮罩的颜色不是 --scrim');
+ assert.deepEqual(shown.blur, ['none', 'none'], '设置遮罩或卡片带了模糊');
+ assert.deepEqual(shown.backdrop, ['settings-backdrop-in', 'both']);
+ // 进场填 `backwards`:终点帧留下的 filter 会另起一个 backdrop root,左栏玻璃就只采样得到卡片自己。
+ assert.deepEqual(shown.card, ['board-dialog-in', 'backwards']);
+ /* 安全区内边距让开刘海与 Home 指示条;桌面上没有安全区,两端都是 18px 的底。 */
+ assert.deepEqual(shown.padding, ['18px', '18px']);
+
+ const leaving = await page.locator(PANEL).evaluate((panel) => {
+ (panel.querySelector('#settingsClose') as HTMLButtonElement).click();
+ const card = getComputedStyle(panel.querySelector('[data-settings-card]')!);
+ return { backdrop: getComputedStyle(panel).animationName, card: [card.animationName, card.animationFillMode] };
+ });
+ assert.equal(leaving.backdrop, 'settings-backdrop-out');
+ // 退场要 `both`:终点(透明)不是元素的自然状态。
+ assert.deepEqual(leaving.card, ['board-dialog-out', 'both']);
+ await page.locator(PANEL).waitFor({ state: 'hidden', timeout: 5_000 });
+ } finally {
+ await context.close();
+ }
+ });
+
+ it('设置面板的标题栏占满右栏、压在滚动区上面,滚过那段留白才投下左栏玻璃那道影子', { timeout: 60_000 }, async () => {
+ const opened = await openHome(browser);
+ const { page } = opened;
+ try {
+ await openPanel(page);
+ const shadow = await page.locator(`${PANEL} [data-settings-card]`).evaluate((card) => {
+ const probe = document.createElement('div');
+ probe.style.boxShadow = 'var(--glass-shadow)';
+ card.append(probe);
+ const value = getComputedStyle(probe).boxShadow;
+ probe.remove();
+ return value;
+ });
+ const read = () => page.locator(PANEL).evaluate((panel) => {
+ const head = panel.querySelector('[data-settings-head]')!, scroll = panel.querySelector('[data-settings-scroll]')!;
+ const top = head.getBoundingClientRect(), body = scroll.getBoundingClientRect(), style = getComputedStyle(scroll);
+ return {
+ head: [top.left, top.width, top.bottom], body: [body.left, body.width, body.top],
+ z: getComputedStyle(head).zIndex, shadow: getComputedStyle(head).boxShadow, clip: getComputedStyle(head).clipPath,
+ overflow: style.overflowY, overscroll: style.overscrollBehaviorY, gap: style.paddingTop,
+ };
+ });
+ const resting = await read();
+ assert.deepEqual(resting.head.slice(0, 2), resting.body.slice(0, 2), '标题栏和滚动区不是同一列同一宽');
+ assert.ok(resting.head[2]! <= resting.body[2]! + 0.5, '标题栏没有压在滚动区上面');
+ assert.equal(resting.z, '2');
+ assert.equal(resting.overflow, 'auto');
+ assert.equal(resting.overscroll, 'contain', '滚到底之后滚动会漏给背后的页面');
+ assert.equal(resting.shadow, 'none', '还没滚动标题栏就投了影');
+ // 影子只要往下那一半:往上会糊在标题自己头上、往左会糊到左栏上。
+ assert.equal(resting.clip, 'inset(0px 0px -96px)');
+
+ await page.locator(`${PANEL} [data-settings-scroll]`).evaluate((scroll) => { scroll.scrollTop = 4 });
+ await page.waitForTimeout(100);
+ assert.equal((await read()).shadow, 'none', `滚动量还没过 ${resting.gap} 的留白标题栏就投了影`);
+ await page.locator(`${PANEL} [data-settings-scroll]`).evaluate((scroll) => { scroll.scrollTop = 80 });
+ await page.waitForFunction((want) => getComputedStyle(
+ document.querySelector('#settingsPanel [data-settings-head]')!).boxShadow === want, shadow);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('设置面板左栏当前项自己不铺底,那块玻璃跟着指针走、离开这一列回到当前项', { timeout: 60_000 }, async () => {
+ const opened = await openHome(browser);
+ const { page } = opened;
+ try {
+ await openPanel(page);
+ const nav = page.locator(`${PANEL} [data-settings-nav]`);
+ const glide = () => nav.locator('[data-settings-glide]').evaluate((node) => Math.round(node.getBoundingClientRect().top));
+ const top = (name: string) => nav.getByRole('tab', { name, exact: true })
+ .evaluate((node) => Math.round(node.getBoundingClientRect().top));
+ const selected = await nav.getByRole('tab', { name: '界面', exact: true }).evaluate((node) => {
+ const style = getComputedStyle(node), icon = getComputedStyle(node.querySelector('svg')!);
+ return { face: style.backgroundColor, ring: style.boxShadow, icon: [icon.width, icon.height, icon.fill === style.color, icon.stroke] };
+ });
+ assert.equal(selected.face, 'rgba(0, 0, 0, 0)', '当前项自己铺了底,滑动的那块玻璃被盖住');
+ assert.equal(selected.ring, 'none');
+ // Remix 的线条是 `fill` 画出的轮廓,全站默认的 `stroke:currentColor;fill:none` 会让它整枚消失。
+ assert.deepEqual(selected.icon, ['20px', '20px', true, 'none']);
+ assert.equal(await glide(), await top('界面'), '玻璃没有落在当前项上');
+
+ await nav.getByRole('tab', { name: '播放', exact: true }).hover();
+ const target = await top('播放');
+ await page.waitForFunction(([want]) => Math.round(document.querySelector(
+ '#settingsPanel [data-settings-glide]')!.getBoundingClientRect().top) === want, [target]);
+ assert.equal(await nav.getByRole('tab', { name: '界面', exact: true }).getAttribute('aria-selected'), 'true',
+ '指针移上去就换了分区');
+ await page.locator(`${PANEL} [data-settings-scroll]`).hover();
+ const home = await top('界面');
+ await page.waitForFunction(([want]) => Math.round(document.querySelector(
+ '#settingsPanel [data-settings-glide]')!.getBoundingClientRect().top) === want, [home]);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('设置面板的分组是 --ground 圆角面,开关、主题分段与关闭键各是一副尺寸,窄屏下开关不换行', { timeout: 60_000 }, async () => {
+ for (const viewport of [DESKTOP, MOBILE]) {
+ const opened = await openHome(browser, viewport);
+ const { page } = opened;
+ try {
+ await openPanel(page);
+ const ground = await tokenColor(page, PANEL, '--ground');
+ const shown = await page.locator(PANEL).evaluate((panel) => {
+ const box = (node: Element) => {
+ const rect = node.getBoundingClientRect();
+ return [Math.round(rect.width), Math.round(rect.height)];
+ };
+ const group = getComputedStyle(panel.querySelector('[data-setting-group]:not([hidden])')!);
+ const toggles = [...panel.querySelectorAll('[data-setting-group]:not([hidden]) [data-toggle]')];
+ const on = panel.querySelector('#uiSoundsSetting')!, row = on.closest('[data-setting-row]')!;
+ const title = row.querySelector('b')!.getBoundingClientRect(), knob = on.getBoundingClientRect();
+ const close = panel.querySelector('#settingsClose')!;
+ return {
+ group: [group.backgroundColor, group.borderTopLeftRadius],
+ toggles: [...new Set(toggles.map((node) => box(node).join('×')))],
+ toggleOnRow: knob.top < title.bottom && knob.left > title.right,
+ theme: [...panel.querySelectorAll('#themeSetting label')].map((node) => box(node).join('×')),
+ themeIcon: box(panel.querySelector('#themeSetting svg')!).join('×'),
+ close: [box(close).join('×'), getComputedStyle(close).borderTopLeftRadius, getComputedStyle(close).paddingLeft],
+ };
+ });
+ assert.deepEqual(shown.group, [ground, '16px'], `${viewport.name}:分组不是 --ground 的 16px 圆角面`);
+ assert.deepEqual(shown.toggles, ['42×24'], `${viewport.name}:开关不是同一副 42×24`);
+ // 开关只有 42px,跟标题同一行绰绰有余;跟着换行只是白占一行高度。
+ assert.equal(shown.toggleOnRow, true, `${viewport.name}:开关没有留在标题那一行`);
+ assert.deepEqual(shown.theme, ['32×32', '32×32', '32×32'], `${viewport.name}:主题三档不是 32px 的圆`);
+ assert.equal(shown.themeIcon, '16×16');
+ assert.deepEqual(shown.close, ['24×24', '50%', '0px'], `${viewport.name}:关闭键不是 24px 的圆钮`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ }
+ });
+
+ it('侧栏排序的添加行:触发器与「添加」同高 --control-h,「添加」是主按钮,候选用完时触发器给禁止光标', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', DESKTOP);
+ const { page } = opened;
+ try {
+ const server = await stubServer(page);
+ await page.reload({ waitUntil: 'load' });
+ await settle(page);
+ await openPanel(page);
+ const row = page.locator(`${PANEL} [data-sidebar-add-row]`);
+ await row.scrollIntoViewIfNeeded();
+ const shown = await row.evaluate((node) => {
+ const probe = document.createElement('div');
+ probe.style.height = 'var(--control-h)';
+ node.append(probe);
+ const height = getComputedStyle(probe).height;
+ probe.remove();
+ const primary = document.createElement('button');
+ primary.className = 'geist-button primary';
+ document.body.append(primary);
+ const want = getComputedStyle(primary);
+ const expected = [want.backgroundColor, want.backgroundImage, want.color];
+ primary.remove();
+ const trigger = node.querySelector('[data-sidebar-add-trigger]')!, add = node.querySelector('[data-sidebar-add]')!;
+ const face = getComputedStyle(add);
+ return {
+ height, trigger: getComputedStyle(trigger).height, add: face.height,
+ face: [face.backgroundColor, face.backgroundImage, face.color], expected,
+ cursor: getComputedStyle(trigger).cursor,
+ };
+ });
+ assert.equal(shown.trigger, shown.height, '添加行的触发器没有引用 --control-h');
+ assert.equal(shown.add, shown.height, '「添加」没有引用 --control-h');
+ assert.deepEqual(shown.face, shown.expected, '「添加」没有穿主按钮那一身');
+ assert.equal(shown.cursor, 'pointer');
+
+ /* 一项一项加回去,直到清单里没有可加的入口。 */
+ const add = row.locator('[data-sidebar-add]'), trigger = row.locator('[data-sidebar-add-trigger]');
+ for (let left = 30; left > 0 && await add.isEnabled(); left -= 1) await add.click();
+ assert.equal(await trigger.isDisabled(), true, '全部入口都加回侧栏之后触发器还能点');
+ assert.ok((server.settings.sidebarOrder as string[]).length > ORDER.length, '加回的入口没有写进账本');
+ assert.equal(await trigger.evaluate((node) => getComputedStyle(node).cursor), 'not-allowed',
+ '没有可添加的入口时触发器还是普通光标');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ /* 「关注自动更新」在这台机器上不可用时,开着的那颗开关也被禁:轨道得读成灰的,不能还留着那抹蓝。 */
+ it('开着又被禁的开关是灰轨道加禁止光标,跟开着能点的那颗分得开', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/', DESKTOP);
+ const { page } = opened;
+ try {
+ const server = await stubServer(page);
+ server.schedule.available = false;
+ await page.reload({ waitUntil: 'load' });
+ await settle(page);
+ await openPanel(page, '关注');
+ const blocked = page.locator(`${PANEL} #followScheduleSetting [data-toggle]`);
+ await blocked.and(page.locator(':disabled:checked')).waitFor({ state: 'attached', timeout: 10_000 });
+ const surface = await tokenColor(page, PANEL, '--surface');
+ const face = (node: Element) => {
+ const style = getComputedStyle(node);
+ return { face: style.backgroundColor, knob: getComputedStyle(node, '::before').backgroundImage, cursor: style.cursor };
+ };
+ const grey = await blocked.evaluate(face);
+ const live = await page.locator(`${PANEL} #uiSoundsSetting`).evaluate(face);
+ assert.equal(grey.face, surface, '被禁的开关轨道不是 --surface');
+ assert.equal(grey.cursor, 'not-allowed');
+ assert.notDeepEqual([grey.face, grey.knob], [live.face, live.knob], '被禁的开关和能点的开着那颗长得一样');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('光晕参数块自己让出分组右侧的留白、下边距与设置行同一档;「玻璃原色」那一档只留漂移速度', { timeout: 60_000 }, async () => {
+ for (const viewport of [DESKTOP, MOBILE]) {
+ const opened = await openHome(browser, viewport);
+ const { page } = opened;
+ try {
+ await openPanel(page);
+ const block = page.locator(`${PANEL} [data-glow-setting]`);
+ await block.waitFor({ state: 'visible', timeout: 10_000 });
+ const shown = await block.evaluate((node) => {
+ const group = node.closest('[data-setting-group]')!.getBoundingClientRect(), rect = node.getBoundingClientRect();
+ const row = node.parentElement!.querySelector('[data-setting-row]')!;
+ return {
+ right: Math.round(group.right - rect.right), left: rect.left >= group.left,
+ overflow: node.scrollWidth > node.clientWidth,
+ pad: getComputedStyle(node).paddingBottom, rowPad: getComputedStyle(row).paddingBottom,
+ };
+ });
+ assert.ok(shown.right >= 16 && shown.left, `${viewport.name}:参数块压到了分组的圆角上(右侧只剩 ${shown.right}px)`);
+ assert.equal(shown.overflow, false, `${viewport.name}:参数块被内容顶宽`);
+ assert.equal(shown.pad, shown.rowPad, `${viewport.name}:参数块的下边距和上面每一行不是同一档`);
+
+ await block.locator('[data-glow-preset="native"]').click();
+ await block.locator('[data-glow-native-note]').waitFor({ state: 'visible', timeout: 5_000 });
+ const fields = await block.locator('[data-glow-field]').evaluateAll((nodes) => nodes
+ .filter((node) => node.getClientRects().length > 0).map((node) => (node as HTMLElement).dataset.glowField));
+ assert.deepEqual(fields, ['speed'], `${viewport.name}:「玻璃原色」下还摆着管不着任何东西的拉条`);
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ }
+ });
+
+ it('统计页选中的读数卡:2px 描边压在脚注带上面、圆角跟卡走,接触阴影收掉', { timeout: 60_000 }, async () => {
+ const opened = await visit(browser, '/stats', DESKTOP);
+ try {
+ const page = opened.page;
+ const tab = page.locator('#stats [role="tab"][data-selected]').first();
+ await tab.waitFor({ timeout: 15_000 });
+ await settle(page);
+ const ring = await tokenColor(page, '.peach-react', '--color-border-focus-ring');
+ const shown = await tab.evaluate((element) => {
+ const card = getComputedStyle(element);
+ const after = getComputedStyle(element, '::after');
+ const footer = element.querySelector('small')!;
+ const other = document.querySelector('#stats [role="tab"]:not([data-selected])')!;
+ // `shadow-none` 是五层透明的 0px,不是字面的 none:看有没有一层带颜色。
+ const shadowVisible = [...card.boxShadow.matchAll(/rgba?\([^)]*\)/g)]
+ .some((match) => !/, 0\)$/.test(match[0]));
+ return {
+ shadowVisible, position: card.position, radius: card.borderRadius,
+ after: {
+ content: after.content, position: after.position, width: after.borderTopWidth,
+ color: after.borderTopColor, radius: after.borderRadius, z: after.zIndex,
+ inset: [after.top, after.right, after.bottom, after.left],
+ },
+ footerFace: getComputedStyle(footer).backgroundColor,
+ otherAfter: getComputedStyle(other, '::after').content,
+ };
+ });
+ assert.equal(shown.shadowVisible, false, '选中的卡还压着接触阴影');
+ assert.equal(shown.position, 'relative');
+ assert.equal(shown.after.content, '""', '选中的卡没有画覆盖层');
+ assert.equal(shown.after.position, 'absolute');
+ assert.deepEqual(shown.after.inset, ['0px', '0px', '0px', '0px'], '覆盖层没有铺满整张卡');
+ assert.deepEqual([shown.after.width, shown.after.color], ['2px', ring], '描边不是 2px 焦点环色');
+ assert.equal(shown.after.radius, shown.radius, '覆盖层圆角和卡不一致');
+ assert.ok(Number(shown.after.z) >= 1, `覆盖层 z-index ${shown.after.z},会被脚注带盖住`);
+ assert.notEqual(shown.footerFace, 'rgba(0, 0, 0, 0)', '脚注带没有底色,这条用例守的就是环压在它上面');
+ assert.equal(shown.otherAfter, 'none', '没选中的卡也画了覆盖层');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('索引页容器不横向裁剪:筛选玻璃左右两侧的影洒得出来,页面也不横向溢出', { timeout: 60_000 }, async () => {
+ const opened = await openIndexPage(browser, '/tags');
+ try {
+ const page = opened.page;
+ const clip = await page.evaluate(() => {
+ const index = document.querySelector('#index')!;
+ return {
+ overflow: getComputedStyle(index).overflowX,
+ spill: document.documentElement.scrollWidth - document.documentElement.clientWidth,
+ };
+ });
+ assert.equal(clip.overflow, 'visible', '#index 横向裁剪,玻璃左右两侧的影被切成直边');
+ assert.equal(clip.spill, 0, '不裁剪后页面被撑出横向滚动');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('标签页骨架里就铺着那块筛选玻璃,React 落地时玻璃与开头那组内容都留在原位', { timeout: 60_000 }, async () => {
+ /* 骨架与真页面各量一遍:玻璃的位置与大小、开头那组内容的上沿。药丸、读数与首字要等数据,
+ 骨架里是占位;视图切换此刻就是最终那一档。 */
+ const opened = await visit(browser, '/tags', DESKTOP);
+ try {
+ const page = opened.page;
+ await page.route('**/api/index?**', (route) => route.fulfill({
+ status: 200, contentType: 'application/json',
+ body: JSON.stringify({ items: [{ k: '痴女', n: 4, cat: 'role' }, { k: '秘书OL', n: 2, cat: 'scene' }],
+ has_more: false, categories: { role: 1, scene: 1 } }),
+ }));
+ const release = await holdApi(page);
+ await page.reload({ waitUntil: 'load' });
+ await page.locator('#index [data-skeleton^="index/tags/"]').waitFor({ timeout: 15_000 });
+ const measure = (glass: string, group: string, view: string) => page.evaluate(([glassSelector, groupSelector, viewSelector]) => {
+ const rect = (selector: string) => {
+ const box = document.querySelector(selector)?.getBoundingClientRect();
+ return box ? { top: box.top, left: box.left, width: box.width, height: box.height } : null;
+ };
+ return { glass: rect(glassSelector), group: rect(groupSelector),
+ pills: document.querySelectorAll(`${glassSelector} [data-filter-row="top"] > *`).length,
+ view: rect(`${glassSelector} [data-filter-row="bottom"] ${viewSelector}`) };
+ }, [glass, group, view] as const);
+ const skeleton = await measure('#index .board-filter-frame', '#index [data-skeleton] .alphagroup', '.iconswitch');
+ release();
+ await page.locator('#index [data-alphabet]').waitFor({ timeout: 15_000 });
+ await settle(page);
+ const live = await measure('#index [data-filter-glass]', '#index [data-alpha-group]', '[aria-label="标签视图"]');
+ assert.ok(skeleton.glass && skeleton.group && skeleton.view, '标签页骨架里缺筛选玻璃、开头那组或视图切换');
+ assert.ok(skeleton.pills > 0, '骨架玻璃的上排没有铺药丸占位');
+ assert.ok(live.glass && live.group && live.view, '接管后找不到筛选玻璃、开头那组或视图切换');
+ for (const key of ['top', 'left', 'width', 'height'] as const) {
+ assert.ok(Math.abs(skeleton.glass![key] - live.glass![key]) <= 1,
+ `筛选玻璃的 ${key} 接管时跳了:骨架 ${skeleton.glass![key]},接管后 ${live.glass![key]}`);
+ }
+ assert.ok(Math.abs(skeleton.group!.top - live.group!.top) <= 1,
+ `开头那组内容的上沿接管时跳了:骨架 ${skeleton.group!.top},接管后 ${live.group!.top}`);
+ assert.ok(Math.abs(skeleton.view!.top - live.view!.top) <= 1 && Math.abs(skeleton.view!.left - live.view!.left) <= 1,
+ `视图切换接管时挪了位:骨架 (${skeleton.view!.left}, ${skeleton.view!.top}),接管后 (${live.view!.left}, ${live.view!.top})`);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ for (const viewport of VIEWPORTS) {
+ it(`首页吸顶筛选条的上沿在深浅主题中保持透明(${viewport.name})`, { timeout: 60_000 }, async () => {
+ const opened = await openHome(browser, viewport);
+ try {
+ const page = opened.page;
+ await page.evaluate(() => document.body.insertAdjacentHTML('beforeend', '<div style="height:200vh"></div>'));
+ await page.evaluate(() => window.scrollTo(0, 600));
+ await page.waitForFunction(() => document.querySelector('[data-filter-glass]')?.hasAttribute('data-stuck'));
+ for (const theme of ['light', 'dark']) {
+ const style = await page.evaluate(value => {
+ document.documentElement.dataset.theme = value;
+ const filter = document.querySelector('[data-filter-glass]')!;
+ return { content: getComputedStyle(filter, '::before').content, shadow: getComputedStyle(filter).boxShadow };
+ }, theme);
+ assert.equal(style.content, 'none');
+ assert.match(style.shadow, /inset/);
+ await page.locator('[data-filter-glass]').screenshot({ path: `../build/sticky-${viewport.name}-${theme}.png` });
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close(); }
+ });
+ }
+
+ it('筛选玻璃吸顶使用抬起阴影,深浅主题的上沿保持透明间隙', { timeout: 60_000 }, async () => {
+ const opened = await openIndexPage(browser, '/tags');
+ try {
+ const page = opened.page;
+ const read = () => page.evaluate(() => {
+ const glass = document.querySelector('[data-filter-glass]')!;
+ const root = getComputedStyle(document.documentElement);
+ return {
+ stuck: glass.hasAttribute('data-stuck'),
+ shadow: getComputedStyle(glass).boxShadow,
+ strip: getComputedStyle(glass, '::before'),
+ lift: root.getPropertyValue('--glass-lift'),
+ rest: root.getPropertyValue('--glass-shadow'),
+ };
+ });
+ const readStrip = () => page.evaluate(() => {
+ const strip = getComputedStyle(document.querySelector('[data-filter-glass]')!, '::before');
+ return { content: strip.content, top: strip.top, height: strip.height, z: strip.zIndex, mask: strip.maskImage };
+ });
+ const resting = await read();
+ assert.equal(resting.stuck, false, '还没滚就标成吸顶');
+ assert.equal(farthestShadow(resting.shadow), farthestShadow(resting.rest), '静止态的影不是 --glass-shadow');
+ assert.equal((await readStrip()).content, 'none', '静止态就画了遮带');
+ // 桩数据只有两枚标签,页面不够长滚不动:垫一块高度再滚。
+ await page.evaluate(() => document.body.insertAdjacentHTML('beforeend', '<div style="height:200vh"></div>'));
+ await page.evaluate(() => window.scrollTo(0, 600));
+ await page.waitForFunction(() => document.querySelector('[data-filter-glass]')!.hasAttribute('data-stuck'),
+ undefined, { timeout: 5_000 });
+ const stuck = await read();
+ const strip = await readStrip();
+ assert.equal(farthestShadow(stuck.shadow), farthestShadow(stuck.lift), '吸顶后的影不是 --glass-lift');
+ assert.ok(farthestShadow(stuck.shadow) > farthestShadow(resting.shadow), '吸顶后影没有抬起来');
+ assert.match(stuck.shadow, /inset/, '吸顶后四条内嵌 rim 线丢了');
+ assert.equal(strip.content, 'none');
+ for (const theme of ['light', 'dark']) {
+ await page.evaluate(value => { document.documentElement.dataset.theme = value }, theme);
+ assert.equal((await readStrip()).content, 'none', `${theme} 主题的吸顶上沿存在遮带`);
+ }
+ await page.evaluate(() => window.scrollTo(0, 0));
+ await page.waitForFunction(() => !document.querySelector('[data-filter-glass]')!.hasAttribute('data-stuck'),
+ undefined, { timeout: 5_000 });
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('图片灯箱:竖图按高度整张收进视口,上下让出工具条与缩略图条,左右让出翻页键', { timeout: 60_000 }, async () => {
+ const opened = await openLightbox(browser, { count: 3, width: 1200, height: 4000 });
+ try {
+ const read = await opened.page.evaluate(() => {
+ const rect = (selector: string) => document.querySelector(selector)!.getBoundingClientRect().toJSON() as DOMRect;
+ return { img: rect('[data-photo-main] .swiper-slide-active img'), bar: rect('[data-photo-bar]'),
+ strip: rect('[data-photo-strip]'), back: rect('[data-photo-nav="back"]'), viewport: innerHeight };
+ });
+ const { img } = read;
+ assert.ok(img.top >= 24 - .5 && img.bottom <= read.viewport - 148 + .5, `大图越出了上下安全区:${img.top}–${img.bottom}`);
+ assert.ok(Math.abs(img.width / img.height - 1200 / 4000) < .01, `竖图被拉变形:${img.width}×${img.height}`);
+ assert.ok(Math.abs(img.left + img.width / 2 - DESKTOP.width / 2) <= 1, '大图没有水平居中');
+ assert.ok(read.bar.bottom <= read.strip.top, '工具条压到了缩略图条上');
+ assert.equal(Math.round(read.viewport - read.strip.bottom), 14);
+ assert.ok(read.back.right <= 72, '翻页键伸进了图片那一栏');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('图片灯箱只有一张时不画缩略图条、页码点和翻页键,底部空间还给图片', { timeout: 60_000 }, async () => {
+ const opened = await openLightbox(browser, { count: 1, width: 4000, height: 3000 });
+ try {
+ const read = await opened.page.evaluate(() => {
+ const style = (selector: string) => getComputedStyle(document.querySelector(selector)!);
+ return {
+ strip: style('[data-photo-strip]').display,
+ nav: [...document.querySelectorAll('[data-photo-nav]')].map((button) => getComputedStyle(button).display),
+ pagination: document.querySelectorAll('[data-photo-pagination]').length,
+ padding: style('[data-photo-main] .swiper-zoom-container').paddingBottom,
+ count: document.querySelector('[data-photo-count]')!.textContent,
+ };
+ });
+ assert.deepEqual(read, { strip: 'none', nav: ['none', 'none'], pagination: 0, padding: '76px', count: '1 / 1' });
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('灯箱圆钮:图标压在圆心,线头是圆的、不填充;前进那枚是同一枚箭头转半圈,到头那枚让开', { timeout: 60_000 }, async () => {
+ const opened = await openLightbox(browser, { count: 3, width: 4000, height: 3000 });
+ try {
+ const read = await opened.page.evaluate(() => [
+ '[data-photo-close]', '[data-photo-nav="back"]', '[data-photo-nav="fwd"]', '[data-photo-detail-toggle]',
+ ].map((selector) => {
+ const button = document.querySelector(selector)!, svg = button.querySelector('svg')!;
+ const outer = button.getBoundingClientRect(), inner = svg.getBoundingClientRect(), style = getComputedStyle(svg);
+ return {
+ selector, glyph: svg.querySelector('use')?.getAttribute('href'),
+ off: Math.max(Math.abs(outer.left + outer.width / 2 - inner.left - inner.width / 2),
+ Math.abs(outer.top + outer.height / 2 - inner.top - inner.height / 2)),
+ fill: style.fill, cap: style.strokeLinecap, turn: style.transform,
+ visibility: getComputedStyle(button).visibility,
+ };
+ }));
+ for (const icon of read) {
+ assert.ok(icon.off <= .5, `${icon.selector} 的图标偏离圆心 ${icon.off}px`);
+ assert.equal(icon.fill, 'none', `${icon.selector} 的描边图标被填实了`);
+ // Lucide 的 info 圆点是长度 .01 的短线,没有圆头就缩成看不见的一横。
+ assert.equal(icon.cap, 'round', `${icon.selector} 的线头不是圆的`);
+ }
+ const [close, back, fwd, info] = read;
+ assert.equal(close.glyph, '#i-x');
+ assert.equal(info.glyph, '#i-info');
+ assert.deepEqual([back.glyph, fwd.glyph], ['#i-chevron-left', '#i-chevron-left']);
+ assert.equal(back.turn, 'none');
+ assert.match(fwd.turn, /^matrix\(-1, /, '前进键的箭头没有转半圈');
+ assert.deepEqual([back.visibility, fwd.visibility], ['hidden', 'visible'], '停在第一张时后退键该让开');
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ await opened.close();
+ }
+ });
+
+ it('关注页:标题 24px、窄屏 20px,药丸间距同首页 7px,读数用等宽字', { timeout: 90_000 }, async () => {
+ const read = (page: Page) => page.evaluate(() => {
+ const style = (selector: string) => getComputedStyle(document.querySelector(selector)!);
+ return {
+ title: style('[data-follow-title]').fontSize,
+ gaps: ['[data-follow-filter-glass] [data-entity-states]', '[data-follow-filter-glass] [data-entity-tags]']
+ .map((selector) => style(selector).columnGap),
+ readout: style('[data-follow-readout]').fontFamily,
+ };
+ });
+ const wide = await openFollowFeed(browser, '/follow', DESKTOP);
+ try {
+ const shown = await read(wide.page);
+ assert.equal(shown.title, '24px');
+ assert.deepEqual(shown.gaps, ['7px', '7px'], '关注页的药丸间距和首页那条不一样');
+ assert.match(shown.readout, /Cascadia Mono|Consolas|monospace/, `读数不是等宽字:${shown.readout}`);
+ assert.deepEqual(wide.problems, []);
+ } finally {
+ await wide.close();
+ }
+ const narrow = await openFollowFeed(browser, '/follow', MOBILE);
+ try {
+ assert.equal((await read(narrow.page)).title, '20px', '窄屏的关注标题没有收到 20px');
+ assert.deepEqual(narrow.problems, []);
+ } finally {
+ await narrow.close();
+ }
+ });
+});
diff --git a/frontend/e2e/design.test.ts b/frontend/e2e/design.test.ts
deleted file mode 100644
index d307146a0..000000000
--- a/frontend/e2e/design.test.ts
+++ /dev/null
@@ -1,6400 +0,0 @@
-/* 设计决定按浏览器里的计算值断言,不绑定 CSS 源码的写法。
- *
- * 页面迁到 React 时,旧的源码字符串断言按 ADR-0031 分三类:设计决定落在这里或 lint 规则,
- * 行为落在 vitest,布局与运行期问题归 `smoke.test.ts`。每条用例守一个决定,读的是
- * `getComputedStyle`,类名或样式写法换了照样成立。 */
-import assert from 'node:assert/strict';
-import { after, before, beforeEach, describe, it } from 'node:test';
-
-import type { Browser, Locator, Page } from 'playwright-core';
-
-import { DETAIL, openFollowFeed } from './follow-fixture.ts';
-import {
- configurationBody, expectBody, launch, layout, requiredEnv, settle, visit, VIEWPORTS, type Viewport, type Visit,
-} from './harness.ts';
-import { muteVideos, openImmerse, pickClips, pinQueue, settledClip } from './immerse-fixture.ts';
-import { ITEM, openItemPage } from './item-fixture.ts';
-import { openHome, openPanel, ORDER, PANEL, stubServer } from './settings-fixture.ts';
-
-const DESKTOP = VIEWPORTS.find((viewport) => !viewport.mobile)!;
-const MOBILE = VIEWPORTS.find((viewport) => viewport.mobile)!;
-
-/** 在 `scope` 里解析一个颜色 token:临时挂一个元素读背景色,读完就移除。 */
-async function tokenColor(page: Page, scope: string, token: string): Promise<string> {
- return page.evaluate(([selector, name]) => {
- const probe = document.createElement('div');
- probe.style.backgroundColor = `var(${name})`;
- document.querySelector(selector)!.append(probe);
- const value = getComputedStyle(probe).backgroundColor;
- probe.remove();
- return value;
- }, [scope, token] as const);
-}
-
-/** 配置页「网络与访问」下的访问密码分区。演示库没有 access.json,分区处于系统口令状态。
- * 与冒烟同一口径:先等配置页主体,再 settle、再切分区。 */
-async function openAccess(browser: Browser): Promise<Visit & { form: Locator }> {
- const opened = await visit(browser, '/configuration', DESKTOP);
- await expectBody(opened.page, '/configuration', configurationBody(opened.page));
- await settle(opened.page);
- await opened.page.getByRole('tab', { name: '网络与访问' }).click({ timeout: 5_000 });
- await settle(opened.page);
- const form = opened.page.locator('form[aria-label="访问密码"]');
- await form.waitFor({ timeout: 10_000 });
- return { ...opened, form };
-}
-
-/** 一轮跑完的任务。字段以 `/api/tasks`(`src/peach/routes_tasks.py`)为准。 */
-const settledRun = (id: number, status: string, label: string) => ({
- id, task_key: `task-${id}`, task_label: label, trigger: 'manual', status, host: 'desk',
- started_at: '2026-09-11T10:00:00Z', finished_at: '2026-09-11T10:01:00Z', elapsed_seconds: 60,
- progress_current: null, progress_total: null, progress_label: '',
- result_summary: {}, error: status === 'failed' ? 'RuntimeError: 上游挡回来了' : '',
-});
-
-/** 活动页按给定的一份 `/api/tasks` 打开:演示库里凑不齐失败、被挡下和成功三种状态。 */
-async function openActivity(browser: Browser, runs: unknown[]): Promise<Visit> {
- const opened = await visit(browser, '/activity', DESKTOP);
- await opened.page.route('**/api/tasks', (route) => route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({ available: true, running: [], skipped: [], finished: runs }),
- }));
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('li[data-status]').first().waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return opened;
-}
-
-/** 一条待升级的目标。字段以 `/api/quality-goals`(`src/peach/web_contract.py`)为准。 */
-const qualityGoal = (id: number, name: string) => ({
- id, name, code: null, location: 'local', size: 2147483648, duration: 3725,
- reason: '只有 720p', cost: 'free', has_thumb: true, has_cover: false,
-});
-
-/** 1×1 的透明 PNG,够让 `<img>` 走完一次加载。 */
-const PIXEL = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
-
-/** 口味页浏览器画像的五个维度:头一个是其余的十倍,和真实馆藏的分布一样。 */
-const TASTE_CATEGORIES = [['剧情', 657], ['写真', 68], ['素人', 56], ['偶像', 4], ['企划', 1]]
- .map(([name, score]) => ({ name, score }));
-
-/** 一张全身站姿照的人脸框:脸落在画面上半截的一小块里,小圆框要放大好几倍才看得清。 */
-const TASTE_FACE = { cx: .439, cy: .224, faceW: 67, imgW: 640, imgH: 960 };
-
-/** 口味页按改写过的 `/api/taste` 打开:演示库没有浏览记录,也没有带人脸框的实体图。
- * 字段以 `src/peach/taste_history.py` 与 `src/peach/web_stats.py` 为准;实体图换成与人脸框同尺寸的纯色图。 */
-async function openTaste(browser: Browser, viewport: typeof DESKTOP): Promise<Visit> {
- const opened = await visit(browser, '/taste', viewport);
- const face = (id: number, name: string) => ({
- name, peach_items: 3, peach_score: 5, entity_id: id, has_image: true, avatar_focus: { box: TASTE_FACE },
- });
- await opened.page.route(/\/api\/taste\?/, async (route) => {
- const json = await (await route.fetch()).json();
- await route.fulfill({ json: { ...json, rankings: { ...json.rankings,
- browser_categories: TASTE_CATEGORIES,
- peach_performers: [face(901, '演示女优')],
- peach_creators: [face(902, '演示创作者')],
- } } });
- });
- await opened.page.route(/\/entity-image\?/, (route) => route.fulfill({
- contentType: 'image/svg+xml',
- body: `<svg xmlns="http://www.w3.org/2000/svg" width="${TASTE_FACE.imgW}" height="${TASTE_FACE.imgH}">`
- + `<rect width="${TASTE_FACE.imgW}" height="${TASTE_FACE.imgH}" fill="#888"/></svg>`,
- }));
- await opened.page.reload({ waitUntil: 'load' });
- await expectBody(opened.page, '/taste', [
- opened.page.locator('#stats').getByRole('tab', { name: '浏览器记录', exact: true }),
- ]);
- return opened;
-}
-
-/** 高清版目标页按给定的一份 `/api/quality-goals` 打开:演示库里凑不齐很长的标题。 */
-async function openQualityGoals(browser: Browser, items: unknown[]): Promise<Visit> {
- const opened = await visit(browser, '/quality-goals', DESKTOP);
- await opened.page.route('**/api/quality-goals?limit=200', (route) => route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({ total: items.length, items, offset: 0, has_more: false }),
- }));
- /* 这几条目标是造出来的,演示库里没有对应的抽帧,预览图会 404——而失败请求本身是另一
- 条判据。这一条量的是封面那块的几何,给它一张能加载完的图就够。 */
- await opened.page.route('**/poster**', (route) => route.fulfill({
- status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
- }));
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('li[data-goal-id]').first().waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return opened;
-}
-
-/** 一个采集来源。字段以 `/api/scraping`(`src/peach/web_scraping.py`)为准。 */
-const scrapingSource = (source: string, label: string, cookie: boolean) => ({
- source, label, login: `https://${source}.example/login`,
- accepts_cookie: cookie, network: 'peach', cookie_saved: cookie,
-});
-
-/** 来源和凭证页按给定的一份 `/api/scraping` 打开:演示库里未必同时有收 Cookie 和不收的来源。
- *
- * 站标走服务端的 `/site-mark`,而这几个来源是造出来的,那一趟必然取不到;那是另一条判据,
- * 这里给它一张能加载完的图,免得运行期问题名单里混进与本条无关的失败。 */
-async function openScraping(browser: Browser): Promise<Visit> {
- const opened = await visit(browser, '/scraping', DESKTOP);
- await opened.page.route('**/api/scraping', (route) => route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({
- sources: [scrapingSource('demoa', '演示来源甲', true), scrapingSource('demob', '演示来源乙', false)],
- }),
- }));
- await opened.page.route('**/site-mark**', (route) => route.fulfill({
- status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
- }));
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('form[aria-label="演示来源甲"]').waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return opened;
-}
-
-/** 一行等人判的元数据候选。字段以 `src/peach/web_review.py` 的 `_review_rows` 为准。 */
-const REVIEW_ROW = {
- item_key: 'metadata_fields:ABC-123:studio',
- field: 'studio',
- field_label: '厂牌',
- code: 'ABC-123',
- query: 'ABC-123',
- evidence: '当前值:尚无;1 个匹配资产;2 个来源候选',
- candidates: [{ candidate_key: 'javdb:studio', source: 'javdb', display_value: '示例厂牌' }],
-};
-
-/** 人工复核页按一行造出来的队列打开:演示库里这一格未必正好有候选,而队列空了就没有卡。 */
-async function openReview(browser: Browser): Promise<Visit> {
- const opened = await visit(browser, '/review', DESKTOP);
- await opened.page.route('**/api/review', (route) => route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({
- sections: { metadata_fields: [REVIEW_ROW] }, counts: { metadata_fields: 1 }, genre_tags: [],
- }),
- }));
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('section[data-review-key]').first().waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return opened;
-}
-
-/** CIE L*。一条 1px 的线看不看得见跟的是明度差,不是对比度比值:同样 1.48:1,浅色底上
- * 是一条灰线,深色底上两头的绝对亮度都贴着 0,什么都看不出来。 */
-function lightness([red, green, blue]: number[]): number {
- const linear = (channel: number) => {
- const value = channel / 255;
- return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
- };
- const y = 0.2126 * linear(red!) + 0.7152 * linear(green!) + 0.0722 * linear(blue!);
- return y > 0.008856 ? 116 * Math.cbrt(y) - 16 : 903.3 * y;
-}
-
-/** 按给定的一份 `/api/library-processing` 打开某一页:演示库里那趟任务早就跑完了,
- * 而运行态和失败态正是这两条要看的东西。字段以 `src/peach/web_library_processing.py` 为准。 */
-async function openProcessing(
- browser: Browser, path: string, job: Record<string, unknown>,
-): Promise<Visit> {
- const opened = await visit(browser, path, DESKTOP);
- await opened.page.route('**/api/library-processing', (route) => route.fulfill({
- status: 200, contentType: 'application/json', body: JSON.stringify(job),
- }));
- await opened.page.reload({ waitUntil: 'load' });
- return opened;
-}
-
-/** 1280 的桌面视口比 `--board-content` 还窄,量不出「网格铺满、标题居中」这类差别。 */
-const WIDE = { name: 'wide', width: 1600, height: 900, mobile: false };
-
-/** 垃圾文件页。计数行由垃圾队列那一页画,演示库里一条候选都没有时它照样在;壳铺的
- * 骨架(`[data-junk-count-skeleton]`)也有这两块,等的是页面接管之后的那一版。 */
-const JUNK_COUNT = '#count > .peach-react:not([data-junk-count-skeleton])';
-async function openJunk(browser: Browser): Promise<Visit> {
- const opened = await visit(browser, '/junk-files', WIDE);
- await expectBody(opened.page, '/junk-files', [
- opened.page.locator(`${JUNK_COUNT} [data-collection-summary]`),
- opened.page.locator(`${JUNK_COUNT} [data-junk-filters]`),
- ]);
- await settle(opened.page);
- return opened;
-}
-
-/** 一条垃圾候选。字段以 `/api/ads`(`src/peach/web_batch.py` 的 `q_ads`)为准;类型都挑没有预览
- * 的,造出来的 id 取不到缩略图。 */
-const junkItem = (id: number, kind: string, name: string) => ({
- id, name, junk_kind: kind, why: '文件名像推广', size: 1048576 * id, location: 'local', cost: '',
-});
-
-/** 垃圾文件页按给定的候选打开:演示库里没有垃圾候选。`/api/ads` 每次都按当前名单回话,
- * `/api/batch` 记下请求体、把处置掉的那条从名单里拿掉。 */
-async function openJunkWith(browser: Browser, items: ReturnType<typeof junkItem>[], viewport = WIDE) {
- const opened = await visit(browser, '/junk-files', viewport);
- const state = { items: [...items], batches: [] as { ids: number[]; operation: string }[], reads: [] as string[] };
- await opened.page.route('**/api/ads?**', (route) => {
- const url = new URL(route.request().url());
- state.reads.push(url.search);
- const kind = url.searchParams.get('kind');
- const shown = state.items.filter((item) => !kind || item.junk_kind === kind);
- const counts: Record<string, number> = {};
- for (const item of state.items) counts[item.junk_kind] = (counts[item.junk_kind] || 0) + 1;
- return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({
- items: shown, total: shown.length, all_total: state.items.length, pending_total: state.items.length,
- dismissed_total: 0, counts,
- }) });
- });
- await opened.page.route('**/api/batch', (route) => {
- const body = JSON.parse(route.request().postData() || '{}');
- state.batches.push(body);
- state.items = state.items.filter((item) => !body.ids.includes(item.id));
- return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true, updated: body.ids.length }) });
- });
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('#grid [data-junk-card]').first().waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return { ...opened, state };
-}
-
-/** 一个重复文件。字段以 `/api/duplicates`(`src/peach/web_contract.py`)为准。 */
-const duplicateFile = (id: number, location: string, patch: Record<string, unknown> = {}) => ({
- id, name: `DUPE-${id}.mp4`, path: `R:\\media\\DUPE-${id}.mp4`, location, drive: location === '115' ? 'B:' : 'R:',
- size: 1073741824, duration: 3600, is_largest: false, is_longest: false, ...patch,
-});
-
-/** 重复文件页按给定的两组打开:演示库里没有重复组。一组字节一致,一组本地与 115 混着。
- * 文件是造出来的,抽帧那一趟必然取不到,给它一张能加载完的图。 */
-async function openDuplicates(browser: Browser): Promise<Visit> {
- const opened = await visit(browser, '/duplicates', DESKTOP);
- const groups = [
- { code: 'DUPE-001', count: 2, identical: true, drives: ['R:'], cross_drive: false, reclaimable: 1073741824,
- files: [duplicateFile(9001, 'local', { is_largest: true }), duplicateFile(9002, 'local', { is_longest: true })] },
- { code: 'DUPE-002', count: 2, identical: false, drives: ['R:', 'B:'], cross_drive: true, reclaimable: 1073741824,
- files: [duplicateFile(9003, 'local', { is_largest: true, is_longest: true }), duplicateFile(9004, '115')] },
- ];
- await opened.page.route('**/api/duplicates?**', (route) => route.fulfill({
- status: 200, contentType: 'application/json',
- body: JSON.stringify({ total: 2, files: 4, reclaimable: 2147483648, groups }),
- }));
- await opened.page.route('**/thumb?**', (route) => route.fulfill({
- status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
- }));
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('#stats section[aria-label="DUPE-002"] .duplicate-row').first().waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return opened;
-}
-
-/** 打开一张索引页,名册与词表都换成桩:演示库的索引在一轮里会从空变成有,不桩的话
- * 这一条量到的可能是空态。名册第一格带一张桩图,其余只落首字母。 */
-async function openIndexPage(browser: Browser, path: string): Promise<Visit> {
- const opened = await visit(browser, path, DESKTOP);
- const json = (body: unknown) => ({ status: 200, contentType: 'application/json', body: JSON.stringify(body) });
- await opened.page.route('**/api/index?**', (route) => {
- const kind = new URL(route.request().url()).searchParams.get('kind');
- return route.fulfill(json(kind === 'tags'
- ? { items: [{ k: '痴女', n: 4, cat: 'role' }, { k: '秘书OL', n: 2, cat: 'scene' }], has_more: false,
- categories: { role: 1, scene: 1 } }
- : { items: [{ k: '甲', n: 3, members: 2, entity_id: 90_101, has_image: true }, { k: '乙', n: 1, members: 1 }],
- has_more: false }));
- });
- // 桩图要比框大:比框小的图按原尺寸摆,走的是另一条规则。
- await opened.page.route('**/entity-image?**', (route) => route.fulfill({
- status: 200, contentType: 'image/svg+xml',
- body: '<svg xmlns="http://www.w3.org/2000/svg" width="600" height="800"><rect width="600" height="800" fill="#888"/></svg>',
- }));
- await opened.page.route('**/api/follow/tags?**', (route) => route.fulfill(json({
- items: [{ k: 'some_artist', n: 5, cat: 'artist' }, { k: 'long_hair', n: 9, cat: 'general' }], has_more: false,
- categories: { artist: 1, general: 1 } })));
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('#index [data-index-cell], #index [data-alpha-tag], #index [data-tag-chip]').first()
- .waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return opened;
-}
-
-/** 一串 `box-shadow`(计算值或 token 原文)里最大的那个像素数:落影三层里最远那层的模糊半径。 */
-const farthestShadow = (shadow: string) =>
- Math.max(0, ...[...shadow.matchAll(/(\d+(?:\.\d+)?)px/g)].map((match) => Number(match[1])));
-
-/** 播放列表页按一份造出来的 `/api/playlists`(`src/peach/web_playlists.py`)打开:演示库里
- * 没有播放列表。第一份带三位署名,第二份没人(画标题首字),第三份是空列表(写「无预览」)。
- * 封面是造出来的编号,给一张能加载完的图。 */
-async function openPlaylistsPage(browser: Browser, viewport = DESKTOP): Promise<Visit> {
- const opened = await visit(browser, '/playlists', viewport);
- const face = (id: number, name: string, kind = 'performer') => ({ kind, id, name, has_image: false });
- const row = (id: number, patch: Record<string, unknown> = {}) => ({
- id, name: `列表${id}`, source_kind: 'manual', source_seed_asset_id: null, current_asset_id: null,
- created_at: '2026-09-01 10:00:00', updated_at: '2026-09-01 10:00:00', item_count: 2,
- preview_asset_id: 11, preview_ids: [11, 12], faces: [], ...patch,
- });
- await opened.page.route((url) => url.pathname === '/api/playlists', (route) => route.fulfill({ json: { items: [
- row(1, { source_kind: 'mix', faces: [face(901, '甲'), face(902, '乙'), face(903, '丙', 'creator')] }),
- row(2),
- row(3, { item_count: 0, preview_asset_id: null, preview_ids: [] }),
- ] } }));
- await opened.page.route('**/poster**', (route) => route.fulfill({
- status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
- }));
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('#stats [data-playlist-card]').first().waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return opened;
-}
-
-/** 打开目录并等到读数与卡片一起替下首屏骨架。 */
-async function openCatalog(browser: Browser): Promise<Visit> {
- const opened = await visit(browser, '/', DESKTOP);
- await opened.page.locator('[data-catalog-filter] [data-count-readout]').waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return opened;
-}
-
-/** 打开目录,两排头像与标签条用桩数据铺满:演示库那十几部作品凑不出一排标签。 */
-async function openCatalogBars(browser: Browser, viewport: Viewport = DESKTOP): Promise<Visit> {
- const opened = await visit(browser, '/', viewport);
- const performers = Array.from({ length: 6 }, (_, at) => ({
- id: 96_000 + at, k: `演示女优${at + 1}`, n: 30 - at, has_image: false, has_avatar: false, avatar_focus: null, rep: null,
- }));
- const studios = Array.from({ length: 3 }, (_, at) => ({ k: `演示厂牌${at + 1}`, n: 20 - at, has_logo: false }));
- const tags = Array.from({ length: 8 }, (_, at) => ({ k: `演示标签${at + 1}`, n: 90 - at }));
- await opened.page.route((url) => url.pathname === '/api/tops', (route) =>
- route.fulfill({ json: Number(new URL(route.request().url()).searchParams.get('page') || 0)
- ? { performers: [], studios: [] } : { performers, studios } }));
- await opened.page.route((url) => url.pathname === '/api/facets', async (route) => {
- const response = await route.fetch();
- await route.fulfill({ json: { ...await response.json(), tags } });
- });
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('[data-catalog-filter] [data-catalog-tag]').first().waitFor({ timeout: 15_000 });
- await opened.page.locator('[data-catalog-filter] [data-tier-studio]').first().waitFor({ timeout: 15_000 });
- await settle(opened.page);
- // 关页时还在路上的那一趟桩请求不算失败。
- return { ...opened, close: async () => {
- await opened.page.unrouteAll({ behavior: 'ignoreErrors' });
- await opened.close();
- } };
-}
-
-interface CatalogFixture {
- total: number;
- items: Array<Record<string, unknown>>;
- [key: string]: unknown;
-}
-
-/** 从演示库取一份能完整渲染的真实目录响应,只替换当前判据需要的字段。 */
-async function openCatalogFixture(
- browser: Browser,
- change: (payload: CatalogFixture, url: URL) => void,
-): Promise<Visit> {
- const opened = await visit(browser, '/', DESKTOP);
- let baseline: CatalogFixture | undefined;
- await opened.page.route(/\/api\/items\?/, async (route) => {
- const url = new URL(route.request().url());
- /* `visit()` 返回时,首屏还可能在后台续取下一页。路由接管之后若先撞上 offset>0,
- 那份响应本来就可能没有卡片,不能拿它当首屏基线;让旧请求原样完成,reload 后
- 再以 offset=0 的响应建立夹具。 */
- if (url.searchParams.get('offset') !== '0') {
- await route.continue();
- return;
- }
- if (!baseline) {
- const response = await route.fetch();
- baseline = await response.json() as CatalogFixture;
- }
- const payload = structuredClone(baseline);
- change(payload, url);
- await route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify(payload),
- });
- });
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('[data-catalog-filter] [data-count-readout]').waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return opened;
-}
-
-/** 一趟跑到一半的扫描与采集。 */
-const RUNNING_JOB = { status: 'running', stage: '采集缺失资料', checked: 38, total: 100 };
-
-/** 一趟断在半路、攒下一份长问题清单的扫描与采集:演示库里这两样都凑不出来。 */
-const FAILED_JOB = {
- status: 'failed', job_id: 'one', error: '处理被中断,请检查媒体目录后重试。',
- issue_count: 347, issues_truncated: true, retryable_asset_ids: [1, 2],
- issues_log: 'C:\\peach-data\\state\\library-processing-demo.issues.jsonl',
- issue_preview: Array.from({ length: 20 }, (_, at) => ({
- asset_id: at + 1, title: `示例-${at + 1}.mp4`, path: `B:\\番号\\示例-${at + 1}.mp4`,
- message: '封面未取得:javdb:本趟采集次数已用完,再跑一次接着采;已有图片保留',
- })),
-};
-
-/** 一条关注来源。字段以 `_source_payload`(`src/peach/web_follow.py`)为准。 */
-const followSource = (id: number, author: string, provider: string, label: string, status = 'ok') => ({
- id, provider: provider.toLowerCase(), provider_label: provider, ref: `ref/${id}`, label,
- url: `https://example.com/${id}`, enabled: true, last_status: status,
- last_checked_at: '2026-09-01T00:00:00Z', created_at: '2026-08-01T00:00:00Z',
- author_key: `name:${author}`, author_name: author,
-});
-
-/** 一个站的凭据状态。字段以 `/api/follow/credentials` 为准。 */
-const followCredential = (provider: string, requirement: string, present: boolean, missing: string[]) => ({
- provider: provider.toLowerCase(), provider_label: provider, followable: true, requirement,
- needs: missing, fields: present ? ['cookie'] : [], missing, present,
-});
-
-/** 关注管理页按一份造好的来源与凭据打开:演示库没有关注来源,也凑不齐四种凭据处境。
- * 站标同 `openScraping`:造出来的来源取不到图标,给一张能加载完的图。 */
-async function openFollowManage(browser: Browser, viewport = DESKTOP): Promise<Visit> {
- const opened = await visit(browser, '/follow-manage', viewport);
- await stubFollowManage(opened.page);
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('section[aria-label="kou 的关注来源"]').waitFor({ timeout: 15_000 });
- await settle(opened.page);
- return opened;
-}
-
-async function stubFollowManage(page: Page): Promise<void> {
- const json = (body: unknown) => ({ status: 200, contentType: 'application/json', body: JSON.stringify(body) });
- await page.route('**/api/follow?summary=1', (route) => route.fulfill(json({
- sources: [
- followSource(1, 'kou', 'Kemono', 'kou · Kemono'),
- followSource(2, 'kou', 'Pawchive', 'kou · Pawchive'),
- followSource(3, 'mira', 'Kemono', 'mira · Kemono', 'error'),
- ],
- counts: { new: 0, seen: 0, saved: 0, ignored: 0 },
- author_aliases: [{ canonical_key: 'kou', canonical_name: 'kou', aliases: [{ key: 'kou_art', name: 'kou_art' }] }],
- alias_suggestions: [],
- suggestions: [],
- })));
- await page.route('**/api/follow/credentials', (route) => route.fulfill(json({
- root: 'C:\\peach\\creds',
- providers: [
- followCredential('Fanbox', 'required', false, ['FANBOXSESSID']),
- followCredential('Patreon', 'optional', true, []),
- followCredential('OnlyFans', 'blocked', false, []),
- followCredential('Kemono', 'none', false, []),
- ],
- })));
- await page.route('**/source-icon**', (route) => route.fulfill({
- status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
- }));
- /* 服务端的定时检查可能正在跑,那一趟会让每颗检查键挂着 aria-busy,settle 等不到头。 */
- await page.route('**/api/follow/check', (route) => (route.request().method() === 'GET'
- ? route.fulfill(json({ status: 'idle' })) : route.fallback()));
-}
-
-/** 把 `/api/` 请求挂住,直到调用返回的 `release()`:首屏骨架停在屏幕上,量完再放行。
- * 先注册的桩照常生效:放行走 `fallback()`,交给它们或真实服务端。 */
-async function holdApi(page: Page): Promise<() => void> {
- let release!: () => void;
- const gate = new Promise<void>((resolve) => { release = resolve; });
- await page.route((url) => url.pathname.startsWith('/api/') && url.pathname !== '/api/settings', async (route) => {
- await gate;
- await route.fallback().catch(() => {});
- });
- return release;
-}
-
-/** 一组控件此刻的长相:面色、字色、边线、圆角与外框尺寸,以及按钮组的选中标记。 */
-async function controlFaces(page: Page, selectors: Record<string, string>) {
- return page.evaluate((map) => Object.fromEntries(Object.entries(map).map(([name, selector]) => {
- const node = document.querySelector(selector);
- if (!node) return [name, null];
- const style = getComputedStyle(node);
- const box = node.getBoundingClientRect();
- return [name, {
- face: `${style.backgroundColor} ${style.backgroundImage}`, ink: style.color,
- edge: `${style.borderTopWidth} ${style.borderTopColor}`, radius: style.borderTopLeftRadius,
- size: `${Math.round(box.width)}x${Math.round(box.height)}`, pressed: node.getAttribute('aria-pressed'),
- }];
- })), selectors);
-}
-
-/** 打开一位订了新作、有一排同台艺人的人物页。演示库里没有人物实体,资料照服务端下发的形状写。 */
-async function openPerformer(browser: Browser, viewport = DESKTOP): Promise<Visit> {
- const name = '七沢みあ';
- const opened = await visit(browser, '/', viewport);
- const costar = (id: number, k: string) => ({ id, k, n: 1, rep: null, has_image: false, has_avatar: false, avatar_focus: null });
- await opened.page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
- id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],
- user_aliases: [], asset_count: 0, tags: [],
- related_performers: ['本田愛华', '枢木葵', '美谷朱音', '高杉麻里', '高桥圣子', '今井夏帆'].map((k, at) => costar(90_002 + at, k)),
- links: [], metadata: {}, has_image: false, has_avatar: false, avatar_focus: null, representative_asset_id: null,
- entry_links: [
- { site: 'javdb', label: 'JavDB', ordinal: '', slot: 'mark', mark: 'mark-javdb', url: 'https://javdb.com/actors/NPD3' },
- { site: 'missav', label: 'MISSAV', ordinal: '', slot: 'mark', mark: '', url: 'https://missav.ai/actresses/x' },
- ],
- feed: { following: true },
- } }));
- await opened.page.goto(new URL(`/performers/${encodeURIComponent(name)}`, opened.page.url()).href, { waitUntil: 'load' });
- await opened.page.locator('[data-entry-feed]').waitFor({ timeout: 15_000 });
- await opened.page.locator('[data-entity-foot] [data-related-performer]').first().waitFor({ timeout: 15_000 });
- await settle(opened.page);
- await opened.page.evaluate(() => {
- document.documentElement.dataset.theme = 'light';
- document.documentElement.classList.remove('dark');
- });
- return opened;
-}
-
-/** 照片档:一部作品的两张官方样张加六张本地图片,缩略图都是 1×1 的图,量的是墙的几何。 */
-async function openPhotoWall(browser: Browser, viewport = DESKTOP): Promise<Visit> {
- const name = '七沢みあ';
- const opened = await visit(browser, '/', viewport);
- const { page } = opened;
- await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
- id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [], user_aliases: [],
- asset_count: 0, tags: [], related_performers: [], links: [], metadata: {}, has_image: false, has_avatar: false,
- avatar_focus: null, representative_asset_id: null, entry_links: [], feed: { following: false },
- } }));
- // 下一页一直不回:「载入更多」停在忙态,墙不再变,量得到那枚键的几何。
- await page.route(/\/api\/photos\?/, (route) => Number(new URL(route.request().url()).searchParams.get('offset') || 0) ? undefined : route.fulfill({ json: {
- kind: 'performer', name, entity_id: 90_001, total: 12, seed: '', has_more: true, sample_total: 2,
- items: Array.from({ length: 6 }, (_, i) => ({ id: 200 + i, name: `${200 + i}.jpg`, size: 1, location: 'media' })),
- sets: [{ id: 'code:SSIS-057', kind: 'code', code: 'SSIS-057', name: '雨の日', title: 'SSIS-057 雨の日', n: 2,
- release_date: '2021-05-18', site: 'dmm', site_label: 'DMM', has_cover: true }],
- } }));
- await page.route(/\/(?:photo-thumb|sample-thumb)\?/, (route) => route.fulfill({
- status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
- }));
- await page.goto(new URL(`/performers/${encodeURIComponent(name)}?media=photos`, page.url()).href, { waitUntil: 'load' });
- await page.locator('[data-local-wall] [data-photo-cell] img').first().waitFor({ timeout: 15_000 });
- await settle(page);
- return opened;
-}
-
-/** 本地图片那面墙的排法:网格数列宽,瀑布流数 column-count。 */
-const photoWallFaces = (page: Page) => page.evaluate(() => {
- const wall = document.querySelector<HTMLElement>('[data-local-wall]')!;
- const style = getComputedStyle(wall);
- const cell = wall.querySelector<HTMLElement>('[data-photo-cell]')!;
- const box = cell.getBoundingClientRect();
- return {
- display: style.display,
- columns: style.display === 'grid' ? style.gridTemplateColumns.split(' ').length : Number(style.columnCount),
- gap: style.columnGap,
- square: Math.abs(box.width - box.height) <= 1,
- };
-});
-
-/** 照片档里 `count` 张本地图,点开第一张的灯箱。大图是 `width`×`height` 的 SVG;取图口全部回桩图,
- * `/photo` 原图走计费来源,设计用例也不碰真的。 */
-async function openLightbox(browser: Browser, { count, width, height }: { count: number; width: number; height: number }):
- Promise<Visit & { box: Locator }> {
- const name = '七沢みあ';
- const opened = await visit(browser, '/', DESKTOP);
- const { page } = opened;
- const svg = (w: number, h: number) => ({ status: 200, contentType: 'image/svg+xml',
- body: `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="100%" height="100%" fill="#3a4a5a"/></svg>` });
- await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
- id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [], user_aliases: [],
- asset_count: 0, tags: [], related_performers: [], links: [], metadata: {}, has_image: false, has_avatar: false,
- avatar_focus: null, representative_asset_id: null, entry_links: [], feed: { following: false },
- } }));
- await page.route(/\/api\/photos\?/, (route) => route.fulfill({ json: {
- kind: 'performer', name, entity_id: 90_001, total: count, seed: '', has_more: false, sample_total: 0, sets: [],
- items: Array.from({ length: count }, (_, i) => ({ id: 300 + i, name: `${300 + i}.jpg`, size: 1, location: 'media' })),
- } }));
- await page.route(/\/photo\?/, (route) => route.fulfill(svg(width, height)));
- await page.route(/\/photo-thumb\?/, (route) => route.fulfill(svg(160, 120)));
- await page.goto(new URL(`/performers/${encodeURIComponent(name)}?media=photos`, page.url()).href, { waitUntil: 'load' });
- await page.locator('[data-photo-cell] img').first().waitFor({ timeout: 15_000 });
- await settle(page);
- await page.locator('[data-photo-cell]').first().click();
- const box = page.locator('dialog[data-photo-lightbox][open]');
- await box.waitFor();
- await page.waitForFunction(() => document.querySelector<HTMLImageElement>('[data-photo-main] .swiper-slide-active img')!
- .naturalWidth > 0, undefined, { timeout: 10_000 });
- return { ...opened, box };
-}
-
-/** 有 minnano-av 资料的女优。`profile` 与 `name_groups` 照 `peach.entity_profile.header` 的形状写,
- * 出道片名故意很长:资料表那一格要单行截断。 */
-const PROFILED = {
- name: '篠田ゆう',
- profile: {
- birth_date: '1991-07-21', age: 35, height: 155, bust: 86, waist: 60, hip: 87, cup: 'F',
- debut_date: '2010-12-02', debut_title: 'セキララ 〜今どき世代のゆるい性事情〜 03 はじめての撮影でとまどう素人娘の記録',
- active: { from: '2010', to: '2023' },
- tags: ['美乳', '美臀', '百合', '肛交', '巨乳', '高颜值', '苗条', '高个', '剛毛'],
- },
- name_groups: {
- reading: 'しのだゆう', shown: ['篠崎ゆう子', '高木早希', '橋本真紀'], total: 7,
- groups: [
- { label: '旧名义', names: [{ name: '篠崎ゆう子', reading: 'しのざきゆうこ' }] },
- { label: '舞ワイフ', names: [{ name: '橋本真紀' }, { name: '桧山彩音' }, { name: '篠田杏奈' }] },
- { label: 'ラグジュTV', names: [{ name: '高木早希' }] },
- { label: '其它', names: [{ name: '城田優子' }] },
- ],
- },
-};
-
-/** 打开一位有资料的女优:资料表、名字行和外链照服务端下发的形状写,主题按参数切好。
- * `extra` 覆盖资料里的字段:默认没有看片那一行(`entry_links` 只有 minnano-av 那枚 pill、没有 `feed`),
- * 要验两行都在的几何就从这里补。 */
-async function openProfiledPerformer(browser: Browser, viewport = DESKTOP, theme: 'light' | 'dark' = 'light',
- extra: Record<string, unknown> = {}): Promise<Visit> {
- const opened = await visit(browser, '/', viewport);
- await opened.page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
- id: 90_101, kind: 'performer', canonical_name: PROFILED.name, aliases: ['篠崎ゆう子'], display_aliases: ['篠崎ゆう子'],
- user_aliases: [], asset_count: 42, tags: [], related_performers: [], metadata: {},
- has_image: false, has_avatar: false, avatar_focus: null, representative_asset_id: null,
- agency: { id: 90_102, canonical_name: 'New Actor eXperience', source: 'test', checked_at: '' },
- links: [
- { link_id: 90_201, link_kind: 'official', clickable: true, label: 'New Actor eXperience',
- url: 'https://official.nax-pro.com/actress/shinoda' },
- { link_id: 90_202, link_kind: 'social', clickable: true, label: 'X @shinoda_yu', url: 'https://x.com/shinoda_yu' },
- ],
- entry_links: [{ site: 'minnano-av', label: 'みんなのAV', ordinal: '', slot: 'pill', mark: 'brand-minnano',
- url: 'https://www.minnano-av.com/actress12345.html' }],
- profile: PROFILED.profile, name_groups: PROFILED.name_groups,
- ...extra,
- } }));
- // 这几条链接是造出来的,服务端的圆标取不到;那是另一条判据,这里给一张能加载完的图。
- await opened.page.route('**/link-mark**', (route) => route.fulfill({
- status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
- }));
- await opened.page.goto(new URL(`/performers/${encodeURIComponent(PROFILED.name)}`, opened.page.url()).href, { waitUntil: 'load' });
- await opened.page.locator('[data-entity-card] [data-entity-links]').waitFor({ timeout: 15_000 });
- await settle(opened.page);
- await opened.page.evaluate((dark) => {
- document.documentElement.dataset.theme = dark ? 'dark' : 'light';
- document.documentElement.classList.toggle('dark', dark);
- }, theme === 'dark');
- return opened;
-}
-
-/** 资料卡浮层的落影要和遗留 `.popmenu` 同一副:在同一页造一个空 `.popmenu` 取它的计算值。 */
-async function popmenuShadow(page: Page): Promise<string> {
- return page.evaluate(() => {
- const menu = document.body.appendChild(Object.assign(document.createElement('div'), { className: 'popmenu' }));
- const shadow = getComputedStyle(menu).boxShadow;
- menu.remove();
- return shadow;
- });
-}
-
-/** 下拉栏里一部作品的小图。字段以 `_suggest_work_card`(`src/peach/web_entity.py`)为准。 */
-const suggestCard = (id: number) => ({ id, code: `ABW-${id % 1000}`, has_cover: true, has_thumb: false, cover_frame: null, poster_box: null });
-
-/** 一段输入命中女优、厂牌与视频三类的补全,字段以 `q_suggest` 为准。演示库里没有女优实体。 */
-const SUGGEST = {
- q: '涼森',
- groups: [
- { kind: 'performer', label: '女优', total: 2, items: [
- { value: '涼森れむ', n: 128, matched: '', id: null, entity_id: 90_301, has_image: true, avatar_focus: null, rep: null,
- agency: 'Capsule Agency', works: [1, 2, 3, 4].map((at) => suggestCard(90_400 + at)) },
- { value: '涼森ひより', n: 3, matched: 'すずもりひより', id: null, entity_id: 90_302, has_image: false, rep: null,
- agency: '', works: [] },
- ] },
- { kind: 'studio', label: '厂牌', total: 1, items: [
- { value: 'Prestige', n: 900, matched: '', id: null, entity_id: 90_303, has_image: false, has_logo: true },
- ] },
- { kind: 'asset', label: '视频', total: 12, items: [1, 2, 3, 4, 5].map((at) => ({
- value: `ABW-${500 + at}`, n: 0, matched: '', id: 90_500 + at, code: `ABW-${500 + at}`,
- title: '出演作', who: '涼森れむ', card: suggestCard(90_500 + at),
- })) },
- ],
-};
-
-/** 补全、下拉里的图和点进去的资料页都按上面那份造好的数据答。返回每次补全请求问的种类。
- * 图是造出来的实体和番号,服务端取不到;那是另一条判据,这里给一张能加载完的图。 */
-async function stubSuggest(page: Page): Promise<string[]> {
- const kinds: string[] = [];
- await page.route(/\/api\/suggest\?/, (route) => {
- const kind = new URL(route.request().url()).searchParams.get('kind') || '';
- kinds.push(kind);
- return route.fulfill({ json: { q: SUGGEST.q, groups: SUGGEST.groups.filter((group) => !kind || group.kind === kind) } });
- });
- await page.route(/\/(?:cover|entity-image|avatar|logo)\?/, (route) => route.fulfill({
- status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
- }));
- await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
- id: 90_301, kind: 'performer', canonical_name: '涼森れむ', aliases: [], display_aliases: [], user_aliases: [],
- asset_count: 0, tags: [], related_performers: [], links: [], metadata: {}, entry_links: [],
- has_image: false, has_avatar: false, avatar_focus: null, representative_asset_id: null,
- } }));
- return kinds;
-}
-
-/** 资料卡此刻的几何:身份列、资料表与卡本身的外框,以及资料表那道分隔线落在哪一边。 */
-async function heroGeometry(page: Page) {
- return page.evaluate(() => {
- const rect = (selector: string) => {
- const box = document.querySelector(selector)?.getBoundingClientRect();
- return box ? { left: box.left, right: box.right, top: box.top, bottom: box.bottom } : null;
- };
- const hero = document.querySelector('[data-entity-card]')!;
- const facts = document.querySelector('[data-entity-facts]');
- const style = facts ? getComputedStyle(facts) : null;
- return {
- hero: rect('[data-entity-card]'), identity: rect('[data-entity-identity]'), facts: rect('[data-entity-facts]'),
- heroScrolls: hero.scrollWidth > hero.clientWidth + 1,
- rule: style ? { left: style.borderLeftWidth, top: style.borderTopWidth } : null,
- labels: [...document.querySelectorAll('[data-entity-facts] dt')].map((dt) => dt.textContent!.trim()),
- };
- });
-}
-
-/** 禁用档的三样颜色(peach-web-ui「按钮悬停只抬填充」那条):`--surface` 底、`--border-15` 边、`--muted` 字。 */
-async function disabledTokens(page: Page) {
- return {
- face: await tokenColor(page, '#main', '--surface'),
- ink: await tokenColor(page, '#main', '--muted'),
- ring: await tokenColor(page, '#main', '--border-15'),
- };
-}
-
-/** 骨架里等数据的操作键此刻的长相与状态,按文档顺序。 */
-async function waitingActionFaces(page: Page, selector: string) {
- return page.locator(selector).evaluateAll((buttons) => buttons.map((button) => {
- const style = getComputedStyle(button);
- return {
- name: (button.getAttribute('aria-label') || button.textContent || '').trim(),
- disabled: (button as HTMLButtonElement).disabled, cursor: style.cursor, opacity: style.opacity,
- face: style.backgroundColor, image: style.backgroundImage, ink: style.color, ring: style.boxShadow,
- split: !!button.closest('[data-split-button]'),
- };
- }));
-}
-
-function assertDisabledFace(face: Awaited<ReturnType<typeof waitingActionFaces>>[number],
- expected: Awaited<ReturnType<typeof disabledTokens>>): void {
- assert.equal(face.disabled, true, `${face.name} 在骨架里没有禁用`);
- assert.equal(face.cursor, 'not-allowed', `${face.name} 在骨架里的光标不是禁用那一种`);
- assert.equal(face.opacity, '1', `${face.name} 的禁用态靠透明度,而不是换颜色`);
- assert.equal(face.face, expected.face, `${face.name} 在骨架里不是禁用底色`);
- assert.equal(face.image, 'none', `${face.name} 在骨架里还铺着渐变`);
- assert.equal(face.ink, expected.ink, `${face.name} 在骨架里不是禁用字色`);
- // 分体键的外圈画在整组上,两半各画一圈的话中缝会出现两道线。
- if (!face.split) assert.ok(face.ring.includes(expected.ring), `${face.name} 在骨架里没有禁用描边:${face.ring}`);
-}
-
-/** 切到关注管理页的另一栏。栏名后面可能挂着待配置的数目,按开头认。 */
-async function followTab(opened: Visit, name: string): Promise<void> {
- await opened.page.locator('#stats').getByRole('tab', { name: new RegExp(`^${name}`) }).click({ timeout: 5_000 });
- await settle(opened.page);
-}
-
-describe('设计决定', () => {
- let browser: Browser;
- let browserTests = 0;
-
- before(async () => {
- browser = await launch();
- });
-
- beforeEach(async () => {
- // 每个浏览器至多运行 8 项,页面与图像缓存的累积占用受限。
- if (browserTests === 8) {
- await browser.close();
- browser = await launch();
- browserTests = 0;
- }
- browserTests += 1;
- });
-
- after(async () => {
- await browser.close();
- });
-
- it('聚焦 React 输入框只画 BoardUI 外框,旧样式表的焦点环不进来', { timeout: 60_000 }, async () => {
- const opened = await openAccess(browser);
- try {
- const input = opened.form.locator('#access-password');
- await input.focus();
- const style = await input.evaluate((element) => ({
- outline: getComputedStyle(element).outlineStyle,
- // TextField 经 GroupContext 把外框的 role 设成 presentation。
- ring: getComputedStyle(element.closest('[role="presentation"]')!).boxShadow,
- }));
- assert.equal(style.outline, 'none', '输入框自己画了 outline:旧的全局 :focus-visible 进了 React 子树');
- assert.notEqual(style.ring, 'none', '外框没有聚焦描边');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('详情舞台的焦点:骨架期间留在浮窗本身、不画焦点环,内容到了交给关闭键', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, '/', DESKTOP, { ready: `#grid [data-media-card][data-id="${ITEM.plain}"]` });
- try {
- const page = opened.page;
- let release = () => {};
- const held = new Promise<void>((resolve) => { release = resolve });
- await page.route((url) => url.pathname === '/api/item', async (route) => { await held; await route.fallback() });
- await page.locator(`#grid [data-media-card][data-id="${ITEM.plain}"] [data-media-title]`).first().press('Enter');
- await page.locator('#stage[open] [data-skeleton="detail"]').waitFor();
- /* 键盘打开也一样:骨架里没有可操作的东西,焦点环画在浮窗外沿上只是一圈噪声。 */
- const waiting = await page.evaluate(() => {
- const focused = document.activeElement as HTMLElement;
- return { id: focused?.id, outline: getComputedStyle(focused).outlineStyle, visible: focused.matches(':focus-visible') };
- });
- assert.equal(waiting.id, 'stage', '骨架期间焦点不在浮窗上');
- assert.equal(waiting.outline, 'none', `骨架期间浮窗画了焦点环(:focus-visible=${waiting.visible})`);
- release();
- await page.locator('#stage[open] [data-item-side]').waitFor();
- await page.waitForFunction(() => document.activeElement?.id === 'closeStage', null, { timeout: 5_000 });
- assert.deepEqual(opened.problems.filter((line) => !line.includes('VIDEOJS')), []);
- } finally {
- await opened.close();
- }
- });
-
- it('React 子树读 BoardUI 的 token 原值,不被 board.css 的同名定值盖掉', { timeout: 60_000 }, async () => {
- const opened = await openAccess(browser);
- try {
- const shell = await opened.form.locator('#access-password').evaluate(
- (element) => getComputedStyle(element.closest('[role="presentation"]')!).backgroundColor);
- // BoardUI theme.css 浅色 neutral-200 是 #ebebeb;board.css 在 :root 上给的是 #e5e5e5。
- assert.equal(shell, 'rgb(235, 235, 235)');
- assert.equal(await tokenColor(opened.page, ':root', '--color-background-tertiary-default'), 'rgb(229, 229, 229)');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('持久警示是状态色块,不和字段说明共用灰色小字', { timeout: 60_000 }, async () => {
- const opened = await openAccess(browser);
- try {
- await opened.form.getByText('关闭访问密码', { exact: true }).click({ timeout: 5_000 });
- const note = opened.form.locator('[role="note"]');
- await note.waitFor({ timeout: 5_000 });
- const surface = await note.evaluate((element) => getComputedStyle(element).backgroundColor);
- assert.notEqual(surface, 'rgba(0, 0, 0, 0)', '警示没有底色');
- assert.equal(surface, await tokenColor(opened.page, '.peach-react', '--color-status-yellow-background'));
- const ink = await note.evaluate((element) => getComputedStyle(element).color);
- const hint = await opened.form.getByText('关闭访问密码时无需填写。').evaluate((element) => getComputedStyle(element).color);
- assert.notEqual(ink, hint, '警示文字和字段说明同色');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('跑失败的那一轮整张卡框线换成 danger 色,结束原因还是正文色', { timeout: 60_000 }, async () => {
- const opened = await openActivity(browser, [
- settledRun(1, 'failed', '扫描与采集'), settledRun(2, 'succeeded', '追更检查'),
- ]);
- try {
- const danger = await tokenColor(opened.page, '.peach-react', '--color-border-error-default');
- const border = (status: string) => opened.page.locator(`li[data-status="${status}"]`)
- .evaluate((element) => getComputedStyle(element).borderTopColor);
- assert.equal(await border('failed'), danger, '失败卡的框线不是 danger 色');
- assert.notEqual(await border('succeeded'), danger, '没失败的卡也用了 danger 框线');
- // 一屏十几行里逐行读红字比看一眼哪张卡的框是红的慢:原因那行留正文色。
- const reason = await opened.page.locator('li[data-status="failed"] p').last()
- .evaluate((element) => getComputedStyle(element).color);
- assert.notEqual(reason, danger, '结束原因那行字被涂成了 danger 色');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('状态徽章只有三档颜色:成功绿、失败红、被叫停黄,其余中性', { timeout: 60_000 }, async () => {
- const opened = await openActivity(browser, [
- settledRun(1, 'succeeded', '追更检查'), settledRun(2, 'failed', '扫描与采集'),
- settledRun(3, 'cancelled', '批量操作'), settledRun(4, 'pending', '命令行批处理'),
- ]);
- try {
- const badge = (status: string) => opened.page.locator(`li[data-status="${status}"] span`).first()
- .evaluate((element) => getComputedStyle(element).backgroundColor);
- const token = (name: string) => tokenColor(opened.page, '.peach-react', name);
- assert.equal(await badge('succeeded'), await token('--color-status-lime-background'));
- assert.equal(await badge('failed'), await token('--color-status-rose-background'));
- assert.equal(await badge('cancelled'), await token('--color-status-yellow-background'));
- // 第四种状态不另给颜色:三档之外都读同一个中性底,颜色才还说得出「成功/失败/被叫停」。
- assert.equal(await badge('pending'), await token('--color-background-tertiary-default'));
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('高清版卡片的封面是 150px 宽的 16/10 方块,长标题从中间省略', { timeout: 60_000 }, async () => {
- const long = '这是一个长到必须省略才放得下的文件名,用来盯住中间截断在 React 插进来的节点上也生效.mp4';
- const opened = await openQualityGoals(browser, [
- qualityGoal(1, long), qualityGoal(2, 'short.mp4'),
- ]);
- try {
- const cover = opened.page.locator('li[data-goal-id="1"] button').first();
- const box = await cover.evaluate((element) => ({
- width: getComputedStyle(element).width,
- ratio: getComputedStyle(element).aspectRatio,
- }));
- assert.equal(box.width, '150px');
- assert.equal(box.ratio.replaceAll(' ', ''), '16/10');
- // 中间截断由 `web/js/middle-truncate.js` 的 MutationObserver 接手:React 插进来的
- // 节点不经过遗留层的渲染函数,观察器认不出它就只剩尾部省略。
- const title = opened.page.locator('li[data-goal-id="1"] h3 button');
- await title.waitFor({ timeout: 5_000 });
- await opened.page.locator('li[data-goal-id="1"] h3 button.middle-truncated')
- .waitFor({ timeout: 10_000 });
- assert.ok((await title.textContent())!.includes('…'), '长标题没有被省略');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('一张来源卡底下只有写入那一颗是主按钮,其余次级', { timeout: 60_000 }, async () => {
- const opened = await openScraping(browser);
- try {
- const card = opened.page.locator('form[aria-label="演示来源甲"]');
- const fill = (name: string) => card.getByRole('button', { name, exact: true })
- .evaluate((element) => getComputedStyle(element).backgroundColor);
- // 收 Cookie 且已存了一份的来源,底下三颗:撤销、检查、保存;只有保存是写入。
- assert.equal(await fill('保存'), await tokenColor(opened.page, '.peach-react', '--color-button-primary'));
- const secondary = await tokenColor(opened.page, '.peach-react', '--color-background-primary-default');
- assert.equal(await fill('检查连接'), secondary, '检查连接被画成了主按钮');
- assert.equal(await fill('撤销 Cookie'), secondary, '撤销 Cookie 被画成了主按钮');
- // 没存过 Cookie 的来源没有可撤的对象,那一颗不画。
- const plain = opened.page.locator('form[aria-label="演示来源乙"]');
- assert.equal(await plain.getByRole('button', { name: '撤销 Cookie', exact: true }).count(), 0);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('目录页那条处理横幅在跑的时候不占语气色,失败了才换成状态红并报警', { timeout: 60_000 }, async () => {
- const running = await openProcessing(browser, '/', RUNNING_JOB);
- try {
- const banner = running.page.locator('#libraryProcessingNotice [role="status"]');
- await banner.waitFor({ state: 'visible', timeout: 15_000 });
- assert.match(await banner.innerText(), /采集缺失资料 · 38 \/ 100/);
- // 一圈长度钉成 100,画出来的那一段就是百分比本身。
- assert.equal(await banner.locator('[role="progressbar"]').getAttribute('aria-valuenow'), '38');
- // 判据是「不是语气色」,不钉某一个具体的底:在跑那条走中性底,黄与红留给出事的时候。
- const tint = await banner.evaluate((element) => getComputedStyle(element).backgroundColor);
- for (const tone of ['--color-background-tertiary-error', '--color-status-yellow-background']) {
- assert.notEqual(tint, await tokenColor(running.page, '.peach-react', tone),
- '任务在跑是正在发生的事,配上状态底色就和「出事了」一个分量');
- }
- } finally {
- await running.close();
- }
-
- const failed = await openProcessing(browser, '/', { status: 'failed', error: '来源离线' });
- try {
- const banner = failed.page.locator('#libraryProcessingNotice [role="alert"]');
- await banner.waitFor({ state: 'visible', timeout: 15_000 });
- /* 计算值现在是 `oklab()`/`oklch()`,两种记法之间没法直接比字符串,所以统一在
- canvas 上取回 RGBA 再比。 */
- const surface = await banner.evaluate((element) => {
- const style = getComputedStyle(element);
- const context = document.createElement('canvas').getContext('2d')!;
- const paint = (color: string) => {
- context.clearRect(0, 0, 1, 1);
- context.fillStyle = color;
- context.fillRect(0, 0, 1, 1);
- return [...context.getImageData(0, 0, 1, 1).data];
- };
- return { tint: style.backgroundColor, line: paint(style.borderTopColor), ink: paint(style.color) };
- });
- assert.equal(surface.tint,
- await tokenColor(failed.page, '.peach-react', '--color-background-tertiary-error'));
- // 上下两条线取自己的文字色:红底上横一条中性灰线,读起来是把这一条切成了两半。
- for (const at of [0, 1, 2]) {
- assert.ok(Math.abs(surface.line[at]! - surface.ink[at]!) <= 2,
- `横幅的线没跟着语气走:线 ${surface.line} 与字 ${surface.ink} 不是同一个色`);
- }
- assert.ok(surface.line[3]! < surface.ink[3]!,
- '线和字一样实,整条读起来像三行字');
- // 垃圾文件也是目录路径,但它是数据管理底下的一页:同一趟失败的任务,横幅不跟进去。
- await failed.page.goto(new URL('/junk-files', failed.page.url()).href, { waitUntil: 'load' });
- await failed.page.locator('[data-junk-filters]').waitFor({ state: 'visible', timeout: 15_000 });
- await failed.page.waitForTimeout(1_000);
- assert.equal(await failed.page.locator('#libraryProcessingNotice [role="alert"]').count(), 0,
- '垃圾文件页顶上挂了目录页的处理横幅');
- } finally {
- await failed.close();
- }
- });
-
- it('扫描卡的进度条走焦点环色,底槽是三级底,按下的那颗键转成忙态', { timeout: 60_000 }, async () => {
- const opened = await openProcessing(browser, '/data-cleanup', RUNNING_JOB);
- try {
- const card = opened.page.locator('section[aria-label="扫描与采集"]');
- await card.waitFor({ state: 'visible', timeout: 15_000 });
- const bar = card.locator('[role="progressbar"]');
- assert.equal(await bar.getAttribute('aria-valuenow'), '38');
- assert.equal(await bar.getAttribute('aria-valuemax'), '100');
- const fill = (at: number) =>
- bar.locator('rect').nth(at).evaluate((element) => getComputedStyle(element).fill);
- assert.equal(await fill(0),
- await tokenColor(opened.page, '.peach-react', '--color-background-tertiary-default'));
- assert.equal(await fill(1),
- await tokenColor(opened.page, '.peach-react', '--color-border-focus-ring'));
- // 忙态不改 `disabled`:控件仍可聚焦,重复触发由页面自己挡。
- const scan = card.getByRole('button', { name: '扫描并补全资料', exact: true });
- assert.equal(await scan.getAttribute('aria-busy'), 'true');
- assert.equal(await scan.evaluate((element) => (element as HTMLButtonElement).disabled), false,
- '用原生 disabled 挡的话按钮连焦点都拿不到');
- const split = card.locator('[data-split-button]');
- const parts = split.locator(':scope > button');
- assert.equal(await parts.count(), 2, '拆分按钮没有保持主操作与菜单两区');
- const boxes = await parts.evaluateAll((buttons) => buttons.map((button) => {
- const rect = button.getBoundingClientRect();
- return { left: rect.left, right: rect.right, height: rect.height };
- }));
- assert.ok(Math.abs(boxes[0]!.right - boxes[1]!.left) < 0.5,
- '拆分按钮两区之间留了空隙');
- assert.equal(boxes[0]!.height, boxes[1]!.height, '拆分按钮两区高度不一致');
- const divider = await parts.nth(1).evaluate((element) => {
- const style = getComputedStyle(element, '::after');
- return { width: style.width, color: style.backgroundColor };
- });
- assert.equal(divider.width, '1px', '拆分按钮分隔线宽度不对');
- assert.notEqual(divider.color, 'rgba(0, 0, 0, 0)', '拆分按钮分隔线没有颜色');
- } finally {
- await opened.close();
- }
- });
-
- it('拆分按钮两半各自抬填充:悬停哪半只有哪半变,中缝那条线不动', { timeout: 60_000 }, async () => {
- // Geist 实测(`vercel-geist-split-button.md`「悬停」):两半各是一颗有自己底色的按钮,
- // 悬停只抬指针下那一颗;分隔线是触发档 `::before`,`left:-1px` 盖在主动作最后一列上,
- // 高度顶满、颜色不随悬停变。
- const opened = await openProcessing(browser, '/data-cleanup', { status: 'idle' });
- try {
- // 骨架那张卡同名同结构,等到 React 接管、两半不再带骨架标记才量。
- const split = opened.page.locator('section[aria-label="扫描与采集"] [data-split-button]:not(:has(> [data-skeleton-action]))');
- await split.waitFor({ state: 'visible', timeout: 15_000 });
- await settle(opened.page);
- const parts = split.locator(':scope > button');
- const faces = () => parts.evaluateAll((buttons) => buttons.map((button) => {
- const style = getComputedStyle(button), lift = getComputedStyle(button, '::before');
- return { fill: style.backgroundImage, lift: lift.opacity, ink: style.color };
- }));
- const seam = () => parts.nth(1).evaluate((element) => {
- const line = getComputedStyle(element, '::after');
- return { color: line.backgroundColor, width: line.width, left: line.left,
- height: line.height, full: `${element.getBoundingClientRect().height}px`,
- clip: getComputedStyle(element).overflowX };
- });
- assert.equal(await split.evaluate((element) => getComputedStyle(element).backgroundImage), 'none',
- '底色画在整组上,两半就没法各自抬填充');
- await opened.page.mouse.move(0, 0);
- const rest = await faces();
- assert.match(rest[0]!.fill, /gradient/, '主动作那半没有自己的蓝色填充');
- assert.equal(rest[1]!.fill, rest[0]!.fill, '两半静止时不是同一档填充');
- assert.deepEqual(rest.map((face) => face.lift), ['0', '0'], '没悬停就抬了填充');
- const line = await seam();
- assert.equal(line.width, '1px');
- assert.equal(line.left, '-1px', '分隔线该盖在主动作最后一列上,不占触发档的宽度');
- assert.equal(line.height, line.full, '分隔线没有上下顶满');
- assert.equal(line.clip, 'visible', '触发档把伸到左邻上的分隔线裁掉了,屏幕上看不见');
- assert.notEqual(line.color, 'rgba(0, 0, 0, 0)');
- for (const [at, other] of [[0, 1], [1, 0]] as const) {
- await parts.nth(at).hover();
- // 悬停层按 150ms 淡入淡出,直接读会落在半路;走到终点再比。
- await opened.page.evaluate(() => document.getAnimations().forEach((animation) => animation.finish()));
- const hovered = await faces();
- assert.equal(hovered[at]!.lift, '1', `悬停第 ${at + 1} 半没有抬填充`);
- assert.equal(hovered[other]!.lift, '0', `悬停第 ${at + 1} 半时另一半也跟着变了`);
- assert.deepEqual(hovered.map((face) => face.ink), rest.map((face) => face.ink), '悬停改了字色');
- assert.deepEqual(await seam(), line, '悬停时分隔线变了');
- }
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('失败提示里重试键靠右,问题清单铺满提示并走覆盖式滚动条', { timeout: 60_000 }, async () => {
- const opened = await openProcessing(browser, '/data-cleanup', FAILED_JOB);
- try {
- const alert = opened.page.locator('#libraryProcessing [role="alert"]');
- await alert.waitFor({ state: 'visible', timeout: 15_000 });
- await alert.locator('summary').click();
- const list = alert.locator('ul');
- await list.waitFor({ state: 'visible', timeout: 5_000 });
- const geometry = await alert.evaluate((element) => {
- const note = element.getBoundingClientRect();
- const button = element.querySelector('button')!.getBoundingClientRect();
- const items = element.querySelector('ul')!;
- return {
- padding: parseFloat(getComputedStyle(element).paddingRight),
- noteRight: note.right, buttonRight: button.right,
- listRight: items.getBoundingClientRect().right,
- client: items.clientWidth, offset: items.offsetWidth,
- track: !!element.querySelector('.ovtrack'),
- };
- });
- assert.ok(geometry.noteRight - geometry.buttonRight - geometry.padding < 1,
- '重试键没有贴着提示的右内边,读起来就不是这条提示的主动作');
- assert.ok(geometry.noteRight - geometry.listRight - geometry.padding < 1,
- '问题清单没有铺满提示的宽度');
- assert.equal(geometry.client, geometry.offset, '原生滚动条还占着清单右边一列');
- assert.ok(geometry.track, '清单没有挂上全站那条覆盖式滚动条');
- /* 同一块红底上叠着三段:结论、清单、完整记录。条与条之间要看得见界,完整记录
- 要退回灰字——它不是这条提示在说的事,是出事之后自己去翻的东西。 */
- const layering = await alert.evaluate((element) => {
- const context = document.createElement('canvas').getContext('2d')!;
- const paint = (color: string) => {
- context.clearRect(0, 0, 1, 1);
- context.fillStyle = color;
- context.fillRect(0, 0, 1, 1);
- return [...context.getImageData(0, 0, 1, 1).data];
- };
- // `divide-y` 把线画在每条的下缘(末条除外),所以量的是第一条的下边。
- const first = element.querySelectorAll('li')[0]!;
- const log = element.querySelector('details p')!;
- return {
- divider: parseFloat(getComputedStyle(first).borderBottomWidth),
- dividerInk: paint(getComputedStyle(first).borderBottomColor),
- logInk: paint(getComputedStyle(log).color),
- bodyInk: paint(getComputedStyle(element).color),
- };
- });
- assert.ok(layering.divider > 0, '两条明细之间没有界,几十条连成一片');
- assert.ok(layering.dividerInk[3]! < layering.bodyInk[3]!, '条间的线和正文一样实');
- assert.ok([0, 1, 2].some((at) => Math.abs(layering.logInk[at]! - layering.bodyInk[at]!) > 8),
- '完整记录还跟着提示是红的,读起来像又出了一件事');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('新窗口打开的来源地址两项 rel 都写:不带走会话,也不带走来处', { timeout: 60_000 }, async () => {
- const opened = await openScraping(browser);
- try {
- const link = opened.page.locator('form[aria-label="演示来源甲"] a[target="_blank"]');
- assert.equal(await link.getAttribute('href'), 'https://demoa.example/login');
- assert.equal((await link.getAttribute('rel'))!.split(/\s+/).sort().join(' '), 'noopener noreferrer');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('顶栏版式键保留两枚字形并原地换态', { timeout: 60_000 }, async () => {
- const opened = await openCatalog(browser);
- try {
- await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
- const button = opened.page.locator('#density');
- const swap = button.locator('[data-icon-swap]');
- await swap.waitFor({ timeout: 5_000 });
- assert.equal(await swap.locator('[data-icon]').count(), 2);
- const before = await swap.getAttribute('data-icon-state');
- await swap.evaluate((element) => { element.setAttribute('data-test-identity', 'density-swap'); });
- await button.click();
- assert.notEqual(await swap.getAttribute('data-icon-state'), before,
- '按下后仍停在同一枚字形');
- assert.equal(await swap.locator('[data-icon]').count(), 2,
- '换态不应销毁其中一枚字形');
- await button.click();
- assert.equal(await swap.getAttribute('data-icon-state'), before, '第二次按下没有回到原字形');
- assert.equal(await button.locator('[data-icon-swap][data-test-identity="density-swap"]').count(), 1,
- '两次换态之间重建了字形容器');
- } finally {
- await opened.close();
- }
- });
-
- it('读数首次静态落笔,变值时每一位都有有效动画', { timeout: 60_000 }, async () => {
- const opened = await openCatalogFixture(browser, (payload, url) => {
- payload.total = url.searchParams.has('q') ? 34 : 12;
- });
- try {
- await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
- const result = await opened.page.evaluate(async () => {
- const { popCount } = await import('/js/ui-components.js');
- const host = document.createElement('span');
- document.body.append(host);
- popCount(host, '12');
- const firstWasStatic = !host.firstElementChild?.classList.contains('popping');
- popCount(host, '34');
- const digit = host.querySelector<HTMLElement>('.digits.popping > span');
- const style = digit && getComputedStyle(digit);
- const answer = {
- firstWasStatic,
- animationName: style?.animationName || '',
- duration: style?.animationDuration || '',
- };
- host.remove();
- return answer;
- });
- assert.equal(result.firstWasStatic, true, '首次写入不应弹动');
- assert.equal(result.animationName, 'digit-pop-in');
- assert.equal(result.duration, '0.25s');
-
- const input = opened.page.locator('#q');
- await opened.page.evaluate(() => {
- document.documentElement.removeAttribute('data-count-animation');
- const count = document.querySelector('[data-catalog-filter]');
- const observer = new MutationObserver(() => {
- const digit = count?.querySelector<HTMLElement>('[data-count-readout] .digits.popping > span');
- if (!digit) return;
- const style = getComputedStyle(digit);
- document.documentElement.dataset.countAnimation = JSON.stringify({
- animationName: style.animationName,
- duration: style.animationDuration,
- });
- observer.disconnect();
- });
- observer.observe(count!, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });
- });
- await input.fill('读数变值');
- await input.press('Enter');
- await opened.page.waitForFunction(() =>
- document.querySelector('[data-catalog-filter] [data-count-readout]')?.textContent?.includes('34 个符合'));
- /* 读数更新后还可能因自动续页再重画。在触发前观察真实节点,既能验收
- 动画的计算值,也不把断言绑在之后某一次采样恰好撞上短暂节点。 */
- await opened.page.waitForFunction(() =>
- document.documentElement.hasAttribute('data-count-animation'), undefined, { timeout: 5_000 });
- const liveAnimation = await opened.page.evaluate(() =>
- JSON.parse(document.documentElement.dataset.countAnimation || '{}') as {
- animationName?: string; duration?: string;
- });
- assert.equal(liveAnimation.animationName, 'digit-pop-in', '真实读数节点变值后没有播放动画');
- assert.equal(liveAnimation.duration, '0.25s');
- } finally {
- await opened.close();
- }
- });
-
- it('五枚叠放头像只朝标题方向展开,左缘和窄卡边界不动', { timeout: 60_000 }, async () => {
- const names = Array.from({ length: 7 }, (_, index) => `演示演员 ${index + 1}`);
- const opened = await openCatalogFixture(browser, (payload) => {
- const item = payload.items[0];
- if (!item) throw new Error('演示目录没有可替换的卡片');
- item.creator = '';
- item.performers = names;
- item.performer_total = names.length;
- item.performer_entities = names.map((name, index) => ({ id: 90_000 + index, name, has_image: false }));
- });
- try {
- await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
- const stack = opened.page.locator('[data-media-card][data-id] [data-media-avatars]').first();
- await stack.waitFor({ timeout: 5_000 });
- const avatars = stack.locator('[data-media-avatar]');
- assert.equal(await avatars.count(), 5, 'API 给七位表演者时卡片没有收在五枚以内');
- const before = await avatars.evaluateAll((items) => items.map((item) => item.getBoundingClientRect().x));
- const left = (await stack.boundingBox())!.x;
- const waitForAvatarMotion = () => stack.evaluate(async (element) => {
- const animations = element.getAnimations({ subtree: true });
- await Promise.all(animations.map((animation) => animation.finished.catch(() => undefined)));
- });
-
- await avatars.first().hover();
- await waitForAvatarMotion();
- const firstSpread = await avatars.evaluateAll((items) => items.map((item) => item.getBoundingClientRect().x));
- for (let index = 1; index < firstSpread.length; index += 1) {
- assert.ok(firstSpread[index] > before[index], `首枚悬停时第 ${index + 1} 枚没有向标题方向展开`);
- }
-
- await avatars.nth(2).hover();
- await waitForAvatarMotion();
- const after = await avatars.evaluateAll((items) => items.map((item) => item.getBoundingClientRect().x));
- const card = stack.locator('xpath=ancestor::article[@data-media-card]').first();
- const bounds = await card.evaluate((cardElement) => {
- const stackRect = cardElement.querySelector('[data-media-avatars]')!.getBoundingClientRect();
- const lastRect = cardElement.querySelector('[data-media-avatar]:last-child')!.getBoundingClientRect();
- const firstRect = cardElement.querySelector('[data-media-avatar]')!.getBoundingClientRect();
- const cardRect = cardElement.getBoundingClientRect();
- return {
- stackLeft: stackRect.left,
- firstRingLeft: firstRect.left - 2,
- lastRingRight: lastRect.right + 2,
- cardLeft: cardRect.left,
- cardRight: cardRect.right,
- };
- });
- assert.equal(bounds.stackLeft, left, '展开时左缘发生位移');
- // Chrome 合成层结束 transition 时会留下远小于一个物理像素的浮点残差;这里守的是
- // 头像没有发生可见位移,不把 303 与 302.9933 这种同一像素内的取整差判成布局回退。
- assert.ok(Math.abs(after[0] - before[0]) <= .5, '指向第三枚时第一枚被往左推');
- assert.ok(Math.abs(after[1] - before[1]) <= .5, '指向第三枚时第二枚被往左推');
- assert.ok(after[3] > before[3] && after[4] > before[4], '右侧邻座没有朝标题方向让开');
- assert.ok(bounds.firstRingLeft >= bounds.cardLeft - .5, '首枚放大加描边后被卡片左缘裁切');
- assert.ok(bounds.lastRingRight <= bounds.cardRight + .5, '头像展开越出卡片右缘');
-
- await opened.page.mouse.move(0, 0);
- await avatars.nth(2).focus();
- await waitForAvatarMotion();
- const layers = await avatars.evaluateAll((items) => items.map((item) => Number(getComputedStyle(item).zIndex)));
- assert.equal(layers[2], Math.max(...layers), '键盘焦点所在头像没有升到最高层');
-
- await opened.page.setViewportSize({ width: 390, height: 844 });
- const drawer = opened.page.locator('#drawer');
- if (await drawer.evaluate((element) => element.classList.contains('open'))) {
- await opened.page.locator('#scrim').evaluate((element) => (element as HTMLElement).click());
- await opened.page.waitForFunction(() => !document.querySelector('#drawer')?.classList.contains('open'));
- }
- await avatars.first().hover();
- await waitForAvatarMotion();
- const narrow = await card.evaluate((cardElement) => {
- const cardRect = cardElement.getBoundingClientRect();
- const firstRect = cardElement.querySelector('[data-media-avatar]')!.getBoundingClientRect();
- const lastRect = cardElement.querySelector('[data-media-avatar]:last-child')!.getBoundingClientRect();
- let clip: Element | null = cardElement.parentElement;
- while (clip && clip !== document.documentElement) {
- const style = getComputedStyle(clip);
- if (style.overflowX !== 'visible' || style.overflowY !== 'visible') break;
- clip = clip.parentElement;
- }
- const clipRect = (clip || document.documentElement).getBoundingClientRect();
- return {
- firstRingLeft: firstRect.left - 2,
- lastRingRight: lastRect.right + 2,
- cardLeft: cardRect.left,
- cardRight: cardRect.right,
- clipLeft: clipRect.left,
- clipRight: clipRect.right,
- viewport: document.documentElement.clientWidth,
- };
- });
- assert.ok(narrow.firstRingLeft >= Math.max(narrow.cardLeft, narrow.clipLeft) - .5,
- '390px 视口下首枚头像或描边被最近的裁切祖先截掉');
- assert.ok(narrow.lastRingRight <= Math.min(narrow.cardRight, narrow.clipRight, narrow.viewport) + .5,
- '390px 视口下展开头像越出卡片、裁切祖先或视口');
- } finally {
- await opened.close();
- }
- });
-
- it('搜索框从非空变空时立即清值并溶解原内容', { timeout: 60_000 }, async () => {
- const opened = await openCatalog(browser);
- try {
- await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
- const input = opened.page.locator('#q');
- const text = '一段长到会在搜索框里横向滚动的内容 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ '.repeat(4).trim();
- await input.fill(text);
- await input.evaluate((element) => {
- const field = element as HTMLInputElement;
- field.setSelectionRange(field.value.length, field.value.length);
- field.scrollLeft = field.scrollWidth;
- field.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }));
- });
- assert.ok(await input.evaluate((element) => (element as HTMLInputElement).scrollLeft) > 0,
- '测试内容没有真正让搜索框横向滚动');
- await input.fill('');
- const ghost = opened.page.locator('.search > .cleardissolve');
- await ghost.waitFor({ timeout: 1_000 });
- assert.equal(await input.inputValue(), '', '动画阻塞了真实输入框清空');
- assert.equal(await ghost.locator('[data-dissolve-value]').textContent(), text);
- // 残影节点先挂载,placeholder 再经 CSS transition 淡出;慢速 Windows runner 上
- // 两件事可能跨帧。等待过渡的最终状态,仍然守住 placeholder 必须完全不可见。
- await opened.page.waitForFunction(() => {
- const field = document.querySelector('#q');
- return field !== null && getComputedStyle(field, '::placeholder').opacity === '0';
- }, undefined, { timeout: 1_000 });
- assert.match(await ghost.locator('[data-dissolve-value]').getAttribute('style') || '', /translateX\(-\d+px\)/);
- await ghost.waitFor({ state: 'detached', timeout: 2_000 });
- assert.equal(await input.evaluate((element) => element.classList.contains('dissolving')), false,
- '动画结束后仍压着输入框的溶解状态');
-
- await input.fill(text);
- await input.fill('');
- await opened.page.locator('.search > .cleardissolve').waitFor({ timeout: 1_000 });
- await input.type('新输入');
- assert.equal(await opened.page.locator('.search > .cleardissolve').count(), 0,
- '清空后继续输入仍被旧残影覆盖');
- assert.equal(await input.inputValue(), '新输入');
-
- await input.fill('输入法候选');
- await input.fill('');
- await opened.page.locator('.search > .cleardissolve').waitFor({ timeout: 1_000 });
- await input.evaluate((element) => element.dispatchEvent(new CompositionEvent('compositionstart', {
- bubbles: true,
- data: '候',
- })));
- assert.equal(await opened.page.locator('.search > .cleardissolve').count(), 0,
- '输入法开始组字后旧残影仍覆盖候选字');
- } finally {
- await opened.close();
- }
- });
-
- /* 搜索框住在粘性顶栏里,永远在视口上沿;可 `html` 的 `scroll-padding-top` 把那一条
- 划成「被顶栏盖住」的区域,浏览器每敲一个字就把光标往下滚一次,页面一路往回退。
- 点击走鼠标坐标:定位器的 click 会先替元素滚进视口,那一下不是页面自己的行为。 */
- it('往下翻过之后在搜索框里打字,页面停在原处', { timeout: 60_000 }, async () => {
- const opened = await openCatalog(browser);
- try {
- const { page } = opened;
- await page.setViewportSize({ width: DESKTOP.width, height: 480 });
- await page.mouse.move(DESKTOP.width / 2, 300);
- await page.mouse.wheel(0, 600);
- await page.waitForFunction(() => scrollY > 300, undefined, { timeout: 5_000 });
- const before = await page.evaluate(() => scrollY);
- const box = await page.locator('#q').boundingBox();
- if (!box) throw new Error('搜索框不可见');
- await page.mouse.click(box.x + 40, box.y + box.height / 2);
- await page.keyboard.type('演示abc', { delay: 60 });
- await page.waitForTimeout(300);
- assert.equal(await page.evaluate(() => scrollY), before, '打字时页面跟着滚动了');
- } finally {
- await opened.close();
- }
- });
-
- it('首页版式默认小图,大图统一作品画面框,选择单独记住', { timeout: 60_000 }, async () => {
- /* 首张卡使用番号封面,第二张使用普通预览图。 */
- const opened = await openCatalogFixture(browser, (payload) => {
- Object.assign(payload.items[0], { is_jav: true, code: 'ABC-123', display_code: 'ABC-123', has_cover: true });
- });
- const { page } = opened;
- const ratio = (index: number) => page.locator('#grid [data-media-grid] > [data-media-card][data-id]').nth(index).locator('[data-media-pic]')
- .evaluate((element) => element.getBoundingClientRect().width / element.getBoundingClientRect().height);
- const choice = (value: string) => page.locator(`[data-catalog-filter] input[name="home-layout"][value="${value}"]`);
- try {
- assert.equal(await choice('small').isChecked(), true, '首页版式默认不是小图');
- assert.ok(Math.abs(await ratio(0) - 16 / 9) < 0.05, '小图下番号卡不是 16:9');
- await choice('big').check({ force: true });
- assert.ok(Math.abs(await ratio(0) - 0.75) < 0.05, '大图下番号卡没有拉成正封比例');
- assert.ok(Math.abs(await ratio(1) - 0.75) < 0.05, '大图下普通作品画面框不是 3:4');
- const box = (index: number) => page.locator('#grid [data-media-grid] > [data-media-card][data-id]').nth(index).locator('[data-media-pic]')
- .evaluate((element) => ({ top: element.getBoundingClientRect().top, height: element.getBoundingClientRect().height }));
- const [jav, plain] = [await box(0), await box(1)];
- assert.ok(Math.abs(jav.top - plain.top) < 1, '前两张卡不在同一行,量不到撑高');
- assert.ok(Math.abs(plain.height - jav.height) < 1, '同行作品画面框不等高');
- // `visit()` 的初始化脚本每次导航都重写设置,刷新验不了;直接读存下来的那份。
- const saved = await page.evaluate(() => JSON.parse(localStorage.getItem('peach.settings.v1') || '{}'));
- assert.equal(saved.homeLayout, 'big', '首页版式没有存下来');
- } finally {
- await opened.close();
- }
- });
-
- it('首页标签:没加上去是 --field-ring-hover 的虚线,加上去是玻璃上那圈实线,视图不画虚线;触屏上排 52、视图与标签 36', { timeout: 60_000 }, async () => {
- /* 虚线只说「这条筛选可加、此刻没加」,取 Vercel 筛选令牌未生效那一档;四枚视图恒有一枚生效,不画。
- 圆角同卡片、详情与交集条那一颗(`--tag-radius`)。触屏上 30px 不够一枚指尖。 */
- const opened = await openCatalogBars(browser);
- try {
- const { page } = opened;
- const scope = '[data-catalog-filter]';
- const ring = await tokenColor(page, scope, '--field-ring-hover');
- const low = await tokenColor(page, scope, '--glass-low');
- const edge = (selector: string) => page.locator(`${scope} ${selector}`).first().evaluate((element) => {
- const style = getComputedStyle(element);
- const probe = document.createElement('div');
- probe.style.borderRadius = 'var(--tag-radius)';
- element.append(probe);
- const radius = getComputedStyle(probe).borderTopLeftRadius;
- probe.remove();
- return { style: style.borderTopStyle, color: style.borderTopColor, radius: style.borderTopLeftRadius === radius };
- });
- assert.deepEqual(await edge('[data-catalog-tag][aria-pressed="false"]'), { style: 'dashed', color: ring, radius: true },
- '没加上去的标签不是 --field-ring-hover 的虚线,或圆角不是 --tag-radius');
- assert.notEqual((await edge('[data-catalog-view]')).style, 'dashed', '视图恒有一枚生效,不画虚线');
- await page.locator(`${scope} [data-catalog-tag][aria-pressed="false"]`).first().click();
- await page.locator(`${scope} [data-catalog-tag][aria-pressed="true"]`).waitFor({ timeout: 5_000 });
- assert.deepEqual(await edge('[data-catalog-tag][aria-pressed="true"]'), { style: 'solid', color: low, radius: true },
- '加上去的标签那圈线不是玻璃上的 --glass-low');
- } finally {
- await opened.close();
- }
- const phone = await openCatalogBars(browser, MOBILE);
- try {
- const { page } = phone;
- const heights = await page.evaluate(() => {
- const height = (selector: string) => {
- const element = document.querySelector(`[data-catalog-filter] ${selector}`);
- return element ? Math.round(element.getBoundingClientRect().height) : null;
- };
- return { coarse: matchMedia('(pointer: coarse)').matches, row: height('[data-filter-row="top"]'),
- view: height('[data-catalog-view]'), tag: height('[data-catalog-tag]') };
- });
- assert.deepEqual(heights, { coarse: true, row: 52, view: 36, tag: 36 }, '触屏上筛选条上排没有放大到指尖尺寸');
- } finally {
- await phone.close();
- }
- });
-
- it('首页换一批:头像、厂牌与标签原地藏起来只露一层微光,名字条收成 52px,四枚视图不盖', { timeout: 60_000 }, async () => {
- /* 框就是它们自己的框,零位移;`visibility:hidden` 的控件也不可聚焦。视图由 state 决定,这一趟不改它们。 */
- const opened = await openCatalogBars(browser);
- let release = () => {};
- try {
- const { page } = opened;
- const held = new Promise<void>((resolve) => { release = resolve; });
- // 后注册的先拦:拖住这一趟,放行后交回夹具那一份。
- await page.route((url) => url.pathname === '/api/tops', async (route) => { await held; await route.fallback(); });
- await page.locator('[data-catalog-filter] [data-entity-batch]').click();
- await page.locator('[data-catalog-filter] [data-catalog-root][data-refreshing]').waitFor({ timeout: 5_000 });
- const shown = await page.evaluate(() => {
- const read = (selector: string) => {
- const element = document.querySelector(`[data-catalog-filter] ${selector}`);
- if (!element) return null;
- return { hidden: getComputedStyle(element).visibility, sheen: getComputedStyle(element, '::after').visibility,
- width: Math.round(element.getBoundingClientRect().width) };
- };
- return { tag: read('[data-catalog-tag]'), ring: read('[data-tier-ring]'), name: read('[data-tier-name]'),
- studio: read('[data-tier-studio]'), view: read('[data-catalog-view]') };
- });
- for (const key of ['tag', 'ring', 'name', 'studio'] as const) {
- assert.equal(shown[key]?.hidden, 'hidden', `换一批时${key}没有藏起来:${JSON.stringify(shown[key])}`);
- assert.equal(shown[key]?.sheen, 'visible', `换一批时${key}上没有那层微光:${JSON.stringify(shown[key])}`);
- }
- assert.equal(shown.name?.width, 52, '名字条没有收成首屏骨架那一宽');
- assert.equal(shown.view?.hidden, 'visible', '视图不随这一趟变,不该盖');
- } finally {
- release();
- await opened.close();
- }
- });
-
- /* 骨架是列表回来之前那一屏的形状预告:JAV 默认大图,卡片是 3:4 的正封,骨架照 16:9
- 铺的话,内容一到整屏卡片都被拉高一截。把列表请求扣住,只看骨架本身。 */
- it('作品骨架的封面比例跟当前版式走:JAV 大图 3:4,首页小图 16:9', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', DESKTOP);
- const { page } = opened;
- await page.route(/\/api\/items\?/, () => {});
- /* 骨架挂上的那一帧可能还没排版(宽高都是 0),量出来是 NaN。等它有了尺寸、且连续两帧
- 比例不变再读:量的是这一屏落定后的形状,不是插进 DOM 的那一瞬。 */
- const skeletonRatio = async (path: string) => {
- await page.goto(new URL(path, page.url()).href, { waitUntil: 'load' });
- const handle = await page.waitForFunction(() => {
- const cover = document.querySelector('#grid .catalog-skeleton .skeletoncard i');
- const box = cover?.getBoundingClientRect();
- if (!box || !box.width || !box.height) return false;
- const ratio = box.width / box.height;
- const holder = window as unknown as { skeletonRatioSeen?: number };
- const settled = holder.skeletonRatioSeen === ratio;
- holder.skeletonRatioSeen = ratio;
- return settled && ratio;
- }, undefined, { polling: 'raf', timeout: 15_000 });
- return Number(await handle.jsonValue());
- };
- try {
- assert.ok(Math.abs(await skeletonRatio('/?jav=1') - 0.75) < 0.05, 'JAV 大图下骨架封面不是正封比例');
- assert.ok(Math.abs(await skeletonRatio('/') - 16 / 9) < 0.05, '首页小图下骨架封面不是 16:9');
- } finally {
- await opened.close();
- }
- });
-
- it('卡片悬停反馈不在封面像素上描边', { timeout: 60_000 }, async () => {
- const opened = await openCatalog(browser);
- try {
- const card = opened.page.locator('#grid [data-media-card]').first();
- const picture = card.locator('[data-media-pic]');
- await card.hover();
- const overlay = await picture.evaluate((element) => {
- const style = getComputedStyle(element, '::after');
- return { content: style.content, borderWidth: style.borderTopWidth };
- });
- assert.equal(overlay.content, 'none', '悬停伪元素仍覆盖在封面像素上');
- assert.equal(overlay.borderWidth, '0px', '悬停边线仍污染圆角边缘像素');
- assert.match(await card.evaluate((element) => getComputedStyle(element).boxShadow),
- /0px 0px 0px 8px/, '悬停底色没有在卡片四周向外多铺 8px');
- assert.equal(await card.locator('[data-media-later]').evaluate(
- (element) => getComputedStyle(element).opacity), '1', '移除描边后没有保留悬停反馈');
- } finally {
- await opened.close();
- }
- });
-
- it('馆藏卡片的字取页面正文那一档,角标、悬停控件、进度条、竖屏带、Mix 与回收站卡面按定下的样子画', { timeout: 90_000 }, async () => {
- /* 演示库凑不出回收站里的非视频资源:回收站那一页把第二条换成一个压缩包。
- 目录那一页给前三条挂半程观看进度,量进度条的颜色。 */
- const opened = await openCatalogFixture(browser, (payload, url) => {
- if (url.searchParams.get('state') !== 'trash') {
- for (const item of payload.items.slice(0, 3)) Object.assign(item, { duration: 600, play_seconds: 300 });
- return;
- }
- const item = payload.items[1];
- if (!item) throw new Error('演示目录不够两条');
- Object.assign(item, { medium: 'archive', name: '演示资料.zip', disposal: 'trash' });
- payload.items[0].disposal = 'trash';
- });
- const { page } = opened;
- /* 岛根是 `line-height:1.5`,卡里没写行高的格子会继承它;旧卡读的是页面正文 14px/20px。
- 取值用同一个岛根下的空元素量 token,不在断言里抄像素。 */
- const readStyles = (selectors: Record<string, string>) => page.evaluate((wanted) => {
- const root = document.querySelector('#grid .peach-react')!;
- const pick = (element: Element | null) => {
- if (!element) return null;
- const style = getComputedStyle(element);
- return { fontSize: style.fontSize, lineHeight: style.lineHeight, fontFamily: style.fontFamily,
- letterSpacing: style.letterSpacing, minHeight: style.minHeight, padding: style.padding,
- display: style.display, place: `${style.alignItems} ${style.justifyItems}`, color: style.color,
- background: style.backgroundColor, borderWidth: style.borderTopWidth, borderColor: style.borderTopColor,
- leftRadius: style.borderTopLeftRadius, width: style.width, opacity: style.opacity };
- };
- const probe = (css: string) => {
- const element = document.createElement('div');
- element.style.cssText = css;
- root.append(element);
- const value = pick(element)!;
- element.remove();
- return value;
- };
- return {
- body: probe('font: var(--board-body)'), caption: probe('font: var(--board-caption)'),
- md: probe('font-size: var(--fs-md)'), muted: probe('color: var(--muted)'), text: probe(''),
- ground: probe('background: var(--ground)'), tungsten: probe('background: var(--tungsten)'),
- overlay: probe('background: var(--overlay-5); border: 1px solid var(--border-10)'),
- ...Object.fromEntries(Object.entries(wanted).map(([key, selector]) => [key, pick(root.querySelector(selector))])),
- };
- }, selectors);
- try {
- await page.locator('#grid [data-shorts-strip]').first().waitFor({ timeout: 10_000 });
- await page.locator('#grid [data-media-grid] > [data-media-card] [data-media-progress]').first().waitFor({ timeout: 10_000 });
- const catalog = await readStyles({
- card: '[data-media-grid] > [data-media-card]',
- badge: '[data-media-grid] > [data-media-card] [data-media-badge]',
- shorts: '[data-shorts-strip] > h2',
- mix: '[data-media-grid] > [data-mix-card]',
- mixTitle: '[data-media-grid] > [data-mix-card] [data-mix-title]',
- mixGlyph: '[data-media-grid] > [data-mix-card] [data-mix-glyph]',
- strip: '[data-shorts-strip]',
- progress: '[data-media-grid] > [data-media-card] [data-media-progress] > i',
- seekGlyph: '[data-media-grid] > [data-media-card] [data-media-seek] svg',
- laterButton: '[data-media-grid] > [data-media-card] [data-media-later] button',
- laterGlyph: '[data-media-grid] > [data-media-card] [data-media-later] svg',
- });
- const { body, caption, md, card, badge, shorts, mix, mixTitle } = catalog;
- /* 竖屏带靠底色和网格区分,不描线;宽屏上往左铺过侧栏轨道,贴视口那一侧不留圆角。 */
- assert.deepEqual([catalog.strip?.background, catalog.strip?.borderWidth], [catalog.ground.background, '0px'],
- '竖屏带不是页面底色那一张面,或者描了一圈线');
- assert.equal(catalog.strip?.leftRadius, '0px', '宽屏上竖屏带贴视口的那一侧还留着圆角');
- const edges = await page.evaluate(() => ({
- strip: document.querySelector('#grid [data-shorts-strip]')!.getBoundingClientRect().left,
- grid: document.querySelector('#grid [data-media-grid]')!.getBoundingClientRect().left,
- }));
- assert.ok(edges.strip < edges.grid, `竖屏带左缘 ${edges.strip} 没有越过网格左缘 ${edges.grid} 铺到侧栏底下`);
- /* 沉浸模式是一叠竖着翻的卡,入口用叠卡那一枚字形,不和别的动作共用。 */
- assert.equal(await page.locator('#grid [data-shorts-enter] svg use').first().getAttribute('href'), '#i-gallery-vertical-end',
- '竖屏带的「进入沉浸模式」换了字形');
- assert.equal(catalog.progress?.background, catalog.tungsten.background, '观看进度条不是钨丝蓝');
- assert.deepEqual([catalog.mixGlyph?.background, catalog.mixGlyph?.borderWidth, catalog.mixGlyph?.borderColor],
- [catalog.overlay.background, '1px', catalog.overlay.borderColor], 'Mix 署名位那枚字形不是半透明底加细边');
- /* 居中的快退快进和右下角「稍后看」是同一种控件,只是尺寸不同:58px 配 34px 图标,36px 配 21px。 */
- assert.deepEqual([catalog.seekGlyph?.width, catalog.laterButton?.width, catalog.laterGlyph?.width], ['34px', '36px', '21px'],
- '悬停控件的尺寸和图标比例变了');
- const denseShort = await page.evaluate(() => {
- document.body.dataset.density = 'dense';
- const width = getComputedStyle(document.querySelector('#grid [data-shorts-strip] [data-media-card]')!).width;
- delete document.body.dataset.density;
- return width;
- });
- assert.equal(denseShort, '107px', '密集模式下竖屏带里的卡没有跟着缩到 214px 的一半');
- assert.deepEqual([card?.fontSize, card?.lineHeight], ['14px', '20px'], '作品卡的字不是页面正文那一档,岛根的 1.5 行高漏了进来');
- assert.deepEqual([badge?.fontSize, badge?.lineHeight], [caption.fontSize, caption.lineHeight], '来源角标的字不是 caption 那一档');
- assert.equal(badge?.minHeight, '24px', '来源角标矮于 24px');
- assert.deepEqual([shorts?.fontFamily, shorts?.lineHeight], [body.fontFamily, '20px'], '竖屏带标题的字体或行高不同页面正文');
- assert.ok(mix && mixTitle, '夹具目录里没有插进 Mix');
- assert.deepEqual([mix.fontSize, mix.lineHeight], ['14px', '20px'], '网格里的 Mix 卡没取页面正文那一档');
- assert.equal(mixTitle.letterSpacing, 'normal', '网格里的 Mix 标题带着字距');
- assert.ok(Math.abs(parseFloat(mixTitle.lineHeight) - parseFloat(md.fontSize) * 1.45) < .5,
- `网格里的 Mix 标题行高 ${mixTitle.lineHeight},不是 --fs-md 的 1.45 倍`);
-
- await page.goto(new URL('/trash', page.url()).href, { waitUntil: 'load' });
- await page.locator('#grid [data-media-card][data-variant="resource"]').first().waitFor({ timeout: 15_000 });
- await settle(page);
- const trash = await readStyles({
- meta: '[data-media-grid] > [data-media-card] [data-media-meta]',
- glyph: '[data-variant="resource"] [data-media-glyph]',
- kind: '[data-variant="resource"] [data-media-kind-glyph]',
- });
- /* 回收站卡有边框:量实际盒子,头像、标题与最后一行都要和框、封面隔开,一行文件名不留空行。 */
- const inset = await page.locator('#grid [data-media-card][data-variant="resource"]').first().evaluate((card) => {
- const box = (selector: string) => card.querySelector(selector)!.getBoundingClientRect();
- const frame = card.getBoundingClientRect();
- const [pic, avatar, title, byline] = ['[data-media-pic]', '[data-media-avatar]', '[data-media-title]', '[data-media-byline]'].map(box);
- return { left: avatar.left - frame.left, top: title.top - pic.bottom, bottom: frame.bottom - byline.bottom,
- title: title.height, lineHeight: parseFloat(getComputedStyle(card.querySelector('[data-media-title]')!).lineHeight),
- skew: Math.abs((avatar.top + avatar.bottom) / 2 - (title.top + byline.bottom) / 2) };
- });
- assert.ok(inset.left >= 10 && inset.top >= 8 && inset.bottom >= 10,
- `回收站卡的元信息区贴着边框或封面:左 ${inset.left}、上 ${inset.top}、下 ${inset.bottom}`);
- assert.ok(inset.title < inset.lineHeight * 1.5, `一行文件名的标题仍占 ${inset.title}px,预留了第二行`);
- assert.ok(inset.skew <= 3, `头像没有和标题加署名那一块居中对齐,偏 ${inset.skew}px`);
- assert.deepEqual([trash.glyph?.display, trash.glyph?.place, trash.glyph?.color], ['grid', 'center center', trash.muted.color],
- '回收站资源卡封面格里的字形没有居中或不是次要文字色');
- assert.deepEqual([trash.kind?.display, trash.kind?.place, trash.kind?.color], ['grid', 'center center', trash.text.color],
- '回收站资源卡头像位的字形没有居中或不是正文色');
- /* 悬停扫视层是壳插进封面格的 `img.hvframes`:待删卡的灰化要连它一起,否则悬停时整卡「复活」成正常色。 */
- const scan = await page.locator('#grid [data-media-card][data-pending-delete]:not([data-variant="resource"]) [data-media-pic]')
- .first().evaluate((pic) => {
- const layer = document.createElement('img');
- layer.className = 'hvframes';
- pic.append(layer);
- const filter = getComputedStyle(layer).filter;
- layer.remove();
- return filter;
- });
- assert.match(scan, /grayscale\(0\.9\)/, '待删卡的悬停扫视层没有跟着灰化');
- /* 待删卡整块压暗:元信息区降透明度,封面两侧那层模糊垫底也要重写一遍 blur 再灰化,
- `filter` 不叠加,只写灰化会把模糊冲掉。 */
- const pending = await page.locator('#grid [data-media-card][data-pending-delete]:not([data-variant="resource"])')
- .first().evaluate((card) => ({
- meta: getComputedStyle(card.querySelector('[data-media-meta]')!).opacity,
- backdrop: getComputedStyle(card.querySelector('[data-media-pic]')!, '::before').filter,
- }));
- assert.equal(pending.meta, '0.58', '待删卡的元信息区没有压暗');
- assert.match(pending.backdrop, /blur\(26px\) grayscale\(0\.9\) brightness\(0\.27\)/, '待删卡封面两侧的模糊垫底没有跟着灰化');
- } finally {
- await opened.close();
- }
- });
-
- it('回收站的骨架和落地同一副几何,计数栏在两种主题下都和页面底色分得开', { timeout: 90_000 }, async () => {
- /* 回收站多是图片与压缩包,骨架照资源卡排:夹具把回收站那一页全换成图片。 */
- const opened = await openCatalogFixture(browser, (payload, url) => {
- if (url.searchParams.get('state') !== 'trash') return;
- for (const [at, item] of payload.items.entries()) {
- Object.assign(item, { medium: 'image', name: `演示图片-${at}.jpg`, disposal: 'trash' });
- }
- });
- const { page } = opened;
- const measure = () => page.evaluate(() => {
- const box = (element: Element | null) => {
- if (!element) return null;
- const rect = element.getBoundingClientRect();
- return [Math.round(rect.top), Math.round(rect.height)];
- };
- const lede = document.querySelector<HTMLElement>('[data-manage-lede]');
- const card = document.querySelector('#grid .catalog-skeleton .skeletoncard')
- || document.querySelector('#grid [data-media-card][data-variant="resource"]');
- /* 读数与「清空回收站」各自的竖直中线:两者说的是同一批文件,同在说明行一行里。 */
- const middle = (element: Element | null | undefined) => {
- if (!element) return null;
- const rect = element.getBoundingClientRect();
- return Math.round(rect.top + rect.height / 2);
- };
- return { lede: box(lede), card: box(card),
- cells: [...lede?.querySelectorAll<HTMLElement>('[data-trash-lede-skeleton]') ?? []].map((cell) => cell.dataset.trashLedeSkeleton),
- text: lede?.querySelector('[data-lede-text]')?.textContent ?? null,
- row: [middle(lede?.querySelector('[data-lede-text]')), middle(lede?.querySelector('[data-empty-trash]'))] };
- });
- try {
- const release = await holdApi(page);
- await page.goto(new URL('/trash', page.url()).href, { waitUntil: 'load' });
- await page.locator('#grid .catalog-skeleton .skeletoncard').first().waitFor({ timeout: 15_000 });
- const waiting = await measure();
- release();
- await page.locator('#grid [data-media-card][data-variant="resource"]').first().waitFor({ timeout: 15_000 });
- await settle(page);
- const landed = await measure();
- assert.ok(waiting.lede, '回收站骨架期间没有计数栏,读数到了才冒出来把网格往下推');
- assert.deepEqual([waiting.cells, waiting.text], [['text', 'action'], null], `骨架期间说明行不是两格占位:${JSON.stringify(waiting)}`);
- assert.match(landed.text ?? '', /个符合 · 显示 \d+/, `读数没有落进说明行:${JSON.stringify(landed)}`);
- assert.deepEqual(landed.cells, [], '读数落地后占位还在');
- const [textMiddle, buttonMiddle] = landed.row;
- assert.ok(textMiddle != null && buttonMiddle != null && Math.abs(textMiddle - buttonMiddle) <= 1,
- `读数和清空键没并在说明行同一行:${JSON.stringify(landed.row)}`);
- assert.deepEqual(waiting.lede, landed.lede, `计数栏落地时位置或高度跳了:${JSON.stringify({ waiting, landed })}`);
- assert.deepEqual(waiting.card, landed.card, `回收站首张卡落地时位置或高度跳了:${JSON.stringify({ waiting, landed })}`);
- /* 同一页重画(前进后退回到同一条 /trash):读数接口还在路上时说明行留着上一次的读数,不再铺占位。 */
- await page.evaluate(() => {
- const flags = window as unknown as { trashLedeFlashed?: boolean };
- flags.trashLedeFlashed = false;
- new MutationObserver(() => {
- if (document.querySelector('[data-trash-lede-skeleton]')) flags.trashLedeFlashed = true;
- }).observe(document.querySelector('[data-manage-header]')!, { childList: true, subtree: true });
- });
- const again = await holdApi(page);
- const reread = page.waitForRequest((request) => {
- const url = new URL(request.url());
- return url.pathname === '/api/items' && url.searchParams.get('state') === 'trash';
- }, { timeout: 15_000 });
- await page.evaluate(() => dispatchEvent(new PopStateEvent('popstate')));
- await reread;
- const holding = await measure();
- again();
- await page.locator('#grid [data-media-card][data-variant="resource"]').first().waitFor({ timeout: 15_000 });
- await settle(page);
- assert.deepEqual([holding.cells, holding.text], [[], landed.text], `同页重画时说明行回到了占位:${JSON.stringify(holding)}`);
- assert.equal(await page.evaluate(() => (window as unknown as { trashLedeFlashed?: boolean }).trashLedeFlashed), false,
- '同页重画期间说明行闪回了占位');
- const surfaces = await page.evaluate(() => {
- const root = document.documentElement;
- const before = root.dataset.theme;
- const read = (theme: string) => {
- root.dataset.theme = theme;
- return [getComputedStyle(document.querySelector('[data-manage-lede]')!).backgroundColor,
- getComputedStyle(document.body).backgroundColor];
- };
- const result = { light: read('light'), dark: read('dark') };
- if (before === undefined) delete root.dataset.theme;
- else root.dataset.theme = before;
- return result;
- });
- for (const [theme, [lede, ground]] of Object.entries(surfaces)) {
- assert.notEqual(lede, ground, `${theme} 主题下回收站计数栏和页面同一个底色:${lede}`);
- }
- } finally {
- await opened.close();
- }
- });
-
- it('批量条的键是 17px 字形、计数是 --ink-2;批量条与清空回收站两颗危险键读同一组红', { timeout: 90_000 }, async () => {
- const opened = await openCatalogFixture(browser, (payload, url) => {
- if (url.searchParams.get('state') !== 'trash') return;
- for (const item of payload.items) Object.assign(item, { disposal: 'trash' });
- });
- const { page } = opened;
- try {
- await page.goto(new URL('/trash', page.url()).href, { waitUntil: 'load' });
- const cards = page.locator('#grid [data-media-card][data-id]');
- await cards.nth(1).waitFor({ timeout: 15_000 });
- await page.locator('[data-manage-lede] [data-empty-trash]').waitFor({ timeout: 15_000 });
- for (const at of [0, 1]) await cards.nth(at).click({ modifiers: ['Control'], position: { x: 20, y: 20 } });
- await page.locator('[data-batch-dock] [data-selection-dock]').waitFor({ timeout: 10_000 });
- await settle(page);
- const read = await page.evaluate(() => {
- const dock = document.querySelector('[data-batch-dock] [data-selection-dock]')!;
- /* 两颗危险键的静止面与悬停层各自读出来,再与直接解析 token 的探针比:同一份定义才会三者一致。 */
- const probe = (token: string) => {
- const node = document.createElement('div');
- node.style.background = `var(${token})`;
- document.body.append(node);
- const value = getComputedStyle(node).backgroundImage;
- node.remove();
- return value;
- };
- const paint = (key: Element) => [getComputedStyle(key).backgroundImage, getComputedStyle(key, '::before').backgroundImage];
- return {
- glyphs: [...dock.querySelectorAll('button svg')].map((svg) => {
- const box = svg.getBoundingClientRect();
- return [box.width, box.height];
- }),
- count: getComputedStyle(dock.querySelector('[role="status"]')!).color,
- batch: paint(dock.querySelector('[data-batch-action="delete"]')!),
- empty: paint(document.querySelector('[data-manage-lede] [data-empty-trash]')!),
- tokens: [probe('--board-red'), probe('--board-red-hover')],
- };
- });
- assert.deepEqual(read.glyphs, [[17, 17], [17, 17], [17, 17]], `批量条的字形不是 17px:${JSON.stringify(read.glyphs)}`);
- assert.equal(read.count, await tokenColor(page, 'body', '--ink-2'), '批量条的计数不是次级墨色');
- assert.match(read.tokens[0], /^linear-gradient/, `--board-red 没解析成渐变:${read.tokens[0]}`);
- assert.deepEqual(read.batch, read.tokens, `批量条「彻底删除」的红不是 --board-red 那一组:${JSON.stringify(read)}`);
- assert.deepEqual(read.empty, read.tokens, `「清空回收站」的红不是 --board-red 那一组:${JSON.stringify(read)}`);
- } finally {
- await opened.close();
- }
- });
-
- it('管理区页头:面包屑当前项升到 --ink、上一级与分隔符钉在 --muted,按下的页签蓝字配一条同宽蓝线', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/duplicates', DESKTOP);
- try {
- const { page } = opened;
- await page.locator('[data-manage-crumb] [aria-current="true"]').waitFor({ timeout: 15_000 });
- await page.locator('[data-manage-indicator][data-ready]').waitFor({ timeout: 15_000 });
- await settle(page);
- /* 指示线落位走一条弹簧过渡:等它停在按下那一枚底下再读;停不下来由下面的断言报出偏差。 */
- await page.waitForFunction(() => {
- const a = document.querySelector('[data-manage][aria-pressed="true"]')!.getBoundingClientRect();
- const b = document.querySelector('[data-manage-indicator]')!.getBoundingClientRect();
- return Math.abs(a.left - b.left) < 0.5 && Math.abs(a.width - b.width) < 0.5;
- }, null, { timeout: 5_000 }).catch(() => undefined);
- const [ink, muted, accent] = await Promise.all(['--ink', '--muted', '--tungsten'].map((token) => tokenColor(page, 'body', token)));
- const read = await page.evaluate(() => {
- const items = [...document.querySelectorAll<HTMLElement>('[data-manage-crumb] li')];
- const pressed = document.querySelector<HTMLElement>('[data-manage][aria-pressed="true"]')!;
- const line = document.querySelector<HTMLElement>('[data-manage-indicator]')!;
- const [a, b] = [pressed.getBoundingClientRect(), line.getBoundingClientRect()];
- return {
- colors: items.map((item) => getComputedStyle(item).color),
- separators: items.map((item) => item.querySelector('svg') ? getComputedStyle(item.querySelector('svg')!).stroke : null),
- gap: getComputedStyle(document.querySelector('[data-manage-crumb] ol')!).columnGap,
- tab: getComputedStyle(pressed).color,
- line: getComputedStyle(line).backgroundColor,
- under: [Math.round(b.left - a.left), Math.round(b.width - a.width), Math.round(a.bottom - b.bottom)],
- };
- });
- assert.deepEqual(read.colors, [muted, ink], '上一级不是 --muted,或当前项没升到 --ink');
- assert.deepEqual(read.separators, [muted, null], '分隔符跟着当前项提亮了,或最后一项也带了分隔符');
- assert.equal(read.gap, '6px');
- assert.deepEqual([read.tab, read.line], [accent, accent], '按下的页签不是蓝字配蓝线');
- assert.deepEqual(read.under, [0, 0, 0], `指示线没压在按下那一枚底下、同宽:${JSON.stringify(read.under)}`);
- assert.deepEqual(opened.problems.filter((line) => !line.includes('/api/links/check')), []);
- } finally {
- await opened.close();
- }
- });
-
- it('分卷卡不翻卡、悬停走分段预览,叠层纸边和封面同一档圆角', { timeout: 60_000 }, async () => {
- /* 各卷共用同一个番号的封套,翻过去还是那张图。演示库没有分卷,给首张卡挂一个。 */
- const opened = await openCatalogFixture(browser, (payload) => {
- const [first, second] = payload.items;
- payload.items[0] = { ...first, part_group: {
- key: 'DEMO-PART', title: 'DEMO-PART', count: 2, seed_id: first.id,
- item_ids: [first.id, second.id], total_duration: 120, total_size: 1 } };
- });
- try {
- const shapeOf = (selector: string) => opened.page.locator(selector).first().evaluate((element) => {
- const stack = element.querySelector('[data-media-stack],[data-mix-stack]')!;
- const cover = element.querySelector('[data-media-pic],[data-mix-cover]')!;
- return {
- // 封面格的圆角由 clip-path 裁出来(media-card.css),格子本身不写 border-radius。
- cover: getComputedStyle(cover).clipPath.match(/round (\S+)\)$/)?.[1] ?? '0px',
- ground: getComputedStyle(cover).backgroundColor,
- layers: ['::before', '::after'].map((pseudo) => getComputedStyle(stack, pseudo).borderTopLeftRadius),
- faces: element.querySelectorAll('[data-mix-faces]').length,
- preview: Boolean(element.querySelector('[data-media-preview]')),
- };
- });
- await opened.page.locator('[data-media-card][data-part-seed]').first().waitFor({ timeout: 10_000 });
- const part = await shapeOf('[data-media-card][data-part-seed]');
- assert.notEqual(part.cover, '0px', '封面没有圆角,比对失去意义');
- assert.deepEqual(part.layers, [part.cover, part.cover], '分卷卡的叠层纸边和封面不是同一档圆角');
- // 封面格背后压着纸边:格子是空的,纸边线条就从封面没盖住的地方透出来。
- assert.notEqual(part.ground, 'rgba(0, 0, 0, 0)', '叠层卡的封面格是透明的,纸边会透进封面');
- assert.equal(part.faces, 0, '分卷卡仍挂着翻卡面板');
- assert.ok(part.preview, '分卷卡悬停没有分段预览入口');
- if (await opened.page.locator('#grid [data-mix-card]').count()) {
- const mix = await shapeOf('#grid [data-mix-card]');
- assert.deepEqual(mix.layers, [mix.cover, mix.cover], 'Mix 卡的叠层纸边和封面不是同一档圆角');
- }
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('分卷计数在悬停与键盘聚焦时淡出,右上角让给倒计时圈', { timeout: 60_000 }, async () => {
- const opened = await openCatalogFixture(browser, (payload) => {
- const [first, second] = payload.items;
- payload.items[0] = { ...first, part_group: {
- key: 'DEMO-PART', title: 'DEMO-PART', count: 2, seed_id: first.id,
- item_ids: [first.id, second.id], total_duration: 120, total_size: 1 } };
- });
- try {
- const page = opened.page;
- const card = page.locator('[data-media-card][data-part-seed]').first();
- await card.waitFor({ timeout: 10_000 });
- const read = () => card.evaluate(async (element) => {
- await new Promise((resolve) => setTimeout(resolve, 300));
- const group = element.querySelector<HTMLElement>('[data-media-group]')!;
- const box = group.getBoundingClientRect();
- const hit = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2);
- return {
- group: [getComputedStyle(group).opacity, getComputedStyle(group).visibility],
- later: getComputedStyle(element.querySelector('[data-media-later]')!).opacity,
- hitGroup: hit?.closest('[data-media-group]') === group,
- };
- });
- await page.mouse.move(0, 0);
- assert.deepEqual(await read(), { group: ['1', 'visible'], later: '0', hitGroup: true }, '不悬停时分卷计数没有照常显示');
-
- await card.locator('[data-media-pic]').hover();
- assert.deepEqual(await read(), { group: ['0', 'hidden'], later: '1', hitGroup: false },
- '悬停时分卷计数没有淡出,或仍压在右上角的悬停工具上');
-
- await page.mouse.move(0, 0);
- const opener = card.locator('[data-media-open]');
- await opener.focus();
- assert.equal(await opener.evaluate((element) => element.matches(':focus-visible')), true);
- assert.deepEqual(await read(), { group: ['0', 'hidden'], later: '1', hitGroup: false }, '键盘聚焦时分卷计数没有淡出');
- assert.equal(await card.locator('[data-media-preview]').evaluate((element) => getComputedStyle(element).opacity), '1',
- '键盘聚焦时右上角没有打开预览的键');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('抬起与推开只属于作品卡的共演头像', { timeout: 60_000 }, async () => {
- const opened = await openCatalog(browser);
- try {
- await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
- for (const selector of ['[data-tier-performer]', '[data-tier-studio]']) {
- const entry = opened.page.locator(selector).first();
- if (!await entry.count()) continue;
- await entry.hover();
- await opened.page.waitForTimeout(320);
- assert.equal(await entry.evaluate((element) => getComputedStyle(element).transform), 'none',
- `${selector} 仍套用了作品共演头像的抬起效果`);
- }
- } finally {
- await opened.close();
- }
- });
-
- it('视频卡整块是入口且内部链接保持独立', { timeout: 60_000 }, async () => {
- const opened = await openCatalogFixture(browser, (payload) => {
- payload.items[0] = { ...payload.items[0], tags: ['演示标签'] };
- });
- try {
- const card = opened.page.locator('#grid [data-media-card][data-id]').first();
- const opener = card.locator('[data-media-open]');
- const boxes = await Promise.all([card.boundingBox(), opener.boundingBox()]);
- assert.deepEqual(boxes[1], boxes[0], '全卡入口没有覆盖图片、文字与卡内空白');
- await card.hover();
- assert.notEqual(await card.evaluate((element) => getComputedStyle(element).backgroundColor),
- 'rgba(0, 0, 0, 0)', '悬停整卡没有灰色反馈');
-
- await opened.page.setViewportSize({ width: 390, height: 844 });
- const narrow = await Promise.all([card.boundingBox(), opener.boundingBox()]);
- assert.deepEqual(narrow[1], narrow[0], '390px 下全卡入口没有覆盖完整卡片');
- assert.ok((narrow[0]?.x || 0) >= 0 && (narrow[0]?.x || 0) + (narrow[0]?.width || 0) <= 390,
- '390px 下视频卡越出视口');
-
- const nested = card.locator('[data-media-tag]:not(:disabled)').first();
- const tag = await nested.getAttribute('data-tag');
- assert.ok(tag, '演示卡没有可操作的内部标签');
- await nested.focus();
- assert.equal(await nested.evaluate((element) => element.matches(':focus-visible')), true,
- '卡内链接不能用键盘聚焦');
- await nested.press('Enter');
- await opened.page.waitForURL((url) => url.searchParams.get('tag') === tag, { timeout: 10_000 });
- assert.doesNotMatch(opened.page.url(), /\/item\//, '卡内链接冒泡打开了视频');
- } finally {
- await opened.close();
- }
- });
-
- for (const [label, viewport, inset] of [['390px', MOBILE, 12], ['宽屏', DESKTOP, 24]] as const) {
- it(`${label} 下教程浮窗贴着右下角,Toast 让到它上方,批量选择条盖在它上面`, { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', viewport);
- try {
- await opened.page.evaluate(() => {
- localStorage.setItem('peach.post-setup-tutorial.v1', 'pending');
- localStorage.removeItem('peach.post-setup-tutorial-collapsed.v1');
- localStorage.removeItem('peach.post-setup-tutorial-skipped.v1');
- });
- await opened.page.reload({ waitUntil: 'load' });
- /* 目录网格画出来时 paintSelection 已经按当前页收好批量条的按钮;教程卡取数期间的
- 占位带 aria-busy,settle 等到的是最终那张卡。 */
- await expectBody(opened.page, '/', [
- opened.page.locator('#grid [data-media-card][data-id]').first(),
- opened.page.locator('#postSetupTutorial .post-setup-notification'),
- ]);
- await settle(opened.page);
- /* 批量条只在有选中项时才画:Ctrl 点两张卡进多选,再在浮条中心点取最上层元素。窄屏上它
- 横跨整行,一定落在教程卡上;宽屏上两者不在同一处,这一条只在窄屏量。 */
- const cards = opened.page.locator('#grid [data-media-card][data-id]');
- for (const at of [0, 1]) await cards.nth(at).click({ modifiers: ['Control'], position: { x: 20, y: 20 } });
- await opened.page.locator('[data-batch-dock] [data-selection-dock]').waitFor({ timeout: 10_000 });
- await settle(opened.page);
- const probe = await opened.page.evaluate(() => {
- const dock = document.querySelector('[data-batch-dock] [data-selection-dock]')!;
- const tutorial = document.querySelector('#postSetupTutorial .post-setup-notification')!;
- const card = tutorial.getBoundingClientRect();
- const box = dock.getBoundingClientRect();
- const x = box.left + box.width / 2;
- const y = box.top + box.height / 2;
- const top = document.elementFromPoint(x, y);
- return { top: card.top, bottom: card.bottom, left: card.left, right: card.right,
- dock: { overlaps: x >= card.left && x <= card.right && y >= card.top && y <= card.bottom,
- tutorialOnTop: !!top && tutorial.contains(top) } };
- });
- assert.ok(Math.abs(probe.bottom - (viewport.height - inset)) <= 1,
- `教程浮窗没有贴着右下角:下沿 ${probe.bottom},应为 ${viewport.height - inset}`);
- if (viewport.mobile) {
- assert.ok(probe.dock.overlaps, '批量选择条的中心没落在教程浮窗上,这条判据没有量到重叠');
- assert.ok(!probe.dock.tutorialOnTop, '教程浮窗盖住了批量选择条');
- }
- assert.ok(probe.top >= 0 && probe.left >= 0 && probe.right <= viewport.width,
- `教程浮窗越出了 ${viewport.width}px 视口`);
-
- /* 回执走真的入口发一条不会自己消失的,等栈里每一条都进场停稳再量。演示库刚跑完扫描,
- 「扫描与资料采集已完成」随时可能也进栈,所以判据是栈里每一条都在卡上沿之上。 */
- await opened.page.evaluate(async () => {
- const entry = '/dist/peach-ui.js';
- const ui = await import(entry);
- ui.showToast(document.getElementById('toasts'), { success: '', error: '' }, 'e2e-tutorial-lift',
- { html: '已保存配置', alert: false, timeout: 0, action: null });
- });
- await opened.page.locator('#toasts [data-sonner-toast]').first().waitFor();
- await opened.page.waitForFunction(() => [...document.querySelectorAll('#toasts [data-sonner-toast]')]
- .every((node) => node.getAttribute('data-mounted') === 'true' && node.getAnimations().length === 0));
- const stack = await opened.page.evaluate(() => {
- const card = document.querySelector('#postSetupTutorial .post-setup-notification')!.getBoundingClientRect();
- const boxes = [...document.querySelectorAll('#toasts [data-sonner-toast]')].map((node) => node.getBoundingClientRect());
- return { cardTop: card.top, lowest: Math.max(...boxes.map((box) => box.bottom)),
- highest: Math.min(...boxes.map((box) => box.top)) };
- });
- assert.ok(stack.lowest <= stack.cardTop,
- `Toast 压在教程浮窗上:Toast 下沿 ${stack.lowest},教程上沿 ${stack.cardTop}`);
- assert.ok(stack.highest >= 0, `Toast 被顶出了视口:上沿 ${stack.highest}`);
- } finally {
- await opened.close();
- }
- });
- }
-
- it('复核筛选条上的下拉和按钮一样高', { timeout: 60_000 }, async () => {
- const opened = await openReview(browser);
- try {
- /* BoardUI 的 Button 和 Input 都写死 h-8/h-9,Select 的 trigger 只有内边距,
- 自己撑到 28px/38px。三颗并排时那 4px 一眼就看得见。量的是整条筛选条上每一颗
- 控件,而不是点名某一颗:这一排以后加什么,都得落在同一档上。 */
- const heights = await opened.page.locator('[data-review-filter]')
- .evaluate((bar) => [...bar.querySelectorAll('button')]
- .map((node) => Math.round(node.getBoundingClientRect().height)));
- assert.ok(heights.length >= 2, `筛选条上只量到 ${heights.length} 颗控件`);
- assert.deepEqual([...new Set(heights)], [heights[0]],
- `筛选条上的控件高度不齐:${heights.join(' / ')}`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('复核卡的勾选框和标题共用一条中线', { timeout: 60_000 }, async () => {
- const opened = await openReview(browser);
- try {
- /* 勾选框 16px、标题那行 24px(字段名是一枚 caption Chip)。两个高度不同的东西
- 顶对顶排在一起,读的人看到的是勾选框比标题高出一截,而它们说的是同一张卡。 */
- const offset = await opened.page.locator('section[data-review-key] header').first()
- .evaluate((element) => {
- const middle = (node: Element) => {
- const box = node.getBoundingClientRect();
- return box.top + box.height / 2;
- };
- return middle(element.querySelector('label > span')!) - middle(element.querySelector('h4')!);
- });
- assert.ok(Math.abs(offset) <= 1, `勾选框比标题偏了 ${offset.toFixed(1)}px,不在同一条中线上`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('复核滚动边缘按方向出现,当前信息在分隔线之间居中', { timeout: 60_000 }, async () => {
- const opened = await openReview(browser);
- try {
- const card = opened.page.locator('section[data-review-key]').first();
- const scroller = card.locator('div[data-overlay-scrollbar]').first();
- // 增加候选内容,覆盖图片加载或队列更新后的溢出重算。
- await scroller.evaluate((node) => {
- const content = document.createElement('div');
- content.style.cssText = 'height:1000px;flex-shrink:0';
- content.dataset.scrollTest = '';
- node.append(content);
- });
- const edges = scroller.locator('..').locator('.ov-edges');
- await opened.page.waitForFunction(() => !!document.querySelector('[data-review-key] .can-scroll-bottom'));
- assert.equal(await edges.evaluate((node) => node.classList.contains('can-scroll-top')), false);
- await scroller.evaluate((node) => { node.scrollTop = 100 });
- await opened.page.waitForFunction(() => !!document.querySelector('[data-review-key] .can-scroll-top.can-scroll-bottom'));
- assert.equal(await edges.evaluate((node) => getComputedStyle(node).pointerEvents), 'none');
- assert.equal(await edges.locator('.ov-edge-top').evaluate((node) => getComputedStyle(node).backdropFilter), 'blur(2px)');
- const track = scroller.locator('..').locator('.ovtrack.ov-y');
- for (const viewport of [DESKTOP, MOBILE]) {
- await opened.page.setViewportSize({ width: viewport.width, height: viewport.height });
- const bounds = await track.evaluate((node) => {
- const scroll = node.parentElement!.querySelector('[data-overlay-scrollbar]')!.getBoundingClientRect();
- const rail = node.getBoundingClientRect();
- const card = node.closest('section')!.getBoundingClientRect();
- return { gap: rail.left - scroll.right, inset: card.right - rail.right };
- });
- assert.ok(bounds.gap >= -1, `滚动条命中区覆盖正文:${JSON.stringify(bounds)}`);
- assert.ok(bounds.inset >= 1, `滚动条越出卡片:${JSON.stringify(bounds)}`);
- }
- await opened.page.setViewportSize({ width: DESKTOP.width, height: DESKTOP.height });
- const thumb = await track.locator('.ovthumb').boundingBox();
- assert.ok(thumb);
- await opened.page.mouse.move(thumb.x + thumb.width / 2, thumb.y + thumb.height / 2);
- await opened.page.mouse.down();
- await opened.page.mouse.move(thumb.x + thumb.width / 2, thumb.y + thumb.height / 2 + 30);
- await opened.page.mouse.up();
- assert.ok(await scroller.evaluate((node) => node.scrollTop > 100), '右侧轨道拖动没有滚动正文');
- await scroller.evaluate((node) => { node.scrollTop = node.scrollHeight });
- await opened.page.waitForFunction(() => !document.querySelector('[data-review-key] .can-scroll-bottom'));
- await scroller.locator('[data-scroll-test]').evaluate((node) => node.remove());
- await opened.page.waitForFunction(() => !document.querySelector('[data-review-key] [data-scroll-edges]'));
- const spacing = await card.getByRole('region', { name: '当前信息' }).evaluate((node) => {
- const style = getComputedStyle(node);
- const footer = node.closest('section')!.querySelector('footer')!.getBoundingClientRect();
- return { top: parseFloat(style.paddingTop), bottom: parseFloat(style.paddingBottom), gap: footer.top - node.getBoundingClientRect().bottom };
- });
- assert.equal(spacing.top, spacing.bottom);
- assert.ok(Math.abs(spacing.gap) <= 1, `当前信息下方多出 ${spacing.gap}px`);
- assert.deepEqual(opened.problems, []);
- } finally { await opened.close() }
- });
-
- it('暗色下没选中的勾选框边线不比浅色下更弱', { timeout: 60_000 }, async () => {
- const opened = await openReview(browser);
- try {
- /* 这颗框的底和卡面同色,所以整个形状全靠那一圈 1px 的边说话。浅色下它是白底上的
- 浅灰线,暗色下必须至少同样清楚——否则卡上看着就是「没有框」。 */
- /* 计算值是 `oklch()` 原样,解析不出通道;画进 1×1 的画布再读回来就是 RGBA。 */
- const edge = () => opened.page.locator('section[data-review-key] header label > span').first()
- .evaluate((node) => {
- const context = document.createElement('canvas').getContext('2d')!;
- const paint = (color: string) => {
- context.clearRect(0, 0, 1, 1);
- context.fillStyle = color;
- context.fillRect(0, 0, 1, 1);
- return [...context.getImageData(0, 0, 1, 1).data];
- };
- const style = getComputedStyle(node);
- return [paint(style.borderTopColor), paint(style.backgroundColor)] as const;
- });
- const [lightEdge, lightFace] = await edge();
- // `web/app.js` 的 `applyTheme('dark')` 就是这两句;这里只借它换一次配色。
- await opened.page.evaluate(() => {
- document.documentElement.dataset.theme = 'dark';
- document.documentElement.classList.add('dark');
- });
- const [darkEdge, darkFace] = await edge();
- const light = Math.abs(lightness(lightEdge) - lightness(lightFace));
- const dark = Math.abs(lightness(darkEdge) - lightness(darkFace));
- assert.ok(dark >= light,
- `暗色下边线与框内只差 ${dark.toFixed(1)} 个明度,浅色下有 ${light.toFixed(1)}`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('暗色下分隔线在两种卡面上都不比浅色更弱', { timeout: 60_000 }, async () => {
- const opened = await openReview(browser);
- try {
- /* 量的是 token 对而不是某一条线:`separator-border` 画在哪种面上由各处自己决定,
- 复核卡的外框和候选块之间那条线落在 `primary`,脚注带那条落在 `secondary`。逐条去点名,
- 新加一处就得记得再补一条用例,而漏补和「这处本来就没线」在屏幕上看不出区别。
- 末尾再核一次复核卡自己的框线确实取的就是这个 token,免得两档都合格却根本没落到现场。 */
- const read = () => opened.page.locator('section[data-review-key]').first()
- .evaluate((node) => {
- const context = document.createElement('canvas').getContext('2d')!;
- const paint = (color: string) => {
- context.clearRect(0, 0, 1, 1);
- context.fillStyle = color;
- context.fillRect(0, 0, 1, 1);
- return [...context.getImageData(0, 0, 1, 1).data];
- };
- const style = getComputedStyle(node);
- const token = (name: string) => paint(style.getPropertyValue(name).trim());
- return {
- line: token('--color-separator-border'),
- card: token('--color-background-primary-default'),
- filled: token('--color-background-secondary-default'),
- edge: paint(style.borderTopColor),
- };
- });
- const before = await read();
- // `web/app.js` 的 `applyTheme('dark')` 就是这两句;这里只借它换一次配色。
- await opened.page.evaluate(() => {
- document.documentElement.dataset.theme = 'dark';
- document.documentElement.classList.add('dark');
- });
- const after = await read();
- for (const [face, label] of [['card', '描边卡面'], ['filled', '填充卡面']] as const) {
- const light = Math.abs(lightness(before.line) - lightness(before[face]));
- const dark = Math.abs(lightness(after.line) - lightness(after[face]));
- assert.ok(dark >= light,
- `暗色下分隔线压在${label}上只差 ${dark.toFixed(1)} 个明度,浅色下有 ${light.toFixed(1)}`);
- }
- assert.deepEqual(after.edge, after.line, '复核卡的框线没走 separator-border');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('垃圾文件的计数行是两块看得见、跟标题同宽的面', { timeout: 60_000 }, async () => {
- const opened = await openJunk(browser);
- try {
- /* 三件事一起量,它们是同一条:这一行装着摘要和分类切换两块整宽的面,横排时后者
- 被挤成 0 宽;两块面和网格只要有一支不受 --board-content 约束,宽屏上标题就缩在
- 中间、卡片顶着两边;浅色下 primary 就是页面底色,不换一档这两块面整个消失。 */
- const box = await opened.page.evaluate(() => {
- // 浅色是两块面最容易消失的那一档:深色下 primary 本来就比页面亮一级。
- document.documentElement.dataset.theme = 'light';
- document.documentElement.classList.remove('dark');
- const span = (selector: string) => {
- const rect = document.querySelector(selector)!.getBoundingClientRect();
- return { left: Math.round(rect.left), width: Math.round(rect.width) };
- };
- const face = (selector: string) =>
- getComputedStyle(document.querySelector(selector)!).backgroundColor;
- return {
- title: span('[data-manage-title]'),
- summary: span('#count [data-collection-summary]'),
- filters: span('#count [data-junk-filters-frame]'),
- grid: span('#grid'),
- summaryFace: face('#count [data-collection-summary]'),
- filtersFace: face('#count [data-junk-filters-frame]'),
- page: getComputedStyle(document.body).backgroundColor,
- };
- });
- assert.ok(box.filters.width > 0, '分类切换被摘要挤成 0 宽,整条在宽屏上看不见');
- for (const [label, measured] of [['摘要', box.summary], ['分类切换', box.filters],
- ['网格', box.grid]] as const) {
- assert.deepEqual(measured, box.title,
- `${label}和标题不同宽:${measured.left}+${measured.width} 对 ${box.title.left}+${box.title.width}`);
- }
- assert.notEqual(box.summaryFace, box.page, '摘要那块面和页面底色同色,整块看不见');
- assert.notEqual(box.filtersFace, box.page, '分类切换那块面和页面底色同色,整块看不见');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('垃圾文件等数据时画的仍是它自己那条计数行', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/junk-files', WIDE);
- try {
- /* 把等待态停在屏幕上:让这一页唯一那次取数挂着不回。等的只有读数,分类切换由
- URL 决定、此刻就画得出最终样子;画成目录那条的话,等待期间摆着一排这一页根本
- 没有的换批与排序键,数据到货整行再换成另一种东西。 */
- await opened.page.route('**/api/ads?**', () => {});
- await opened.page.reload({ waitUntil: 'load' });
- // 等 island 接管:壳铺的骨架和它等数据时那一版相同,接管之后仍是这一版才算数。
- await opened.page.locator(`${JUNK_COUNT} [data-junk-filters]`).waitFor({ timeout: 15_000 });
- const row = await opened.page.locator('#count').evaluate((node) => ({
- busy: node.getAttribute('aria-busy'),
- filters: node.querySelectorAll('[data-junk-filters] a').length,
- placeholder: node.querySelectorAll('[data-collection-summary] [data-skeleton="count"]').length,
- sorts: node.querySelectorAll('.sorts').length,
- }));
- assert.equal(row.busy, 'true', '等待态没有对辅助技术公开');
- assert.ok(row.filters > 0, '等待期间这一行没有分类切换');
- assert.equal(row.placeholder, 1, '占位没有落在读数那一格');
- assert.equal(row.sorts, 0, '等待期间摆着这一页没有的排序键');
- } finally {
- await opened.close();
- }
- });
-
- it('垃圾卡处置发出一条批量请求、卡随之离开;换分类不整页跳转', { timeout: 90_000 }, async () => {
- const opened = await openJunkWith(browser, [
- junkItem(9101, 'archive', '推广合集.zip'), junkItem(9102, 'url', '官网.url'), junkItem(9103, 'audio', '广告.mp3'),
- ]);
- try {
- const page = opened.page;
- const cards = page.locator('#grid [data-junk-card]');
- assert.equal(await cards.count(), 3);
- await cards.first().locator('[data-junk-action="dispose"]').click();
- await page.waitForFunction(() => document.querySelectorAll('#grid [data-junk-card]').length === 2, null,
- { timeout: 10_000 });
- assert.deepEqual(opened.state.batches, [{ ids: [9101], operation: 'dispose' }]);
- await page.getByText('已移入回收站', { exact: true }).first().waitFor({ timeout: 5_000 });
-
- // 分类是 `<a href>`,普通左键由壳改地址重读:整页重载的话,页面上记的这个标记会丢。
- await page.evaluate(() => { (window as { junkStay?: boolean }).junkStay = true });
- await page.locator(`${JUNK_COUNT} [data-junk-kind-link="url"]`).click();
- await page.waitForFunction(() => location.search === '?type=url'
- && document.querySelectorAll('#grid [data-junk-card]').length === 1, null, { timeout: 10_000 });
- assert.equal(await page.evaluate(() => (window as { junkStay?: boolean }).junkStay), true, '换分类整页重载了');
- assert.match(opened.state.reads.at(-1)!, /kind=url/);
- assert.equal(await page.locator(`${JUNK_COUNT} [data-junk-kind-link="url"]`).getAttribute('aria-current'), 'page');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('垃圾卡是一块有边的面:三颗键等宽居中,移入回收站静止就是实底红', { timeout: 90_000 }, async () => {
- const opened = await openJunkWith(browser, [junkItem(9201, 'archive', '推广.zip'), junkItem(9202, 'url', '官网.url')]);
- try {
- const page = opened.page;
- const read = () => page.evaluate(() => {
- const card = document.querySelector('#grid [data-junk-card]')!;
- const keys = [...card.querySelectorAll('[data-junk-action]')].map((button) => {
- const style = getComputedStyle(button);
- const rect = button.getBoundingClientRect();
- return {
- action: (button as HTMLElement).dataset.junkAction, width: Math.round(rect.width), height: Math.round(rect.height),
- justify: style.justifyContent, border: style.borderTopWidth, face: style.backgroundColor, ink: style.color,
- label: getComputedStyle(button.querySelector('[data-junk-label]')!).display,
- };
- });
- const rect = (node: Element | null) => {
- if (!node) return null;
- const { left, top, width, height } = node.getBoundingClientRect();
- return [left, top, width, height].map(Math.round);
- };
- const links = [...document.querySelectorAll('#count [data-junk-filters] a')].map((link) => ({
- current: link.getAttribute('aria-current') === 'page', face: getComputedStyle(link).backgroundColor,
- height: Math.round(link.getBoundingClientRect().height), box: rect(link),
- }));
- // 计数徽标到货时玻璃带动画重新落位:跑完再量,量的是它停下的地方。
- document.querySelector('#count [data-view-glide]')?.getAnimations().forEach((one) => one.finish());
- const glide = rect(document.querySelector('#count [data-view-glide]:not([hidden])'));
- // 卡在 island 里取 oklch,页面底是 rgb:各画一个像素再比,字面不同不等于颜色不同。
- const pixel = (color: string) => {
- const context = document.createElement('canvas').getContext('2d')!;
- context.fillStyle = color;
- context.fillRect(0, 0, 1, 1);
- return [...context.getImageData(0, 0, 1, 1).data].join(',');
- };
- const style = getComputedStyle(card);
- const ground = [document.body, document.documentElement].map((el) => pixel(getComputedStyle(el).backgroundColor))
- .find((value) => !value.endsWith(',0')) ?? '255,255,255,255';
- return { edge: style.borderTopWidth, line: pixel(style.borderTopColor), page: ground, keys, links, glide };
- });
- const red = await tokenColor(page, 'body', '--board-red');
- const wide = await read();
- // 浅色下卡底与页面同为白,卡的轮廓全靠这圈边:边宽 1px、颜色不能跟页面底一样。
- assert.equal(wide.edge, '1px', '垃圾卡没有描边');
- assert.notEqual(wide.line, wide.page, '垃圾卡的边和页面底色同色');
- assert.equal(new Set(wide.keys.map((key) => key.width)).size, 1, `三颗键不等宽:${wide.keys.map((key) => key.width)}`);
- for (const key of wide.keys) {
- assert.equal(key.justify, 'center', `${key.action} 的图标与标签没有居中`);
- assert.equal(key.height, 36, `${key.action} 高 ${key.height}`);
- }
- const dispose = wide.keys.find((key) => key.action === 'dispose')!;
- assert.equal(dispose.face, red, '移入回收站静止态不是实底红');
- assert.equal(dispose.ink, 'rgb(255, 255, 255)');
- for (const key of wide.keys.filter((one) => one.action !== 'dispose')) assert.equal(key.border, '1px', `${key.action} 没有描边`);
- const current = wide.links.filter((link) => link.current);
- assert.equal(current.length, 1);
- // 分类条是首页筛选条那一副:键自己不铺底,当前那一类底下垫的是那块滑动玻璃。
- assert.ok(wide.links.every((link) => link.face === 'rgba(0, 0, 0, 0)'), '分类键自己铺了底,不是首页那副滑动玻璃');
- assert.deepEqual(wide.glide, current[0]!.box, '滑动玻璃没有落在当前那一类上');
-
- // 紧凑密度下键上只剩图标。
- await page.evaluate(() => { document.body.dataset.density = 'dense' });
- assert.ok((await read()).keys.every((key) => key.label === 'none'), '紧凑密度下键上还有字');
- await page.evaluate(() => { delete document.body.dataset.density });
-
- // 手机上够手指点:分类与三颗键都到 44px。
- await page.setViewportSize({ width: MOBILE.width, height: MOBILE.height });
- const narrow = await read();
- assert.ok(narrow.keys.every((key) => key.height >= 44), `手机上键高 ${narrow.keys.map((key) => key.height)}`);
- assert.ok(narrow.links.every((link) => link.height >= 44), `手机上分类高 ${narrow.links.map((link) => link.height)}`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('关注列表工具行里的主动作、版式开关、排序框和方向键同高', { timeout: 60_000 }, async () => {
- const opened = await openFollowManage(browser);
- try {
- const page = opened.page;
- const controls = {
- 检查全部: page.locator('button[aria-label="检查全部"]'),
- // 两枚图标键拼成一组,对齐的是整组的外框,不是组里单个键。
- 版式开关: page.locator('[aria-label="关注列表版式"]'),
- 排序框: page.locator('button[aria-label="关注列表排序"]'),
- 方向键: page.locator('button[aria-label^="按检查时间"]'),
- };
- const heights: Record<string, number> = {};
- for (const [name, control] of Object.entries(controls)) {
- heights[name] = (await control.boundingBox())!.height;
- }
- assert.equal(new Set(Object.values(heights)).size, 1, `同一排控件高度不一:${JSON.stringify(heights)}`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- for (const viewport of [DESKTOP, MOBILE]) {
- it(`关注列表骨架的偏好控件和接管后同一副长相,等数据的操作键是禁用态(${viewport.name})`, { timeout: 60_000 }, async () => {
- /* 骨架与真页面各量一遍。版式、排序和方向是这台浏览器的偏好,骨架里就是最终那一档;
- 检查全部、全部收起和行尾的移除键要等名单,骨架里是禁用态,只有尺寸与接管后一致。
- 窄屏上工具行收成纯图标,两边按同一条线收,尺寸也要对得上。 */
- const opened = await visit(browser, '/follow-manage', viewport);
- try {
- const page = opened.page;
- await stubFollowManage(page);
- const release = await holdApi(page);
- await page.reload({ waitUntil: 'load' });
- await page.locator('[data-skeleton="board/follow-manage"] .follow-skeleton-toolbar').waitFor({ timeout: 15_000 });
- const toolbar = '[data-skeleton] .follow-skeleton-toolbar';
- const skeleton = await controlFaces(page, {
- 检查全部: `${toolbar} > button:nth-of-type(1)`,
- 默认视图: `${toolbar} > [data-button-group] > button:first-child`,
- 表格视图: `${toolbar} > [data-button-group] > button:last-child`,
- 排序框: `${toolbar} button[aria-haspopup="listbox"]`,
- 方向键: `${toolbar} > button:nth-of-type(2)`,
- 全部收起: `${toolbar} > button:nth-of-type(3)`,
- 移除来源: '[data-skeleton] .follow-skeleton-source > span:last-child > button:last-child',
- });
- const expected = await disabledTokens(page);
- const waiting = await waitingActionFaces(page, '[data-skeleton] [data-skeleton-action]');
- assert.ok(waiting.length >= 3, '关注列表骨架里没有标出等数据的操作键');
- for (const face of waiting) assertDisabledFace(face, expected);
- release();
- await page.locator('section[aria-label="kou 的关注来源"]').waitFor({ timeout: 15_000 });
- await settle(page);
- const final = await controlFaces(page, {
- 检查全部: 'button[aria-label="检查全部"]',
- 默认视图: '[aria-label="关注列表版式"] > button:first-child',
- 表格视图: '[aria-label="关注列表版式"] > button:last-child',
- 排序框: 'button[aria-label="关注列表排序"]',
- 方向键: 'button[aria-label^="按检查时间"]',
- 全部收起: 'button[aria-label="全部收起"]',
- 移除来源: '[data-source-divider] > div > span:last-child > button:last-child',
- });
- const waitsForData = new Set(['检查全部', '全部收起', '移除来源']);
- for (const name of Object.keys(final)) {
- assert.ok(final[name], `接管后找不到 ${name}`);
- if (waitsForData.has(name)) {
- assert.equal(skeleton[name]!.size, final[name]!.size, `${name} 接管时尺寸跳了`);
- continue;
- }
- assert.deepEqual(skeleton[name], final[name], `${name} 在骨架里和接管后长得不一样`);
- }
- assert.equal(final['默认视图']!.pressed, 'true', '默认版式下选中的不是网格那颗');
- } finally {
- await opened.close();
- }
- });
- }
-
- /* 整行都能点选之后,指着哪一行得看得出来。卡片视图的来源行和表格行走同一条规则;选中行
- 有自己的底色,指着它时不换。 */
- it('关注列表指着哪一行哪一行换底色,两种视图都是,选中行的底色不被 hover 盖掉', { timeout: 60_000 }, async () => {
- const opened = await openFollowManage(browser);
- try {
- const page = opened.page;
- const background = (locator: Locator) => locator.evaluate((element) => {
- for (const animation of element.getAnimations()) animation.finish();
- return getComputedStyle(element).backgroundColor;
- });
- /* 勾选框的 input 视觉隐藏在画出来的方框底下,点它要 force,和上面选中底色那条用例一样。 */
- const select = () => page.getByRole('checkbox', { name: '选择 kou · Kemono' })
- .check({ force: true, timeout: 5_000 });
- const card = page.locator('[data-source-divider] > div').first();
- const cardRested = await background(card);
- await card.hover();
- assert.notEqual(await background(card), cardRested, '指着卡片视图的来源行时底色没换');
- await select();
- const cardSelectedHovered = await background(card);
- await page.mouse.move(0, 0);
- const cardSelectedRested = await background(card);
- assert.equal(cardSelectedHovered, cardSelectedRested, '卡片视图选中行指着时换了底色,盖掉了选中态');
- assert.notEqual(cardSelectedRested, cardRested, '卡片视图选中行没有自己的底色');
-
- await page.locator('button[aria-label="表格视图"]').click({ timeout: 5_000 });
- const row = page.locator('[data-board-data-table] tbody tr').first();
- await row.waitFor({ timeout: 15_000 });
- await page.mouse.move(0, 0);
- const selectedRested = await background(row);
- await row.hover();
- assert.equal(await background(row), selectedRested, '表格视图选中行指着时换了底色,盖掉了选中态');
- await page.getByRole('checkbox', { name: '选择 kou · Kemono' }).uncheck({ force: true, timeout: 5_000 });
- await page.mouse.move(0, 0);
- const rested = await background(row);
- assert.notEqual(selectedRested, rested, '表格视图选中行没有自己的底色');
- await row.hover();
- assert.notEqual(await background(row), rested, '指着表格行时底色没换');
- } finally {
- await opened.close();
- }
- });
-
- it('数据管理骨架里等数据的操作键是禁用态,数据到了才换回蓝色主按钮', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/data-cleanup', DESKTOP);
- try {
- const page = opened.page;
- // 没有任务在跑:跑着的那一档会把扫描键压成忙碌态,那是数据不是骨架。
- await page.route('**/api/library-processing', (route) => route.fulfill({
- status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'idle' }),
- }));
- const release = await holdApi(page);
- await page.reload({ waitUntil: 'load' });
- await page.locator('[data-skeleton="cleanup"] .cleanupscraping [data-split-button]').waitFor({ timeout: 15_000 });
- const expected = await disabledTokens(page);
- const waiting = await waitingActionFaces(page, '[data-skeleton="cleanup"] [data-skeleton-action]');
- assert.deepEqual(waiting.map((face) => face.name),
- ['扫描并补全资料', '更多扫描与采集方式', '开始修复', '预览', '检查死链', '检查文件']);
- for (const face of waiting) assertDisabledFace(face, expected);
- const ring = await page.locator('[data-skeleton="cleanup"] [data-split-button]')
- .evaluate((element) => getComputedStyle(element).boxShadow);
- assert.ok(ring.includes(expected.ring), `骨架里的分体键外圈不是禁用那一档描边:${ring}`);
- const sizes = await controlFaces(page, {
- 扫描并补全资料: '.cleanupscraping [data-split-button] > button:first-child',
- 更多方式: '.cleanupscraping [data-split-button] > button:last-child',
- 开始修复: '.cleanupmediarepair footer > button',
- });
- release();
- await page.locator('[data-skeleton="cleanup"]').waitFor({ state: 'detached', timeout: 15_000 });
- // 正式页面先摆一份同样的骨架卡,等 React 岛接管;键上没了 `data-skeleton-action` 才算接管完。
- await page.locator('section[aria-label="扫描与采集"] [data-split-button] > button:first-child:not([data-skeleton-action])')
- .waitFor({ timeout: 15_000 });
- await page.locator('section[aria-label="媒体修复"] footer > button:not([data-skeleton-action])')
- .waitFor({ timeout: 15_000 });
- await settle(page);
- const final = await controlFaces(page, {
- 扫描并补全资料: 'section[aria-label="扫描与采集"] [data-split-button] > button:first-child',
- 更多方式: 'section[aria-label="扫描与采集"] [data-split-button] > button:last-child',
- 开始修复: 'section[aria-label="媒体修复"] footer > button',
- });
- for (const name of Object.keys(sizes)) {
- assert.equal(sizes[name]!.size, final[name]!.size, `${name} 接管时尺寸跳了`);
- assert.match(final[name]!.face, /gradient/, `${name} 接管后没换回蓝色主按钮`);
- }
- const enabled = await page.locator('section[aria-label="扫描与采集"] [data-split-button] > button')
- .evaluateAll((buttons) => buttons.map((button) => (button as HTMLButtonElement).disabled));
- assert.deepEqual(enabled, [false, false], '数据到了扫描键还是禁用的');
- } finally {
- await opened.close();
- }
- });
-
- it('数据管理卡外的分区标题是 20px 的 Title 2,链接读数照旧版字号与行高', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/data-cleanup', DESKTOP);
- try {
- const page = opened.page;
- await page.locator('#link-manager .link-stat-grid b').first().waitFor({ timeout: 15_000 });
- await page.locator('#resource-sync-title').waitFor({ timeout: 15_000 });
- await settle(page);
- const faces = await page.evaluate(() => {
- const style = (selector: string) => {
- const computed = getComputedStyle(document.querySelector(selector)!);
- return {
- size: computed.fontSize, weight: computed.fontWeight, line: computed.lineHeight,
- top: computed.marginTop, bottom: computed.marginBottom,
- };
- };
- return {
- links: style('#link-manager-title'),
- sync: style('#resource-sync-title'),
- label: style('#link-manager .link-stat-grid span'),
- figure: style('#link-manager .link-stat-grid b'),
- };
- });
- /* 这一页挂在 `#stats` 里,遗留样式表给那里的二级标题定了 24px 与 4px 底距。 */
- for (const [name, heading] of [['链接管理', faces.links], ['资源同步', faces.sync]] as const) {
- assert.equal(heading.size, '20px', `${name}标题字号不是 Title 2`);
- assert.equal(heading.bottom, '0px', `${name}标题带着遗留那 4px 底距`);
- }
- assert.deepEqual([faces.label.size, faces.label.line], ['12px', '20px'], '链接读数的标签不是 12/20');
- assert.deepEqual([faces.figure.size, faces.figure.weight, faces.figure.line], ['20px', '700', '20px'],
- '链接读数的数字不是 20px 粗体、20px 行高');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('可点的卡悬停时铺卡面掺 5% 主文字色的那一档面,不是透明', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/data-cleanup', DESKTOP);
- try {
- const page = opened.page;
- const selector = '.peach-react [data-cleanup-go]';
- const card = page.locator(selector).first();
- await card.waitFor({ timeout: 15_000 });
- await settle(page);
- const rest = await card.evaluate((element) => getComputedStyle(element).backgroundColor);
- await card.hover();
- // 过渡跑完才读:等到底色变了,或三秒后照实读出没变的那个值。
- await page.waitForFunction(([target, before]) =>
- getComputedStyle(document.querySelector(target)!).backgroundColor !== before,
- [selector, rest] as const, { timeout: 3_000 }).catch(() => undefined);
- const hovered = await card.evaluate((element) => getComputedStyle(element).backgroundColor);
- assert.notEqual(hovered, 'rgba(0, 0, 0, 0)', '悬停底色落成了透明:token 在根上就折掉了');
- assert.notEqual(hovered, rest, '悬停没有换面');
- assert.equal(hovered, await tokenColor(page, '.peach-react', '--card-hover'), '悬停底色不是卡面掺 5% 主文字色');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('索引页名册格用遗留卡面那一套:格底 --ground、头像框 --sunk、首字与读数 --muted 配 Bahnschrift,悬停掺 6% 主文字色;页头过滤框与版式切换同为 36px 高,切换两枚共 66px 宽', { timeout: 60_000 }, async () => {
- const opened = await openIndexPage(browser, '/performers');
- try {
- const page = opened.page;
- const selector = '#index [data-index-cell]';
- const cell = page.locator(selector).first();
- const rest = await cell.evaluate((element) => getComputedStyle(element).backgroundColor);
- const face = await page.evaluate(() => {
- const ring = document.querySelector('#index [data-person-ring]')!;
- const initial = document.querySelector('#index [data-person-ring] .ini')!;
- const readout = document.querySelector('#index [data-index-readout]')!;
- return { ring: getComputedStyle(ring).backgroundColor, initial: getComputedStyle(initial).color,
- font: getComputedStyle(initial).fontFamily, readout: getComputedStyle(readout).color };
- });
- assert.equal(rest, await tokenColor(page, 'html', '--ground'), '名册格底不是 --ground');
- assert.equal(face.ring, await tokenColor(page, 'html', '--sunk'), '头像框底不是 --sunk');
- const muted = await page.evaluate(() => {
- const probe = document.createElement('div');
- probe.style.color = 'var(--muted)';
- document.documentElement.append(probe);
- const value = getComputedStyle(probe).color;
- probe.remove();
- return value;
- });
- assert.deepEqual([face.initial, face.readout], [muted, muted], '首字与读数不是 --muted');
- assert.match(face.font, /^Bahnschrift/, '首字不是 Bahnschrift');
- await cell.hover();
- await page.waitForFunction(([target, before]) =>
- getComputedStyle(document.querySelector(target)!).backgroundColor !== before,
- [selector, rest] as const, { timeout: 3_000 }).catch(() => undefined);
- const hovered = await cell.evaluate((element) => getComputedStyle(element).backgroundColor);
- const lifted = await page.evaluate(() => {
- const probe = document.createElement('div');
- probe.style.backgroundColor = 'color-mix(in srgb, var(--ink) 6%, var(--ground))';
- document.documentElement.append(probe);
- const value = getComputedStyle(probe).backgroundColor;
- probe.remove();
- return value;
- });
- assert.equal(hovered, lifted, '名册格悬停不是格底掺 6% 主文字色');
- const head = await page.evaluate(() => {
- const input = document.querySelector('#index [data-index-search] input')!;
- const shell = input.closest('[role="presentation"]')!;
- const toggle = document.querySelector('#index [data-index-layout]')!;
- return { search: getComputedStyle(shell).height, toggle: getComputedStyle(toggle).height,
- width: getComputedStyle(toggle).width };
- });
- assert.deepEqual(head, { search: '36px', toggle: '36px', width: '66px' });
- // 人脸放大把 img 撑得比框还宽再负偏移;Preflight 的 `max-width:100%` 会把它压回框宽。
- const photo = page.locator('#index [data-person-ring] img').first();
- await photo.waitFor({ state: 'attached', timeout: 5_000 });
- await page.waitForFunction(() => document.querySelector('#index [data-person-ring]')?.hasAttribute('data-native-small'),
- undefined, { timeout: 5_000 });
- assert.equal(await photo.evaluate((element) => getComputedStyle(element).maxWidth), 'none');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('索引页换一档 Tabs 时那条蓝线沿弹簧滑过去,不是一跳', { timeout: 60_000 }, async () => {
- const opened = await openIndexPage(browser, '/studios');
- try {
- const page = opened.page;
- await page.emulateMedia({ reducedMotion: 'no-preference' });
- const indicator = page.locator('#index [data-tab-indicator]');
- await page.waitForFunction(() => document.querySelector('#index [data-tab-indicator]')?.hasAttribute('data-ready'),
- undefined, { timeout: 5_000 });
- const motion = await indicator.evaluate((element) => {
- const style = getComputedStyle(element);
- return { property: style.transitionProperty, duration: style.transitionDuration, height: style.height };
- });
- assert.equal(motion.property, 'transform, width');
- assert.notEqual(motion.duration.split(',')[0]!.trim(), '0s', '蓝线没有过渡时长');
- assert.equal(motion.height, '2px');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('播放列表卡:封面后压两层纸边、黑底封面、玻璃徽标、38px 头像叠 22px;标题 32/44,菜单键静止透明', { timeout: 60_000 }, async () => {
- const opened = await openPlaylistsPage(browser);
- try {
- const page = opened.page;
- const look = await page.evaluate(() => {
- const card = document.querySelector('#stats [data-playlist-card="1"]')!;
- const css = (selector: string) => getComputedStyle(card.querySelector(selector)!);
- const stack = card.querySelector('[data-mix-stack]')!;
- const back = getComputedStyle(stack, '::before');
- const mid = getComputedStyle(stack, '::after');
- const title = getComputedStyle(document.querySelector('#stats header h2')!);
- const cover = css('[data-mix-cover]');
- const badge = css('[data-mix-badge]');
- const menu = css('[data-playlist-menu]');
- const blank = getComputedStyle(document.querySelector('#stats [data-playlist-card="3"] [data-mix-cover] > span')!);
- return {
- title: [title.fontSize, title.lineHeight, title.fontWeight],
- gap: getComputedStyle(document.querySelector('#stats [data-playlist-grid]')!).gap,
- back: [back.borderTopWidth, back.inset, back.transform, back.opacity],
- mid: [mid.borderTopWidth, mid.inset, mid.transform, mid.opacity],
- cover: [cover.backgroundColor, cover.clipPath],
- badge: [badge.backgroundColor, badge.backdropFilter, badge.minHeight, badge.borderRadius, badge.right, badge.bottom],
- avatars: [...card.querySelectorAll('[data-mix-avatars] button')].map((button) => {
- const style = getComputedStyle(button);
- return [style.width, style.marginLeft, style.zIndex];
- }),
- menu: [menu.width, menu.height, menu.borderRadius, menu.backgroundColor],
- blank: [blank.letterSpacing, blank.textTransform],
- };
- });
- assert.deepEqual(look, {
- title: ['32px', '44px', '500'],
- gap: '18px',
- back: ['1px', '0px 12px 8px', 'matrix(1, 0, 0, 1, 0, -7)', '0.54'],
- mid: ['1px', '0px 6px 4px', 'matrix(1, 0, 0, 1, 0, -4)', '0.78'],
- cover: ['rgb(0, 0, 0)', 'inset(0px round 14px)'],
- badge: ['rgba(12, 8, 8, 0.72)', 'blur(10px)', '28px', '10px', '9px', '9px'],
- avatars: [['38px', '0px', '5'], ['38px', '-22px', '4'], ['38px', '-22px', '3']],
- menu: ['30px', '30px', '10px', 'rgba(0, 0, 0, 0)'],
- blank: ['1.44px', 'uppercase'],
- });
- // 指到的头像抬起 4px、放大到 1.05,右边那位朝标题让开 10px。
- await page.locator('#stats [data-playlist-card="1"] [data-mix-avatars] button').first().hover();
- const lifted = await page.evaluate(() => {
- document.getAnimations().forEach((animation) => animation.finish());
- return [...document.querySelectorAll('#stats [data-playlist-card="1"] [data-mix-avatars] button')]
- .slice(0, 2).map((button) => getComputedStyle(button).transform);
- });
- assert.deepEqual(lifted, ['matrix(1.05, 0, 0, 1.05, 0, -4)', 'matrix(1, 0, 0, 1, 10, -1.8)']);
- // 点点点菜单外宽 172px,同旧卡片菜单。
- await page.locator('#stats [data-playlist-card="1"] [data-playlist-menu]').click();
- const panel = page.locator(':has(> [role="dialog"][aria-label="播放列表操作:列表1"])');
- await panel.waitFor({ timeout: 5_000 });
- assert.equal(await panel.evaluate((element) => getComputedStyle(element).width), '172px');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('播放列表页窄屏:页头改竖排,新建框字号 16px 免得 iOS 聚焦时放大', { timeout: 60_000 }, async () => {
- const opened = await openPlaylistsPage(browser, MOBILE);
- try {
- const narrow = await opened.page.evaluate(() => ({
- header: getComputedStyle(document.querySelector('#stats header')!).flexDirection,
- input: getComputedStyle(document.querySelector('#stats [data-playlist-create] input')!).fontSize,
- title: getComputedStyle(document.querySelector('#stats header h2')!).fontSize,
- }));
- assert.deepEqual(narrow, { header: 'column', input: '16px', title: '32px' });
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('分段底板支持鼠标反向、键盘即时切换与减少动态效果', { timeout: 60_000 }, async () => {
- const opened = await openIndexPage(browser, '/performers');
- const { page } = opened;
- try {
- await page.emulateMedia({ reducedMotion: 'no-preference' });
- const track = page.locator('[data-index-layout]');
- const choices = track.locator('label');
- const pane = track.locator('[data-moving-surface]');
- await pane.waitFor();
- const aligned = async () => {
- await page.waitForFunction(() => {
- const host = document.querySelector('[data-index-layout]')!;
- const pane = host.querySelector('[data-moving-surface]')!.getBoundingClientRect();
- const selected = host.querySelector('label[data-selected]')!.getBoundingClientRect();
- return Math.abs(pane.x - selected.x) < 1 && Math.abs(pane.width - selected.width) < 1;
- });
- };
- const assertInstant = async () => {
- const offset = await pane.evaluate((node) => {
- const selected = node.parentElement!.querySelector('label[data-selected]')!.getBoundingClientRect();
- const box = node.getBoundingClientRect();
- return { x: box.x - selected.x, width: box.width - selected.width };
- });
- assert.ok(Math.abs(offset.x) < 1 && Math.abs(offset.width) < 1,
- `即时切换的底板位置:${JSON.stringify(offset)}`);
- };
- await choices.nth(0).click();
- await aligned();
- const endpoints = await choices.evaluateAll((nodes) => nodes.slice(0, 2).map((node) => node.getBoundingClientRect().x));
- await pane.evaluate((node) => {
- const samples: number[] = [];
- const sample = () => {
- samples.push(node.getBoundingClientRect().x);
- if (samples.length < 24) requestAnimationFrame(sample);
- else (node as HTMLElement).dataset.motionSamples = JSON.stringify(samples);
- };
- requestAnimationFrame(sample);
- });
- await choices.nth(1).click();
- await page.waitForFunction(() => document.querySelector('[data-index-layout] [data-motion-samples]'));
- const samples = JSON.parse((await pane.getAttribute('data-motion-samples'))!) as number[];
- assert.ok(samples.some((x) => x > Math.min(...endpoints) + 1 && x < Math.max(...endpoints) - 1),
- `鼠标切换应经过两项之间的位置:${JSON.stringify(samples)}`);
- await choices.nth(0).click();
- await choices.nth(1).click();
- await choices.nth(0).click();
- await aligned();
- assert.equal(await pane.count(), 1);
- assert.equal(await pane.getAttribute('aria-hidden'), 'true');
- await track.getByRole('radio').nth(0).focus();
- await page.keyboard.press('ArrowRight');
- await assertInstant();
- assert.equal(await track.getByRole('radio').nth(1).isChecked(), true);
- assert.equal(await pane.evaluate((node) => node.getAnimations().length), 0);
- assert.match(await choices.nth(1).evaluate((node) => getComputedStyle(node).getPropertyValue('--tw-ring-shadow')), /2px/,
- '选中底板不能抹掉键盘焦点环');
- await page.emulateMedia({ reducedMotion: 'reduce' });
- await choices.nth(0).click();
- await assertInstant();
- assert.equal(await pane.evaluate((node) => node.getAnimations().length), 0);
- await page.setViewportSize({ width: 390, height: 844 });
- await aligned();
- assert.deepEqual(opened.problems, []);
- } finally { await opened.close(); }
- });
-
- it('短菜单共享悬停面,弹窗关闭释放焦点与遮罩', { timeout: 60_000 }, async () => {
- const opened = await openPlaylistsPage(browser);
- const { page } = opened;
- try {
- await page.emulateMedia({ reducedMotion: 'no-preference' });
- const trigger = page.locator('[data-playlist-card="1"] [data-playlist-menu]');
- await trigger.click();
- const menu = page.getByRole('dialog', { name: '播放列表操作:列表1' });
- await menu.getByRole('button', { name: '编辑名称' }).hover();
- const pane = menu.locator('[data-moving-surface]');
- await pane.waitFor();
- await menu.getByRole('button', { name: '删除播放列表' }).hover();
- await page.waitForFunction(() => {
- const host = document.querySelector('[data-surface-host="hover"]')!;
- const pane = host.querySelector('[data-moving-surface]')!.getBoundingClientRect();
- const button = [...host.querySelectorAll('button')].at(-1)!.getBoundingClientRect();
- return Math.abs(pane.y - button.y) < 1;
- });
- await page.keyboard.press('Tab');
- assert.equal(await pane.isVisible(), false);
- await menu.getByRole('button', { name: '编辑名称' }).click();
- const modal = page.locator('[data-modal-motion]');
- await modal.waitFor();
- await modal.getByRole('textbox', { name: '名称' }).waitFor();
- assert.equal(await modal.locator('[data-modal-surface]').evaluate((node) =>
- getComputedStyle(node).transitionProperty.includes('transform')), true);
- await modal.locator('form').getByRole('button', { name: '取消', exact: true }).click();
- await modal.waitFor({ state: 'detached' });
- await trigger.click();
- await menu.getByRole('button', { name: '编辑名称' }).focus();
- await page.keyboard.press('Enter');
- await modal.waitFor();
- assert.equal(await modal.getAttribute('data-motion-instant'), 'true');
- await page.waitForFunction(() => Boolean(document.activeElement?.closest('[data-modal-motion]')),
- null, { timeout: 5_000 });
- await page.keyboard.press('Escape');
- await modal.waitFor({ state: 'detached' });
- assert.equal(await page.evaluate(() => document.activeElement?.closest('[data-modal-motion]') !== null), false);
- assert.deepEqual(opened.problems, []);
- } finally { await opened.close(); }
- });
-
- it('批量选择条更新计数保持节点,清空后退出且不保留可操作控件', { timeout: 60_000 }, async () => {
- const opened = await openIndexPage(browser, '/tags');
- const { page } = opened;
- try {
- await page.emulateMedia({ reducedMotion: 'no-preference' });
- await page.locator('#selectMode').click();
- const tags = page.locator('#index [data-alpha-tag]');
- await tags.nth(0).click();
- const dock = page.locator('[data-selection-dock]');
- await dock.waitFor();
- await dock.evaluate((node) => node.setAttribute('data-test-identity', 'retained'));
- await tags.nth(1).click();
- assert.equal(await dock.getAttribute('data-test-identity'), 'retained');
- assert.match(await dock.textContent() ?? '', /已选 2 个标签/);
- await dock.getByRole('button', { name: '清空', exact: true }).click();
- await page.waitForFunction(() => {
- const dock = document.querySelector<HTMLElement>('[data-selection-dock]');
- return !dock || (dock.inert && dock.getAttribute('aria-hidden') === 'true');
- });
- await dock.waitFor({ state: 'detached' });
- await tags.nth(0).click();
- await dock.waitFor();
- await page.emulateMedia({ reducedMotion: 'reduce' });
- await dock.getByRole('button', { name: '清空', exact: true }).click();
- await dock.waitFor({ state: 'detached' });
- assert.deepEqual(opened.problems, []);
- } finally { await opened.close(); }
- });
-
- it('标签多选坞出现时页底让出 96px;在线词表的类型色走上游 tag_type 那一套', { timeout: 60_000 }, async () => {
- const opened = await openIndexPage(browser, '/tags');
- try {
- const page = opened.page;
- await page.locator('#selectMode').click({ timeout: 5_000 });
- await page.locator('#index [data-alpha-tag]').nth(0).click({ timeout: 5_000 });
- await page.locator('#index [data-alpha-tag]').nth(1).click({ timeout: 5_000 });
- const dock = page.locator('[data-selection-dock]');
- await dock.waitFor({ timeout: 5_000 });
- const padding = await page.evaluate(() =>
- getComputedStyle(document.querySelector('#index .peach-react')!).paddingBottom);
- assert.equal(padding, '96px', '选择坞盖住了最后一行标签');
- await page.locator('#index [role="tab"][data-tab="online"]').click({ timeout: 5_000 });
- const dot = page.locator('#index [data-alpha-tag][data-tag-cat="r34-artist"] [data-tag-dot]');
- await dot.waitFor({ timeout: 5_000 });
- assert.equal(await dot.evaluate((element) => getComputedStyle(element).backgroundColor), 'rgb(227, 108, 108)');
- assert.equal(await dock.count(), 0, '在线词表不给多选坞');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('标签云一枚里名字与计数只隔一个空格宽;筛选浮层的 Aa 字形摆进 16×16 的框', { timeout: 60_000 }, async () => {
- const opened = await openIndexPage(browser, '/tags?view=cloud');
- try {
- const page = opened.page;
- const spacing = await page.locator('#index [data-tag-chip]').first().evaluate((chip) => {
- // 名字那段文字按字符切开量:字的右缘到计数左缘,与末尾那个空格自己画出来的宽度相比。
- const name = chip.firstChild!;
- const end = name.textContent!.trimEnd().length;
- const box = (from: number, to: number) => {
- const part = document.createRange();
- part.setStart(name, from);
- part.setEnd(name, to);
- return part.getBoundingClientRect();
- };
- const count = chip.querySelector('[data-tag-n]')!.getBoundingClientRect();
- return { gap: count.left - box(0, end).right, space: box(end, name.textContent!.length).width,
- columnGap: getComputedStyle(chip).columnGap };
- });
- assert.equal(spacing.columnGap, 'normal', '名字与计数之间不另加 flex 间距');
- assert.ok(spacing.space > 2 && Math.abs(spacing.gap - spacing.space) < 0.5,
- `名字与计数隔了 ${spacing.gap}px,一个空格是 ${spacing.space}px`);
- const glyph = page.locator('#index svg:has(use[href="#i-text-aa"])');
- assert.deepEqual(await glyph.evaluate((element) => {
- const style = getComputedStyle(element);
- return [style.width, style.height];
- }), ['16px', '16px']);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('重复文件的汇总条是玻璃面,组卡 14px 圆角、组头 20px 内边距,每行上方一条 1px 分隔线', { timeout: 60_000 }, async () => {
- const opened = await openDuplicates(browser);
- try {
- const faces = await opened.page.evaluate(() => {
- const glass = getComputedStyle(document.querySelector('[data-filter-glass]')!);
- const group = document.querySelector('#stats section[aria-label="DUPE-002"]')!;
- const head = group.firstElementChild!;
- const card = getComputedStyle(group);
- const header = getComputedStyle(head);
- const code = getComputedStyle(head.querySelector('b')!);
- return {
- glass: { filter: glass.backdropFilter, padding: glass.padding, height: glass.height },
- card: { radius: card.borderRadius, overflow: card.overflow, face: card.backgroundColor },
- head: { padding: header.padding, face: header.backgroundColor, size: code.fontSize, weight: code.fontWeight },
- rows: [...group.querySelectorAll('.duplicate-row')].map((row) => {
- const computed = getComputedStyle(row);
- return [computed.borderTopWidth, computed.padding];
- }),
- };
- });
- assert.match(faces.glass.filter, /blur\(/, '汇总条没有背景模糊,不是玻璃面');
- assert.deepEqual([faces.glass.padding, faces.glass.height], ['10px 16px', '50px']);
- assert.deepEqual([faces.card.radius, faces.card.overflow], ['14px', 'hidden'], '组卡圆角或裁切不对');
- assert.notEqual(faces.head.face, faces.card.face, '组头和组卡同色,番号那一行分不出来');
- assert.deepEqual([faces.head.padding, faces.head.size, faces.head.weight], ['20px', '20px', '500']);
- assert.deepEqual(faces.rows, [['1px', '16px 20px'], ['1px', '16px 20px']],
- '组内每一行上方不是 1px 分隔线,或内边距不是 16/20');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('整页空态沉一档底色、20px 圆角、至少 320px 高,图标装进 54px 描边方框;卡里的空态不带方框', { timeout: 60_000 }, async () => {
- // 演示库在一轮里凑得出重复组,桩成空的才一定落到整页空态上。
- const opened = await visit(browser, '/duplicates', DESKTOP);
- try {
- const page = opened.page;
- await page.route('**/api/duplicates?**', (route) => route.fulfill({
- status: 200, contentType: 'application/json',
- body: JSON.stringify({ total: 0, files: 0, reclaimable: 0, groups: [] }),
- }));
- await page.reload({ waitUntil: 'load' });
- await page.locator('#stats [data-empty-state]').waitFor({ timeout: 15_000 });
- await settle(page);
- const face = await page.evaluate(() => {
- const root = document.querySelector('#stats [data-empty-state]')!;
- const glyph = root.querySelector('svg')!;
- const box = glyph.parentElement!;
- const shell = getComputedStyle(root);
- const frame = getComputedStyle(box);
- const title = getComputedStyle(root.querySelector('h3')!);
- const copy = getComputedStyle(root.querySelector('p')!);
- return {
- shell: { face: shell.backgroundColor, line: shell.borderTopColor, width: shell.borderTopWidth,
- radius: shell.borderTopLeftRadius, minHeight: shell.minHeight },
- boxed: box !== root,
- frame: { width: frame.width, height: frame.height, radius: frame.borderTopLeftRadius,
- line: frame.borderTopWidth, glyph: getComputedStyle(glyph).width },
- title: [title.fontSize, title.fontWeight], copy: [copy.maxWidth, copy.lineHeight],
- };
- });
- assert.equal(face.shell.face, await tokenColor(page, '.peach-react', '--color-background-secondary-default'),
- '整页空态没有沉一档底色');
- assert.equal(face.shell.line, await tokenColor(page, '.peach-react', '--color-separator-border'), '外框不是分隔线色');
- assert.deepEqual([face.shell.width, face.shell.radius, face.shell.minHeight], ['1px', '20px', '320px']);
- assert.ok(face.boxed, '整页空态的图标没有装进方框');
- assert.deepEqual(face.frame, { width: '54px', height: '54px', radius: '20px', line: '1px', glyph: '32px' });
- assert.deepEqual(face.title, ['14px', '600']);
- assert.deepEqual(face.copy, ['340px', '20.15px']);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- // 卡里那一档(活动页没有任务记录)图标直接挂在空态上,外面没有方框。
- const activity = await visit(browser, '/activity', DESKTOP);
- try {
- await activity.page.route('**/api/tasks', (route) => route.fulfill({
- status: 200, contentType: 'application/json',
- body: JSON.stringify({ available: true, running: [], skipped: [], finished: [] }),
- }));
- await activity.page.reload({ waitUntil: 'load' });
- const empty = activity.page.locator('[data-empty-state]');
- await empty.waitFor({ timeout: 15_000 });
- await settle(activity.page);
- assert.equal(await empty.evaluate((root) => root.querySelector('svg')!.parentElement === root), true,
- '卡里的空态也套了图标方框');
- assert.deepEqual(activity.problems, []);
- } finally {
- await activity.close();
- }
- });
-
- it('骨架里的占位和按键悬停不给任何反馈,也点不中', { timeout: 120_000 }, async () => {
- const name = '七沢みあ';
- const pages: { path: string; ready: string; targets: string[]; prepare?: (page: Page) => Promise<void> }[] = [
- { path: `/performers/${encodeURIComponent(name)}`, ready: '[data-skeleton="entity/performer"] .entityfoot .avskeleton',
- targets: ['[data-skeleton] .entityfoot .avskeleton'],
- prepare: (page) => page.route(/\/api\/entity\/shapes/, (route) => route.fulfill({ json: {
- ok: true, entities: [{ id: 90_001, kind: 'performer', names: [name], parts: ['costars'] }] } })) },
- { path: '/data-cleanup', ready: '[data-skeleton="cleanup"] [data-skeleton-action]',
- targets: ['[data-skeleton] .board-plain-stat', '[data-skeleton] a[href="/scraping"]',
- '[data-skeleton] [data-skeleton-action]', '[data-skeleton] .cleanupfieldset [data-skeleton-action]'] },
- { path: '/review', ready: '[data-skeleton="review"] .reviewtabs button',
- targets: ['[data-skeleton] .reviewtabs button', '[data-skeleton] .skeletoncard'] },
- { path: '/follow', ready: '.followauthors .avskeleton',
- targets: ['.followauthors .avskeleton', '.followworks .brandskeleton', '[data-skeleton^="cards/"] > div > *'] },
- { path: '/follow-manage', ready: '[data-skeleton="board/follow-manage"] .follow-skeleton-toolbar',
- targets: ['[data-skeleton] .follow-skeleton-toolbar > button:nth-of-type(2)',
- '[data-skeleton] .follow-skeleton-toolbar > button:nth-of-type(1)'] },
- ];
- for (const { path, ready, targets, prepare } of pages) {
- const opened = await visit(browser, '/', DESKTOP);
- try {
- const page = opened.page;
- // 后登记的路由先拿到请求:桩要排在挂住 /api/ 那条之后,不然它也被挂住。
- await holdApi(page);
- await prepare?.(page);
- await page.goto(new URL(path, page.url()).href, { waitUntil: 'load' });
- await page.locator(ready).first().waitFor({ state: 'visible', timeout: 15_000 });
- for (const target of targets) {
- const node = page.locator(target).first();
- await node.waitFor({ state: 'visible', timeout: 5_000 });
- // 落在首屏以下的目标(数据管理的整理卡)先滚进视口:`elementFromPoint` 只认视口里的点。
- await node.scrollIntoViewIfNeeded();
- const box = (await node.boundingBox())!;
- const look = () => node.evaluate((element) => [element, ...element.querySelectorAll('*')].slice(0, 6).map((part) => {
- const style = getComputedStyle(part);
- return [style.borderColor, style.boxShadow, style.backgroundColor, style.backgroundImage,
- style.outlineStyle, style.color, style.scale, style.transform].join(' | ');
- }));
- await page.mouse.move(0, 0);
- const rest = await look();
- const [x, y] = [box.x + box.width / 2, box.y + box.height / 2];
- await page.mouse.move(x, y);
- assert.deepEqual(await look(), rest, `${path} ${target} 悬停时变了样子`);
- // 分层骨架那一排(`data-skeleton-tier`)是最终那条轨道本身,点中它等于点在页面底上;
- // 要问的是指针有没有落在某一枚占位或整块骨架里。
- const hit = await page.evaluate(([px, py]) => {
- const at = document.elementFromPoint(px!, py!);
- return { cursor: at ? getComputedStyle(at).cursor : '',
- inside: !!at?.closest('[data-skeleton],.avskeleton,.brandskeleton,.tagskeleton,.skeletoncard'),
- disabled: !!at?.closest('button:disabled') };
- }, [x, y]);
- assert.ok(['auto', 'default', 'not-allowed'].includes(hit.cursor), `${path} ${target} 悬停换了光标:${hit.cursor}`);
- assert.ok(!hit.inside || hit.disabled, `${path} ${target} 在骨架里还能点中`);
- }
- } finally {
- await opened.close();
- }
- }
- });
-
- it('勾中的来源在卡片和表格里都铺 BoardUI 数据表那一档选中底色', { timeout: 60_000 }, async () => {
- const opened = await openFollowManage(browser);
- try {
- const page = opened.page;
- const selected = await tokenColor(page, '.peach-react', '--color-background-secondary-default');
- await page.getByRole('checkbox', { name: '选择 kou · Kemono' }).check({ force: true, timeout: 5_000 });
- const cardRow = page.locator('[data-source-divider] > [data-selected]');
- assert.equal(await cardRow.count(), 1);
- assert.equal(await cardRow.evaluate((row) => getComputedStyle(row).backgroundColor), selected,
- '卡片里的选中行没有铺选中底色');
-
- await page.locator('button[aria-label="表格视图"]').click({ timeout: 5_000 });
- const tableRow = page.locator('[data-follow-selected]');
- await tableRow.waitFor({ timeout: 5_000 });
- assert.equal(await tableRow.evaluate((row) => getComputedStyle(row).backgroundColor), selected,
- '表格里的选中行和卡片里的不是同一档');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('别名的组数是次要字色的读数,不借提醒或主按钮的颜色', { timeout: 60_000 }, async () => {
- const opened = await openFollowManage(browser);
- try {
- await followTab(opened, '添加关注');
- const count = opened.page.getByText('1 组', { exact: true });
- const look = await count.evaluate((node) => ({
- ink: getComputedStyle(node).color, face: getComputedStyle(node).backgroundColor,
- }));
- assert.equal(look.ink, await tokenColor(opened.page, '.peach-react', '--color-text-secondary'));
- assert.equal(look.face, 'rgba(0, 0, 0, 0)', '组数画成了带底色的徽章');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- /* 建议由这里给,两组共 30 条,两个视口下字段下方都装不下。桌面取 1280×1000,
- 字段下缘在视口中段偏下,正是只能往下开、又放不全的那种处境。 */
- for (const viewport of [{ ...DESKTOP, height: 1000 }, MOBILE]) {
- it(`添加关注的建议下拉压在字段下方剩下的空间里,装不下在菜单内滚,选中行滚进可见区(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openFollowManage(browser, viewport);
- try {
- const { page } = opened;
- await page.route(/\/api\/follow\/suggest\?/, (route) => route.fulfill({ json: {
- q: 'bulging',
- groups: [['归档站', 18], ['站方分类', 12]].map(([label, count]) => ({
- kind: String(label), label,
- items: Array.from({ length: Number(count) }, (_, at) => ({
- value: `bulging ${label} ${at + 1}`, matched: 'Kemono', n: 120 - at,
- })),
- })),
- } }));
- await followTab(opened, '添加关注');
- const before = await page.evaluate(() => document.documentElement.scrollHeight);
- const input = page.getByRole('textbox', { name: '来源链接、名字或 id' });
- await input.click({ timeout: 5_000 });
- await input.fill('bulging');
- const menu = page.locator('[aria-label="来源建议"]');
- await menu.locator('button').nth(29).waitFor({ state: 'attached', timeout: 10_000 });
- const measure = () => menu.evaluate((element) => {
- for (const animation of element.getAnimations({ subtree: true })) animation.finish();
- const box = element.getBoundingClientRect();
- const field = element.ownerDocument.querySelector('input[aria-label="来源链接、名字或 id"]')!
- .getBoundingClientRect();
- const row = element.querySelector('[aria-current="true"]')?.getBoundingClientRect();
- return {
- top: box.top, bottom: box.bottom, fieldBottom: field.bottom, viewport: innerHeight,
- overflowing: element.scrollHeight > element.clientHeight,
- overscroll: getComputedStyle(element).overscrollBehaviorY,
- page: document.documentElement.scrollHeight, pageWidth: document.documentElement.scrollWidth,
- width: innerWidth, y: scrollY,
- row: row ? { top: row.top, bottom: row.bottom } : null,
- };
- });
- const open = await measure();
- assert.ok(open.bottom <= open.viewport + .5, `下拉底边 ${open.bottom} 越出视口 ${open.viewport}`);
- assert.ok(open.top >= open.fieldBottom, `下拉上沿 ${open.top} 盖住了字段(下缘 ${open.fieldBottom})`);
- assert.ok(open.overflowing, '30 条建议没有让下拉溢出,这条用例没练到内滚');
- assert.equal(open.overscroll, 'contain', '下拉滚到头会带着页面一起滚');
- assert.ok(open.page <= before, `下拉把页面从 ${before} 撑到 ${open.page}`);
- assert.ok(open.pageWidth <= open.width, `页面被撑出横向滚动:${open.pageWidth} > ${open.width}`);
-
- // 走到最后一条:它在初始可见区外面,得被滚进来,页面本身不动。
- for (let step = 0; step < 30; step++) await input.press('ArrowDown');
- const last = await measure();
- assert.ok(last.row, '上下键没有选中任何一行');
- assert.ok(last.row.top >= last.top - .5 && last.row.bottom <= last.bottom + .5,
- `选中行 ${last.row.top}–${last.row.bottom} 不在下拉可见区 ${last.top}–${last.bottom} 内`);
- assert.equal(last.y, open.y, '选中行滚进可见区时把页面也滚了');
- await input.press('ArrowDown');
- const first = await measure();
- assert.ok(first.row && first.row.top >= first.top - .5, '绕回第一条后它没有滚回可见区');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
- }
-
- it('凭据的四种处境四副底色:待办和完成一眼分得开', { timeout: 60_000 }, async () => {
- const opened = await openFollowManage(browser);
- try {
- await followTab(opened, '来源和凭证');
- const faces: Record<string, string> = {};
- for (const state of ['需要', '已配置', '接不进来', '不需要']) {
- faces[state] = await opened.page.getByText(state, { exact: true }).first()
- .evaluate((chip) => getComputedStyle(chip).backgroundColor);
- }
- assert.equal(new Set(Object.values(faces)).size, 4, `有两种处境同色:${JSON.stringify(faces)}`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('浅色下看片那两枚标识悬停时有底,资料卡上带订阅新作开关', { timeout: 60_000 }, async () => {
- // 演示库里没有人物实体:资料由这里给,入口与开关字段照服务端拼好下发的形状写。
- const name = '七沢みあ';
- const opened = await visit(browser, '/', DESKTOP);
- try {
- await opened.page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
- id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],
- user_aliases: [], asset_count: 0, tags: [], related_performers: [], links: [],
- metadata: {}, has_image: false, has_avatar: false, avatar_focus: null,
- representative_asset_id: null,
- entry_links: [{ site: 'javdb', label: 'JavDB', ordinal: '', slot: 'mark',
- mark: 'mark-javdb', url: 'https://javdb.com/actors/NPD3' }],
- feed: { following: false },
- } }));
- await opened.page.goto(new URL(`/performers/${encodeURIComponent(name)}`,
- opened.page.url()).href, { waitUntil: 'load' });
- const mark = opened.page.locator('[data-entry-marks] a[data-entry-mark]').first();
- await mark.waitFor({ timeout: 15_000 });
- await settle(opened.page);
- // 浅色下 `--hover` 与资料卡的 `--ground` 同是 #f5f5f5,垫上去等于没垫。
- await opened.page.evaluate(() => {
- document.documentElement.dataset.theme = 'light';
- document.documentElement.classList.remove('dark');
- });
- await mark.hover();
- const faces = await mark.evaluate((element) => ({
- mark: getComputedStyle(element).backgroundColor,
- card: getComputedStyle(element.closest('[data-entity-card]')!).backgroundColor,
- }));
- assert.notEqual(faces.mark, 'rgba(0, 0, 0, 0)', '悬停没有垫底');
- assert.notEqual(faces.mark, faces.card, '悬停底色和资料卡同色,看不出来');
- const toggle = opened.page.getByRole('switch', { name: '订阅新作' });
- assert.equal(await toggle.count(), 1, '资料卡上没有订阅新作开关');
- assert.equal(await toggle.isChecked(), false);
- const feed = opened.page.locator('[data-entry-feed]');
- await opened.page.emulateMedia({ reducedMotion: 'no-preference' });
- assert.equal(await feed.evaluate((element) => getComputedStyle(element).animationName),
- 'entryfeed-breathe', '没订的那枚图标不呼吸,一枚墨色小图标没人注意到');
- const tip = opened.page.locator('#entityFeedTip');
- assert.equal(await tip.isVisible(), false);
- await feed.hover();
- assert.equal(await tip.isVisible(), true, '悬停没有说明这枚图标是干嘛的');
- assert.equal(await tip.innerText(), '订阅新作');
- const placed = await tip.evaluate((element) => {
- const box = element.getBoundingClientRect();
- return box.left >= 0 && box.right <= innerWidth && box.bottom <= innerHeight;
- });
- assert.ok(placed, '说明浮层越出了视口');
- await toggle.focus();
- await opened.page.keyboard.press('Escape');
- assert.equal(await tip.isVisible(), false, 'Escape 收不起说明浮层');
- } finally {
- await opened.close();
- }
- });
-
- for (const viewport of [DESKTOP, MOBILE]) {
- it(`订阅新作的说明浮层整块露在外面:不被资料卡裁掉,也不被同台艺人那条盖住(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openPerformer(browser, viewport);
- try {
- const page = opened.page;
- const feed = page.locator('[data-entry-feed]');
- await feed.hover();
- const tip = page.locator('#entityFeedTip');
- await tip.waitFor({ state: 'visible', timeout: 5_000 });
- const placement = await tip.evaluate((element) => {
- const box = element.getBoundingClientRect();
- const clippedBy: string[] = [];
- // 顶层里的元素不受祖先 overflow 裁切,只有写在文档流里的浮层才要逐层量。
- const topLayer = element.matches(':popover-open');
- for (let node = topLayer ? null : element.parentElement; node; node = node.parentElement) {
- const style = getComputedStyle(node);
- if (style.overflowX === 'visible' && style.overflowY === 'visible') continue;
- const clip = node.getBoundingClientRect();
- if (box.left < clip.left - 0.5 || box.right > clip.right + 0.5
- || box.top < clip.top - 0.5 || box.bottom > clip.bottom + 0.5) clippedBy.push(node.className || node.tagName);
- }
- // 浮层本身不接指针;临时放开再问四条边和正中最上面是谁,盖在它上面的东西就现形了。
- // 取样点离角 16px:圆角外那一小块本来就不属于它。
- element.style.pointerEvents = 'auto';
- const [midX, midY] = [box.left + box.width / 2, box.top + box.height / 2];
- const covered = [[box.left + 16, box.top + 2], [box.right - 16, box.top + 2], [box.left + 16, box.bottom - 2],
- [box.right - 16, box.bottom - 2], [box.left + 2, midY], [box.right - 2, midY], [midX, midY]]
- .map(([x, y]) => document.elementFromPoint(x!, y!))
- .filter((hit) => !hit || !element.contains(hit)).map((hit) => hit?.className || 'null');
- element.style.pointerEvents = '';
- return { inView: box.left >= 0 && box.right <= innerWidth && box.top >= 0 && box.bottom <= innerHeight,
- clippedBy, covered, below: box.top >= document.querySelector('[data-entry-feed]')!.getBoundingClientRect().bottom };
- });
- assert.ok(placement.inView, '说明浮层越出了视口');
- assert.deepEqual(placement.clippedBy, [], '说明浮层被外层容器裁掉了一截');
- assert.deepEqual(placement.covered, [], '说明浮层被别的东西盖住了');
- assert.ok(placement.below, '视口下方放得下时说明浮层应该在图标下面');
- const page_ = await layout(page);
- assert.ok(page_.scrollWidth <= page_.viewportWidth, '说明浮层把页面撑出了横向滚动');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
- }
-
- // 1000px 窗口侧栏展开时内容区只剩七百来像素:三栏的判据量的是内容区,这一档要排成两层,
- // 身份那一栏不能被资料表挤到只剩一个字宽。
- for (const [viewport, stacked] of [[DESKTOP, false], [{ name: 'wide', width: 1440, height: 900, mobile: false }, false],
- [{ name: 'mid', width: 1000, height: 900, mobile: false }, true], [MOBILE, true]] as const) {
- it(`女优页头:宽屏资料表在身份信息右侧隔一道竖线,窄屏排到下面隔一道横线,整张卡不横向溢出(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openProfiledPerformer(browser, viewport);
- try {
- const geometry = await heroGeometry(opened.page);
- assert.deepEqual(geometry.labels, ['生日', '身材', '出道', '生涯', '标签'], '资料表不是那五项');
- assert.ok(geometry.facts && geometry.identity && geometry.hero, '页头缺了资料表');
- assert.ok(geometry.identity.right - geometry.identity.left >= 240, '身份那一栏被挤窄了');
- if (stacked) {
- assert.ok(geometry.facts.top >= geometry.identity.bottom - 0.5, '窄屏下资料表没有排到身份信息下面');
- assert.deepEqual(geometry.rule, { left: '0px', top: '1px' }, '窄屏下资料表该用横线和身份信息隔开');
- } else {
- assert.ok(geometry.facts.left >= geometry.identity.right - 0.5, '宽屏下资料表没有排在身份信息右侧');
- assert.deepEqual(geometry.rule, { left: '1px', top: '0px' }, '宽屏下资料表该用竖线和身份信息隔开');
- }
- assert.ok(geometry.facts.right <= geometry.hero.right + 0.5, '资料表越出了资料卡');
- assert.equal(geometry.heroScrolls, false, '资料卡里有东西被横向裁掉');
- const debut = await opened.page.locator('[data-entity-facts] dd[title]').evaluate((dd) => ({
- title: dd.getAttribute('title'), wrap: getComputedStyle(dd).whiteSpace,
- cut: getComputedStyle(dd).textOverflow, clipped: dd.scrollWidth > dd.clientWidth,
- lines: Math.round(dd.getBoundingClientRect().height / parseFloat(getComputedStyle(dd).lineHeight)),
- }));
- assert.equal(debut.title, PROFILED.profile.debut_title, '出道那一格的 title 没给全名');
- assert.deepEqual([debut.wrap, debut.cut, debut.lines], ['nowrap', 'ellipsis', 1], '出道片名没有单行截断');
- const page_ = await layout(opened.page);
- assert.ok(page_.scrollWidth <= page_.viewportWidth, `页头把页面撑出了横向滚动:${page_.offenders.join(',')}`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
- }
-
- for (const viewport of [DESKTOP, MOBILE]) {
- it(`公司资料页显示公司与品牌事实且长地址可折行(${viewport.name})`, { timeout: 60_000 }, async () => {
- const fact = (value: string) => ({ value, source_url: 'https://company.example/about' });
- const opened = await openProfiledPerformer(browser, viewport, 'light', {
- kind: 'studio', canonical_name: 'Company', profile: undefined, agency: undefined,
- company_profile: { legal_name: fact('Example Company, LLC'), founded: fact('2002-05'),
- launched: fact('2016'), operator: fact('General Media Systems, LLC'),
- location: fact('LongOfficeAddressWithoutSpaces'.repeat(5)) },
- });
- try {
- await opened.page.goto(new URL('/studios/Company', opened.page.url()).href, { waitUntil: 'load' });
- await opened.page.locator('[data-entity-facts]').waitFor();
- await settle(opened.page);
- const geometry = await heroGeometry(opened.page);
- assert.deepEqual(geometry.labels, ['公司名称', '公司成立', '品牌启动', '所在地', '运营公司']);
- assert.equal(geometry.heroScrolls, false);
- assert.ok(geometry.hero && geometry.facts && geometry.facts.right <= geometry.hero.right + 1);
- assert.equal(await opened.page.locator('[data-entity-facts] [title]').count(), 0);
- const page_ = await layout(opened.page);
- assert.ok(page_.scrollWidth <= page_.viewportWidth);
- assert.deepEqual(opened.problems, []);
- } finally { await opened.close(); }
- });
- }
-
- it('女优页头名字下面一行:视频数、事务所与读音加前三个别名,外链一律 36px 纯图标方块', { timeout: 60_000 }, async () => {
- const opened = await openProfiledPerformer(browser, DESKTOP);
- try {
- const page = opened.page;
- const line = await page.locator('[data-entity-alias]').evaluate((alias) => ({
- glyphs: [...alias.querySelectorAll(':scope > [data-meta-item] > svg use')].map((use) => use.getAttribute('href')),
- names: [...alias.querySelectorAll('[data-alias-names] > span')].map((span) => span.textContent!.trim()),
- more: alias.querySelector('[data-hero-more="alias"]')?.textContent?.trim() ?? '',
- agency: alias.querySelector('a[data-agency]')?.textContent?.trim() ?? '',
- }));
- assert.deepEqual(line.glyphs, ['#i-film', '#i-briefcase', '#i-id-card'], '名字那一行的三项不是视频、事务所、别名');
- assert.deepEqual(line.names, ['しのだゆう', '篠崎ゆう子', '高木早希', '橋本真紀'], '读音没有排在别名最前,或别名不是前三个');
- assert.equal(line.more, '+4', '「+N」数的不是剩下那几个别名');
- assert.equal(line.agency, 'New Actor eXperience');
- const links = await page.locator('[data-entity-links] a').evaluateAll((anchors) => anchors.map((a) => {
- const box = a.getBoundingClientRect();
- return { size: `${Math.round(box.width)}x${Math.round(box.height)}`, kind: a.getAttribute('data-link'), title: a.getAttribute('title'),
- name: a.getAttribute('aria-label') ?? '', visibleText: a.querySelector('[data-link-label]') !== null };
- }));
- assert.equal(links.length, 3);
- for (const link of links) {
- assert.deepEqual([link.size, link.kind, link.visibleText], ['36x36', 'icon', false], `${link.title} 不是纯图标方块`);
- assert.equal(link.name, link.title, `${link.title} 给读屏的名字和悬停提示不一致`);
- }
- assert.deepEqual(links.map((link) => link.title), ['みんなのAV', 'New Actor eXperience 官方资料', 'X @shinoda_yu']);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- for (const viewport of [DESKTOP, MOBILE]) {
- it(`别名的「+N」浮层进顶层按名义分组:悬停、聚焦都出,不被资料卡裁掉,Escape 收起(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openProfiledPerformer(browser, viewport);
- try {
- const page = opened.page;
- const more = page.locator('[data-hero-more="alias"]');
- const pop = page.locator('#entityAliasPop');
- assert.equal(await pop.isVisible(), false);
- await more.hover();
- await pop.waitFor({ state: 'visible', timeout: 5_000 });
- assert.equal(await more.getAttribute('aria-expanded'), 'true');
- const shown = await pop.evaluate((element) => {
- const box = element.getBoundingClientRect();
- return {
- topLayer: element.matches(':popover-open'),
- inView: box.left >= 0 && box.right <= innerWidth && box.top >= 0 && box.bottom <= innerHeight,
- title: element.querySelector('[data-hero-pop-head]')?.textContent?.trim(),
- groups: [...element.querySelectorAll('dt')].map((dt) => dt.textContent!.trim()),
- face: getComputedStyle(element).backgroundColor,
- shadow: getComputedStyle(element).boxShadow,
- };
- });
- assert.equal(shown.shadow, await popmenuShadow(page), '别名浮层的落影和 .popmenu 不是同一副');
- assert.equal(shown.topLayer, true, '别名浮层没进顶层,会被资料卡的 overflow:hidden 裁掉');
- assert.ok(shown.inView, '别名浮层越出了视口');
- assert.equal(shown.title, '7 个别名');
- assert.deepEqual(shown.groups, ['旧名义', '舞ワイフ', 'ラグジュTV', '其它']);
- assert.notEqual(shown.face, 'rgba(0, 0, 0, 0)', '别名浮层没有底色');
- // 指针从按钮挪到浮层上读名字,浮层不能在半路收起。
- const box = (await pop.boundingBox())!;
- await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 4 });
- await page.waitForTimeout(300);
- assert.equal(await pop.isVisible(), true, '指针移到浮层上它就收起了');
- await page.mouse.move(1, 1);
- await pop.waitFor({ state: 'hidden', timeout: 5_000 });
- await more.focus();
- await page.keyboard.press('Tab');
- await page.keyboard.press('Shift+Tab');
- await pop.waitFor({ state: 'visible', timeout: 5_000 });
- await page.keyboard.press('Escape');
- assert.equal(await pop.isVisible(), false, 'Escape 收不起别名浮层');
- const page_ = await layout(page);
- assert.ok(page_.scrollWidth <= page_.viewportWidth, '别名浮层把页面撑出了横向滚动');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
- }
-
- // 名字右边那枚按钮往左开的话,260px 的菜单越过名字压在头像上(用户报过)。
- for (const viewport of [DESKTOP, MOBILE]) {
- it(`名字与别名菜单从按钮左缘往右开,不盖住页头头像(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openProfiledPerformer(browser, viewport);
- try {
- const page = opened.page;
- await page.locator('[data-namepick-toggle]').click();
- await page.locator('[data-namepick-menu]').waitFor({ state: 'visible', timeout: 5_000 });
- const box = await page.evaluate(() => {
- const rect = (selector: string) => {
- const b = document.querySelector(selector)!.getBoundingClientRect();
- return { left: b.left, right: b.right, top: b.top, bottom: b.bottom };
- };
- return { menu: rect('[data-namepick-menu]'), portrait: rect('[data-entity-portrait]'), toggle: rect('[data-namepick-toggle]') };
- });
- const overlaps = box.menu.left < box.portrait.right && box.menu.right > box.portrait.left
- && box.menu.top < box.portrait.bottom && box.menu.bottom > box.portrait.top;
- assert.equal(overlaps, false, `名字菜单盖住了头像:${JSON.stringify(box)}`);
- assert.ok(box.menu.left >= 0 && box.menu.right <= viewport.width, '名字菜单越出了视口');
- if (!viewport.mobile) assert.ok(Math.abs(box.menu.left - box.toggle.left) < 1, '宽屏下菜单没有对齐按钮左缘');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
- }
-
- for (const [viewport, split] of [[WIDE, true], [MOBILE, false]] as const) {
- it(`搜索下拉按种类分页签;宽屏分两栏、人名带头像与近作、视频排成封面格,窄屏一栏(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', viewport);
- try {
- const page = opened.page;
- const kinds = await stubSuggest(page);
- await expectBody(page, '/', [page.locator('#grid [data-media-card][data-id]').first()]);
- await settle(page);
- if (viewport.mobile) await page.locator('#searchBtn').click();
- await page.locator('#q').fill(SUGGEST.q);
- const menu = page.locator('#searchMenu');
- await menu.locator('[data-search-option="person"]').first().waitFor({ state: 'visible', timeout: 5_000 });
- const shown = await page.evaluate(() => {
- const menuBox = document.querySelector('#searchMenu')!.getBoundingClientRect();
- const results = document.querySelector<HTMLElement>('#searchMenu [data-search-results]')!;
- const columns = [...results.querySelectorAll(':scope > [data-search-col]')];
- const person = document.querySelector('#searchMenu [data-search-option="person"]')!;
- /* 命中的别名与作品数是这一行的注脚:字号小一档、字色退一档,作品数靠右。 */
- const footnote = (selector: string) => {
- const note = document.querySelector<HTMLElement>(`#searchMenu ${selector}`)!;
- const row = note.closest('[data-search-option]')!;
- const name = note.previousElementSibling!;
- const [noteStyle, nameStyle] = [getComputedStyle(note), getComputedStyle(name)];
- return {
- smaller: parseFloat(noteStyle.fontSize) < parseFloat(nameStyle.fontSize),
- quieter: noteStyle.color !== nameStyle.color,
- trailing: Math.round(row.getBoundingClientRect().right - note.getBoundingClientRect().right),
- };
- };
- return {
- matched: footnote('[data-search-matched]'),
- count: footnote('[data-search-n]'),
- radius: getComputedStyle(person).borderRadius === getComputedStyle(document.documentElement).getPropertyValue('--control-radius').trim(),
- tabs: [...document.querySelectorAll('#searchMenu [role="tab"]')].map((tab) => tab.textContent!.trim()),
- tracks: getComputedStyle(results).gridTemplateColumns.split(' ').filter((track) => track !== 'none').length,
- divider: getComputedStyle(results, '::before').content,
- dividerHeight: parseFloat(getComputedStyle(results, '::before').height),
- resultsHeight: results.getBoundingClientRect().height,
- right: columns.at(-1)!.querySelector('[data-search-group]')?.getAttribute('data-kind'),
- videoGrid: getComputedStyle(document.querySelector('#searchMenu [data-search-group][data-kind="asset"] [data-search-items]')!).display,
- peeks: getComputedStyle(person.querySelector('[data-search-peeks]')!).display,
- peekCount: person.querySelectorAll('[data-open-work]').length,
- sub: person.querySelector('[data-search-sub]')!.textContent,
- face: person.querySelector('[data-search-face] img')?.getAttribute('src'),
- inView: menuBox.left >= 0 && menuBox.right <= innerWidth,
- edges: [Math.round(menuBox.left), Math.round(innerWidth - menuBox.right)],
- };
- });
- assert.deepEqual(shown.tabs, ['全部', '女优2', '厂牌1', '视频12'], '页签不是「全部」加各类命中数');
- assert.equal(shown.tracks, split ? 2 : 0, split ? '宽屏下拉没有分两栏' : '窄屏下拉不该分栏');
- assert.equal(shown.divider, split ? '""' : 'none', split ? '宽屏两栏之间没有分隔线' : '窄屏一栏不该有分隔线');
- if (split) {
- assert.ok(Math.abs(shown.dividerHeight - shown.resultsHeight) <= 1,
- `分隔线高 ${shown.dividerHeight}px,两栏高 ${shown.resultsHeight}px`);
- }
- assert.equal(shown.right, 'asset', '视频不在最后一栏');
- assert.equal(shown.videoGrid, split ? 'grid' : 'block', split ? '宽屏视频没排成封面格' : '窄屏视频该一行一部');
- assert.equal(shown.peeks, split ? 'flex' : 'none', split ? '宽屏人名一行没摆近作' : '窄屏人名一行不摆近作');
- assert.equal(shown.peekCount, 4);
- assert.equal(shown.sub, '128 个视频 · Capsule Agency');
- assert.equal(shown.face, '/entity-image?kind=performer&id=90301&thumb=1');
- for (const [name, note] of [['别名', shown.matched], ['作品数', shown.count]] as const) {
- assert.ok(note.smaller && note.quieter, `${name}没有退成注脚:${JSON.stringify(note)}`);
- }
- assert.equal(shown.count.trailing, 10, '作品数没有靠右贴着行的内边距');
- assert.ok(shown.radius, '补全行的圆角不是 --control-radius');
- assert.ok(shown.inView, '下拉栏越出了视口');
- // 窄屏下拉栏盖过返回键那一列,和顶栏两侧一样各留 8,不缩进到搜索框底下。
- if (viewport.mobile) assert.deepEqual(shown.edges, [8, 8], '窄屏下拉栏两侧留白不是 8');
- const page_ = await layout(page);
- assert.ok(page_.scrollWidth <= page_.viewportWidth, `下拉把页面撑出了横向滚动:${page_.offenders.join(',')}`);
-
- await menu.getByRole('tab', { name: /^女优/ }).click();
- await page.waitForFunction(() => document.querySelectorAll('#searchMenu [data-search-group][data-kind]').length === 1);
- assert.equal(await menu.isVisible(), true, '点页签把下拉栏收掉了');
- assert.ok(kinds.includes('performer'), '选了一类没有按这一类去拉满');
- assert.equal(await menu.getByRole('tab', { name: /^女优/ }).getAttribute('aria-selected'), 'true');
-
- // 人名那一行点开的是资料页,不是按名字再搜一遍。
- await page.keyboard.press('ArrowDown');
- await page.keyboard.press('Enter');
- await page.waitForURL(/\/performers\//, { timeout: 5_000 });
- assert.equal(decodeURIComponent(new URL(page.url()).pathname), '/performers/涼森れむ');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
- }
-
- it('只看视频时封面格按列均分铺满整栏,每格有宽度上限', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', WIDE);
- try {
- const page = opened.page;
- await stubSuggest(page);
- await expectBody(page, '/', [page.locator('article[data-media-card][data-id]').first()]);
- await settle(page);
- await page.locator('#q').fill(SUGGEST.q);
- const menu = page.locator('#searchMenu');
- await menu.locator('[data-search-option="person"]').first().waitFor({ state: 'visible', timeout: 5_000 });
- await menu.getByRole('tab', { name: /^视频/ }).click();
- await page.waitForFunction(() => document.querySelectorAll('#searchMenu [data-search-group][data-kind]').length === 1);
- const grid = await page.evaluate(() => {
- const items = document.querySelector('#searchMenu [data-search-group][data-kind="asset"] [data-search-items]')!;
- const box = items.getBoundingClientRect();
- const cards = [...items.querySelectorAll('[data-search-option="work"]')].map((card) => card.getBoundingClientRect());
- return {
- rows: new Set(cards.map((card) => Math.round(card.top))).size,
- widths: cards.map((card) => Math.round(card.width)),
- slack: Math.round(box.right - cards.at(-1)!.right),
- };
- });
- assert.equal(grid.rows, 1, '五部视频没排在同一行');
- assert.ok(grid.slack <= 1, `封面格右侧空出 ${grid.slack}px`);
- assert.ok(grid.widths.every((width) => width >= 96 && width <= 242), `封面宽度越出 96~242:${grid.widths.join('、')}`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('资料页照片墙:1280 宽小图 4 列、大图 2 列,手机 2 列;固定版式是方格,瀑布流按列填;格子是一块等图的空底', { timeout: 90_000 }, async () => {
- const opened = await openPhotoWall(browser);
- try {
- const { page } = opened;
- // 默认瀑布流、小图。
- assert.deepEqual(await photoWallFaces(page), { display: 'block', columns: 4, gap: '10px', square: true });
- const cell = await page.evaluate(() => {
- const node = document.querySelector<HTMLElement>('[data-local-wall] [data-photo-cell]')!;
- const style = getComputedStyle(node);
- const head = document.querySelector('[data-photo-group]')!;
- return {
- radius: style.borderRadius, cursor: style.cursor, sunk: style.backgroundColor,
- token: getComputedStyle(document.documentElement).getPropertyValue('--surface-radius').trim(),
- alt: getComputedStyle(node.querySelector('img')!).color,
- headTop: getComputedStyle(head).marginTop,
- rows: [head, head.querySelector('b')!].map((node) => getComputedStyle(node).lineHeight),
- code: getComputedStyle(head.querySelector('b')!).fontFamily,
- meta: getComputedStyle(head.querySelector('[data-photo-group-meta]')!).marginLeft !== '0px',
- };
- });
- assert.equal(cell.radius, cell.token, '照片格的圆角是 --surface-radius');
- assert.equal(cell.cursor, 'zoom-in');
- assert.equal(cell.alt, 'rgba(0, 0, 0, 0)', '等图时 alt 文件名不画出来');
- assert.notEqual(cell.sunk, 'rgba(0, 0, 0, 0)', '格子自带一块沉底色');
- assert.equal(cell.headTop, '28px', '每段上方留出段距');
- assert.deepEqual(cell.rows, ['20px', '20px'], '段头一行 20px,番号不按自己的字号撑高');
- assert.match(cell.code, /Cascadia Mono/, '段头番号是等宽字');
- assert.ok(cell.meta, '来源与张数靠右');
- assert.equal(await page.locator('#index [data-entity-more]').evaluate((node) => {
- const style = getComputedStyle(node);
- return `${style.height} ${style.borderRadius} ${style.fontSize} ${style.fontWeight}`;
- }), '36px 10px 14px 500', '载入更多是 36px 高、10px 圆角的 secondary 按钮');
- await page.locator('[data-entity-layout][aria-label="图片布局"] label:has(input[value="fixed"])').click();
- await page.waitForFunction(() => document.querySelector('[data-local-wall]')?.getAttribute('data-layout') === 'fixed');
- assert.deepEqual(await photoWallFaces(page), { display: 'grid', columns: 4, gap: '10px', square: true });
- // 顶栏那枚大小键在照片档里换的是照片的大小档,一次请求都不发。
- await page.locator('#density').click();
- await page.waitForFunction(() => document.querySelector('[data-local-wall]')?.getAttribute('data-size') === 'big');
- assert.deepEqual(await photoWallFaces(page), { display: 'grid', columns: 2, gap: '10px', square: true });
- assert.equal(await page.locator('#density').getAttribute('title'), '当前:大图');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- const phone = await openPhotoWall(browser, MOBILE);
- try {
- const { page } = phone;
- assert.deepEqual(await photoWallFaces(page), { display: 'block', columns: 2, gap: '10px', square: true });
- await page.locator('[data-entity-layout][aria-label="图片布局"] label:has(input[value="fixed"])').click();
- await page.waitForFunction(() => document.querySelector('[data-local-wall]')?.getAttribute('data-layout') === 'fixed');
- assert.deepEqual(await photoWallFaces(page), { display: 'grid', columns: 2, gap: '8px', square: true });
- assert.deepEqual(phone.problems, []);
- } finally {
- await phone.close();
- }
- });
-
- it('空输入时搜索记录与推荐并排,两栏之间的分隔线从顶画到底', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', WIDE);
- try {
- const page = opened.page;
- const history = Array.from({ length: 10 }, (_, at) => `搜索记录 ${at + 1}`);
- await page.route(/\/api\/search-history\?/, (route) => route.fulfill({ json: { items: history } }));
- await page.reload({ waitUntil: 'load' });
- await expectBody(page, '/', [page.locator('article[data-media-card][data-id]').first()]);
- await settle(page);
- await page.locator('#q').click();
- await page.locator('#searchMenu [data-search-results][data-split]').waitFor({ state: 'visible', timeout: 5_000 });
- const split = await page.evaluate(() => {
- const results = document.querySelector('#searchMenu [data-search-results]')!;
- const [left, right] = [...results.querySelectorAll(':scope > [data-search-col]')].map((col) => col.getBoundingClientRect());
- const box = results.getBoundingClientRect();
- const line = getComputedStyle(results, '::before');
- return {
- box: box.height, left: left.height, right: right.height, line: parseFloat(line.height),
- offset: parseFloat(line.left) + parseFloat(line.width) / 2 - ((left.right + right.left) / 2 - box.left),
- };
- });
- assert.ok(split.right < split.left, `推荐一栏(${split.right}px)应比十条搜索记录(${split.left}px)短`);
- assert.ok(Math.abs(split.line - split.box) <= 1, `分隔线高 ${split.line}px,两栏高 ${split.box}px`);
- assert.ok(Math.abs(split.offset) <= 1, `分隔线偏离两栏之间的缝 ${split.offset}px`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('资料表的标签只列前四个,余下的收进「+N」,浮层进顶层列全部标签', { timeout: 60_000 }, async () => {
- const opened = await openProfiledPerformer(browser, DESKTOP);
- try {
- const page = opened.page;
- const cell = await page.locator('[data-entity-facts] dd[data-fact="tags"]').evaluate((dd) => ({
- shown: [...dd.querySelectorAll(':scope > [data-fact-tag]')].map((tag) => tag.textContent!.trim()),
- more: dd.querySelector(':scope > [data-hero-more="fact"]')?.textContent?.trim() ?? '',
- }));
- assert.deepEqual(cell.shown, PROFILED.profile.tags.slice(0, 4), '标签那一格不是前四个');
- assert.equal(cell.more, '+5', '「+N」数的不是剩下那几个标签');
- const pop = page.locator('#entityTagPop');
- assert.equal(await pop.isVisible(), false);
- await page.locator('[data-hero-more="fact"]').hover();
- await pop.waitFor({ state: 'visible', timeout: 5_000 });
- const shown = await pop.evaluate((element) => {
- const box = element.getBoundingClientRect();
- return {
- topLayer: element.matches(':popover-open'),
- inView: box.left >= 0 && box.right <= innerWidth && box.top >= 0 && box.bottom <= innerHeight,
- title: element.querySelector('[data-hero-pop-head]')?.textContent?.trim(),
- tags: [...element.querySelectorAll('[data-fact-tag]')].map((tag) => tag.textContent!.trim()),
- };
- });
- assert.equal(shown.topLayer, true, '标签浮层没进顶层,会被资料卡的 overflow:hidden 裁掉');
- assert.ok(shown.inView, '标签浮层越出了视口');
- assert.equal(shown.title, '9 个标签');
- assert.deepEqual(shown.tags, PROFILED.profile.tags);
- await page.mouse.move(1, 1);
- await pop.waitFor({ state: 'hidden', timeout: 5_000 });
- // 点一下钉住:指针离开也不收,Escape 才收。
- await page.locator('[data-hero-more="fact"]').click();
- await page.mouse.move(1, 1);
- await page.waitForTimeout(300);
- assert.equal(await pop.isVisible(), true, '点按钉住的标签浮层指针一走就收了');
- await page.keyboard.press('Escape');
- assert.equal(await pop.isVisible(), false, 'Escape 收不起标签浮层');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('换头像的加号量在圆框上:整行比圆框高时也贴着圆框右下角', { timeout: 60_000 }, async () => {
- const opened = await openProfiledPerformer(browser, { name: 'wide', width: 1440, height: 900, mobile: false });
- try {
- const page = opened.page;
- const button = page.locator('[data-entity-portrait-wrap] [data-avatar-picker] button');
- await button.waitFor({ timeout: 15_000 });
- // 行有多高看她有多少资料、别名那一行折不折;这里直接把身份列撑高,量的是加号跟不跟圆框。
- await page.addStyleTag({ content: '[data-entity-identity]{padding-block:40px}' });
- const box = await page.evaluate(() => {
- const rect = (element: Element) => element.getBoundingClientRect();
- const wrap = rect(document.querySelector('[data-entity-portrait-wrap]')!);
- const circle = rect(document.querySelector('[data-entity-portrait]')!);
- const plus = rect(document.querySelector('[data-entity-portrait-wrap] [data-avatar-picker] button')!);
- return { wrap: wrap.height, circle: { right: circle.right, bottom: circle.bottom, height: circle.height },
- plus: { right: plus.right, bottom: plus.bottom } };
- });
- assert.ok(box.wrap > box.circle.height + 8, `这一行没有比圆框高,用例量不出偏移(行 ${box.wrap},圆框 ${box.circle.height})`);
- // Tailwind 的 `right-1 bottom-1`:按钮离圆框外框右、下各 4px。
- assert.ok(Math.abs(box.circle.bottom - box.plus.bottom - 4) < 1, `加号没有贴着圆框底边:${JSON.stringify(box)}`);
- assert.ok(Math.abs(box.circle.right - box.plus.right - 4) < 1, `加号没有贴着圆框右边:${JSON.stringify(box)}`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('女优页头深色主题:资料表与别名浮层跟着主题取墨色和浮层底', { timeout: 60_000 }, async () => {
- const opened = await openProfiledPerformer(browser, DESKTOP, 'dark');
- try {
- const page = opened.page;
- const ink = await tokenColor(page, '#main', '--ink');
- const muted = await tokenColor(page, '#main', '--muted');
- const ground = await tokenColor(page, '#main', '--ground');
- const facts = await page.locator('[data-entity-facts]').evaluate((dl) => ({
- dd: getComputedStyle(dl.querySelector('dd')!).color, dt: getComputedStyle(dl.querySelector('dt')!).color,
- }));
- assert.equal(facts.dd, ink, '深色下资料表的值不是墨色');
- assert.equal(facts.dt, muted, '深色下资料表的项名不是次级字色');
- await page.locator('[data-hero-more="alias"]').hover();
- const pop = page.locator('#entityAliasPop');
- await pop.waitFor({ state: 'visible', timeout: 5_000 });
- const { face, shadow } = await pop.evaluate((element) => {
- const style = getComputedStyle(element);
- return { face: style.backgroundColor, shadow: style.boxShadow };
- });
- assert.notEqual(face, 'rgba(0, 0, 0, 0)');
- assert.notEqual(face, 'rgb(255, 255, 255)', '深色下别名浮层还是白底');
- assert.equal(shadow, await popmenuShadow(page), '深色下别名浮层的落影和 .popmenu 不是同一副');
- assert.notEqual(ground, 'rgb(255, 255, 255)', '主题没有切到深色');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('详情出演区每一组的标题、头像和名字共用一条左边缘', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', DESKTOP);
- try {
- const page = opened.page;
- /* 演示库的作品没有女优与厂牌,身份数据按 `/api/item` 的 `entity_refs` 形状换进去;
- 名字比头像宽的那种最容易看出错位,所以女优名取四个字。 */
- await page.route(/\/api\/item\?/, async (route) => {
- const payload = await (await route.fetch()).json();
- Object.assign(payload, {
- is_jav: true, performers: ['凉森玲梦'], studio: 'Prestige', creator: '',
- entity_refs: {
- creator: [], series: [],
- performer: [{ id: 90_101, name: '凉森玲梦', has_image: true }],
- studio: [{ id: 90_102, name: 'Prestige', has_image: false, has_logo: true }],
- },
- });
- await route.fulfill({ json: payload });
- });
- const square = { contentType: 'image/svg+xml',
- body: '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect width="200" height="200" fill="#888"/></svg>' };
- await page.route(/\/entity-image\?/, (route) => route.fulfill(square));
- await page.route(/\/logo\?/, (route) => route.fulfill(square));
- await page.goto(new URL(`/item/${requiredEnv('PEACH_E2E_ITEM')}`, page.url()).href, { waitUntil: 'load' });
- await page.locator('[data-item-identity] [data-id-group="studio"] [data-id-name]').waitFor({ timeout: 15_000 });
- const edges = await page.evaluate(() => Object.fromEntries(
- ['performer', 'studio'].map((kind) => {
- const group = document.querySelector(`[data-item-identity] [data-id-group="${kind}"]`)!;
- const name = document.createRange();
- name.selectNodeContents(group.querySelector('[data-id-name]')!);
- return [kind, {
- label: group.querySelector('[data-id-label]')!.getBoundingClientRect().left,
- face: group.querySelector('[data-id-face]')!.getBoundingClientRect().left,
- name: name.getBoundingClientRect().left,
- }];
- })));
- for (const [kind, edge] of Object.entries(edges)) {
- assert.ok(Math.abs(edge.face - edge.label) < 0.5, `${kind} 组头像左缘 ${edge.face} 不在标题左缘 ${edge.label}`);
- assert.ok(Math.abs(edge.name - edge.label) < 0.5, `${kind} 组名字左缘 ${edge.name} 不在标题左缘 ${edge.label}`);
- }
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('人物页同台艺人的头像悬停和首页顶栏女优头像同一副:抬整格填充、不描圈', { timeout: 60_000 }, async () => {
- const opened = await openPerformer(browser, DESKTOP);
- try {
- const page = opened.page;
- const person = page.locator('[data-entity-foot] [data-related-performer]').first();
- const face = () => person.evaluate((element) => {
- const style = getComputedStyle(element), ring = getComputedStyle(element.querySelector('[data-hero-ring]')!);
- return { fill: style.backgroundColor, ink: style.color, radius: style.borderRadius, padding: style.padding,
- width: style.width, ring: ring.boxShadow, size: ring.width };
- });
- await page.mouse.move(0, 0);
- const rest = await face();
- await person.hover();
- const hovered = await face();
- // 首页那一格(board.css「首页顶部两排」):76px 宽、6/4px 内边距、12px 圆角,悬停铺
- // primary-hover、字换主文字色,48px 圆头像不另描圈。
- const home = {
- fill: await tokenColor(page, '#main', '--color-background-primary-hover'),
- ink: await tokenColor(page, '#main', '--color-text-primary'),
- };
- assert.equal(rest.fill, 'rgba(0, 0, 0, 0)', '没悬停就垫了底');
- assert.deepEqual({ radius: hovered.radius, padding: hovered.padding, width: hovered.width, size: hovered.size },
- { radius: '12px', padding: '6px 4px', width: '76px', size: '48px' }, '同台艺人那一格和首页头像格不是同一副几何');
- assert.equal(hovered.fill, home.fill, '悬停没有铺首页那一档填充');
- assert.equal(hovered.ink.replace(/\s/g, ''), home.ink.replace(/\s/g, ''), '悬停没有换成主文字色');
- assert.equal(hovered.ring, 'none', '悬停还在给圆头像描圈');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('资料卡大位与同台艺人的头像按人脸框放大:图保持原比例、盖满圆框,不被预检的 max-width 夹住', { timeout: 60_000 }, async () => {
- const name = '七沢みあ';
- const opened = await visit(browser, '/', DESKTOP);
- try {
- const page = opened.page;
- const focus = { box: TASTE_FACE };
- await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
- id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],
- user_aliases: [], asset_count: 0, tags: [], links: [], metadata: {}, entry_links: [],
- related_performers: [{ id: 90_002, k: '共演者', n: 1, rep: null, has_image: true, has_avatar: false,
- avatar_focus: focus }],
- has_image: true, has_avatar: false, avatar_focus: focus, representative_asset_id: null,
- } }));
- await page.route(/\/entity-image\?/, (route) => route.fulfill({
- contentType: 'image/svg+xml',
- body: `<svg xmlns="http://www.w3.org/2000/svg" width="${TASTE_FACE.imgW}" height="${TASTE_FACE.imgH}">`
- + `<rect width="${TASTE_FACE.imgW}" height="${TASTE_FACE.imgH}" fill="#888"/></svg>`,
- }));
- await page.goto(new URL(`/performers/${encodeURIComponent(name)}`, page.url()).href, { waitUntil: 'load' });
- for (const [where, selector] of [['大位', '[data-entity-portrait] > img[data-facebox]'],
- ['同台艺人', '[data-hero-ring] > img[data-facebox]']] as const) {
- const img = page.locator(selector).first();
- await img.waitFor({ state: 'attached', timeout: 15_000 });
- // 放大是图加载后 `avatarFrame` 写进内联 style 的;等到那一步落地再量。
- await page.waitForFunction((element) => element instanceof HTMLImageElement
- && element.complete && element.naturalWidth > 0 && element.style.width !== '',
- await img.elementHandle(), { timeout: 15_000 });
- const frame = await img.evaluate((element) => {
- const ring = element.parentElement!.getBoundingClientRect();
- const box = element.getBoundingClientRect();
- return {
- maxWidth: getComputedStyle(element).maxWidth, maxHeight: getComputedStyle(element).maxHeight,
- ring: ring.width, width: box.width, aspect: box.width / box.height,
- gaps: [box.left - ring.left, ring.right - box.right, box.top - ring.top, ring.bottom - box.bottom],
- initial: getComputedStyle(element.parentElement!.querySelector('span')!).display,
- };
- });
- assert.deepEqual([frame.maxWidth, frame.maxHeight], ['none', 'none'], `${where}的图被预检的 max-width 夹住`);
- assert.ok(frame.width > frame.ring, `${where}没有按人脸框放大:图宽 ${frame.width}px,圆框 ${frame.ring}px`);
- assert.ok(Math.abs(frame.aspect - TASTE_FACE.imgW / TASTE_FACE.imgH) < .02, `${where}的图宽高比 ${frame.aspect},被压扁了`);
- assert.ok(frame.gaps.every((gap) => gap <= .5), `${where}的图没盖满圆框:${frame.gaps.join('、')}`);
- if (where === '大位') assert.equal(frame.initial, 'none', '大位有图时首字母没有让位');
- }
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- for (const viewport of [DESKTOP, MOBILE]) {
- it(`资料卡外链的圆盘不垫底、社媒字形铺满圆盘;手机上那一排不换行、横滑,滚动层顶到卡沿(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openProfiledPerformer(browser, viewport);
- try {
- const row = await opened.page.locator('[data-entity-links]').evaluate((element) => {
- const style = getComputedStyle(element);
- const card = element.closest('[data-entity-card]')!.getBoundingClientRect();
- const box = element.getBoundingClientRect();
- const brand = element.querySelector('[data-link-icon="brand"]')!;
- const glyph = brand.querySelector('svg')!.getBoundingClientRect(), plate = brand.getBoundingClientRect();
- return {
- wrap: style.flexWrap, overflowX: style.overflowX, justify: style.justifyContent,
- edges: [box.left - card.left, card.right - box.right],
- discs: [...element.querySelectorAll('[data-link-icon]')].map((disc) => getComputedStyle(disc).backgroundColor),
- glyph: [Math.round(glyph.width), Math.round(glyph.height)], plate: [Math.round(plate.width), Math.round(plate.height)],
- };
- });
- // 垫一层底会让圆盘比周围暗一档,看着像这条链接被禁用了。
- assert.ok(row.discs.every((fill) => fill === 'rgba(0, 0, 0, 0)'), `外链圆盘垫了底色:${row.discs.join('、')}`);
- assert.deepEqual(row.glyph, row.plate, '社媒字形没有铺满圆盘,场色的角露出底');
- if (viewport.mobile) {
- // 普通 `center` 在溢出时把前半排推到滚动起点之前,那几条滑不到。
- assert.deepEqual([row.wrap, row.overflowX, row.justify], ['nowrap', 'auto', 'safe center'], '窄屏外链不是一行横滑');
- assert.ok(row.edges.every((gap) => Math.abs(gap) < 0.5), `窄屏外链的滚动层没有顶到卡沿:${row.edges.join('、')}`);
- } else {
- assert.equal(row.wrap, 'wrap', '宽屏外链该换行,不横滑');
- }
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it(`名字菜单:当前统称抬一档底色并打勾,其余行的勾位空着;手机上开关画 32px、命中区 44px,菜单行 44px(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openProfiledPerformer(browser, viewport);
- try {
- const page = opened.page;
- const toggle = page.locator('[data-namepick-toggle]');
- const hit = await toggle.evaluate((element) => {
- const box = element.getBoundingClientRect(), after = getComputedStyle(element, '::after');
- return { drawn: [Math.round(box.width), Math.round(box.height)], hit: [after.width, after.height] };
- });
- assert.deepEqual(hit.drawn, [32, 32], '名字旁那枚开关画出来不是 32px');
- if (viewport.mobile) assert.deepEqual(hit.hit, ['44px', '44px'], '手机上开关的命中区不到 44px');
- await toggle.click();
- await page.locator('[data-namepick-menu]').waitFor({ state: 'visible', timeout: 5_000 });
- const rows = await page.locator('[data-namepick-menu] [role="menuitemradio"]').evaluateAll((items) => items.map((item) => ({
- checked: item.getAttribute('aria-checked') === 'true', fill: getComputedStyle(item).backgroundColor,
- tick: getComputedStyle(item.querySelector('svg')!).visibility, height: item.getBoundingClientRect().height,
- menu: getComputedStyle(item.closest('[data-namepick-menu]')!).backgroundColor,
- })));
- assert.deepEqual(rows.map((row) => row.checked), [true, false], '菜单里当前统称不是第一行,或不止一行被选中');
- const [current, other] = rows;
- assert.notEqual(current!.fill, 'rgba(0, 0, 0, 0)', '当前统称那一行没有抬底');
- assert.notEqual(current!.fill, current!.menu, '当前统称那一行的底色和菜单面同色,看不出来');
- assert.deepEqual([current!.tick, other!.tick], ['visible', 'hidden'], '勾没有只给当前统称,或未选中那行不留勾位');
- assert.equal(other!.fill, 'rgba(0, 0, 0, 0)', '未选中那一行也抬了底');
- const least = viewport.mobile ? 44 : 36;
- const alias = await page.locator('[data-namepick-alias]').evaluate((item) => item.getBoundingClientRect().height);
- assert.ok([...rows.map((row) => row.height), alias].every((height) => height >= least - 0.5), `菜单行矮于 ${least}px`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
- }
-
- /* 尺寸按身份列有哪几行定:外链与看片那一行都在是 160px,缺一行是 120px。取行高百分比的话
- 圆框宽、列宽、别名折行、行高绕成一个圈,折行多出的那截压进卡底内边距。
- 有资料的女优默认只有外链那一行,两行都在的那位要补上看片标识与订阅开关;七沢みあ只有看片那一行。 */
- for (const viewport of VIEWPORTS) {
- it(`分类图标与视频数量同排,分类位于身份行最左侧(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openProfiledPerformer(browser, viewport, 'light', { identity_labels: ['女优','西方'] });
- try {
- const geometry = await opened.page.locator('[data-entity-alias="meta"]').evaluate((element) => {
- const classification = element.querySelector('[data-identity-classification]')!;
- const count = classification.nextElementSibling!;
- const label = classification.getBoundingClientRect(), video = count.getBoundingClientRect();
- const glyph = classification.querySelector('svg')!.getBoundingClientRect();
- return { first: element.firstElementChild === classification, top: [label.top, video.top],
- edges: [label.right, video.left], glyph: [glyph.width, glyph.height] };
- });
- assert.equal(geometry.first, true);
- assert.ok(Math.abs(geometry.top[0]! - geometry.top[1]!) < 1, '分类与视频数量另起了行');
- assert.ok(geometry.edges[0]! <= geometry.edges[1]!, '分类没有排在视频数量左侧');
- assert.deepEqual(geometry.glyph, [16, 16]);
- const measured = await layout(opened.page);
- assert.ok(measured.scrollWidth <= measured.viewportWidth + 1);
- assert.deepEqual(measured.offenders, []);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
- }
- const openBothRows = (browser: Browser, viewport: typeof DESKTOP) => openProfiledPerformer(browser, viewport, 'light', {
- entry_links: [
- { site: 'minnano-av', label: 'みんなのAV', ordinal: '', slot: 'pill', mark: 'brand-minnano',
- url: 'https://www.minnano-av.com/actress12345.html' },
- { site: 'javdb', label: 'JavDB', ordinal: '', slot: 'mark', mark: 'mark-javdb', url: 'https://javdb.com/actors/NPD3' },
- ],
- feed: { following: false },
- });
- for (const [label, open, size] of [
- ['外链与看片那一行都在', openBothRows, 160],
- ['只有看片那一行', openPerformer, 120],
- ['只有外链那一行', openProfiledPerformer, 120],
- ] as const) {
- it(`资料卡大位按身份列的行数定尺寸:${label}是 ${size}px 正圆,身份列不压进卡底内边距`, { timeout: 60_000 }, async () => {
- const opened = await open(browser, DESKTOP);
- try {
- const box = await opened.page.locator('[data-entity-portrait]').evaluate((element) => {
- const portrait = element.getBoundingClientRect();
- const profile = element.closest('[data-entity-profile]')!.getBoundingClientRect();
- const identity = element.closest('[data-entity-profile]')!.querySelector('[data-entity-identity]')!.getBoundingClientRect();
- return { width: portrait.width, height: portrait.height, room: profile.bottom - identity.bottom };
- });
- assert.ok(Math.abs(box.height - size) < 1, `头像 ${box.height}px,应是 ${size}px`);
- assert.ok(Math.abs(box.width - box.height) < 1, '头像不是正圆');
- assert.ok(box.room >= 19.5, `身份列离卡底只剩 ${box.room}px,压进了 20px 的内边距`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
- }
-
- it('看片那一行:两枚标识隔 32px、按 22px 字高对齐;MISSAV 按它站上的排字,AV 用它的粉;第二枚带序号', { timeout: 60_000 }, async () => {
- const name = '七沢みあ';
- const opened = await visit(browser, '/', DESKTOP);
- try {
- const page = opened.page;
- await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
- id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],
- user_aliases: [], asset_count: 0, tags: [], related_performers: [], links: [], metadata: {},
- has_image: false, has_avatar: false, avatar_focus: null, representative_asset_id: null,
- entry_links: [
- { site: 'javdb', label: 'JavDB', ordinal: '', slot: 'mark', mark: 'mark-javdb', url: 'https://javdb.com/actors/NPD3' },
- { site: 'missav', label: 'MISSAV', ordinal: '2', slot: 'mark', mark: '', url: 'https://missav.ws/actresses/x' },
- ],
- } }));
- await page.goto(new URL(`/performers/${encodeURIComponent(name)}`, page.url()).href, { waitUntil: 'load' });
- await page.locator('[data-missav-mark]').waitFor({ timeout: 15_000 });
- const marks = await page.locator('[data-entry-marks]').evaluate((row) => {
- const wordmark = row.querySelector('[data-missav-mark]')!;
- const [miss, av] = [...wordmark.children].map((part) => getComputedStyle(part).color);
- return {
- gap: getComputedStyle(row).columnGap,
- javdb: row.querySelector('[data-entry-mark] svg')!.getBoundingClientRect().height,
- family: getComputedStyle(wordmark).fontFamily, weight: getComputedStyle(wordmark).fontWeight,
- miss, av, ink: getComputedStyle(wordmark.closest('a')!).color,
- ordinal: row.querySelector('[data-entry-ordinal]')?.textContent ?? '',
- hrefs: [...row.querySelectorAll('a[data-entry-mark]')].map((a) => a.getAttribute('href')),
- };
- });
- assert.equal(marks.gap, '32px', '两枚标识的间距不是 32px');
- assert.equal(Math.round(marks.javdb), 22, 'JavDB 标识的字高不是 22px');
- assert.match(marks.family, /^Halant/, 'MISSAV 没有用 Halant 排字');
- assert.equal(marks.weight, '500');
- assert.equal(marks.miss, marks.ink, 'MISS 那半没有跟页面墨色');
- assert.equal(marks.av, 'rgb(254, 98, 142)', 'AV 那半不是 MISSAV 的粉');
- assert.equal(marks.ordinal, '2', '第二枚没带服务端编好的序号');
- assert.deepEqual(marks.hrefs, ['https://javdb.com/actors/NPD3', 'https://missav.ws/actresses/x'], '入口地址不是服务端下发的那个');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('厂牌页资料卡:标识铺满方框;指回自家站的官网写「官方网站」,带站点圆标、字距 .02em', { timeout: 60_000 }, async () => {
- const name = 'S1 NO.1 STYLE';
- const opened = await visit(browser, '/', DESKTOP);
- try {
- const page = opened.page;
- await page.route(/\/api\/entity\?/, (route) => route.fulfill({ json: {
- id: 90_601, kind: 'studio', canonical_name: name, aliases: [], display_aliases: [], user_aliases: [],
- asset_count: 3, tags: [], related_performers: [], labels: [], metadata: {}, entry_links: [],
- has_image: false, has_avatar: false, has_logo: true, avatar_focus: null, representative_asset_id: null,
- links: [{ link_id: 90_602, link_kind: 'official', clickable: true, label: 'S1', url: 'https://www.s1s1s1.com/' }],
- } }));
- // 标识比方框大,走铺满那条;比框小的走原尺寸居中,是另一条判据。
- await page.route(/\/logo\?/, (route) => route.fulfill({
- contentType: 'image/svg+xml',
- body: '<svg xmlns="http://www.w3.org/2000/svg" width="600" height="600"><rect width="600" height="600" fill="#888"/></svg>',
- }));
- await page.route('**/link-mark**', (route) => route.fulfill({
- status: 200, contentType: 'image/png', body: Buffer.from(PIXEL, 'base64'),
- }));
- await page.goto(new URL(`/studios/${encodeURIComponent(name)}`, page.url()).href, { waitUntil: 'load' });
- const logo = page.locator('[data-entity-portrait] > img');
- await logo.waitFor({ state: 'attached', timeout: 15_000 });
- await page.waitForFunction((element) => element instanceof HTMLImageElement && element.complete && element.naturalWidth > 0,
- await logo.elementHandle(), { timeout: 15_000 });
- const face = await logo.evaluate((element) => {
- const frame = element.parentElement!, box = element.getBoundingClientRect(), outer = frame.getBoundingClientRect();
- return { shape: frame.getAttribute('data-entity-portrait'), radius: getComputedStyle(frame).borderTopLeftRadius,
- fit: getComputedStyle(element).objectFit,
- gaps: [box.left - outer.left, outer.right - box.right, box.top - outer.top, outer.bottom - box.bottom] };
- });
- assert.equal(face.shape, 'square');
- assert.notEqual(face.radius, '50%', '厂牌的标识框画成了圆');
- // 标识走「图比框小就别放大」那组:contain 不裁字标,比框大的按框收,所以照样铺满。
- assert.equal(face.fit, 'contain', '厂牌标识被裁成了铺满');
- assert.ok(face.gaps.every((gap) => Math.abs(gap) < 0.5), `标识没盖满方框:${face.gaps.join('、')}`);
- const site = await page.locator('[data-entity-links] a[data-link="url"]').evaluate((a) => ({
- text: a.querySelector('[data-link-label]')?.textContent ?? '',
- spacing: parseFloat(getComputedStyle(a).letterSpacing) / parseFloat(getComputedStyle(a).fontSize),
- mark: a.querySelector('[data-link-icon] img')?.getAttribute('src') ?? '',
- referrer: a.querySelector('[data-link-icon] img')?.getAttribute('referrerpolicy') ?? '',
- }));
- assert.equal(site.text, '官方网站');
- assert.ok(Math.abs(site.spacing - 0.02) < 0.001, `官网那一格的字距是 ${site.spacing}em`);
- assert.deepEqual([site.mark, site.referrer], ['/link-mark?id=90602', 'no-referrer'], '官网没带本机合成的站点圆标');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('人物页骨架第一帧就带着这一位有的新作行与同台艺人,数据到了一次换齐、高度不变、封面不再等第二遍', { timeout: 60_000 }, async () => {
- const name = '七沢みあ';
- const opened = await visit(browser, '/', DESKTOP);
- try {
- await opened.page.route(/\/api\/entity\/shapes/, (route) => route.fulfill({ json: {
- ok: true, entities: [{ id: 90_001, kind: 'performer', names: [name], parts: ['feed', 'costars'] }] } }));
- // 骨架插进页面的那一刻就记下它带着哪几块:之后才补进去的,就是在骨架里跳了一下。
- await opened.page.addInitScript(() => {
- const first = { feed: null as boolean | null, foot: null as boolean | null, sheen: '' };
- (window as unknown as { skeletonFirst: typeof first }).skeletonFirst = first;
- new MutationObserver(() => {
- const skeleton = document.querySelector('[data-skeleton="entity/performer"]');
- if (!skeleton || first.feed !== null) return;
- first.feed = !!skeleton.querySelector('.feednew');
- first.foot = !!skeleton.querySelector('.entityfoot');
- // 骨架卡的微光和骨架同一帧就在:晚一步的话,那一步里露出来的是封面格的黑底。
- const pic = skeleton.querySelector('.feednewskeleton .pic.imgwait');
- first.sheen = pic ? getComputedStyle(pic, '::after').opacity : '';
- }).observe(document, { childList: true, subtree: true });
- // 真实库上启动脚本发出名单请求后还要连续跑四五百毫秒,名单的响应就在这段时间里到、
- // 排在队里。这里在发请求的同一个任务末尾占住主线程 700ms,把那一段复现出来。
- const fetch = window.fetch;
- let blocked = false;
- window.fetch = (...args) => {
- if (!blocked && String(args[0]).includes('/api/entity/shapes')) {
- blocked = true;
- queueMicrotask(() => { const end = performance.now() + 700; while (performance.now() < end); });
- }
- return fetch(...args);
- };
- });
- let release = () => {};
- const held = new Promise<void>((resolve) => { release = resolve; });
- await opened.page.route(/\/api\/entity\?/, async (route) => {
- await held;
- await route.fulfill({ json: {
- id: 90_001, kind: 'performer', canonical_name: name, aliases: [], display_aliases: [],
- user_aliases: [], asset_count: 0, tags: [],
- related_performers: [{ id: 90_002, k: '共演者', n: 1, rep: null, has_image: false,
- has_avatar: false, avatar_focus: null }],
- links: [], metadata: {}, has_image: false, has_avatar: false, avatar_focus: null,
- representative_asset_id: null, entry_links: [], feed: { following: true },
- } });
- });
- await opened.page.route(/\/api\/feeds\/discoveries\?/, (route) => route.fulfill({ json: {
- ok: true, more: false, items: [{
- id: 1, code: 'ABC-001', title: '标题', link: 'https://javdb.com/v/x', cover_url: null,
- has_cover: true, cover_frame: null, poster_box: null, release_date: '2026-09-01',
- studio: '厂牌', performers: name, source_name: '', read: false, ignored: false,
- scrape_error: null }] } }));
- // 封面比数据晚到一截:整页要等它,而不是先换上真卡、再在封面格里微光一遍。
- await opened.page.route(/\/cover\?code=ABC-001/, async (route) => {
- await new Promise((resolve) => setTimeout(resolve, 400));
- await route.fulfill({ contentType: 'image/png', body: Buffer.from(PIXEL, 'base64') });
- });
- await opened.page.goto(new URL(`/performers/${encodeURIComponent(name)}`,
- opened.page.url()).href, { waitUntil: 'load' });
- const skeleton = opened.page.locator('[data-skeleton="entity/performer"]');
- await skeleton.locator('.feednew .feednewskeleton').first().waitFor({ timeout: 15_000 });
- const before = await skeleton.evaluate((element) => {
- const row = element.querySelector('.feednew')!;
- const foot = element.querySelector('.entityhero > .entityfoot');
- // 同一个 `.pic.imgwait` 放在新作那一行外面,它的微光就是全站等待态那一种。
- const probe = document.createElement('div');
- probe.className = 'pic imgwait';
- document.querySelector('#main')!.append(probe);
- const plain = getComputedStyle(probe, '::after').backgroundImage;
- probe.remove();
- return { height: row.getBoundingClientRect().height,
- footHeight: foot?.getBoundingClientRect().height ?? 0,
- between: !!row.previousElementSibling?.matches('[data-filter-frame]')
- && !!row.nextElementSibling?.matches('.entitysection'),
- sheen: getComputedStyle(row.querySelector('.pic.imgwait')!, '::after').backgroundImage, plain,
- first: (window as unknown as { skeletonFirst: { feed: boolean; foot: boolean; sheen: string } }).skeletonFirst };
- });
- assert.ok(before.between, '骨架里的新作那一行不在筛选框和作品之间');
- const { sheen, ...parts } = before.first;
- assert.deepEqual(parts, { feed: true, foot: true }, '骨架先画了一版,新作行或同台艺人是后来才补进去的');
- assert.equal(sheen, '1', '新作骨架卡的微光晚于骨架出现,中间露出封面格的黑底');
- assert.ok(before.footHeight > 0, '骨架的资料卡底没有同台艺人那一条');
- assert.equal(before.sheen, before.plain, '新作骨架的微光另起了一种颜色');
- // 画好的页面上那一行一出现就得是真卡:再露一回它自己的骨架,就是同一行等了两遍。
- await opened.page.evaluate(() => {
- const seen = { second: false };
- (window as unknown as { feedSeen: typeof seen }).feedSeen = seen;
- new MutationObserver(() => {
- if (document.querySelector('[data-feed-new] .feednewskeleton')) seen.second = true;
- }).observe(document.querySelector('#index')!, { childList: true, subtree: true });
- });
- release();
- const row = opened.page.locator('[data-feed-new]');
- await row.locator('[data-feed-id]').waitFor({ timeout: 15_000 });
- const after = await row.evaluate((element) => ({
- height: element.getBoundingClientRect().height, busy: element.getAttribute('aria-busy'),
- waiting: element.querySelectorAll('[data-feed-id] .pic.imgwait').length,
- footHeight: document.querySelector('[data-entity-card] > [data-entity-foot]')?.getBoundingClientRect().height ?? 0,
- second: (window as unknown as { feedSeen: { second: boolean } }).feedSeen.second }));
- assert.equal(after.height, before.height, '占位行和到货的那一行不一样高,下面的作品网格会跳');
- assert.equal(after.footHeight, before.footHeight, '同台艺人那一条占位和真的不一样高,资料卡会伸缩');
- assert.equal(after.busy, null);
- assert.equal(after.second, false, '整页画出来之后新作那一行又单独骨架了一轮');
- assert.equal(after.waiting, 0, '骨架退场后封面格里又微光了一遍');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('卡片悬停面不顶到邻卡,三处卡片网格同一副列距', { timeout: 60_000 }, async () => {
- const opened = await openCatalog(browser);
- try {
- const card = opened.page.locator('#grid [data-media-grid] > [data-media-card]').first();
- await card.hover();
- const geometry = await card.evaluate((element) => {
- const box = element.getBoundingClientRect();
- const neighbor = [...element.parentElement!.children].find((other) => other !== element
- && Math.abs(other.getBoundingClientRect().top - box.top) < 1)!;
- const spread = Number(/0px 0px 0px (\d+(?:\.\d+)?)px/.exec(getComputedStyle(element).boxShadow)?.[1]);
- // 壳画的骨架网格和关注页岛的视频列表不在首页这叠卡里:各挂一个同形的空壳读列距。
- const columnGap = (build: (probe: HTMLElement) => HTMLElement) => {
- const probe = document.createElement('div');
- const host = build(probe);
- document.querySelector('#main')!.append(host);
- const gap = parseFloat(getComputedStyle(probe).columnGap);
- host.remove();
- return gap;
- };
- return {
- spread, clearance: neighbor.getBoundingClientRect().left - (box.right + spread),
- home: parseFloat(getComputedStyle(element.parentElement!).columnGap),
- skeleton: columnGap((probe) => { probe.className = 'grid'; return probe }),
- follow: columnGap((probe) => {
- const island = document.createElement('div');
- island.className = 'peach-react';
- probe.setAttribute('data-follow-list', '');
- island.append(probe);
- return island;
- }),
- };
- });
- assert.ok(geometry.spread > 0, '卡片悬停面没有往盒外铺');
- assert.ok(geometry.clearance >= geometry.spread,
- `悬停面离邻卡只剩 ${geometry.clearance}px,比它自己往外铺的 ${geometry.spread}px 还窄`);
- assert.equal(geometry.skeleton, geometry.home, '壳画的骨架网格的列距和首页不一样,真卡换上来时整排挪位');
- assert.equal(geometry.follow, geometry.home, '关注页视频列表的列距和首页不一样');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('跳过渲染的元信息区不裁掉贴着边的头像悬停描边和焦点环', { timeout: 60_000 }, async () => {
- /* 演示库的作品都未归属,头像是不可聚焦的 `<span>`;首张卡归给一位女优,头像才是按钮。 */
- const opened = await openCatalogFixture(browser, (payload) => {
- const item = payload.items[0];
- if (!item) throw new Error('演示目录没有可替换的卡片');
- item.creator = '';
- item.performers = ['演示演员'];
- item.performer_total = 1;
- item.performer_entities = [{ id: 90_000, name: '演示演员', has_image: false }];
- });
- try {
- /* 视口外跳过渲染连带 paint containment,元信息区里画出 padding box 的像素一律裁掉;
- 几何照算,所以这里比的是描边外沿与 padding box,不是与内容盒。头像贴着内容盒的
- 左缘和上缘。这条不读 `overflow-clip-margin`:Safari 不认它,裁切边只能靠盒子本身。 */
- const { page } = opened;
- const avatar = page.locator('#grid [data-media-grid] > [data-media-card] [data-media-meta] > button[data-media-avatar]').first();
- const edges = () => avatar.evaluate((element) => {
- const meta = element.closest('[data-media-meta]')!;
- const style = getComputedStyle(element);
- const shadow = Number(/0px 0px 0px (\d+(?:\.\d+)?)px/.exec(style.boxShadow)?.[1] ?? 0);
- const outline = style.outlineStyle === 'none' ? 0
- : parseFloat(style.outlineWidth) + parseFloat(style.outlineOffset);
- const ring = Math.max(shadow, outline);
- const box = element.getBoundingClientRect();
- const clip = meta.getBoundingClientRect();
- const left = clip.left + meta.clientLeft, top = clip.top + meta.clientTop;
- return {
- contained: getComputedStyle(meta).contentVisibility === 'auto',
- focused: element.matches(':focus-visible'), ring,
- // 描边外沿到裁切边还剩多少,四边取最小的那一边。
- room: Math.min(box.left - ring - left, box.top - ring - top,
- left + meta.clientWidth - (box.right + ring), top + meta.clientHeight - (box.bottom + ring)),
- };
- });
- await avatar.hover();
- const hovered = await edges();
- assert.ok(hovered.contained, '首页卡片的元信息区不再跳过渲染:这条用例守的裁切前提变了,改用例');
- assert.ok(hovered.ring > 0, '头像悬停没有描边');
- assert.ok(hovered.room >= -.5, `头像悬停描边越过了元信息区的裁切边 ${-hovered.room}px,那一截会被裁掉`);
- await page.mouse.move(0, 0);
- await page.keyboard.press('Tab');
- await avatar.focus();
- const focused = await edges();
- assert.ok(focused.focused && focused.ring > 0, '键盘聚焦的头像没有焦点环');
- assert.ok(focused.room >= -.5, `头像焦点环越过了元信息区的裁切边 ${-focused.room}px,那一截会被裁掉`);
- } finally {
- await opened.close();
- }
- });
-
- it('头像圆框里的图按人脸框写进的内联尺寸不被岛里的预检夹回框宽', { timeout: 60_000 }, async () => {
- /* 演示库没有实体图,往首张卡的头像框里塞一张按人脸框放大的图:宽超过框宽时图就该那么宽,
- 由圆框的 overflow 裁;被夹回框宽的话脸偏到左边,右侧露出底下的首字母。 */
- const opened = await openCatalogFixture(browser, (payload) => {
- const item = payload.items[0];
- if (!item) throw new Error('演示目录没有可替换的卡片');
- item.creator = '';
- item.performers = ['演示演员'];
- item.performer_total = 1;
- item.performer_entities = [{ id: 90_000, name: '演示演员', has_image: false }];
- });
- try {
- const avatar = opened.page.locator('#grid [data-media-grid] > [data-media-card] [data-media-meta] > button[data-media-avatar]').first();
- const framed = await avatar.evaluate((element) => {
- const img = document.createElement('img');
- img.setAttribute('style', 'position:absolute;inset:-25% auto auto 0;width:150%;height:195%');
- element.appendChild(img);
- const frame = element.getBoundingClientRect();
- const box = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- return { maxWidth: style.maxWidth, maxHeight: style.maxHeight,
- width: box.width / frame.width, height: box.height / frame.height };
- });
- assert.equal(framed.maxWidth, 'none', '头像图还带着预检的 max-width');
- assert.equal(framed.maxHeight, 'none', '头像图还带着 max-height');
- assert.ok(Math.abs(framed.width - 1.5) <= .02, `按人脸框放大到 1.5 倍框宽的图被夹成了 ${framed.width} 倍`);
- assert.ok(Math.abs(framed.height - 1.95) <= .02, `按人脸框放大到 1.95 倍框高的图被夹成了 ${framed.height} 倍`);
- } finally {
- await opened.close();
- }
- });
-
- it('亮暗按钮保持尺寸与悬停面色,卡片和回执保持接触阴影', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/stats', DESKTOP);
- try {
- // 选中的那张页签按基线收掉接触阴影,读旁边没选中的一张。
- const card = opened.page.locator('#main [class~="shadow-card"]:not([data-selected])').first();
- await card.waitFor({ timeout: 15_000 });
- await settle(opened.page);
- const checkSecondaryButton = async () => {
- await opened.page.mouse.move(0, 0);
- const dimensions = await opened.page.evaluate(() => {
- const holder = document.createElement('div');
- holder.style.cssText = 'position:fixed;right:16px;bottom:16px;z-index:10000';
- const button = document.createElement('button');
- button.className = 'geist-button';
- button.dataset.buttonProbe = '';
- button.textContent = '操作';
- holder.append(button);
- document.body.append(holder);
- const style = getComputedStyle(button);
- return [style.boxSizing, style.height, style.paddingTop, style.paddingRight,
- style.borderTopWidth, style.display];
- });
- assert.deepEqual(dimensions, ['border-box', '36px', '8px', '12px', '1px', 'inline-flex']);
- const button = opened.page.locator('[data-button-probe]');
- try {
- const idle = await button.evaluate(element => getComputedStyle(element).backgroundColor);
- assert.equal(idle, await tokenColor(opened.page, 'body', '--color-background-primary-default'));
- const border = await button.evaluate(element => getComputedStyle(element).borderTopColor);
- await button.hover();
- await settle(opened.page);
- const hovered = await button.evaluate(element => getComputedStyle(element).backgroundColor);
- assert.equal(hovered, await tokenColor(opened.page, 'body', '--control-hover'));
- assert.equal(await button.evaluate(element => getComputedStyle(element).borderTopColor), border);
- } finally {
- await button.evaluate(element => element.parentElement!.remove());
- }
- };
- /* Tailwind 把阴影 token 的字面值抄进工具类,`.dark` 里改 `--shadow-*` 够不着它;
- 旧样式表里写死的浅色阴影同样不跟主题走。读三类来源各一处的计算值。 */
- const alphas = () => opened.page.evaluate(() => {
- const strongest = (shadow: string) => Math.max(0, ...[...shadow.matchAll(
- /rgba\(0, 0, 0, ([\d.]+)\)|rgb\(0, 0, 0\)/g)].map((match) => (match[1] ? Number(match[1]) : 1)));
- const probe = (html: string, parent: Element = document.body) => {
- const holder = document.createElement('div');
- holder.innerHTML = html;
- const element = holder.firstElementChild!;
- // 挂在 React 岛外面:岛里的重置会把旧样式表的按钮阴影清掉。
- parent.append(element);
- const shadow = getComputedStyle(element).boxShadow;
- element.remove();
- return strongest(shadow);
- };
- return {
- card: strongest(getComputedStyle(document.querySelector('#main [class~="shadow-card"]:not([data-selected])')!).boxShadow),
- button: probe('<button class="geist-button" type="button">键</button>'),
- // Toast 的面只在 #toasts 里成立:阴影写在 Sonner 那一条的属性选择器上。
- toast: probe('<li data-sonner-toast data-styled="true">回执</li>', document.getElementById('toasts')!),
- };
- });
- await opened.page.evaluate(() => {
- document.documentElement.dataset.theme = 'light';
- document.documentElement.classList.remove('dark');
- });
- const light = await alphas();
- await checkSecondaryButton();
- // `web/app.js` 的 `applyTheme('dark')` 就是这两句;这里只借它换一次配色。
- await opened.page.evaluate(() => {
- document.documentElement.dataset.theme = 'dark';
- document.documentElement.classList.add('dark');
- });
- const dark = await alphas();
- await checkSecondaryButton();
- for (const key of Object.keys(light) as Array<keyof typeof light>) {
- assert.ok(light[key] > 0 && light[key] < .2, `浅色下 ${key} 的阴影 ${light[key]} 不在浅色那一档`);
- assert.ok(dark[key] > light[key] && dark[key] <= .2,
- `暗色 ${key} 阴影应保留接触感而不形成重边:${dark[key]}`);
- }
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- for (const viewport of [DESKTOP, MOBILE]) {
- it(`JAV 订阅卡片包含分页与贴边底栏(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openFollowManage(browser, viewport);
- try {
- const page = opened.page;
- await page.route('**/api/feeds', route => route.fulfill({ json: {
- unread: 81, sources: Array.from({ length: 25 }, (_, i) => ({
- id: i + 1, kind: 'javdb-actor', kind_label: 'JAV 订阅', name: `测试订阅 ${i + 1}`,
- url: `https://example.com/actors/${i + 1}`, entity_id: null, entity_name: null,
- has_image: false, enabled: true, interval_minutes: 360, last_fetched_at: null,
- last_error: null, last_new_count: 0, seen: 0,
- })),
- } }));
- await page.reload({ waitUntil: 'load' });
- await page.getByRole('tab', { name: 'JAV 订阅源', exact: true }).click();
- const card = page.getByRole('region', { name: 'JAV 订阅列表', exact: true });
- await card.getByText('1–20 / 25 个订阅源', { exact: true }).waitFor();
- assert.equal(await card.locator('[role="row"][data-key]').count(), 20);
- await card.getByRole('button', { name: '下一页', exact: true }).click();
- await card.getByText('21–25 / 25 个订阅源', { exact: true }).waitFor();
- assert.equal(await card.locator('[role="row"][data-key]').count(), 5);
- for (const theme of ['light', 'dark']) {
- await page.evaluate(value => {
- document.documentElement.dataset.theme = value;
- document.documentElement.classList.toggle('dark', value === 'dark');
- }, theme);
- const surface = await card.evaluate(element => {
- const footer = element.querySelector('footer')!;
- const box = element.getBoundingClientRect();
- const bottom = footer.getBoundingClientRect();
- return { background: getComputedStyle(element).backgroundColor,
- footerBackground: getComputedStyle(footer).backgroundColor,
- left: bottom.left - box.left, right: box.right - bottom.right,
- bottom: box.bottom - bottom.bottom };
- });
- assert.notEqual(surface.background, 'rgba(0, 0, 0, 0)');
- assert.notEqual(surface.background, surface.footerBackground);
- for (const edge of ['left', 'right', 'bottom'] as const) assert.ok(Math.abs(surface[edge]) <= 1);
- const dimensions = await layout(page);
- assert.ok(dimensions.scrollWidth <= dimensions.viewportWidth + 1, JSON.stringify(dimensions));
- }
- assert.deepEqual(opened.problems, []);
- } finally { await opened.close(); }
- });
- it(`关注分类使用 Pills,凭据按要求分组并带描边(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openFollowManage(browser, viewport);
- try {
- const page = opened.page;
- const tabs = page.getByRole('tablist', { name: '关注管理区域' });
- for (const theme of ['light', 'dark']) {
- await page.evaluate((value) => {
- document.documentElement.dataset.theme = value;
- document.documentElement.classList.toggle('dark', value === 'dark');
- }, theme);
- await tabs.getByRole('tab', { name: /来源和凭证/ }).click();
- const face = await tabs.evaluate((element) => {
- const selected = element.querySelector('[aria-selected=true]')!;
- return { track: getComputedStyle(element).backgroundColor,
- selected: getComputedStyle(selected).backgroundColor,
- shadow: getComputedStyle(selected).boxShadow };
- });
- assert.equal(face.track, 'rgba(0, 0, 0, 0)', 'Pills 容器应透明');
- assert.notEqual(face.selected, face.track, '当前分类应有独立底色');
- assert.equal(face.shadow, 'none', 'Pills 不使用浮起滑块');
- for (const name of ['可配置凭据', '不需要凭据', '暂不支持']) {
- const group = page.getByRole('region', { name, exact: true });
- const rows = await group.evaluate((element) => {
- const style = getComputedStyle(element.lastElementChild!);
- return { shadow: style.boxShadow, width: style.borderTopWidth,
- border: style.borderTopColor, background: style.backgroundColor };
- });
- assert.equal(rows.shadow, 'none');
- assert.equal(rows.width, '1px');
- assert.notEqual(rows.border, rows.background);
- }
- assert.match(await page.getByRole('region', { name: '不需要凭据', exact: true }).innerText(), /Kemono/);
- assert.match(await page.getByRole('region', { name: '暂不支持', exact: true }).innerText(), /OnlyFans/);
- await tabs.getByRole('tab', { name: /来源和凭证/ }).focus();
- await page.keyboard.press('Home');
- await page.keyboard.press('Enter');
- assert.equal(await tabs.getByRole('tab', { name: '关注列表', exact: true }).getAttribute('aria-selected'), 'true');
- const dimensions = await layout(page);
- assert.ok(dimensions.scrollWidth <= dimensions.viewportWidth + 1, JSON.stringify(dimensions));
- }
- await page.route('**/api/follow/resolve', (route) => route.fulfill({
- status: 200, contentType: 'application/json', body: JSON.stringify({
- status: 'done', results: [{ line: '主题测试来源', candidates: [{
- provider: 'kemono', provider_label: 'Kemono', label: '主题测试候选', url: 'https://example.com/creator',
- }] }],
- }),
- }));
- await tabs.getByRole('tab', { name: '添加关注', exact: true }).click();
- await page.getByRole('textbox', { name: '来源链接、名字或 id' }).fill('主题测试来源');
- await page.getByRole('button', { name: '查找', exact: true }).click();
- const result = page.getByText('主题测试来源', { exact: true }).locator('..');
- await result.waitFor();
- for (const theme of ['light', 'dark']) {
- await page.evaluate((value) => {
- document.documentElement.dataset.theme = value;
- document.documentElement.classList.toggle('dark', value === 'dark');
- }, theme);
- const surface = await result.evaluate((element) => {
- const s = getComputedStyle(element);
- return { shadow: s.boxShadow, width: s.borderTopWidth, border: s.borderTopColor, bg: s.backgroundColor };
- });
- assert.equal(surface.shadow, 'none');
- assert.equal(surface.width, '1px');
- assert.notEqual(surface.border, surface.bg, '结果分组必须有可辨认边界');
- }
- assert.deepEqual(opened.problems, []);
- } finally { await opened.close(); }
- });
- }
-
- it('使用空间按字节量级的真实容量画出已用那一段,每个卷一行、不越出卡片', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/stats', DESKTOP);
- try {
- const page = opened.page;
- const TB = 1024 ** 4;
- const volumes = [
- { kind: 'system', label: '系统盘', root: 'C:\\', online: true, total: 2 * TB, used: 1.8 * TB, free: .2 * TB },
- { kind: 'media', label: '资源盘', root: 'R:\\media', online: false, total: null, used: null, free: null },
- { kind: 'media', label: 'PikPak 网盘', root: 'A:\\', online: true, total: 10240 * TB, used: 0, free: 10240 * TB },
- ];
- await page.route(/\/api\/stats(?:\?|$)/, async (route) => {
- const json = await (await route.fetch()).json();
- await route.fulfill({ json: { ...json, storage_volumes: volumes, storage_summary: {
- volumes: 3, online: 2, measured: 2, free: 10240.2 * TB, used: 1.8 * TB, total: 10242 * TB,
- } } });
- });
- await page.reload({ waitUntil: 'load' });
- await page.getByRole('tab', { name: /使用空间/ }).click();
- const panel = page.locator('[role="tabpanel"]').first();
- await panel.locator('[role="progressbar"]').first().waitFor({ state: 'visible', timeout: 15_000 });
- await settle(page);
- const shown = await panel.evaluate((element) => {
- const card = element.firstElementChild!;
- const cardBox = card.getBoundingClientRect();
- const detail = card.lastElementChild!.getBoundingClientRect();
- return {
- filled: [...element.querySelectorAll('[role="progressbar"]')].map((bar) =>
- Math.round(bar.querySelectorAll('rect')[1]!.getBoundingClientRect().width / bar.getBoundingClientRect().width * 100)),
- rows: [...element.querySelectorAll('article')].map((row) => getComputedStyle(row).borderBottomWidth),
- overflow: detail.right - (cardBox.right - parseFloat(getComputedStyle(card).paddingRight)),
- text: element.textContent ?? '',
- };
- });
- assert.deepEqual(shown.filled, [90, 0], '进度条画出来的已用比例不对');
- assert.deepEqual(shown.rows, ['1px', '1px', '0px'], '卷与卷之间没有覆盖率那样的分隔线');
- assert.ok(shown.overflow <= .5, `使用空间的详情越出卡片内边距 ${shown.overflow}px`);
- assert.ok(shown.text.includes('10.00 PB'), '网盘容量没按 PB 写');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- for (const viewport of VIEWPORTS) {
- it(`口味维度排名宽屏跟雷达那一栏等高、窄屏按条数给高度,图拉高时条不变粗(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openTaste(browser, viewport);
- try {
- const page = opened.page;
- const bars = page.locator('section[aria-label="口味维度排名"]');
- await bars.locator('.recharts-bar-rectangle').first().waitFor({ state: 'visible', timeout: 15_000 });
- await settle(page);
- const shown = await page.locator('section[aria-label="浏览器画像"]').evaluate((section) => {
- const radar = section.firstElementChild!.getBoundingClientRect();
- const ranked = section.querySelector('section[aria-label="口味维度排名"]')!.getBoundingClientRect();
- return {
- radar: radar.height,
- ranked: ranked.height,
- thickness: [...section.querySelectorAll('.recharts-bar-rectangle')]
- .map((bar) => bar.getBoundingClientRect().height),
- };
- });
- assert.equal(shown.thickness.length, TASTE_CATEGORIES.length);
- if (viewport.mobile) {
- assert.ok(shown.ranked >= 32 * TASTE_CATEGORIES.length,
- `窄屏排行条只有 ${shown.ranked}px,${TASTE_CATEGORIES.length} 条挤不下`);
- } else {
- assert.ok(Math.abs(shown.ranked - shown.radar) < 2,
- `排行条 ${shown.ranked}px,雷达那一栏 ${shown.radar}px,两栏不等高`);
- }
- // 26 是一格 32 里默认留出的粗细;图被拉高时多出来的高度拉开条距,不进条本身。
- assert.ok(shown.thickness.every((height) => height <= 26.5), `条粗 ${shown.thickness.join('、')}px`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
- }
-
- it('口味榜的女优与创作者头像按人脸框放大:图保持原比例、盖满圆框,不露出底下的首字母', { timeout: 60_000 }, async () => {
- const opened = await openTaste(browser, DESKTOP);
- try {
- const page = opened.page;
- await page.getByRole('tablist', { name: '口味证据来源' }).getByRole('tab', { name: 'Peach 内部' }).click();
- for (const name of ['女优', '创作者']) {
- await page.getByRole('tablist', { name: 'Peach 口味维度' }).getByRole('tab', { name }).click();
- const img = page.getByRole('tabpanel', { name }).locator('img[data-facebox]').first();
- await img.scrollIntoViewIfNeeded();
- // 放大是图加载后 `avatarFrame` 写进内联 style 的;等到那一步落地再量。
- await page.waitForFunction((element) => element instanceof HTMLImageElement
- && element.complete && element.naturalWidth > 0 && element.style.width !== '',
- await img.elementHandle(), { timeout: 15_000 });
- const frame = await img.evaluate((element) => {
- const ring = element.parentElement!.getBoundingClientRect();
- const box = element.getBoundingClientRect();
- return {
- maxWidth: getComputedStyle(element).maxWidth, ring: ring.width,
- width: box.width, aspect: box.width / box.height,
- gaps: [box.left - ring.left, ring.right - box.right, box.top - ring.top, ring.bottom - box.bottom],
- };
- });
- assert.equal(frame.maxWidth, 'none', `${name}头像的图被预检的 max-width 夹住`);
- assert.ok(frame.width > frame.ring, `${name}头像没有按人脸框放大:图宽 ${frame.width}px,圆框 ${frame.ring}px`);
- assert.ok(Math.abs(frame.aspect - TASTE_FACE.imgW / TASTE_FACE.imgH) < .02,
- `${name}头像的图宽高比 ${frame.aspect},被压扁了`);
- assert.ok(frame.gaps.every((gap) => gap <= .5), `${name}头像的图没盖满圆框:${frame.gaps.join('、')}`);
- }
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('被打断的那一轮只有结束原因,卡片正文下面不留空行', { timeout: 60_000 }, async () => {
- const opened = await openActivity(browser, [
- { ...settledRun(1, 'interrupted', '追更检查'), error: '服务重启,这一轮没有跑完' },
- ]);
- try {
- const body = await opened.page.locator('li[data-status="interrupted"] > div').first()
- .evaluate((element) => ({
- trailing: element.getBoundingClientRect().bottom - element.lastElementChild!.getBoundingClientRect().bottom,
- padding: parseFloat(getComputedStyle(element).paddingBottom),
- }));
- assert.ok(Math.abs(body.trailing - body.padding) <= .5,
- `正文最后一行下面空出 ${body.trailing}px,底边距只有 ${body.padding}px`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- /* 首页「未入库的新作」那一排会自己横着走,每一帧都发一次 scroll。手机上侧栏是抽屉,
- 两枚弹层一打开就碰上它;演示库没有订阅,这一排由拦下的 `/api/feeds/discoveries`
- 画出来(字段以 `src/peach/web_feeds.py` 为准)。夹具关了动效,自动滚动不起步,
- 所以这里亲手滚它,发出的是同一种 scroll。 */
- it('390px 下侧栏两枚弹层不随别处那一排横滚收起,整页滚动才收', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', MOBILE);
- try {
- const items = Array.from({ length: 12 }, (_, index) => ({
- id: index + 1, code: `DEMO-${String(index + 1).padStart(3, '0')}`, title: `演示新作 ${index + 1}`,
- studio: '演示厂牌', release_date: '2026-09-01', has_cover: false, cover_url: '', link: '', read: false,
- }));
- await opened.page.route((url) => url.pathname === '/api/feeds/discoveries', (route) => route.fulfill({
- status: 200, contentType: 'application/json', body: JSON.stringify({ items }),
- }));
- await opened.page.reload({ waitUntil: 'load' });
- const row = opened.page.locator('#feedNew .feednewrow');
- await row.waitFor({ state: 'visible', timeout: 15_000 });
- await settle(opened.page);
- assert.ok(await row.evaluate((element) => element.scrollWidth > element.clientWidth + 120),
- '新作那一排在 390px 下没有可横滚的余量,这条用例量不到东西');
- await opened.page.locator('#filterBtn').tap();
- await opened.page.waitForFunction(() => document.querySelector('#drawer')?.classList.contains('open'));
- for (const [trigger, menuId] of [['#brandHome', 'boardLibraryMenu'], ['#boardGlowBtn', 'boardGlowMenu']] as const) {
- const menu = opened.page.locator(`#${menuId}`);
- await opened.page.locator(trigger).tap();
- await menu.waitFor({ state: 'visible', timeout: 5_000 });
- for (let step = 0; step < 4; step += 1) {
- await row.evaluate((element) => { element.scrollLeft += 30; });
- await opened.page.waitForTimeout(100);
- }
- assert.ok(await menu.isVisible(), `${trigger} 打开的弹层随新作那一排横滚收起了`);
- // 菜单装不下时本来就要在内部滚;捕获阶段的 scroll 连它自己的也收得到。
- await menu.evaluate((element) => element.dispatchEvent(new Event('scroll')));
- await opened.page.waitForTimeout(100);
- assert.ok(await menu.isVisible(), `${trigger} 打开的弹层随它自己的内部滚动收起了`);
- assert.equal(await opened.page.locator(trigger).getAttribute('aria-expanded'), 'true');
- await opened.page.evaluate(() => document.dispatchEvent(new Event('scroll')));
- await menu.waitFor({ state: 'hidden', timeout: 5_000 });
- }
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('设置里的光晕配色和侧栏配色卡是同一组预设色块,键盘选一档两处一起换', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', DESKTOP);
- try {
- await settle(opened.page);
- await opened.page.locator('#settingsBtn').click();
- const grid = opened.page.locator('#homeGlowControls [data-glow-grid]');
- await grid.waitFor({ state: 'visible', timeout: 10_000 });
- const chips = (root: string) => opened.page.locator(`${root} [data-glow-preset]`).evaluateAll((nodes) =>
- nodes.map((node) => ({
- key: (node as HTMLElement).dataset.glowPreset,
- label: node.getAttribute('aria-label'),
- pressed: node.getAttribute('aria-pressed'),
- ball: getComputedStyle(node.querySelector('[data-glow-ball]')!).backgroundImage,
- })));
- const inSettings = await chips('#homeGlowControls');
- assert.ok(inSettings.length >= 2, '设置里没有预设色块');
- assert.deepEqual(inSettings, await chips('#boardGlowMenu'), '设置里的预设色块和侧栏配色卡不是同一组');
- const size = await grid.locator('[data-glow-ball]').first().evaluate((node) => node.getBoundingClientRect().width);
- assert.equal(size, 28, '设置里的色块和侧栏那一枚不是同一副尺寸');
- /* 设置这一行有整块设置那么宽:列数跟着可用宽度走,每格就是一枚球,挨着排满再换行,
- 间距与侧栏那条 `[data-glow-grid]` 同一个值;侧栏那张卡仍是六列。 */
- const gridStyle = (root: string) => opened.page.locator(`${root} [data-glow-grid]`).evaluate((node) => {
- const style = getComputedStyle(node);
- return { tracks: style.gridTemplateColumns, gap: style.columnGap, inline: style.paddingLeft };
- });
- const swatchLayout = () => grid.evaluate((node) => {
- const box = node.getBoundingClientRect();
- const chips = [...node.querySelectorAll('[data-glow-preset]')].map((chip) => chip.getBoundingClientRect());
- const firstTop = chips[0]!.top;
- return {
- count: chips.length,
- firstRow: chips.filter((chip) => chip.top === firstTop).length,
- rows: new Set(chips.map((chip) => chip.top)).size,
- steps: chips.slice(1).filter((chip) => chip.top === firstTop).map((chip, index) => chip.left - chips[index]!.left),
- startsAt: chips[0]!.left - box.left,
- overflow: node.scrollWidth > node.clientWidth || chips.some((chip) => chip.right > box.right + 0.5),
- viewportOverflow: document.documentElement.scrollWidth > document.documentElement.clientWidth,
- };
- });
- const settingsGrid = await gridStyle('#homeGlowControls');
- const sidebarGrid = await gridStyle('#boardGlowMenu');
- assert.ok(settingsGrid.tracks.split(' ').every((track) => track === '28px'), '设置里的色块每格不是一枚球的宽度');
- assert.equal(settingsGrid.gap, sidebarGrid.gap, '设置里的色块间距和侧栏配色卡不同');
- assert.equal(settingsGrid.inline, '0px', '设置里的色块没有从这一行的内容左缘起');
- // 侧栏配色卡此刻收着,计算值停在声明式 `repeat(6, 1fr)`;展开时是六个解析后的宽度。
- assert.ok(sidebarGrid.tracks === 'repeat(6, 1fr)' || sidebarGrid.tracks.split(' ').length === 6,
- `侧栏配色卡不再是每行六枚:${sidebarGrid.tracks}`);
- const wide = await swatchLayout();
- assert.ok(wide.firstRow > 6, `桌面宽度下第一行只排了 ${wide.firstRow} 枚,右边的空间没用上`);
- assert.ok(wide.steps.every((step) => step === 34), `设置里的色块没有挨着排:步长 ${wide.steps.join('/')}`);
- assert.equal(wide.startsAt, 0, '设置里的第一枚色块没有从这一行的内容左缘起');
- assert.equal(wide.overflow, false, '桌面宽度下色块越出了这一行');
- assert.equal(await grid.getAttribute('role'), 'group');
- assert.ok(await grid.getAttribute('aria-label'), '预设色块那一组没有无障碍名称');
-
- const target = inSettings.find((chip) => chip.pressed === 'false')!;
- const chip = grid.locator(`[data-glow-preset="${target.key}"]`);
- await chip.focus();
- await opened.page.keyboard.press('Space');
- await opened.page.waitForFunction((key) => document.querySelector(
- `#homeGlowControls [data-glow-preset="${key}"]`)?.getAttribute('aria-pressed') === 'true', target.key);
- assert.equal(await grid.locator('[aria-pressed="true"]').count(), 1);
- assert.equal(await opened.page.evaluate(() => (document.activeElement as HTMLElement | null)?.dataset.glowPreset
- && document.activeElement!.closest('#homeGlowControls [data-glow-grid]') ? (document.activeElement as HTMLElement).dataset.glowPreset : null),
- target.key, '选完之后焦点离开了刚选的那一枚色块');
- assert.equal(await opened.page.locator(`#boardGlowMenu [data-glow-preset="${target.key}"]`)
- .getAttribute('aria-pressed'), 'true', '侧栏配色卡没有跟着换到同一档');
- assert.equal(await opened.page.locator('#homeGlowControls [data-glow-preset-name]').textContent(), target.label);
- assert.equal(await opened.page.evaluate(() => JSON.parse(localStorage.getItem('peach.settings.v1')!).homeGlow.preset),
- target.key, '选中的那一档没有写进设置');
-
- await opened.page.setViewportSize({ width: MOBILE.width, height: MOBILE.height });
- await grid.waitFor({ state: 'visible', timeout: 10_000 });
- const narrow = await swatchLayout();
- assert.ok(narrow.firstRow < narrow.count && narrow.rows > 1, `${MOBILE.width}px 下色块没有换行`);
- assert.ok(narrow.steps.every((step) => step === 34), `${MOBILE.width}px 下色块没有挨着排`);
- assert.equal(narrow.startsAt, 0, `${MOBILE.width}px 下第一枚色块没有从内容左缘起`);
- assert.equal(narrow.overflow, false, `${MOBILE.width}px 下色块越出了这一行`);
- assert.equal(narrow.viewportOverflow, false, `${MOBILE.width}px 下页面出现横向溢出`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- /* ADR-0050:设置弹层只放一行一个值、改完就生效的控件;带「保存配置」的表单在配置页,
- 要确认、要看进度的长任务在数据管理页,订阅源在关注管理页。 */
- it('设置弹层「这台电脑」只有摘要卡,按钮直达配置页;媒体修复与订阅源都不在设置和配置页里', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', DESKTOP);
- try {
- const { page } = opened;
- await settle(page);
- await page.locator('#settingsBtn').click();
- const panel = page.locator('#settingsPanel');
- await panel.getByRole('tab', { name: '这台电脑' }).click({ timeout: 10_000 });
- const machine = panel.locator('#machineSettings');
- const go = machine.getByRole('button', { name: '打开配置页', exact: true });
- await go.waitFor({ state: 'visible', timeout: 10_000 });
- assert.deepEqual(await machine.locator('dt').allTextContents(), ['媒体库', '端口', '更新']);
- assert.equal(await machine.locator('input, textarea, select, form, [role="switch"], [aria-haspopup="listbox"]').count(), 0,
- '摘要卡里出现了可编辑的控件');
- assert.equal(await panel.locator('.configpage').count(), 0, '设置弹层里又挂了一份配置页');
- for (const text of ['媒体修复', '订阅源', '保持登录时间']) {
- assert.equal(await panel.getByText(text, { exact: true }).count(), 0, `设置弹层里还有「${text}」`);
- }
-
- await go.click();
- await expectBody(page, '/configuration', configurationBody(page));
- assert.equal(new URL(page.url()).pathname, '/configuration');
- assert.equal(await panel.isHidden(), true, '去配置页之后设置弹层没有关');
- await settle(page);
- for (const text of ['媒体修复', '订阅源']) {
- assert.equal(await page.locator('#stats').getByText(text, { exact: true }).count(), 0, `配置页上还有「${text}」`);
- }
- const entry = page.locator('[data-manage-bar] [data-manage="configuration"]');
- await entry.waitFor({ state: 'attached', timeout: 10_000 });
- assert.equal(await entry.getAttribute('aria-pressed'), 'true', '管理菜单里的「配置」没有标成当前页');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- /* 设置面板:盖住整页的弹层与作品详情浮窗同一档遮罩、同一组进出场;遮罩不带模糊,值只来自 `--scrim`。
- 动效要真跑起来才读得到关键帧名,这一条自建不减动态的上下文。 */
- it('设置面板的遮罩取 --scrim、不带模糊、压在最顶层,卡片用弹层那一组关键帧进出', { timeout: 60_000 }, async () => {
- const context = await browser.newContext({ viewport: { width: DESKTOP.width, height: DESKTOP.height } });
- await context.addInitScript(() => localStorage.setItem('peach.settings.v1', JSON.stringify({ detailAutoplay: false })));
- try {
- const page = await context.newPage();
- await stubServer(page);
- await page.goto(`${requiredEnv('PEACH_E2E_ORIGIN')}/`, { waitUntil: 'load' });
- await settle(page);
- await openPanel(page);
- const scrim = await tokenColor(page, 'body', '--scrim');
- const shown = await page.locator(PANEL).evaluate((panel) => {
- const style = getComputedStyle(panel);
- const card = getComputedStyle(panel.querySelector('[data-settings-card]')!);
- return {
- position: style.position, z: style.zIndex, inset: [style.top, style.right, style.bottom, style.left],
- layer: getComputedStyle(document.documentElement).getPropertyValue('--layer-dialog').trim(),
- face: style.backgroundColor, blur: [style.backdropFilter, card.backdropFilter],
- backdrop: [style.animationName, style.animationFillMode], card: [card.animationName, card.animationFillMode],
- padding: [style.paddingTop, style.paddingBottom],
- };
- });
- assert.equal(shown.position, 'fixed');
- assert.equal(shown.z, shown.layer, '设置遮罩不在 --layer-dialog 那一层');
- assert.deepEqual(shown.inset, ['0px', '0px', '0px', '0px'], '设置遮罩没有铺满视口');
- assert.equal(shown.face, scrim, '设置遮罩的颜色不是 --scrim');
- assert.deepEqual(shown.blur, ['none', 'none'], '设置遮罩或卡片带了模糊');
- assert.deepEqual(shown.backdrop, ['settings-backdrop-in', 'both']);
- // 进场填 `backwards`:终点帧留下的 filter 会另起一个 backdrop root,左栏玻璃就只采样得到卡片自己。
- assert.deepEqual(shown.card, ['board-dialog-in', 'backwards']);
- /* 安全区内边距让开刘海与 Home 指示条;桌面上没有安全区,两端都是 18px 的底。 */
- assert.deepEqual(shown.padding, ['18px', '18px']);
-
- const leaving = await page.locator(PANEL).evaluate((panel) => {
- (panel.querySelector('#settingsClose') as HTMLButtonElement).click();
- const card = getComputedStyle(panel.querySelector('[data-settings-card]')!);
- return { backdrop: getComputedStyle(panel).animationName, card: [card.animationName, card.animationFillMode] };
- });
- assert.equal(leaving.backdrop, 'settings-backdrop-out');
- // 退场要 `both`:终点(透明)不是元素的自然状态。
- assert.deepEqual(leaving.card, ['board-dialog-out', 'both']);
- await page.locator(PANEL).waitFor({ state: 'hidden', timeout: 5_000 });
- } finally {
- await context.close();
- }
- });
-
- it('设置面板的标题栏占满右栏、压在滚动区上面,滚过那段留白才投下左栏玻璃那道影子', { timeout: 60_000 }, async () => {
- const opened = await openHome(browser);
- const { page } = opened;
- try {
- await openPanel(page);
- const shadow = await page.locator(`${PANEL} [data-settings-card]`).evaluate((card) => {
- const probe = document.createElement('div');
- probe.style.boxShadow = 'var(--glass-shadow)';
- card.append(probe);
- const value = getComputedStyle(probe).boxShadow;
- probe.remove();
- return value;
- });
- const read = () => page.locator(PANEL).evaluate((panel) => {
- const head = panel.querySelector('[data-settings-head]')!, scroll = panel.querySelector('[data-settings-scroll]')!;
- const top = head.getBoundingClientRect(), body = scroll.getBoundingClientRect(), style = getComputedStyle(scroll);
- return {
- head: [top.left, top.width, top.bottom], body: [body.left, body.width, body.top],
- z: getComputedStyle(head).zIndex, shadow: getComputedStyle(head).boxShadow, clip: getComputedStyle(head).clipPath,
- overflow: style.overflowY, overscroll: style.overscrollBehaviorY, gap: style.paddingTop,
- };
- });
- const resting = await read();
- assert.deepEqual(resting.head.slice(0, 2), resting.body.slice(0, 2), '标题栏和滚动区不是同一列同一宽');
- assert.ok(resting.head[2]! <= resting.body[2]! + 0.5, '标题栏没有压在滚动区上面');
- assert.equal(resting.z, '2');
- assert.equal(resting.overflow, 'auto');
- assert.equal(resting.overscroll, 'contain', '滚到底之后滚动会漏给背后的页面');
- assert.equal(resting.shadow, 'none', '还没滚动标题栏就投了影');
- // 影子只要往下那一半:往上会糊在标题自己头上、往左会糊到左栏上。
- assert.equal(resting.clip, 'inset(0px 0px -96px)');
-
- await page.locator(`${PANEL} [data-settings-scroll]`).evaluate((scroll) => { scroll.scrollTop = 4 });
- await page.waitForTimeout(100);
- assert.equal((await read()).shadow, 'none', `滚动量还没过 ${resting.gap} 的留白标题栏就投了影`);
- await page.locator(`${PANEL} [data-settings-scroll]`).evaluate((scroll) => { scroll.scrollTop = 80 });
- await page.waitForFunction((want) => getComputedStyle(
- document.querySelector('#settingsPanel [data-settings-head]')!).boxShadow === want, shadow);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('设置面板左栏当前项自己不铺底,那块玻璃跟着指针走、离开这一列回到当前项', { timeout: 60_000 }, async () => {
- const opened = await openHome(browser);
- const { page } = opened;
- try {
- await openPanel(page);
- const nav = page.locator(`${PANEL} [data-settings-nav]`);
- const glide = () => nav.locator('[data-settings-glide]').evaluate((node) => Math.round(node.getBoundingClientRect().top));
- const top = (name: string) => nav.getByRole('tab', { name, exact: true })
- .evaluate((node) => Math.round(node.getBoundingClientRect().top));
- const selected = await nav.getByRole('tab', { name: '界面', exact: true }).evaluate((node) => {
- const style = getComputedStyle(node), icon = getComputedStyle(node.querySelector('svg')!);
- return { face: style.backgroundColor, ring: style.boxShadow, icon: [icon.width, icon.height, icon.fill === style.color, icon.stroke] };
- });
- assert.equal(selected.face, 'rgba(0, 0, 0, 0)', '当前项自己铺了底,滑动的那块玻璃被盖住');
- assert.equal(selected.ring, 'none');
- // Remix 的线条是 `fill` 画出的轮廓,全站默认的 `stroke:currentColor;fill:none` 会让它整枚消失。
- assert.deepEqual(selected.icon, ['20px', '20px', true, 'none']);
- assert.equal(await glide(), await top('界面'), '玻璃没有落在当前项上');
-
- await nav.getByRole('tab', { name: '播放', exact: true }).hover();
- const target = await top('播放');
- await page.waitForFunction(([want]) => Math.round(document.querySelector(
- '#settingsPanel [data-settings-glide]')!.getBoundingClientRect().top) === want, [target]);
- assert.equal(await nav.getByRole('tab', { name: '界面', exact: true }).getAttribute('aria-selected'), 'true',
- '指针移上去就换了分区');
- await page.locator(`${PANEL} [data-settings-scroll]`).hover();
- const home = await top('界面');
- await page.waitForFunction(([want]) => Math.round(document.querySelector(
- '#settingsPanel [data-settings-glide]')!.getBoundingClientRect().top) === want, [home]);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('设置面板的分组是 --ground 圆角面,开关、主题分段与关闭键各是一副尺寸,窄屏下开关不换行', { timeout: 60_000 }, async () => {
- for (const viewport of [DESKTOP, MOBILE]) {
- const opened = await openHome(browser, viewport);
- const { page } = opened;
- try {
- await openPanel(page);
- const ground = await tokenColor(page, PANEL, '--ground');
- const shown = await page.locator(PANEL).evaluate((panel) => {
- const box = (node: Element) => {
- const rect = node.getBoundingClientRect();
- return [Math.round(rect.width), Math.round(rect.height)];
- };
- const group = getComputedStyle(panel.querySelector('[data-setting-group]:not([hidden])')!);
- const toggles = [...panel.querySelectorAll('[data-setting-group]:not([hidden]) [data-toggle]')];
- const on = panel.querySelector('#uiSoundsSetting')!, row = on.closest('[data-setting-row]')!;
- const title = row.querySelector('b')!.getBoundingClientRect(), knob = on.getBoundingClientRect();
- const close = panel.querySelector('#settingsClose')!;
- return {
- group: [group.backgroundColor, group.borderTopLeftRadius],
- toggles: [...new Set(toggles.map((node) => box(node).join('×')))],
- toggleOnRow: knob.top < title.bottom && knob.left > title.right,
- theme: [...panel.querySelectorAll('#themeSetting label')].map((node) => box(node).join('×')),
- themeIcon: box(panel.querySelector('#themeSetting svg')!).join('×'),
- close: [box(close).join('×'), getComputedStyle(close).borderTopLeftRadius, getComputedStyle(close).paddingLeft],
- };
- });
- assert.deepEqual(shown.group, [ground, '16px'], `${viewport.name}:分组不是 --ground 的 16px 圆角面`);
- assert.deepEqual(shown.toggles, ['42×24'], `${viewport.name}:开关不是同一副 42×24`);
- // 开关只有 42px,跟标题同一行绰绰有余;跟着换行只是白占一行高度。
- assert.equal(shown.toggleOnRow, true, `${viewport.name}:开关没有留在标题那一行`);
- assert.deepEqual(shown.theme, ['32×32', '32×32', '32×32'], `${viewport.name}:主题三档不是 32px 的圆`);
- assert.equal(shown.themeIcon, '16×16');
- assert.deepEqual(shown.close, ['24×24', '50%', '0px'], `${viewport.name}:关闭键不是 24px 的圆钮`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- }
- });
-
- it('侧栏排序的添加行:触发器与「添加」同高 --control-h,「添加」是主按钮,候选用完时触发器给禁止光标', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', DESKTOP);
- const { page } = opened;
- try {
- const server = await stubServer(page);
- await page.reload({ waitUntil: 'load' });
- await settle(page);
- await openPanel(page);
- const row = page.locator(`${PANEL} [data-sidebar-add-row]`);
- await row.scrollIntoViewIfNeeded();
- const shown = await row.evaluate((node) => {
- const probe = document.createElement('div');
- probe.style.height = 'var(--control-h)';
- node.append(probe);
- const height = getComputedStyle(probe).height;
- probe.remove();
- const primary = document.createElement('button');
- primary.className = 'geist-button primary';
- document.body.append(primary);
- const want = getComputedStyle(primary);
- const expected = [want.backgroundColor, want.backgroundImage, want.color];
- primary.remove();
- const trigger = node.querySelector('[data-sidebar-add-trigger]')!, add = node.querySelector('[data-sidebar-add]')!;
- const face = getComputedStyle(add);
- return {
- height, trigger: getComputedStyle(trigger).height, add: face.height,
- face: [face.backgroundColor, face.backgroundImage, face.color], expected,
- cursor: getComputedStyle(trigger).cursor,
- };
- });
- assert.equal(shown.trigger, shown.height, '添加行的触发器没有引用 --control-h');
- assert.equal(shown.add, shown.height, '「添加」没有引用 --control-h');
- assert.deepEqual(shown.face, shown.expected, '「添加」没有穿主按钮那一身');
- assert.equal(shown.cursor, 'pointer');
-
- /* 一项一项加回去,直到清单里没有可加的入口。 */
- const add = row.locator('[data-sidebar-add]'), trigger = row.locator('[data-sidebar-add-trigger]');
- for (let left = 30; left > 0 && await add.isEnabled(); left -= 1) await add.click();
- assert.equal(await trigger.isDisabled(), true, '全部入口都加回侧栏之后触发器还能点');
- assert.ok((server.settings.sidebarOrder as string[]).length > ORDER.length, '加回的入口没有写进账本');
- assert.equal(await trigger.evaluate((node) => getComputedStyle(node).cursor), 'not-allowed',
- '没有可添加的入口时触发器还是普通光标');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- /* 「关注自动更新」在这台机器上不可用时,开着的那颗开关也被禁:轨道得读成灰的,不能还留着那抹蓝。 */
- it('开着又被禁的开关是灰轨道加禁止光标,跟开着能点的那颗分得开', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', DESKTOP);
- const { page } = opened;
- try {
- const server = await stubServer(page);
- server.schedule.available = false;
- await page.reload({ waitUntil: 'load' });
- await settle(page);
- await openPanel(page, '关注');
- const blocked = page.locator(`${PANEL} #followScheduleSetting [data-toggle]`);
- await blocked.and(page.locator(':disabled:checked')).waitFor({ state: 'attached', timeout: 10_000 });
- const surface = await tokenColor(page, PANEL, '--surface');
- const face = (node: Element) => {
- const style = getComputedStyle(node);
- return { face: style.backgroundColor, knob: getComputedStyle(node, '::before').backgroundImage, cursor: style.cursor };
- };
- const grey = await blocked.evaluate(face);
- const live = await page.locator(`${PANEL} #uiSoundsSetting`).evaluate(face);
- assert.equal(grey.face, surface, '被禁的开关轨道不是 --surface');
- assert.equal(grey.cursor, 'not-allowed');
- assert.notDeepEqual([grey.face, grey.knob], [live.face, live.knob], '被禁的开关和能点的开着那颗长得一样');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('光晕参数块自己让出分组右侧的留白、下边距与设置行同一档;「玻璃原色」那一档只留漂移速度', { timeout: 60_000 }, async () => {
- for (const viewport of [DESKTOP, MOBILE]) {
- const opened = await openHome(browser, viewport);
- const { page } = opened;
- try {
- await openPanel(page);
- const block = page.locator(`${PANEL} [data-glow-setting]`);
- await block.waitFor({ state: 'visible', timeout: 10_000 });
- const shown = await block.evaluate((node) => {
- const group = node.closest('[data-setting-group]')!.getBoundingClientRect(), rect = node.getBoundingClientRect();
- const row = node.parentElement!.querySelector('[data-setting-row]')!;
- return {
- right: Math.round(group.right - rect.right), left: rect.left >= group.left,
- overflow: node.scrollWidth > node.clientWidth,
- pad: getComputedStyle(node).paddingBottom, rowPad: getComputedStyle(row).paddingBottom,
- };
- });
- assert.ok(shown.right >= 16 && shown.left, `${viewport.name}:参数块压到了分组的圆角上(右侧只剩 ${shown.right}px)`);
- assert.equal(shown.overflow, false, `${viewport.name}:参数块被内容顶宽`);
- assert.equal(shown.pad, shown.rowPad, `${viewport.name}:参数块的下边距和上面每一行不是同一档`);
-
- await block.locator('[data-glow-preset="native"]').click();
- await block.locator('[data-glow-native-note]').waitFor({ state: 'visible', timeout: 5_000 });
- const fields = await block.locator('[data-glow-field]').evaluateAll((nodes) => nodes
- .filter((node) => node.getClientRects().length > 0).map((node) => (node as HTMLElement).dataset.glowField));
- assert.deepEqual(fields, ['speed'], `${viewport.name}:「玻璃原色」下还摆着管不着任何东西的拉条`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- }
- });
-
- it('统计页选中的读数卡:2px 描边压在脚注带上面、圆角跟卡走,接触阴影收掉', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/stats', DESKTOP);
- try {
- const page = opened.page;
- const tab = page.locator('#stats [role="tab"][data-selected]').first();
- await tab.waitFor({ timeout: 15_000 });
- await settle(page);
- const ring = await tokenColor(page, '.peach-react', '--color-border-focus-ring');
- const shown = await tab.evaluate((element) => {
- const card = getComputedStyle(element);
- const after = getComputedStyle(element, '::after');
- const footer = element.querySelector('small')!;
- const other = document.querySelector('#stats [role="tab"]:not([data-selected])')!;
- // `shadow-none` 是五层透明的 0px,不是字面的 none:看有没有一层带颜色。
- const shadowVisible = [...card.boxShadow.matchAll(/rgba?\([^)]*\)/g)]
- .some((match) => !/, 0\)$/.test(match[0]));
- return {
- shadowVisible, position: card.position, radius: card.borderRadius,
- after: {
- content: after.content, position: after.position, width: after.borderTopWidth,
- color: after.borderTopColor, radius: after.borderRadius, z: after.zIndex,
- inset: [after.top, after.right, after.bottom, after.left],
- },
- footerFace: getComputedStyle(footer).backgroundColor,
- otherAfter: getComputedStyle(other, '::after').content,
- };
- });
- assert.equal(shown.shadowVisible, false, '选中的卡还压着接触阴影');
- assert.equal(shown.position, 'relative');
- assert.equal(shown.after.content, '""', '选中的卡没有画覆盖层');
- assert.equal(shown.after.position, 'absolute');
- assert.deepEqual(shown.after.inset, ['0px', '0px', '0px', '0px'], '覆盖层没有铺满整张卡');
- assert.deepEqual([shown.after.width, shown.after.color], ['2px', ring], '描边不是 2px 焦点环色');
- assert.equal(shown.after.radius, shown.radius, '覆盖层圆角和卡不一致');
- assert.ok(Number(shown.after.z) >= 1, `覆盖层 z-index ${shown.after.z},会被脚注带盖住`);
- assert.notEqual(shown.footerFace, 'rgba(0, 0, 0, 0)', '脚注带没有底色,这条用例守的就是环压在它上面');
- assert.equal(shown.otherAfter, 'none', '没选中的卡也画了覆盖层');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('索引页容器不横向裁剪:筛选玻璃左右两侧的影洒得出来,页面也不横向溢出', { timeout: 60_000 }, async () => {
- const opened = await openIndexPage(browser, '/tags');
- try {
- const page = opened.page;
- const clip = await page.evaluate(() => {
- const index = document.querySelector('#index')!;
- return {
- overflow: getComputedStyle(index).overflowX,
- spill: document.documentElement.scrollWidth - document.documentElement.clientWidth,
- };
- });
- assert.equal(clip.overflow, 'visible', '#index 横向裁剪,玻璃左右两侧的影被切成直边');
- assert.equal(clip.spill, 0, '不裁剪后页面被撑出横向滚动');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('标签页骨架里就铺着那块筛选玻璃,React 落地时玻璃与开头那组内容都留在原位', { timeout: 60_000 }, async () => {
- /* 骨架与真页面各量一遍:玻璃的位置与大小、开头那组内容的上沿。药丸、读数与首字要等数据,
- 骨架里是占位;视图切换此刻就是最终那一档。 */
- const opened = await visit(browser, '/tags', DESKTOP);
- try {
- const page = opened.page;
- await page.route('**/api/index?**', (route) => route.fulfill({
- status: 200, contentType: 'application/json',
- body: JSON.stringify({ items: [{ k: '痴女', n: 4, cat: 'role' }, { k: '秘书OL', n: 2, cat: 'scene' }],
- has_more: false, categories: { role: 1, scene: 1 } }),
- }));
- const release = await holdApi(page);
- await page.reload({ waitUntil: 'load' });
- await page.locator('#index [data-skeleton^="index/tags/"]').waitFor({ timeout: 15_000 });
- const measure = (glass: string, group: string, view: string) => page.evaluate(([glassSelector, groupSelector, viewSelector]) => {
- const rect = (selector: string) => {
- const box = document.querySelector(selector)?.getBoundingClientRect();
- return box ? { top: box.top, left: box.left, width: box.width, height: box.height } : null;
- };
- return { glass: rect(glassSelector), group: rect(groupSelector),
- pills: document.querySelectorAll(`${glassSelector} [data-filter-row="top"] > *`).length,
- view: rect(`${glassSelector} [data-filter-row="bottom"] ${viewSelector}`) };
- }, [glass, group, view] as const);
- const skeleton = await measure('#index .board-filter-frame', '#index [data-skeleton] .alphagroup', '.iconswitch');
- release();
- await page.locator('#index [data-alphabet]').waitFor({ timeout: 15_000 });
- await settle(page);
- const live = await measure('#index [data-filter-glass]', '#index [data-alpha-group]', '[aria-label="标签视图"]');
- assert.ok(skeleton.glass && skeleton.group && skeleton.view, '标签页骨架里缺筛选玻璃、开头那组或视图切换');
- assert.ok(skeleton.pills > 0, '骨架玻璃的上排没有铺药丸占位');
- assert.ok(live.glass && live.group && live.view, '接管后找不到筛选玻璃、开头那组或视图切换');
- for (const key of ['top', 'left', 'width', 'height'] as const) {
- assert.ok(Math.abs(skeleton.glass![key] - live.glass![key]) <= 1,
- `筛选玻璃的 ${key} 接管时跳了:骨架 ${skeleton.glass![key]},接管后 ${live.glass![key]}`);
- }
- assert.ok(Math.abs(skeleton.group!.top - live.group!.top) <= 1,
- `开头那组内容的上沿接管时跳了:骨架 ${skeleton.group!.top},接管后 ${live.group!.top}`);
- assert.ok(Math.abs(skeleton.view!.top - live.view!.top) <= 1 && Math.abs(skeleton.view!.left - live.view!.left) <= 1,
- `视图切换接管时挪了位:骨架 (${skeleton.view!.left}, ${skeleton.view!.top}),接管后 (${live.view!.left}, ${live.view!.top})`);
- } finally {
- await opened.close();
- }
- });
-
- for (const viewport of VIEWPORTS) {
- it(`首页吸顶筛选条的上沿在深浅主题中保持透明(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openHome(browser, viewport);
- try {
- const page = opened.page;
- await page.evaluate(() => document.body.insertAdjacentHTML('beforeend', '<div style="height:200vh"></div>'));
- await page.evaluate(() => window.scrollTo(0, 600));
- await page.waitForFunction(() => document.querySelector('[data-filter-glass]')?.hasAttribute('data-stuck'));
- for (const theme of ['light', 'dark']) {
- const style = await page.evaluate(value => {
- document.documentElement.dataset.theme = value;
- const filter = document.querySelector('[data-filter-glass]')!;
- return { content: getComputedStyle(filter, '::before').content, shadow: getComputedStyle(filter).boxShadow };
- }, theme);
- assert.equal(style.content, 'none');
- assert.match(style.shadow, /inset/);
- await page.locator('[data-filter-glass]').screenshot({ path: `../build/sticky-${viewport.name}-${theme}.png` });
- }
- assert.deepEqual(opened.problems, []);
- } finally { await opened.close(); }
- });
- }
-
- it('筛选玻璃吸顶使用抬起阴影,深浅主题的上沿保持透明间隙', { timeout: 60_000 }, async () => {
- const opened = await openIndexPage(browser, '/tags');
- try {
- const page = opened.page;
- const read = () => page.evaluate(() => {
- const glass = document.querySelector('[data-filter-glass]')!;
- const root = getComputedStyle(document.documentElement);
- return {
- stuck: glass.hasAttribute('data-stuck'),
- shadow: getComputedStyle(glass).boxShadow,
- strip: getComputedStyle(glass, '::before'),
- lift: root.getPropertyValue('--glass-lift'),
- rest: root.getPropertyValue('--glass-shadow'),
- };
- });
- const readStrip = () => page.evaluate(() => {
- const strip = getComputedStyle(document.querySelector('[data-filter-glass]')!, '::before');
- return { content: strip.content, top: strip.top, height: strip.height, z: strip.zIndex, mask: strip.maskImage };
- });
- const resting = await read();
- assert.equal(resting.stuck, false, '还没滚就标成吸顶');
- assert.equal(farthestShadow(resting.shadow), farthestShadow(resting.rest), '静止态的影不是 --glass-shadow');
- assert.equal((await readStrip()).content, 'none', '静止态就画了遮带');
- // 桩数据只有两枚标签,页面不够长滚不动:垫一块高度再滚。
- await page.evaluate(() => document.body.insertAdjacentHTML('beforeend', '<div style="height:200vh"></div>'));
- await page.evaluate(() => window.scrollTo(0, 600));
- await page.waitForFunction(() => document.querySelector('[data-filter-glass]')!.hasAttribute('data-stuck'),
- undefined, { timeout: 5_000 });
- const stuck = await read();
- const strip = await readStrip();
- assert.equal(farthestShadow(stuck.shadow), farthestShadow(stuck.lift), '吸顶后的影不是 --glass-lift');
- assert.ok(farthestShadow(stuck.shadow) > farthestShadow(resting.shadow), '吸顶后影没有抬起来');
- assert.match(stuck.shadow, /inset/, '吸顶后四条内嵌 rim 线丢了');
- assert.equal(strip.content, 'none');
- for (const theme of ['light', 'dark']) {
- await page.evaluate(value => { document.documentElement.dataset.theme = value }, theme);
- assert.equal((await readStrip()).content, 'none', `${theme} 主题的吸顶上沿存在遮带`);
- }
- await page.evaluate(() => window.scrollTo(0, 0));
- await page.waitForFunction(() => !document.querySelector('[data-filter-glass]')!.hasAttribute('data-stuck'),
- undefined, { timeout: 5_000 });
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('图片灯箱:竖图按高度整张收进视口,上下让出工具条与缩略图条,左右让出翻页键', { timeout: 60_000 }, async () => {
- const opened = await openLightbox(browser, { count: 3, width: 1200, height: 4000 });
- try {
- const read = await opened.page.evaluate(() => {
- const rect = (selector: string) => document.querySelector(selector)!.getBoundingClientRect().toJSON() as DOMRect;
- return { img: rect('[data-photo-main] .swiper-slide-active img'), bar: rect('[data-photo-bar]'),
- strip: rect('[data-photo-strip]'), back: rect('[data-photo-nav="back"]'), viewport: innerHeight };
- });
- const { img } = read;
- assert.ok(img.top >= 24 - .5 && img.bottom <= read.viewport - 148 + .5, `大图越出了上下安全区:${img.top}–${img.bottom}`);
- assert.ok(Math.abs(img.width / img.height - 1200 / 4000) < .01, `竖图被拉变形:${img.width}×${img.height}`);
- assert.ok(Math.abs(img.left + img.width / 2 - DESKTOP.width / 2) <= 1, '大图没有水平居中');
- assert.ok(read.bar.bottom <= read.strip.top, '工具条压到了缩略图条上');
- assert.equal(Math.round(read.viewport - read.strip.bottom), 14);
- assert.ok(read.back.right <= 72, '翻页键伸进了图片那一栏');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('图片灯箱只有一张时不画缩略图条、页码点和翻页键,底部空间还给图片', { timeout: 60_000 }, async () => {
- const opened = await openLightbox(browser, { count: 1, width: 4000, height: 3000 });
- try {
- const read = await opened.page.evaluate(() => {
- const style = (selector: string) => getComputedStyle(document.querySelector(selector)!);
- return {
- strip: style('[data-photo-strip]').display,
- nav: [...document.querySelectorAll('[data-photo-nav]')].map((button) => getComputedStyle(button).display),
- pagination: document.querySelectorAll('[data-photo-pagination]').length,
- padding: style('[data-photo-main] .swiper-zoom-container').paddingBottom,
- count: document.querySelector('[data-photo-count]')!.textContent,
- };
- });
- assert.deepEqual(read, { strip: 'none', nav: ['none', 'none'], pagination: 0, padding: '76px', count: '1 / 1' });
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('灯箱圆钮:图标压在圆心,线头是圆的、不填充;前进那枚是同一枚箭头转半圈,到头那枚让开', { timeout: 60_000 }, async () => {
- const opened = await openLightbox(browser, { count: 3, width: 4000, height: 3000 });
- try {
- const read = await opened.page.evaluate(() => [
- '[data-photo-close]', '[data-photo-nav="back"]', '[data-photo-nav="fwd"]', '[data-photo-detail-toggle]',
- ].map((selector) => {
- const button = document.querySelector(selector)!, svg = button.querySelector('svg')!;
- const outer = button.getBoundingClientRect(), inner = svg.getBoundingClientRect(), style = getComputedStyle(svg);
- return {
- selector, glyph: svg.querySelector('use')?.getAttribute('href'),
- off: Math.max(Math.abs(outer.left + outer.width / 2 - inner.left - inner.width / 2),
- Math.abs(outer.top + outer.height / 2 - inner.top - inner.height / 2)),
- fill: style.fill, cap: style.strokeLinecap, turn: style.transform,
- visibility: getComputedStyle(button).visibility,
- };
- }));
- for (const icon of read) {
- assert.ok(icon.off <= .5, `${icon.selector} 的图标偏离圆心 ${icon.off}px`);
- assert.equal(icon.fill, 'none', `${icon.selector} 的描边图标被填实了`);
- // Lucide 的 info 圆点是长度 .01 的短线,没有圆头就缩成看不见的一横。
- assert.equal(icon.cap, 'round', `${icon.selector} 的线头不是圆的`);
- }
- const [close, back, fwd, info] = read;
- assert.equal(close.glyph, '#i-x');
- assert.equal(info.glyph, '#i-info');
- assert.deepEqual([back.glyph, fwd.glyph], ['#i-chevron-left', '#i-chevron-left']);
- assert.equal(back.turn, 'none');
- assert.match(fwd.turn, /^matrix\(-1, /, '前进键的箭头没有转半圈');
- assert.deepEqual([back.visibility, fwd.visibility], ['hidden', 'visible'], '停在第一张时后退键该让开');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('关注页:标题 24px、窄屏 20px,药丸间距同首页 7px,读数用等宽字', { timeout: 90_000 }, async () => {
- const read = (page: Page) => page.evaluate(() => {
- const style = (selector: string) => getComputedStyle(document.querySelector(selector)!);
- return {
- title: style('[data-follow-title]').fontSize,
- gaps: ['[data-follow-filter-glass] [data-entity-states]', '[data-follow-filter-glass] [data-entity-tags]']
- .map((selector) => style(selector).columnGap),
- readout: style('[data-follow-readout]').fontFamily,
- };
- });
- const wide = await openFollowFeed(browser, '/follow', DESKTOP);
- try {
- const shown = await read(wide.page);
- assert.equal(shown.title, '24px');
- assert.deepEqual(shown.gaps, ['7px', '7px'], '关注页的药丸间距和首页那条不一样');
- assert.match(shown.readout, /Cascadia Mono|Consolas|monospace/, `读数不是等宽字:${shown.readout}`);
- assert.deepEqual(wide.problems, []);
- } finally {
- await wide.close();
- }
- const narrow = await openFollowFeed(browser, '/follow', MOBILE);
- try {
- assert.equal((await read(narrow.page)).title, '20px', '窄屏的关注标题没有收到 20px');
- assert.deepEqual(narrow.problems, []);
- } finally {
- await narrow.close();
- }
- });
-
- it('关注详情的翻页圆钮:48px 玻璃底、窄屏 44px;落在图片黑边的视觉中心,太窄才退回 16/10 的安全内距;圆点离底 18/12', { timeout: 90_000 }, async () => {
- const read = (page: Page) => page.evaluate(() => {
- const frame = document.querySelector<HTMLElement>('#stage [data-follow-detail-media="image"]')!;
- const next = frame.querySelector('[data-follow-image-arrow="next"]')!, style = getComputedStyle(next);
- const outer = frame.getBoundingClientRect(), box = next.getBoundingClientRect();
- const dots = frame.querySelector('[data-follow-image-dots]')!.getBoundingClientRect();
- // 桩里的图都是 600×800:object-fit:contain 之后左右各留一道黑边。
- const rendered = Math.min(outer.width, outer.height * 600 / 800);
- const gutter = (outer.width - rendered) / 2;
- return {
- size: [box.width, box.height], background: style.backgroundColor, blur: style.backdropFilter,
- inset: outer.right - box.right, gutter, dotsBottom: outer.bottom - dots.bottom,
- framed: frame.hasAttribute('data-framed'),
- ratio: getComputedStyle(frame.querySelector('[data-follow-detail-poster]')!).aspectRatio,
- };
- });
- const centered = (shown: { gutter: number; size: number[] }, safe: number) =>
- shown.gutter >= shown.size[0]! + safe * 2 ? (shown.gutter - shown.size[0]!) / 2 : safe;
- const wide = await openFollowFeed(browser, `/follow/item/${DETAIL.gallery}`, DESKTOP,
- { ready: '#stage [data-follow-image-arrow="next"]' });
- try {
- await wide.page.waitForFunction(() => (document.querySelector('#stage [data-follow-detail-poster]') as HTMLImageElement)?.complete);
- const shown = await read(wide.page);
- assert.deepEqual(shown.size, [48, 48]);
- assert.equal(shown.background, 'rgba(0, 0, 0, 0.6)');
- assert.equal(shown.blur, 'blur(16px)');
- assert.ok(Math.abs(shown.inset - centered(shown, 16)) <= 1, `箭头没落在黑边中心:${JSON.stringify(shown)}`);
- assert.ok(Math.abs(shown.dotsBottom - 18) <= .5, `圆点离底 ${shown.dotsBottom}px`);
- // 画框比例跟整组图走:换图时详情不忽高忽低。
- assert.equal(shown.framed, true);
- assert.match(shown.ratio, /^0\.75\b/);
- assert.deepEqual(wide.problems, []);
- } finally {
- await wide.close();
- }
- const narrow = await openFollowFeed(browser, `/follow/item/${DETAIL.gallery}`, MOBILE,
- { ready: '#stage [data-follow-image-arrow="next"]' });
- try {
- await narrow.page.waitForFunction(() => (document.querySelector('#stage [data-follow-detail-poster]') as HTMLImageElement)?.complete);
- const shown = await read(narrow.page);
- assert.deepEqual(shown.size, [44, 44]);
- assert.ok(Math.abs(shown.inset - centered(shown, 10)) <= 1, `窄屏箭头内距不对:${JSON.stringify(shown)}`);
- assert.ok(Math.abs(shown.dotsBottom - 12) <= .5, `窄屏圆点离底 ${shown.dotsBottom}px`);
- assert.deepEqual(narrow.problems, []);
- } finally {
- await narrow.close();
- }
- });
-
- it('关注详情:没有预览的那一格占 16:9;标签按来源记下的类型取 r34 色板,未知类型取中性灰', { timeout: 60_000 }, async () => {
- const opened = await openFollowFeed(browser, `/follow/item/${DETAIL.bare}`, DESKTOP,
- { ready: '#stage [data-follow-detail-tags]' });
- try {
- const page = opened.page;
- const shown = await page.evaluate(() => ({
- placeholder: getComputedStyle(document.querySelector('#stage [data-follow-detail-placeholder]')!).aspectRatio,
- tags: Object.fromEntries([...document.querySelectorAll<HTMLElement>('#stage [data-follow-tag]')].map((tag) =>
- [tag.dataset.followTag, getComputedStyle(tag).getPropertyValue('--tag-color').trim()])),
- }));
- assert.equal(shown.placeholder, '16 / 9');
- const muted = await tokenColor(page, '#stage [data-follow-detail]', '--muted');
- const unknown = await page.evaluate(() => {
- const tag = document.querySelector<HTMLElement>('#stage [data-follow-tag="odd"]')!;
- const probe = document.createElement('div');
- probe.style.backgroundColor = 'var(--tag-color)';
- tag.append(probe);
- const value = getComputedStyle(probe).backgroundColor;
- probe.remove();
- return value;
- });
- assert.deepEqual({ ...shown.tags, odd: unknown }, {
- ow: '#d675d6', tracer: '#68c76f', kou: '#e36c6c', solo: '#55a7ff', animated: '#f5a24a', odd: muted,
- });
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- /* 作品详情(`item-detail` 岛)。桩数据见 `item-fixture.ts`:普通那一条评了 3 星、两位出演、
- 一个厂牌一个系列,都带实体 id。桩里的片源没有正片,播放器那一条 VIDEOJS 错误不算。 */
- const withoutPlayer = (problems: string[]) => problems.filter((line) => !line.includes('VIDEOJS'));
-
- it('作品详情标题与评分:来源徽标站在标题第一行开头;整排星一种琥珀、评没评只看填不填,悬停预演到指针那一颗', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
- try {
- const page = opened.page;
- const title = await page.evaluate(() => {
- const text = document.querySelector('#stage [data-detail-title]')!;
- const badge = text.querySelector('[class~="srcbig"]')!;
- const style = getComputedStyle(badge);
- return {
- clamp: getComputedStyle(text).webkitLineClamp,
- first: text.firstElementChild === badge,
- badge: { display: style.display, width: style.width, height: style.height, gap: style.marginRight },
- tools: document.querySelector('#stage [data-title-tools]')!.getBoundingClientRect().top
- >= text.getBoundingClientRect().bottom - 0.5,
- };
- });
- assert.deepEqual(title, {
- clamp: '2', first: true, badge: { display: 'inline-grid', width: '17px', height: '28px', gap: '8px' }, tools: true,
- }, '徽标是行内块、随文字一起被两行折叠裁住;那排键自成一行排在标题下面');
-
- const stars = page.locator('#stage [data-rate]');
- const read = () => stars.evaluateAll((nodes) => nodes.map((node) => ({
- color: getComputedStyle(node).color, filled: getComputedStyle(node.querySelector('svg')!).fill !== 'none',
- })));
- const amber = await tokenColor(page, '#stage [data-item-detail]', '--rating');
- await page.mouse.move(0, 0);
- const rest = await read();
- assert.deepEqual(rest.map((star) => star.color), Array(5).fill(amber), '换色那一档在浅色主题下凑不出两级都成立的灰');
- assert.deepEqual(rest.map((star) => star.filled), [true, true, true, false, false]);
- await stars.nth(1).hover();
- const preview = await read();
- assert.deepEqual(preview.map((star) => star.color), Array(5).fill(amber));
- assert.deepEqual(preview.map((star) => star.filled), [true, true, false, false, false]);
- const edges = await page.evaluate(() => {
- const box = (selector: string) => document.querySelector(`#stage ${selector}`)!.getBoundingClientRect();
- return { stars: box('[data-rating-stars]').left, title: box('[data-detail-title]').left };
- });
- assert.equal(edges.stars, edges.title - 4, '26px 命中区里的星形靠右约 4px 起笔,这一排往左让回来');
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- it('作品详情身份区:各组按内容宽并排换行,名字行框容得下下伸部;系列是整行宽的图标链接,不是标签胶囊', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
- try {
- const page = opened.page;
- const shown = await page.evaluate(() => {
- const stage = document.querySelector('#stage')!;
- const primary = stage.querySelector('[data-identity-primary]')!;
- const width = primary.getBoundingClientRect().width;
- const name = getComputedStyle(stage.querySelector('[data-id-group="performer"] [data-id-name]')!);
- const series = stage.querySelector('[data-series-link]')!;
- const link = getComputedStyle(series);
- return {
- primary: [getComputedStyle(primary).display, getComputedStyle(primary).flexWrap],
- narrower: [...primary.querySelectorAll('[data-id-group]')].every((group) => group.getBoundingClientRect().width < width),
- name: { ratio: parseFloat(name.lineHeight) / parseFloat(name.fontSize), overflow: name.textOverflow, align: name.textAlign },
- cursor: getComputedStyle(stage.querySelector('[data-id-group="performer"] [data-id-cell]')!).cursor,
- face: getComputedStyle(stage.querySelector('[data-id-group="performer"] [data-id-face]')!).backgroundColor,
- series: {
- display: link.display, wrap: link.overflowWrap, border: link.borderTopWidth,
- full: Math.abs(series.getBoundingClientRect().width - series.parentElement!.getBoundingClientRect().width) < 0.5,
- },
- };
- });
- assert.deepEqual(shown.primary, ['flex', 'wrap']);
- assert.equal(shown.narrower, true, '组按内容宽,共演作品不会一组占满一行');
- assert.ok(shown.name.ratio >= 1.5, `名字行高 ${shown.name.ratio} 倍字号,拉丁字母的下伸部会被省略号那层 overflow 裁掉`);
- assert.deepEqual([shown.name.overflow, shown.name.align], ['ellipsis', 'left']);
- assert.equal(shown.cursor, 'pointer');
- assert.notEqual(shown.face, 'rgba(0, 0, 0, 0)', '没图的头像画首字盘');
- assert.deepEqual(shown.series, { display: 'flex', wrap: 'anywhere', border: '0px', full: true });
- await page.locator('#stage [data-series-link]').hover();
- const hovered = await page.locator('#stage [data-series-link]').evaluate((node) =>
- [getComputedStyle(node).color, getComputedStyle(node).textDecorationLine]);
- assert.deepEqual(hovered, [await tokenColor(page, '#stage [data-item-detail]', '--tungsten'), 'none']);
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- for (const viewport of VIEWPORTS) {
- it(`作品详情头像按有尺寸的圆框取景并显示(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, viewport);
- try {
- const page = opened.page;
- const base = await page.evaluate(() => fetch('/api/item?id=14').then((response) => response.json()));
- const payload = { ...base, performers: ['取景艺人', '无图艺人'],
- entity_refs: { ...base.entity_refs, performer: [
- { id: 3, name: '取景艺人', has_image: true, image_version: 'face-version',
- avatar_focus: { box: { cx: 0.58, cy: 0.49, faceW: 344, imgW: 1000, imgH: 1000 } } },
- { id: 4, name: '无图艺人', has_image: false },
- ] } };
- await page.route((url) => url.pathname === '/api/item', (route) => route.fulfill({ json: payload }));
- await page.route('**/entity-image**', (route) => route.fulfill({ contentType: 'image/svg+xml',
- body: '<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000"><rect width="1000" height="1000" fill="#ddd"/></svg>' }));
- await page.goto(new URL('/item/14', page.url()).href, { waitUntil: 'load' });
- const face = page.locator('#stage [data-entity-name="取景艺人"] [data-id-face]');
- await face.scrollIntoViewIfNeeded();
- await page.waitForFunction(() => {
- const image = document.querySelector<HTMLImageElement>('#stage [data-id-cell="performer"] img');
- return image?.complete && image.naturalWidth > 0;
- });
- const geometry = await face.evaluate((ring) => {
- const image = ring.querySelector('img')!, frame = ring.getBoundingClientRect(), pixels = image.getBoundingClientRect();
- return { visible: getComputedStyle(image).visibility, framed: image.hasAttribute('data-face-framed'),
- direct: image.parentElement === ring, zoomed: pixels.width > frame.width,
- covers: pixels.left <= frame.left + 0.5 && pixels.right >= frame.right - 0.5
- && pixels.top <= frame.top + 0.5 && pixels.bottom >= frame.bottom - 0.5 };
- });
- assert.deepEqual(geometry, { visible: 'visible', framed: true, direct: true, zoomed: true, covers: true });
- assert.equal(await page.locator('#stage [data-entity-name="无图艺人"] img').count(), 0);
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally { await opened.close(); }
- });
- }
-
- it('作品详情身份区:没实体 id 的格子不给手形,厂牌标识铺满方框', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
- try {
- const page = opened.page;
- // 先经桩取到原样的那一条;`route.fetch()` 会绕过桩直接打到服务器。
- const base = await page.evaluate(() => fetch('/api/item?id=14').then((response) => response.json()));
- const payload = {
- ...base, performers: ['无名氏'], performer_total: 1, performer_entities: [{ id: 0, has_image: false }], has_studio_logo: true,
- entity_refs: { ...base.entity_refs,
- performer: [{ id: 0, name: '无名氏', has_image: false, avatar_focus: null }],
- studio: [{ id: 50, name: 'Peach Studio', has_image: false, has_logo: true }] },
- };
- await page.route((url) => url.pathname === '/api/item', (route) => route.fulfill({ json: payload }));
- await page.goto(new URL('/item/14', page.url()).href, { waitUntil: 'load' });
- await page.locator('#stage [data-id-cell="studio"] img').waitFor({ timeout: 15_000 });
- await settle(page);
- const shown = await page.evaluate(() => {
- const cell = (kind: string) => document.querySelector(`#stage [data-id-cell="${kind}"]`)!;
- const face = cell('studio').querySelector('[data-id-face]')!.getBoundingClientRect();
- const img = cell('studio').querySelector('img')!;
- const box = img.getBoundingClientRect();
- return {
- performer: [cell('performer').tagName, getComputedStyle(cell('performer')).cursor],
- studio: getComputedStyle(cell('studio')).cursor,
- fit: getComputedStyle(img).objectFit,
- filled: [box.left - face.left, box.top - face.top, box.width - face.width, box.height - face.height]
- .every((delta) => Math.abs(delta) < 0.5),
- };
- });
- assert.deepEqual(shown, { performer: ['SPAN', 'default'], studio: 'pointer', fit: 'cover', filled: true },
- '标识文件自带边距,页面再补 inset 或换成 contain 就多围出一圈框');
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- it('作品详情标签与反馈键:标签和卡片同一张脸,筛选那半边悬停抬填充;反馈条每一枚悬停都换色', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
- try {
- const page = opened.page;
- const face = await page.evaluate(() => {
- const tag = document.querySelector('#stage [data-detail-tag]')!;
- const probe = document.createElement('div');
- probe.style.cssText = 'border:1px solid var(--line);border-radius:var(--tag-radius);background:var(--tag-fill);color:var(--ink-2)';
- tag.parentElement!.append(probe);
- const want = getComputedStyle(probe);
- const expected = { radius: want.borderTopLeftRadius, line: want.borderTopColor, fill: want.backgroundColor, ink: want.color };
- probe.remove();
- const style = getComputedStyle(tag);
- return { expected, actual: { radius: style.borderTopLeftRadius, line: style.borderTopColor,
- fill: style.backgroundColor, ink: getComputedStyle(tag.querySelector('[data-tag]')!).color } };
- });
- assert.deepEqual(face.actual, face.expected, '圆角、线、填充与字色都走卡片那颗 `.tg` 的同一组 token');
- const filter = page.locator('#stage [data-detail-tag] [data-tag]').first();
- await filter.hover();
- assert.equal(await filter.evaluate((node) => getComputedStyle(node).backgroundColor),
- await tokenColor(page, '#stage [data-item-detail]', '--hover'));
-
- const buttons = ['[data-fb="like"]', '[data-fb="reason"]', '[data-stage-action="dislike"]', '[data-stage-action="seen"]', '[data-stage-action="later"]', '[data-fb="playlist"]',
- '[data-fb="quality"]', '[data-fb="dispose"]'];
- const unchanged: string[] = [];
- for (const selector of buttons) {
- const button = page.locator(`#stage [data-stage-actions] ${selector}`);
- const color = () => button.evaluate((node) => {
- node.getAnimations({ subtree: true }).forEach((animation) => animation.finish());
- return getComputedStyle(node).color;
- });
- await page.mouse.move(0, 0);
- const rest = await color();
- await button.hover();
- if (await color() === rest) unchanged.push(selector);
- }
- assert.deepEqual(unchanged, [], '漏写配色的那一枚全程停在 --muted,看着像不能点');
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- it('作品详情喜爱理由框与「接着看」:输入框聚焦画 BoardUI 那枚 2px 内环;接着看和侧栏同底、顶上一条细线', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
- try {
- const page = opened.page;
- await page.locator('#stage [data-media-card]').first().waitFor({ timeout: 15_000 });
- await page.locator('#preferenceToggle').click();
- const field = page.locator('#stage [data-item-preference] textarea');
- await field.focus();
- const ring = await field.evaluate((node) => {
- node.getAnimations().forEach((animation) => animation.finish());
- return getComputedStyle(node).boxShadow;
- });
- const active = await tokenColor(page, '#stage [data-item-detail]', '--color-border-button-active');
- assert.equal(ring, `${active} 0px 0px 0px 2px inset`);
-
- const related = await page.evaluate(() => {
- const block = document.querySelector('#stage [data-item-related]')!;
- const style = getComputedStyle(block);
- const row = getComputedStyle(block.querySelector('[data-related-row]')!);
- return {
- fill: style.backgroundColor, side: getComputedStyle(document.querySelector('#stage [data-item-side]')!).backgroundColor,
- line: [style.borderTopWidth, style.borderTopStyle, style.borderTopColor],
- heading: getComputedStyle(block.querySelector('h3')!).fontWeight,
- row: [row.display, row.overflowX, row.scrollbarWidth],
- };
- });
- assert.equal(related.fill, related.side, '同一格详情的两块,底色同源,不然整幅宽度上留一道色差');
- assert.deepEqual(related.line, ['1px', 'solid', await tokenColor(page, '#stage', '--line-soft')]);
- assert.equal(related.heading, '600');
- assert.deepEqual(related.row, ['flex', 'auto', 'none'], '那一排横滚,不露系统滚动条');
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- it('作品详情队列与说明块:版次徽章和标题同一行、不斜体;脱盘说明块铺满播放器格', { timeout: 60_000 }, async () => {
- const editions = await openItemPage(browser, `/editions/${ITEM.edition}/${ITEM.edition}`, DESKTOP,
- { ready: '#stage [data-queue-edition]' });
- try {
- const shown = await editions.page.evaluate(() => {
- const badge = document.querySelector('#stage [data-queue-edition]')!;
- const head = badge.parentElement!;
- const name = head.querySelector('b')!.getBoundingClientRect();
- const box = badge.getBoundingClientRect();
- return {
- head: [getComputedStyle(head).display, getComputedStyle(head).flexDirection],
- badge: [getComputedStyle(badge).fontStyle, getComputedStyle(badge).flexShrink],
- sameRow: box.top < name.bottom && box.bottom > name.top,
- heading: getComputedStyle(document.querySelector('#stage [data-mix-queue-head] h2')!).fontWeight,
- };
- });
- assert.deepEqual(shown, { head: ['flex', 'row'], badge: ['normal', '0'], sameRow: true, heading: '600' },
- '`<i>` 默认斜体,徽章不是强调语气');
- /* 队列头的按钮是关闭一类的操作,走控件圆角,不是圆形标签。 */
- const head = await editions.page.evaluate(() => {
- const button = document.querySelector('#stage [data-mix-queue-head] button')!;
- return [getComputedStyle(button).borderTopLeftRadius, getComputedStyle(button).getPropertyValue('--control-radius').trim()];
- });
- assert.equal(head[0], head[1]);
- assert.deepEqual(withoutPlayer(editions.problems), []);
- } finally {
- await editions.close();
- }
- const offline = await openItemPage(browser, `/item/${ITEM.offline}`, DESKTOP, { ready: '#stage #offlineGate' });
- try {
- const fit = await offline.page.evaluate(() => {
- const gate = document.querySelector('#stage #offlineGate')!;
- const cell = gate.parentElement!;
- const a = gate.getBoundingClientRect(), b = cell.getBoundingClientRect();
- return {
- filled: [a.left - b.left, a.top - b.top, a.width - b.width, a.height - b.height].every((delta) => Math.abs(delta) < 0.5),
- radius: [getComputedStyle(gate).borderTopLeftRadius, getComputedStyle(cell).borderTopLeftRadius],
- };
- });
- assert.equal(fit.filled, true, '说明块铺满播放器格,不上下留黑');
- assert.equal(fit.radius[0], fit.radius[1], '圆角跟着格走');
- assert.notEqual(fit.radius[0], '0px');
- assert.deepEqual(offline.problems, []);
- } finally {
- await offline.close();
- }
- });
-
- it('作品详情标签选择器用全站下拉面板那一对开合动效,减少动态效果时当场开合', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
- try {
- const page = opened.page;
- const picker = page.locator('#stage [data-tag-picker]');
- const motion = () => page.evaluate(() => {
- const node = document.querySelector<HTMLElement>('#stage [data-tag-picker]');
- return node && !node.hidden ? getComputedStyle(node).animationName : 'closed';
- });
- const cycle = async () => {
- await page.locator('#tagPlus').click();
- await page.locator('#tagPickSearch').waitFor();
- const opening = await motion();
- await page.locator('#stage [data-rating-value]').click();
- const closing = await motion();
- await picker.waitFor({ state: 'hidden' });
- return [opening, closing];
- };
- assert.deepEqual(await cycle(), ['none', 'closed']);
- await page.emulateMedia({ reducedMotion: 'no-preference' });
- assert.deepEqual(await cycle(), ['board-menu-in', 'board-menu-out']);
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- /* 舞台与播放器的外观:数值照 YouTube 桌面版 delhi-modern 的播放器与 ytd-miniplayer 实测定下。
- 桩里的片源放不出来,Video.js 停在错误态,控件照样挂着,读的是计算值。 */
- const PLAYER_BAR = '#stage .video-js .vjs-control-bar';
- const PLAYER_BLACK = 'rgba(0, 0, 0, 0.6)';
- const styleOf = (page: Page, selector: string, properties: string[], pseudo = '') => page.evaluate(
- ([target, names, element]) => {
- const node = document.querySelector(target);
- if (!node) return null;
- const style = getComputedStyle(node, element || null);
- return Object.fromEntries(names.map((name) => [name, style.getPropertyValue(name)]));
- }, [selector, properties, pseudo] as const);
- const tokenOf = (page: Page, selector: string, token: string) => page.evaluate(([target, name]) =>
- getComputedStyle(document.querySelector(target)!).getPropertyValue(name).trim(), [selector, token] as const);
-
- it('详情浮窗:遮罩同一档 --scrim、不带模糊,进出场同设置弹层;关闭键是压在画面上的 40px 黑圆;媒体格只圆左上角,剧场模式圆上面两角、排成单列', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP, { settings: { theme: 'light' } });
- try {
- const page = opened.page;
- const scrim = await tokenColor(page, 'body', '--scrim');
- assert.equal(scrim, 'rgba(0, 0, 0, 0.7)');
- await page.emulateMedia({ reducedMotion: 'no-preference' });
- assert.deepEqual(await styleOf(page, '#stage', ['background-color', 'backdrop-filter', 'animation-name'], '::backdrop'),
- { 'background-color': scrim, 'backdrop-filter': 'none', 'animation-name': 'settings-backdrop-in' });
- assert.equal((await styleOf(page, '#stage', ['animation-name']))!['animation-name'], 'board-dialog-in');
- /* 亮色主题下白底白晕看不出悬停,用户以 YouTube 为参照:播放器上的键在亮色下也是黑底。 */
- assert.deepEqual(await styleOf(page, '#closeStage', ['width', 'height', 'border-top-left-radius', 'background-color', 'color']),
- { width: '40px', height: '40px', 'border-top-left-radius': '50%', 'background-color': PLAYER_BLACK, color: 'rgb(255, 255, 255)' });
-
- const corners = () => styleOf(page, '#stage [data-stage-media]',
- ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-left-radius']);
- const wide = (await corners())!;
- assert.notEqual(wide['border-top-left-radius'], '0px', '媒体格左上角没圆');
- assert.deepEqual([wide['border-top-right-radius'], wide['border-bottom-left-radius']], ['0px', '0px'],
- '媒体格右边贴着侧栏、下面接着「接着看」,只圆左上角');
- /* `overflow-y:auto` 会把 overflow-x 算成 auto,内容宽出 1px 就冒横向滚动条;侧栏撑满所在那一行,不露半截底色。 */
- assert.deepEqual(await styleOf(page, '#stage [data-stage-side-content]', ['overflow-x', 'overflow-y']),
- { 'overflow-x': 'hidden', 'overflow-y': 'auto' });
- assert.equal((await styleOf(page, '#stage [data-stage-side]', ['align-self']))!['align-self'], 'stretch');
- await page.locator('#stage [data-player-theater]').dispatchEvent('click');
- await page.locator('#stage[data-theater]').waitFor();
- const theater = (await corners())!;
- assert.deepEqual([theater['border-top-right-radius'], theater['border-bottom-left-radius']],
- [wide['border-top-left-radius'], '0px'], '剧场模式下媒体格圆上面两角');
- const columns = (await styleOf(page, '#stage [data-stage-grid]', ['grid-template-columns']))!['grid-template-columns']!;
- assert.equal(columns.split(' ').length, 1, `剧场模式没排成单列:${columns}`);
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- it('手机上详情浮窗离屏幕边 8px,滚的是里面那一层,视频格吸在它顶上', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, MOBILE);
- try {
- const page = opened.page;
- await page.locator(PLAYER_BAR).waitFor({ state: 'attached' });
- const box = (await page.locator('#stage').boundingBox())!;
- assert.deepEqual([box.x, box.y, box.width], [8, 8, MOBILE.width - 16]);
- assert.equal((await styleOf(page, '#stage > [data-stage-scroll]', ['overflow-y']))!['overflow-y'], 'auto');
- assert.deepEqual(await styleOf(page, '#stage [data-stage-media]', ['position', 'top']), { position: 'sticky', top: '0px' });
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- it('播放器控件:40px 黑圆播放键、同一档黑的右侧胶囊与提示、钨丝色进度、页面字体;统计键与加载速度角标压在左上;报错是一张盖在统计上面的卡', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
- try {
- const page = opened.page;
- await page.locator(PLAYER_BAR).waitFor({ state: 'attached' });
- assert.deepEqual(await styleOf(page, `${PLAYER_BAR} > .vjs-play-control`, ['width', 'height', 'border-top-left-radius', 'background-color']),
- { width: '40px', height: '40px', 'border-top-left-radius': '50%', 'background-color': PLAYER_BLACK });
- assert.equal((await styleOf(page, '#stage .vjs-peach-right-controls', ['background-color']))!['background-color'], PLAYER_BLACK);
- /* 错误态下控件条收起、量不到盒子,读它离播放器四边的计算值。 */
- assert.deepEqual(await styleOf(page, PLAYER_BAR, ['left', 'right', 'bottom', 'height']),
- { left: '12px', right: '12px', bottom: '8px', height: '59px' });
- /* 彩条 6px,抓取区 18px,多出来的 12px 全在条上方:往下扩会盖住按钮那一排的顶边。 */
- assert.deepEqual(await styleOf(page, '#stage .vjs-progress-control', ['height', 'top']), { height: '18px', top: '-12px' });
- assert.equal((await styleOf(page, '#stage .vjs-progress-holder', ['height']))!.height, '6px', '彩条本身不变粗');
- assert.equal((await styleOf(page, '#stage .vjs-play-progress', ['background-color']))!['background-color'],
- await tokenColor(page, '#stage', '--tungsten'));
- assert.deepEqual(await styleOf(page, '#stage .vjs-big-play-button', ['width', 'height']), { width: '56px', height: '56px' });
- assert.equal((await styleOf(page, '#stage .video-js', ['font-family']))!['font-family'],
- (await styleOf(page, 'body', ['font-family']))!['font-family'], '播放器里的字用页面字体,不是 Video.js 的 Arial');
- assert.deepEqual(await styleOf(page, '#stage [data-player-theater] > .vjs-peach-tooltip',
- ['background-color', 'color', 'padding-top', 'padding-left', 'backdrop-filter', 'white-space']),
- { 'background-color': PLAYER_BLACK, color: 'rgb(255, 255, 255)', 'padding-top': '5px', 'padding-left': '9px',
- 'backdrop-filter': 'blur(16px)', 'white-space': 'nowrap' });
- assert.deepEqual(await styleOf(page, '#stage #playerStatsBtn', ['left', 'top', 'width', 'height', 'border-top-left-radius', 'background-color']),
- { left: '11px', top: '11px', width: '40px', height: '40px', 'border-top-left-radius': '50%', 'background-color': PLAYER_BLACK });
- /* 音量胶囊和右边那枚同一排,毛玻璃同一档:只有一边磨砂,展开后它就比邻居更透。 */
- assert.equal((await styleOf(page, `${PLAYER_BAR} > .vjs-volume-panel`, ['backdrop-filter']))!['backdrop-filter'], 'blur(16px)');
- assert.deepEqual(await styleOf(page, '#stage #playerNet', ['left', 'top', 'height', 'white-space']),
- { left: '58px', top: '11px', height: '40px', 'white-space': 'nowrap' }, '速率断成两行会顶破 40px 的胶囊');
- /* sprite 里的仪表盘是描边图形,容器不声明就按 SVG 默认填成黑块,压在黑底上等于没有图标。
- 演示库的片子放不出来、角标没有速率可写,量的是临时塞进去的一枚 svg。 */
- const gauge = await page.evaluate(() => {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- document.querySelector('#stage #playerNet')!.append(svg);
- const style = getComputedStyle(svg);
- const shown = { fill: style.fill, stroke: style.stroke };
- svg.remove();
- return shown;
- });
- assert.deepEqual(gauge, { fill: 'none', stroke: 'rgb(255, 255, 255)' });
- await page.locator('#stage .video-js.vjs-error').waitFor({ timeout: 10_000 });
- const error = (await styleOf(page, '#stage .vjs-error-display .vjs-modal-dialog-content', ['background-color', 'z-index']))!;
- const stats = (await styleOf(page, '#stage #playerStats', ['z-index']))!;
- assert.equal(error['background-color'], 'rgba(2, 4, 8, 0.86)');
- assert.ok(Number(error['z-index']) > Number(stats['z-index']), `报错卡压在统计面板底下:${error['z-index']} / ${stats['z-index']}`);
- const card = (await page.locator('#stage .vjs-error-display .vjs-modal-dialog-content').boundingBox())!;
- const frame = (await page.locator('#stage .video-js').boundingBox())!;
- assert.ok(Math.abs(card.x + card.width / 2 - (frame.x + frame.width / 2)) < 1
- && Math.abs(card.y + card.height / 2 - (frame.y + frame.height / 2)) < 1, '报错卡居中在画面里,躲开左上角的速率角标');
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- it('播放器的设置面板与右键菜单:同一档黑、浮层圆角、48px 的行;右键菜单悬停抬一层白', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
- try {
- const page = opened.page;
- await page.locator('#stage #playerStatsBtn').waitFor();
- const menu = '#stage .vjs-peach-settings-menu';
- /* 关闭态不能是 display:none:它没有可过渡的中间态,面板只会瞬间消失。 */
- assert.deepEqual(await styleOf(page, menu, ['display', 'opacity', 'visibility']),
- { display: 'block', opacity: '0', visibility: 'hidden' });
- await page.locator('#stage .vjs-peach-settings-toggle').dispatchEvent('click');
- const floating = await tokenOf(page, menu, '--floating-radius');
- const settings = (await styleOf(page, menu, ['background-color', 'border-top-left-radius', 'width', 'backdrop-filter']))!;
- assert.equal(settings['background-color'], PLAYER_BLACK);
- assert.equal(settings['backdrop-filter'], 'blur(16px)', '设置面板的毛玻璃没生效');
- assert.equal(settings['border-top-left-radius'], floating);
- assert.ok(parseFloat(settings.width!) <= 274, `设置面板宽 ${settings.width}`);
- assert.equal((await styleOf(page, `${menu} .vjs-peach-menu-row`, ['min-height']))!['min-height'], '48px');
- await page.locator('#stage .vjs-peach-settings-toggle').dispatchEvent('click');
-
- await page.locator('#stage .video-js').click({ button: 'right' });
- await page.locator('#playerMenu:popover-open').waitFor();
- assert.deepEqual(await styleOf(page, '#playerMenu', ['padding-top', 'background-color', 'border-top-left-radius', 'backdrop-filter']),
- { 'padding-top': '8px', 'background-color': PLAYER_BLACK, 'border-top-left-radius': await tokenOf(page, '#playerMenu', '--floating-radius'),
- 'backdrop-filter': 'blur(16px)' });
- const row = (await styleOf(page, '#playerMenu [data-player-menu]', ['min-height', 'grid-template-columns']))!;
- assert.equal(row['min-height'], '48px');
- const tracks = row['grid-template-columns']!.split(' ');
- assert.deepEqual([tracks[0], tracks.at(-1)], ['56px', '32px'], `右键菜单行的列:${row['grid-template-columns']}`);
- await page.locator('#playerMenu [data-player-menu]').first().hover();
- assert.equal((await styleOf(page, '#playerMenu [data-player-menu]', ['background-color']))!['background-color'],
- 'rgba(255, 255, 255, 0.1)');
- await page.keyboard.press('Escape');
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- it('统计图 20px 高,缓冲那条按健康度换色;小窗照 ytd-miniplayer:固定在右下角 16px、宽 400px、层级在弹层之下,快退快进键 36px', { timeout: 60_000 }, async () => {
- const opened = await openItemPage(browser, `/item/${ITEM.plain}`, DESKTOP);
- try {
- const page = opened.page;
- await page.locator('#stage #playerStatsBtn').click();
- const plot = '#stage [data-player-stats-plot="buffer"]';
- assert.equal((await styleOf(page, plot, ['height']))!.height, '20px');
- const colors = await page.evaluate((selector) => ['low', 'mid'].map((state) => {
- const bar = document.createElement('i');
- bar.dataset.bar = state;
- document.querySelector(selector)!.append(bar);
- const color = getComputedStyle(bar).backgroundColor;
- bar.remove();
- return color;
- }), plot);
- assert.deepEqual(colors, ['rgb(225, 105, 98)', 'rgb(239, 181, 95)']);
-
- await page.locator('#closeStage').focus();
- await page.keyboard.press('i');
- await page.locator('#miniplayer:not([hidden]) .video-js').waitFor({ timeout: 10_000 });
- assert.deepEqual(await styleOf(page, '#miniplayer', ['position', 'z-index']), { position: 'fixed', 'z-index': '900' });
- const box = (await page.locator('#miniplayer').boundingBox())!;
- assert.deepEqual([box.width, box.x + box.width, box.y + box.height], [400, DESKTOP.width - 16, DESKTOP.height - 16]);
- assert.deepEqual(await styleOf(page, '#miniplayerBack', ['width', 'height']), { width: '36px', height: '36px' });
- assert.deepEqual(withoutPlayer(opened.problems), []);
- } finally {
- await opened.close();
- }
- });
-
- /** 一组元素的外框,取到小数点后一位。 */
- const rectsOf = (page: Page, selectors: Record<string, string>) => page.evaluate((entries) => Object.fromEntries(
- Object.entries(entries).map(([name, selector]) => {
- const box = document.querySelector(selector)!.getBoundingClientRect();
- const round = (value: number) => Math.round(value * 10) / 10;
- return [name, { left: round(box.left), top: round(box.top), right: round(box.right), bottom: round(box.bottom), width: round(box.width), height: round(box.height) }];
- })), selectors);
- const IMMERSE = {
- root: '[data-immerse]', stage: '[data-immerse-stage]', actions: '[data-immerse-actions]', ui: '[data-immerse-ui]',
- bar: '[data-immerse-bar]', close: '[data-immerse-close]',
- };
-
- it('沉浸模式桌面照 Shorts 三段:9:16 舞台居中、动作列贴舞台右侧 12px、作者标题在左下;横片换成 16:9,动作列收进框里;浅色主题下仍是深色层', { timeout: 90_000 }, async () => {
- const opened = await visit(browser, '/', DESKTOP);
- try {
- const { page } = opened;
- const { wide, tall } = await pickClips(page);
- await pinQueue(page, [tall, wide]);
- await muteVideos(page);
- await openImmerse(page, tall.id);
- const portrait = await rectsOf(page, IMMERSE);
- assert.deepEqual(portrait.stage, { left: 415, top: 0, right: 865, bottom: 800, width: 450, height: 800 });
- assert.deepEqual([portrait.actions.left, portrait.actions.width, portrait.actions.bottom], [877, 72, 792]);
- assert.deepEqual([portrait.ui.left, portrait.ui.bottom], [20, 780]);
- assert.deepEqual(portrait.bar, { left: 0, top: 780, right: 1280, bottom: 800, width: 1280, height: 20 });
- assert.deepEqual([portrait.close.top, portrait.close.right, portrait.close.width], [15, 1265, 42]);
- const faces = await page.evaluate(() => {
- const read = (selector: string, names: string[]) => {
- const style = getComputedStyle(document.querySelector(selector)!);
- return Object.fromEntries(names.map((name) => [name, style.getPropertyValue(name)]));
- };
- return {
- root: read('[data-immerse]', ['background-color']),
- track: read('[data-immerse-track]', ['border-radius', 'background-color']),
- floating: (() => {
- const probe = document.createElement('div');
- probe.style.borderRadius = 'var(--floating-radius)';
- document.querySelector('[data-immerse]')!.append(probe);
- const value = getComputedStyle(probe).borderRadius;
- probe.remove();
- return value;
- })(),
- circle: read('[data-immerse-circle]', ['width', 'height', 'border-radius', 'background-color', 'color']),
- glyph: read('[data-immerse-circle] svg', ['width', 'height', 'fill', 'stroke']),
- author: read('[data-immerse-author]>a', ['color', 'font-weight']),
- title: read('[data-immerse-title]', ['font-size', 'font-weight', 'text-overflow', 'white-space', 'pointer-events']),
- caption: read('[data-immerse-ui]', ['pointer-events']),
- progress: read('[data-immerse-bar] i', ['height']),
- };
- });
- const { floating, ...face } = faces;
- assert.notEqual(floating, '0px');
- assert.deepEqual(face, {
- root: { 'background-color': 'rgb(15, 15, 15)' },
- track: { 'border-radius': floating, 'background-color': 'rgb(0, 0, 0)' },
- circle: { width: '48px', height: '48px', 'border-radius': '50%', 'background-color': 'rgba(255, 255, 255, 0.1)', color: 'rgb(241, 241, 241)' },
- glyph: { width: '24px', height: '24px', fill: 'none', stroke: 'rgb(241, 241, 241)' },
- author: { color: 'rgb(241, 241, 241)', 'font-weight': '600' },
- title: { 'font-size': '20px', 'font-weight': '600', 'text-overflow': 'ellipsis', 'white-space': 'nowrap', 'pointer-events': 'auto' },
- caption: { 'pointer-events': 'none' },
- progress: { height: '4px' },
- });
-
- // 进度:4px 的线贴着 20px 热区的底,走钨丝蓝;指针靠近才变粗。
- assert.equal(await page.evaluate(() => getComputedStyle(document.querySelector('[data-immerse-bar] i')!).backgroundColor),
- await tokenColor(page, '[data-immerse]', '--tungsten'));
- await page.hover('[data-immerse-bar]');
- await page.waitForFunction(() => getComputedStyle(document.querySelector('[data-immerse-bar] i')!).height === '9px');
-
- // 动作键:悬停放大 1.05、按住缩到 .96;选中反相成浅底深字(压在画面上,抬一档的面会被画面吃掉)。
- await page.route('**/api/feedback', (route) => route.fulfill({ json: { feedback: 'seen', o_count: 0 } }));
- const seen = '[data-immerse-actions] button[aria-label="标为看过"]';
- await page.hover(seen);
- const scale = (value: string) => page.waitForFunction(([selector, want]) =>
- getComputedStyle(document.querySelector(selector!)!).scale === want, [seen, value] as const);
- await scale('1.05');
- await page.mouse.down();
- await scale('0.96');
- await page.mouse.up();
- await page.locator(`${seen}[aria-pressed="true"]`).waitFor({ timeout: 5_000 });
- await page.mouse.move(0, 0);
- assert.deepEqual(await page.evaluate((selector) => {
- const style = getComputedStyle(document.querySelector(selector)!);
- return [style.backgroundColor, style.color];
- }, seen), ['rgb(241, 241, 241)', 'rgb(15, 15, 15)']);
-
- await page.keyboard.press('ArrowDown');
- await page.waitForFunction((id) => location.search === `?id=${id}`, wide.id);
- await settledClip(page);
- const landscape = await rectsOf(page, IMMERSE);
- assert.deepEqual(landscape.stage, { left: 230.4, top: 169.6, right: 1049.6, bottom: 630.4, width: 819.2, height: 460.8 });
- assert.deepEqual([landscape.actions.right, landscape.actions.bottom], [1037.6, 612.4]);
- assert.equal(landscape.ui.width, 404.8);
-
- await page.evaluate(() => { document.documentElement.dataset.theme = 'light' });
- assert.deepEqual(await page.evaluate(() => [
- getComputedStyle(document.querySelector('[data-immerse]')!).backgroundColor,
- getComputedStyle(document.querySelector('[data-immerse-author]>a')!).color,
- ]), ['rgb(15, 15, 15)', 'rgb(241, 241, 241)']);
- assert.deepEqual(opened.problems.filter((line) => !line.includes('VIDEOJS')), []);
- } finally {
- await opened.close();
- }
- });
-
- it('沉浸模式手机铺满视口:舞台不留圆角,动作列贴右、作者标题贴左下,作者那行的时长与序号收起', { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/', MOBILE);
- try {
- const { page } = opened;
- const { wide, tall } = await pickClips(page);
- await pinQueue(page, [tall, wide]);
- await muteVideos(page);
- await openImmerse(page, tall.id);
- const rects = await rectsOf(page, { ...IMMERSE, avatar: '[data-immerse-avatar]' });
- assert.deepEqual(rects.stage, { left: 0, top: 0, right: 390, bottom: 844, width: 390, height: 844 });
- assert.deepEqual([rects.actions.right, rects.actions.bottom, rects.actions.width], [382, 752, 56]);
- assert.deepEqual([rects.ui.left, rects.ui.right, rects.ui.bottom], [14, 308, 816]);
- assert.deepEqual([rects.avatar.width, rects.avatar.height], [36, 36]);
- assert.deepEqual([rects.close.top, rects.close.right], [10, 380]);
- assert.deepEqual(await page.evaluate(() => ({
- radius: getComputedStyle(document.querySelector('[data-immerse-track]')!).borderRadius,
- meta: getComputedStyle(document.querySelector('[data-immerse-author]>span')!).display,
- title: getComputedStyle(document.querySelector('[data-immerse-title]')!).fontSize,
- })), { radius: '0px', meta: 'none', title: '14px' });
- assert.deepEqual(opened.problems.filter((line) => !line.includes('VIDEOJS')), []);
- } finally {
- await opened.close();
- }
- });
-
- /* ── 侧栏岛(`frontend/src/react/sidebar/sidebar.css`) ── */
-
- /** 打开首页等侧栏的分组画出来。聚合照演示库真取,只保证时长那一组在(演示库的短片可能凑不出总时长)。 */
- async function openSidebar(viewport: Viewport): Promise<Visit> {
- const opened = await visit(browser, '/', viewport);
- await opened.page.route((url) => url.pathname === '/api/facets', async (route) => {
- const real = await (await route.fetch()).json() as { stats?: Record<string, unknown> };
- await route.fulfill({ json: { ...real, stats: { ...real.stats, duration: real.stats?.duration || 540 } } });
- });
- await opened.page.reload({ waitUntil: 'load' });
- await opened.page.locator('#drawer [data-sidebar-group="时长"]').waitFor({ state: 'attached', timeout: 15_000 });
- await settle(opened.page);
- return { ...opened, close: async () => {
- await opened.page.unrouteAll({ behavior: 'ignoreErrors' });
- await opened.close();
- } };
- }
-
- it('侧栏当前项自己不铺底,由挂在抽屉上的那块玻璃标出;悬停时玻璃跟过去,离开这一列回到当前项', { timeout: 60_000 }, async () => {
- const opened = await openSidebar(DESKTOP);
- try {
- const { page } = opened;
- const read = (key: string) => page.evaluate((target) => {
- const glide = document.querySelector<HTMLElement>('[data-sidebar-glide]')!;
- const button = document.querySelector<HTMLElement>(`#drawer [data-sidebar-nav] [data-nav="${target}"]`)!;
- const box = (node: Element) => {
- const rect = node.getBoundingClientRect();
- return [rect.left, rect.top, rect.width, rect.height].map(Math.round);
- };
- const style = getComputedStyle(button);
- return {
- glide: box(glide), button: box(button), parent: glide.parentElement?.id,
- layer: getComputedStyle(glide).zIndex, radius: getComputedStyle(glide).borderRadius,
- fill: [style.backgroundColor, style.backgroundImage, style.boxShadow], color: style.color,
- };
- }, key);
- const current = await read('');
- assert.equal(current.parent, 'drawer', '玻璃没有挂在抽屉上,纵滚时会被滚动层切掉');
- assert.deepEqual([current.layer, current.radius], ['-1', '10px'], '玻璃要压在字底下、圆角照按钮的 10px');
- assert.deepEqual(current.glide, current.button, '玻璃没有垫在当前项下面');
- assert.deepEqual(current.fill, ['rgba(0, 0, 0, 0)', 'none', 'none'], '当前项自己铺了底,静止时就是两层底叠着');
- assert.equal(current.color, await tokenColor(page, '#drawer', '--glass-text'), '当前项的字色不是玻璃上的字色');
- const idle = await read('studios');
- assert.equal(idle.color, await tokenColor(page, '#drawer', '--color-text-secondary'), '未选中项的字色不是次要文字色');
-
- await page.locator('#drawer [data-sidebar-nav] [data-nav="studios"]').hover();
- const hovered = await read('studios');
- assert.deepEqual(hovered.glide, hovered.button, '悬停时玻璃没有跟到指着的那一项');
- assert.deepEqual(hovered.fill, ['rgba(0, 0, 0, 0)', 'none', 'none'], '悬停的那一项自己铺了底');
- await page.mouse.move(900, 420);
- const back = await read('');
- assert.deepEqual(back.glide, back.button, '指针离开这一列之后玻璃没有回到当前项');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('侧栏标题行:切换器 32px 圆标识、收起键 20px 高,与导航首项相隔 12px;分组箭头展开时转 90°;收起后只剩 60px 宽的图标列', { timeout: 60_000 }, async () => {
- const opened = await openSidebar(DESKTOP);
- try {
- const { page } = opened;
- const head = await page.evaluate(() => {
- const drawer = document.querySelector('#drawer')!;
- const rect = (selector: string) => drawer.querySelector(selector)!.getBoundingClientRect();
- const mark = drawer.querySelector('#brandHome .mark')!;
- const rotation = (group: Element) => {
- const matrix = new DOMMatrix(getComputedStyle(group.querySelector(':scope > [data-sidebar-toggle] svg')!).transform);
- return Math.round(Math.atan2(matrix.b, matrix.a) * 180 / Math.PI);
- };
- const groups = [...drawer.querySelectorAll<HTMLDetailsElement>('[data-sidebar-group]')];
- return {
- gap: Math.round(rect('[data-sidebar-nav]').top - rect('[data-sidebar-head]').bottom),
- mark: [Math.round(rect('#brandHome .mark').width), Math.round(rect('#brandHome .mark').height), getComputedStyle(mark).borderRadius],
- toggle: Math.round(rect('#filterBtn').height),
- open: groups.filter((group) => group.open).map(rotation),
- closed: groups.filter((group) => !group.open).map(rotation),
- };
- });
- assert.equal(head.gap, 12, '切换器与导航首项挨得太近,两块底色读起来像压在一起');
- assert.deepEqual(head.mark, [32, 32, '50%'], '切换器的标识不是 32px 的圆');
- assert.equal(head.toggle, 20, '收起键不是 20px 高');
- assert.ok(head.open.length && head.closed.length, `首页的分组没有一开一合可比:${JSON.stringify(head)}`);
- assert.ok(head.open.every((angle) => angle === 90), `展开的分组箭头没有转到 90°:${head.open}`);
- assert.ok(head.closed.every((angle) => angle === 0), `收着的分组箭头没有回到 0°:${head.closed}`);
-
- await page.locator('#filterBtn').click();
- await page.waitForFunction(() => Math.round(document.querySelector('#drawer')!.getBoundingClientRect().width) === 60,
- undefined, { timeout: 5_000 });
- const rail = await page.evaluate(() => {
- const drawer = document.querySelector('#drawer')!;
- const toggle = drawer.querySelector('#filterBtn')!.getBoundingClientRect();
- return {
- toggle: [Math.round(toggle.width), Math.round(toggle.height)],
- groups: [...new Set([...drawer.querySelectorAll('[data-sidebar-group]')].map((group) => getComputedStyle(group).display))],
- labels: [...new Set([...drawer.querySelectorAll('[data-sidebar-nav] button span')].map((span) => getComputedStyle(span).maxWidth))],
- };
- });
- assert.deepEqual(rail, { toggle: [36, 20], groups: ['none'], labels: ['0px'] }, '收起的窄栏不是一列图标');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('时长拉条:已选段是 accent 渐变,两端读数常显、推到端点也不越出轨道,刚动过的那枚压在上面', { timeout: 60_000 }, async () => {
- const opened = await openSidebar(DESKTOP);
- try {
- const { page } = opened;
- await page.locator('#drawer [data-sidebar-group="时长"] > [data-sidebar-toggle]').click();
- await page.locator('#drawer [data-sidebar-group="时长"] [data-sidebar-collapse]:not([inert])').waitFor({ timeout: 5_000 });
- const read = () => page.evaluate(() => {
- const range = document.querySelector('#durationRange')!;
- const bounds = range.getBoundingClientRect();
- return {
- fill: getComputedStyle(range.querySelector('[data-sidebar-range-fill]')!).backgroundImage,
- tips: [...range.querySelectorAll<HTMLElement>('[data-sidebar-range-tip]')].map((tip) => {
- const box = tip.getBoundingClientRect();
- return {
- end: tip.dataset.rangeEnd, text: tip.textContent, layer: getComputedStyle(tip).zIndex,
- visible: getComputedStyle(tip).visibility === 'visible' && box.width > 0,
- inside: box.left >= bounds.left - 1 && box.right <= bounds.right + 1,
- };
- }),
- };
- });
- const resting = await read();
- const accent = await tokenColor(page, '#drawer', '--color-accent-400');
- assert.ok(resting.fill.startsWith('linear-gradient(90deg') && resting.fill.includes(accent),
- `已选段不是从 accent-400 起的横向渐变:${resting.fill}`);
- assert.deepEqual(resting.tips, [
- { end: 'min', text: '0 分钟', layer: '1', visible: true, inside: true },
- { end: 'max', text: '不限', layer: '2', visible: true, inside: true },
- ], '两端读数要常显、贴着轨道两端不越界,没动过时右端那枚在上');
-
- await page.locator('#durMin').focus();
- await page.keyboard.press('ArrowRight');
- await page.waitForFunction(() => document.querySelector('[data-sidebar-range-tip][data-range-end="min"]')?.hasAttribute('data-range-active'),
- undefined, { timeout: 5_000 });
- const moved = await read();
- assert.deepEqual(moved.tips.map((tip) => [tip.end, tip.layer, tip.inside]), [['min', '2', true], ['max', '1', true]],
- '刚动过的那一端没有压到上面');
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-
- it('手机侧栏:抽屉开着时遮罩外壳隐形、暗色画在 ::before 上,层级低于抽屉;收起时遮罩退出渲染树', { timeout: 60_000 }, async () => {
- const opened = await openSidebar(MOBILE);
- try {
- const { page } = opened;
- const scrim = () => page.evaluate(() => {
- const node = document.querySelector('#scrim')!, drawer = document.querySelector('#drawer')!;
- const before = getComputedStyle(node, '::before');
- return {
- display: getComputedStyle(node).display, visibility: getComputedStyle(node).visibility,
- dim: [before.visibility, before.backgroundColor],
- layers: [Number(getComputedStyle(node).zIndex), Number(getComputedStyle(drawer).zIndex)],
- fill: getComputedStyle(drawer).getPropertyValue('--glass-fill'),
- };
- });
- assert.equal((await scrim()).display, 'none', '抽屉收着时遮罩还在渲染树里,iOS 的 Safari 会拿它给状态栏取色');
- await page.locator('#filterBtn').tap();
- await page.waitForFunction(() => document.querySelector('#drawer')?.classList.contains('open'));
- const shown = await scrim();
- assert.deepEqual([shown.display, shown.visibility], ['block', 'hidden'], '遮罩外壳没有隐形,iOS 的 Safari 会拿它给状态栏取色');
- assert.equal(shown.dim[0], 'visible', '遮罩的暗色没有画在 ::before 上');
- assert.notEqual(shown.dim[1], 'rgba(0, 0, 0, 0)', '遮罩的 ::before 是透明的,压不暗身后的页面');
- assert.ok(shown.layers[0] < shown.layers[1], `遮罩压在抽屉上面,抽屉里就点不动了:${shown.layers}`);
- assert.ok(shown.fill.replace(/\s/g, '').includes('86%'), `窄屏抽屉的填充没有加厚到 86%:${shown.fill}`);
- assert.deepEqual(opened.problems, []);
- } finally {
- await opened.close();
- }
- });
-});
diff --git a/frontend/e2e/follow-fixture.ts b/frontend/e2e/follow-fixture.ts
index 098d98ece..727d62a20 100644
--- a/frontend/e2e/follow-fixture.ts
+++ b/frontend/e2e/follow-fixture.ts
@@ -1,4 +1,4 @@
-/* 关注页与关注详情两个岛的桩数据:`follow-feed.test.ts`、`follow-detail.test.ts` 与 `design.test.ts` 共用。
+/* 关注页与关注详情两个岛的桩数据:`follow-feed.test.ts`、`follow-detail.test.ts` 与设计决定用例(`design-*.test.ts`)共用。
*
* 演示库没有关注来源,这里按 `_source_payload`、`_group_payload`(`src/peach/web_follow.py`)造
* 六位创作者、一页视频与图片、第二页续页,外加详情那几种形态。关注来源的真实抓取一次都不发:`/api/follow/check`
diff --git a/frontend/e2e/item-fixture.ts b/frontend/e2e/item-fixture.ts
index f7aca2e24..60d50bf89 100644
--- a/frontend/e2e/item-fixture.ts
+++ b/frontend/e2e/item-fixture.ts
@@ -1,4 +1,4 @@
-/* 作品详情岛(`item-detail`)的桩数据:`item-detail.test.ts` 与 `design.test.ts` 共用。
+/* 作品详情岛(`item-detail`)的桩数据:`item-detail.test.ts` 与设计决定用例(`design-*.test.ts`)共用。
*
* 演示库里的作品没有共演、分卷、版本和播放列表,这里按 `q_item`、`q_items`(`src/peach/web_catalog.py`)
* 与 `w_playlist`(`src/peach/web_playlists.py`)的形状造几种形态:普通、十二位共演、在脱盘来源上、标题很长、
@@ -149,7 +149,10 @@ async function stub(page: Page): Promise<ItemStub> {
(route) => route.fulfill({ json: { subtitles: [] } }));
await page.route((url) => ['/api/play', '/api/activity', '/api/stream-cancel'].includes(url.pathname),
(route) => route.fulfill({ json: { ok: true } }));
- await page.route((url) => url.pathname === '/api/stream-plan', (route) => route.fulfill({ json: { protocol: 'direct' } }));
+ // 设置读真服务,写就地接住:`settings` 里的本地值会被推上去,改掉并发文件读到的同一份设置。
+ await page.route((url) => url.pathname === '/api/settings',
+ (route) => route.request().method() === 'GET' ? route.fallback() : route.fulfill({ json: { ok: true } }));
+ await page.route((url) => url.pathname === '/api/stream-plan',(route) => route.fulfill({ json: { protocol: 'direct' } }));
await page.route((url) => url.pathname === '/stream', (route) => route.fulfill({ status: 204, body: '' }));
await page.route((url) => ['/poster', '/cover', '/logo', '/entity-image', '/avatar'].includes(url.pathname), (route) => {
const url = new URL(route.request().url());
diff --git a/frontend/e2e/manage-header.test.ts b/frontend/e2e/manage-header.test.ts
index 4511fd095..1ff0f9b9f 100644
--- a/frontend/e2e/manage-header.test.ts
+++ b/frontend/e2e/manage-header.test.ts
@@ -2,7 +2,7 @@
*
* 页头:每个管理区的标题与面包屑、四块(管理条、面包屑、标题、说明行)落在同一条居中窄列上、
* 窄屏标题收档的那几页,以及面包屑普通左键走路由不整页重载。回收站说明行先占位后落读数、同页重画
- * 不闪回占位,由 `design.test.ts` 的回收站几何用例量。
+ * 不闪回占位,由 `design-cards.test.ts` 的回收站几何用例量。
*
* 批量条:目录、回收站、垃圾文件(待判断与已排除)与关注页各自列出的键和计数。回收站与垃圾文件的
* 名单由桩给:演示库里两处都是空的。写接口一次都不点。 */
diff --git a/frontend/e2e/search.test.ts b/frontend/e2e/search.test.ts
index b35d2e4a0..f3889e43d 100644
--- a/frontend/e2e/search.test.ts
+++ b/frontend/e2e/search.test.ts
@@ -1,7 +1,7 @@
/* 顶栏搜索(`search` 岛,ADR-0031):下拉栏里有什么、键盘怎么走、提交之后去哪儿。
*
* 补全(`/api/suggest`)与搜索记录(`/api/search-history`)在这里各给一份桩,好数请求、好看写进去的
- * 是什么;作品与详情沿用 `item-fixture.ts`。下拉栏的排版(两栏、页签、封面格)由 `design.test.ts` 量。 */
+ * 是什么;作品与详情沿用 `item-fixture.ts`。下拉栏的排版(两栏、页签、封面格)由 `design-people.test.ts` 量。 */
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
diff --git a/frontend/e2e/settings-fixture.ts b/frontend/e2e/settings-fixture.ts
index ff3f64806..158fed1c0 100644
--- a/frontend/e2e/settings-fixture.ts
+++ b/frontend/e2e/settings-fixture.ts
@@ -1,4 +1,4 @@
-/* 设置面板(`settings-panel` 岛)的桩与入口:`settings-panel.test.ts` 与 `design.test.ts` 共用。
+/* 设置面板(`settings-panel` 岛)的桩与入口:`settings-panel.test.ts` 与设计决定用例(`design-*.test.ts`)共用。
*
* 跟账本走的 `/api/settings` 与两份机器状态(`/api/follow/schedule`、`/api/thumbnail-jobs`)各给一份
* 内存桩:读写都由它接住,好看写进去的是什么,也让「刷新后保持」不依赖临时服务上的状态。 */
diff --git a/frontend/e2e/settings-panel.test.ts b/frontend/e2e/settings-panel.test.ts
index ecfc227ed..4d33a5f71 100644
--- a/frontend/e2e/settings-panel.test.ts
+++ b/frontend/e2e/settings-panel.test.ts
@@ -1,5 +1,5 @@
/* 设置面板(`settings-panel` 岛,ADR-0031):开合与焦点、每一类设置改完立刻生效并落到该去的地方。
- * 写接口的桩在 `settings-fixture.ts`;面板的版式与像素由 `design.test.ts` 量,这里只写行为。 */
+ * 写接口的桩在 `settings-fixture.ts`;面板的版式与像素由 `design-settings.test.ts` 量,这里只写行为。 */
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
diff --git a/frontend/test/stubs/legacy-ui.ts b/frontend/test/stubs/legacy-ui.ts
index 2f1b6d276..881be30c0 100644
--- a/frontend/test/stubs/legacy-ui.ts
+++ b/frontend/test/stubs/legacy-ui.ts
@@ -44,7 +44,7 @@ export const wireSelectField = (root: HTMLElement) => {
};
export const wireCollapse = (_root: ParentNode, _selector: string, _idPrefix: string): void => {};
/* 只落位,不动画:jsdom 没有布局,量出来处处是零,那段弹簧也就没有什么可跑的。
- 动作本身由 `frontend/e2e/design.test.ts` 在浏览器中验证。 */
+ 动作本身由 `frontend/e2e/design-*.test.ts` 在浏览器中验证。 */
export const moveGlidePane = (
pane: HTMLElement,
_from: unknown,
diff --git a/tests/test_source_assertion_ratchet.py b/tests/test_source_assertion_ratchet.py
index 11e230ef5..d4a638da2 100644
--- a/tests/test_source_assertion_ratchet.py
+++ b/tests/test_source_assertion_ratchet.py
@@ -51,7 +51,6 @@ BASELINE: dict[str, int] = {
"test_studio_site_harvest.py": 1,
"test_subprocess_encoding.py": 2,
"test_tray.py": 3,
- "test_web_e2e.py": 2,
"test_web_js.py": 1,
"test_web_settings.py": 5,
"test_web_ui.py": 19,
diff --git a/tests/test_web_e2e.py b/tests/test_web_e2e.py
index 548782b1a..2799390e0 100644
--- a/tests/test_web_e2e.py
+++ b/tests/test_web_e2e.py
@@ -43,6 +43,7 @@ from support.ledger import fresh_ledger
ROOT = Path(__file__).resolve().parents[1]
FRONTEND = ROOT / "frontend"
+BROWSER_LOGS = ROOT / "build" / "agent-verification" / "browser"
SERVER_START_SECONDS = 60
E2E_SECONDS = 600
@@ -87,28 +88,52 @@ def refuse_network(*args, **kwargs):
raise AssertionError("演示库的 process 不应向任何外部来源发请求")
-def e2e_command(node: str, concurrency: str = "", files: tuple[str, ...] = ()) -> list[str]:
- """串行跑是浏览器进程预算:每条用例的 Chrome 只给一个渲染进程(`e2e/harness.ts`)。
+#: 断言帧数或动画中途位置的用例文件。别的文件并发跑时 CPU 被几个浏览器分走,
+#: 300ms 的过渡里出不了中间帧,就会误报「主线程整段被占住」或「瞬移过去」。
+CPU_SENSITIVE_SUITES = frozenset({
+ "e2e/sidebar-motion.test.ts", # 开合过渡 300ms 里的帧数
+ "e2e/sidebar.test.ts", # 当前项那块玻璃 900ms 内要经过中间位置
+})
- 直接启动 Node 也省掉资源守卫内的一层 npm 进程。
+
+def e2e_concurrency(override: str = "") -> int:
+ """浏览器用例文件的并发数:`PEACH_E2E_CONCURRENCY` 优先,CI 为 1,本机按 CPU 数推导、上限 4。
+
+ 每个文件起一个 Chrome,只给一个渲染进程(`e2e/harness.ts`),一路并发约占四个逻辑核;
+ 上限 4 与 vitest 的 `maxWorkers` 同一份进程预算。
"""
- selected = concurrency or "1"
- if not selected.isdecimal() or int(selected) < 1:
- raise AssertionError("PEACH_E2E_CONCURRENCY 必须是正整数")
- return [node, "--test", f"--test-concurrency={int(selected)}",
- "--test-reporter=tap", *(files or ("e2e/**/*.test.ts",))]
+ if override:
+ if not override.isdecimal() or int(override) < 1:
+ raise AssertionError("PEACH_E2E_CONCURRENCY 必须是正整数")
+ return int(override)
+ if os.environ.get("GITHUB_ACTIONS") == "true":
+ return 1
+ return max(1, min(4, (os.cpu_count() or 1) // 4))
+
+
+def e2e_command(node: str, concurrency: int, files: tuple[str, ...]) -> list[str]:
+ """直接启动 Node,省掉资源守卫内的一层 npm 进程。"""
+ return [node, "--test", f"--test-concurrency={concurrency}", "--test-reporter=tap", *files]
-def e2e_batches(frontend: Path) -> tuple[tuple[str, ...], ...]:
- """设计检查、交互回归与路由冒烟各占一批,每批串行且限时 600 秒。"""
+def e2e_batches(frontend: Path, concurrency: int) -> tuple[tuple[tuple[str, ...], int], ...]:
+ """把 `frontend/e2e` 下全部 `*.test.ts`(含子目录)分批,每批带自己的并发数,限时 600 秒。
+
+ 并发时分两批:其余文件一次并发跑完,CPU 敏感的文件随后串行。并发为 1 时整轮是串行的,
+ 按设计决定、交互回归与路由冒烟分三批,每批都落在限时之内。
+ """
files = tuple(sorted(path.relative_to(frontend).as_posix()
for path in (frontend / "e2e").rglob("*.test.ts")))
if not files:
raise AssertionError("frontend/e2e 没有浏览器用例")
- design = tuple(path for path in files if path == "e2e/design.test.ts")
- routes = tuple(path for path in files if path == "e2e/smoke.test.ts")
- interactions = tuple(path for path in files if path not in design + routes)
- return tuple(batch for batch in (design, interactions, routes) if batch)
+ if concurrency == 1:
+ design = tuple(path for path in files if path.startswith("e2e/design-"))
+ routes = tuple(path for path in files if path == "e2e/smoke.test.ts")
+ interactions = tuple(path for path in files if path not in design + routes)
+ return tuple((batch, 1) for batch in (design, interactions, routes) if batch)
+ sensitive = tuple(path for path in files if path in CPU_SENSITIVE_SUITES)
+ shared = tuple(path for path in files if path not in sensitive)
+ return tuple(batch for batch in ((shared, concurrency), (sensitive, 1)) if batch[0])
@windows_ledger_roots
@@ -149,6 +174,9 @@ class WebE2ESmokeTests(unittest.TestCase):
server.wait(timeout=10)
if getattr(cls, "log", None) is not None:
cls.log.close()
+ # 访问日志留在 TAP 旁边:哪条用例向服务端发了写请求,用例跑完之后还查得到。
+ BROWSER_LOGS.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(cls.root / "serve.log", BROWSER_LOGS / "serve.log")
shutil.rmtree(cls.root, ignore_errors=True)
@classmethod
@@ -266,14 +294,16 @@ class WebE2ESmokeTests(unittest.TestCase):
def test_every_route_holds_the_layout_and_runtime_invariants(self):
env = dict(os.environ, PEACH_E2E_ORIGIN=self.origin, PEACH_E2E_ITEM=str(self.item),
PEACH_E2E_CHROME=self.chrome)
- log_root = ROOT / "build" / "agent-verification" / "browser"
- log_root.mkdir(parents=True, exist_ok=True)
- for index, batch in enumerate(e2e_batches(FRONTEND), 1):
- log_path = log_root / f"batch-{index}.tap"
- with self.subTest(files=batch):
+ BROWSER_LOGS.mkdir(parents=True, exist_ok=True)
+ for stale in BROWSER_LOGS.glob("batch-*.tap"):
+ stale.unlink()
+ concurrency = e2e_concurrency(os.environ.get("PEACH_E2E_CONCURRENCY", "").strip())
+ for index, (batch, lanes) in enumerate(e2e_batches(FRONTEND, concurrency), 1):
+ log_path = BROWSER_LOGS / f"batch-{index}.tap"
+ with self.subTest(files=batch, concurrency=lanes):
try:
completed = subprocess.run(
- e2e_command(self.node, os.environ.get("PEACH_E2E_CONCURRENCY", "").strip(), batch),
+ e2e_command(self.node, lanes, batch),
capture_output=True, text=True, encoding="utf-8", errors="replace",
cwd=str(FRONTEND), env=env, timeout=E2E_SECONDS, check=False)
except subprocess.TimeoutExpired as expired:
@@ -364,12 +394,11 @@ class SetupE2ETests(unittest.TestCase):
self.assertFalse((self.data / settings_file.SETTINGS_FILENAME).exists())
env = dict(os.environ, PEACH_E2E_SETUP_ORIGIN=self.origin, PEACH_E2E_SETUP_MEDIA=str(self.media),
PEACH_E2E_SETUP_DATA=str(self.data), PEACH_E2E_CHROME=self.chrome)
- log_root = ROOT / "build" / "agent-verification" / "browser"
- log_root.mkdir(parents=True, exist_ok=True)
- log_path = log_root / "setup.tap"
+ BROWSER_LOGS.mkdir(parents=True, exist_ok=True)
+ log_path = BROWSER_LOGS / "setup.tap"
try:
completed = subprocess.run(
- e2e_command(self.node, files=("e2e/setup.test.ts",)),
+ e2e_command(self.node, 1, ("e2e/setup.test.ts",)),
capture_output=True, text=True, encoding="utf-8", errors="replace",
cwd=str(FRONTEND), env=env, timeout=E2E_SECONDS, check=False)
except subprocess.TimeoutExpired as expired:
@@ -428,31 +457,58 @@ class MissingPrerequisiteTests(unittest.TestCase):
self.assertEqual(len(cancelled),2)
self.assertEqual(len(set(cancelled)),2)
- def test_browser_batches_cover_every_file_once_and_include_nested_suites(self):
+ PATHS = ("e2e/design-cards.test.ts", "e2e/design-detail.test.ts", "e2e/smoke.test.ts",
+ "e2e/nested/feature.test.ts", "e2e/sidebar-motion.test.ts")
+
+ def batches_for(self, concurrency: int):
with tempfile.TemporaryDirectory() as folder:
frontend = Path(folder).resolve()
- paths = ("e2e/design.test.ts", "e2e/smoke.test.ts", "e2e/nested/feature.test.ts")
- for name in paths:
+ for name in (*self.PATHS, "e2e/harness.ts"):
path = frontend / name
path.parent.mkdir(parents=True, exist_ok=True)
path.touch()
- batches = e2e_batches(frontend)
- self.assertEqual(batches[0], ("e2e/design.test.ts",))
- self.assertEqual(batches[-1], ("e2e/smoke.test.ts",))
- flattened = tuple(path for batch in batches for path in batch)
- self.assertCountEqual(flattened, paths)
- self.assertEqual(len(flattened), len(set(flattened)))
- self.assertEqual(e2e_command("node", files=batches[1])[-len(batches[1]):], list(batches[1]))
+ return e2e_batches(frontend, concurrency)
+
+ def assertEveryFileOnce(self, batches):
+ flattened = tuple(path for files, _ in batches for path in files)
+ self.assertCountEqual(flattened, self.PATHS)
+
+ def test_concurrent_run_puts_cpu_sensitive_suites_in_a_trailing_serial_batch(self):
+ batches = self.batches_for(4)
+ self.assertEveryFileOnce(batches)
+ (shared, lanes), (serial, serial_lanes) = batches
+ self.assertEqual(lanes, 4)
+ self.assertEqual(serial, ("e2e/sidebar-motion.test.ts",))
+ self.assertEqual(serial_lanes, 1)
+ self.assertIn("e2e/nested/feature.test.ts", shared)
+
+ def test_serial_run_splits_design_interactions_and_routes_to_stay_within_the_time_limit(self):
+ batches = self.batches_for(1)
+ self.assertEveryFileOnce(batches)
+ self.assertEqual([files for files, _ in batches], [
+ ("e2e/design-cards.test.ts", "e2e/design-detail.test.ts"),
+ ("e2e/nested/feature.test.ts", "e2e/sidebar-motion.test.ts"),
+ ("e2e/smoke.test.ts",),
+ ])
+ self.assertEqual({lanes for _, lanes in batches}, {1})
def test_browser_batches_require_at_least_one_suite(self):
with tempfile.TemporaryDirectory() as folder:
with self.assertRaisesRegex(AssertionError, "没有浏览器用例"):
- e2e_batches(Path(folder).resolve())
+ e2e_batches(Path(folder).resolve(), 4)
- def test_headless_browser_stays_within_the_resource_guard_process_budget(self):
- harness = (FRONTEND / "e2e" / "harness.ts").read_text(encoding="utf-8")
- self.assertIn("args: ['--renderer-process-limit=1', '--in-process-gpu', '--disable-features=AudioServiceOutOfProcess', '--disable-audio-output']", harness)
- self.assertIn("timeout: 30_000", harness)
+ def test_concurrency_is_serial_on_ci_bounded_locally_and_overridable(self):
+ local = {key: value for key, value in os.environ.items() if key != "GITHUB_ACTIONS"}
+ with mock.patch.dict(os.environ, local, clear=True):
+ for cpus, expected in ((None, 1), (2, 1), (8, 2), (16, 4), (64, 4)):
+ with self.subTest(cpus=cpus), mock.patch("os.cpu_count", return_value=cpus):
+ self.assertEqual(e2e_concurrency(), expected)
+ with mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}), mock.patch("os.cpu_count", return_value=16):
+ self.assertEqual(e2e_concurrency(), 1)
+ self.assertEqual(e2e_concurrency("3"), 3)
+ for invalid in ("0", "-1", "two"):
+ with self.subTest(invalid=invalid), self.assertRaisesRegex(AssertionError, "必须是正整数"):
+ e2e_concurrency(invalid)
def test_missing_prerequisites_skip_locally_and_fail_on_ci(self):
with mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}):
@@ -463,25 +519,6 @@ class MissingPrerequisiteTests(unittest.TestCase):
with self.assertRaises(unittest.SkipTest):
missing_prerequisite("没有 npm")
- def test_the_npm_script_runs_within_the_same_browser_process_budget(self):
- manifest = json.loads((FRONTEND / "package.json").read_text(encoding="utf-8"))
- self.assertEqual(
- manifest["scripts"]["e2e"],
- 'node --test --test-concurrency=1 --test-reporter=tap "e2e/**/*.test.ts"',
- )
-
- def test_e2e_command_serializes_by_default_and_places_the_override_before_the_glob(self):
- self.assertEqual(e2e_command("node", "1"), [
- "node", "--test", "--test-concurrency=1", "--test-reporter=tap",
- "e2e/**/*.test.ts",
- ])
- self.assertEqual(e2e_command("node"), [
- "node", "--test", "--test-concurrency=1", "--test-reporter=tap",
- "e2e/**/*.test.ts",
- ])
- with self.assertRaisesRegex(AssertionError, "必须是正整数"):
- e2e_command("node", "0")
-
if __name__ == "__main__":
unittest.main()