fix(motion): reduce 偏好下 hydration 不匹配(React #418)且元素停在 opacity:0

线上 /about 白屏排查(§16):30 条路由 + 6 种环境里唯一可复现的缺陷是
webkit/chromium + prefers-reduced-motion:reduce ⇒ pageerror #418,main 内 14 个元素
opacity 恒 0(正常环境只有 3 个首屏以下的滚动入场项)。

根因:useReducedMotion 用 window.matchMedia 作 useState 初值 ⇒ SSR false、客户端首帧 true;
scroll-reveal / template / page-transition 又用它决定 initial/variants/甚至早返回不同树结构,
与 SSR HTML 不一致;且 reduce 时 whileInView 被清空 ⇒ 元素停在 initial 的 opacity:0。

修法(结构恒定,减少动效改用「时长 0」表达):
- hook 首帧恒 false,挂载后 effect 同步真实偏好;
- ScrollReveal/StaggerReveal 的 initial/whileInView/variants 不再按 reduce 清空;
- template.tsx 与 StaggerChildren 去掉早返回裸结构,改空 variants。

回归守卫 e2e/reduced-motion-hydration.spec.ts(/about 与 /):断言 reduce 自证生效、
无 hydration 错误、h1 与末段标题 opacity=1。变异验证:hook 改回 matchMedia 初值 ⇒ 2 红,恢复 ⇒ 2 绿。

另:runbook 明确禁止对 dist/_next/static 用 --delete(回访者旧 HTML 会引用上一代 chunk);
本轮已从备份 --ignore-existing 合并回旧代 101 个文件。复算:tsc/type-check:e2e 0、
jest 35 套件 462 例 0、check:visual 0、check:motion 0、视觉 chromium-desktop 25/25。
This commit was merged in pull request #46.
This commit is contained in:
zhangxiang committed 2026-10-20 08:00:20 +08:00
1 parent 524c1b6575
commit d0090cea56
20 files changed
+341 -22

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 527 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 365 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 678 KiB

@@ -0,0 +1,28 @@
import { chromium } from 'playwright';
const sm = await fetch('https://www.novalon.cn/sitemap.xml').then(r=>r.text()).catch(()=> '');
let routes = [...sm.matchAll(/<loc>([^<]+)<\/loc>/g)].map(m=>new URL(m[1]).pathname);
routes = [...new Set(['/about','/about/brand', ...routes])];
const b = await chromium.launch();
const ctx = await b.newContext({ viewport:{width:1280,height:900} });
const p = await ctx.newPage();
const rows = [];
for (const r of routes.slice(0, 40)) {
const errs = [];
const onErr = e => errs.push(String(e).slice(0,120));
p.on('pageerror', onErr);
const resp = await p.goto('https://www.novalon.cn'+r, { waitUntil:'networkidle', timeout:60000 }).catch(()=>null);
await p.waitForTimeout(700);
const info = await p.evaluate(() => ({
text: (document.querySelector('main')?.innerText ?? document.body.innerText ?? '').trim().length,
mainH: Math.round(document.querySelector('main')?.getBoundingClientRect().height ?? -1),
h1: document.querySelector('h1')?.innerText?.trim().slice(0,18) ?? null,
hidden: [...document.querySelectorAll('main *')].filter(e=>parseFloat(getComputedStyle(e).opacity)===0).length,
}));
rows.push({ r, status: resp?.status() ?? 'ERR', ...info, errs: errs.length });
p.off('pageerror', onErr);
}
await b.close();
const bad = rows.filter(x => x.status !== 200 || x.text < 200 || x.mainH < 300 || x.errs > 0);
console.log(`探测 ${rows.length} 条路由 · 异常 ${bad.length} 条`);
for (const x of bad) console.log(' ⚠', JSON.stringify(x));
console.log('正常样例:', JSON.stringify(rows.slice(0,3)));
@@ -0,0 +1,30 @@
import { chromium } from 'playwright';
const b = await chromium.launch();
const ctx = await b.newContext({ viewport:{width:1280,height:900} });
const p = await ctx.newPage();
const errs = [], cerr = [], failed = [], bad = [];
p.on('pageerror', e => errs.push(String(e).slice(0,300)));
p.on('console', m => { if (m.type()==='error') cerr.push(m.text().slice(0,220)); });
p.on('requestfailed', r => failed.push(`${r.failure()?.errorText} ${r.url().slice(0,120)}`));
p.on('response', r => { if (r.status() >= 400) bad.push(`${r.status()} ${r.url().slice(0,120)}`); });
await p.goto('https://www.novalon.cn/', { waitUntil:'networkidle', timeout:60000 });
// 先关掉 Cookie 条(若挡住点击)
await p.getByRole('button', { name: /拒绝非必要|仅必要|同意/ }).first().click({ timeout: 3000 }).catch(()=>{});
const link = p.locator('[data-testid="desktop-navigation"] a[href="/about"]').first();
await link.waitFor({ state:'visible', timeout:10000 });
await link.click();
await p.waitForTimeout(4000);
const info = await p.evaluate(() => ({
url: location.href, title: document.title,
mainTextLen: (document.querySelector('main')?.innerText ?? '').trim().length,
mainH: Math.round(document.querySelector('main')?.getBoundingClientRect().height ?? -1),
h1: document.querySelector('h1')?.innerText?.slice(0,24) ?? null,
hidden: [...document.querySelectorAll('main *')].filter(e=>parseFloat(getComputedStyle(e).opacity)===0).length,
}));
await p.screenshot({ path:'docs/acceptance/2026-10-20-prod-about/about-clientnav.png', fullPage:true });
console.log(JSON.stringify(info, null, 1));
console.log('pageerrors', JSON.stringify(errs));
console.log('consoleErrors', JSON.stringify(cerr.slice(0,6)));
console.log('failed', JSON.stringify(failed.slice(0,6)));
console.log('http>=400', JSON.stringify(bad.slice(0,8)));
await b.close();
@@ -0,0 +1,41 @@
import { chromium, webkit } from 'playwright';
// A) 找出 SSR 阶段 opacity:0 的元素(首屏是否含 h1)
const b1 = await chromium.launch();
const c1 = await b1.newContext({ viewport: { width: 1280, height: 900 }, javaScriptEnabled: false });
const p1 = await c1.newPage();
await p1.goto('https://www.novalon.cn/about', { waitUntil: 'domcontentloaded', timeout: 60000 }).catch(()=>{});
await p1.waitForTimeout(800);
const hidden = await p1.evaluate(() => {
const out = [];
for (const el of document.querySelectorAll('main *')) {
const cs = getComputedStyle(el);
if (parseFloat(cs.opacity) === 0) {
const r = el.getBoundingClientRect();
out.push({ tag: el.tagName, cls: (el.className||'').toString().slice(0,60), text: (el.innerText||'').slice(0,30), top: Math.round(r.top), h: Math.round(r.height) });
}
}
return out.slice(0, 24);
});
console.log('SSR 隐藏元素:', JSON.stringify(hidden, null, 1));
await b1.close();
// B) WebKit 带 JS 渲染
const b2 = await webkit.launch();
const c2 = await b2.newContext({ viewport: { width: 1280, height: 900 } });
const p2 = await c2.newPage();
const errs = [], cerr = [];
p2.on('pageerror', e => errs.push(String(e).slice(0,300)));
p2.on('console', m => { if (m.type()==='error') cerr.push(m.text().slice(0,200)); });
const r = await p2.goto('https://www.novalon.cn/about', { waitUntil: 'networkidle', timeout: 60000 }).catch(e=>{console.log('GOTO', e.message);return null;});
await p2.waitForTimeout(2000);
const info = await p2.evaluate(() => {
const h1 = document.querySelector('h1'); const cs = h1 ? getComputedStyle(h1) : null;
const r = h1?.getBoundingClientRect();
return { status: document.readyState, bodyTextLen: (document.body.innerText||'').trim().length,
h1: h1?.innerText?.slice(0,20), h1opacity: cs?.opacity, h1visible: !!r && r.height>0 && parseFloat(cs?.opacity||'1')>0,
hiddenCount: [...document.querySelectorAll('main *')].filter(e=>parseFloat(getComputedStyle(e).opacity)===0).length };
});
await p2.screenshot({ path: 'docs/acceptance/2026-10-20-prod-about/about-webkit.png', fullPage: true });
console.log('webkit status', r?.status(), JSON.stringify(info));
console.log('webkit pageerrors', JSON.stringify(errs), 'consoleErrors', JSON.stringify(cerr.slice(0,5)));
await b2.close();
@@ -0,0 +1,36 @@
import { chromium, webkit, devices } from 'playwright';
const cases = [
['chromium-mobile', chromium, { ...devices['iPhone 14'] }],
['webkit-mobile', webkit, { ...devices['iPhone 14'] }],
['webkit-reduced-motion', webkit, { viewport:{width:1280,height:900}, reducedMotion:'reduce' }],
['chromium-dark', chromium, { viewport:{width:1280,height:900}, colorScheme:'dark' }],
['chromium-3g', chromium, { viewport:{width:1280,height:900} }],
];
for (const [name, engine, opts] of cases) {
const b = await engine.launch();
const ctx = await b.newContext(opts);
const p = await ctx.newPage();
const errs = [], cerr = [], failed = [];
p.on('pageerror', e => errs.push(String(e).slice(0,200)));
p.on('console', m => { if (m.type()==='error') cerr.push(m.text().slice(0,160)); });
p.on('requestfailed', r => failed.push(`${r.failure()?.errorText} ${r.url().slice(0,90)}`));
if (name === 'chromium-3g') {
const cdp = await ctx.newCDPSession(p);
await cdp.send('Network.enable');
await cdp.send('Network.emulateNetworkConditions', { offline:false, latency:400, downloadThroughput: 200*1024, uploadThroughput: 100*1024 });
}
const resp = await p.goto('https://www.novalon.cn/about', { waitUntil: 'networkidle', timeout: 90000 }).catch(e=>{console.log(name,'GOTO',e.message);return null;});
await p.waitForTimeout(2500);
const info = await p.evaluate(() => {
const h1 = document.querySelector('h1'); const cs = h1 ? getComputedStyle(h1) : null;
const r = h1?.getBoundingClientRect();
return { bodyTextLen: (document.body.innerText||'').trim().length,
h1visible: !!r && r.height>0 && parseFloat(cs?.opacity||'1')>0, h1opacity: cs?.opacity,
hidden: [...document.querySelectorAll('main *')].filter(e=>parseFloat(getComputedStyle(e).opacity)===0).length,
mainH: Math.round(document.querySelector('main')?.getBoundingClientRect().height ?? -1) };
});
console.log(name.padEnd(24), 'status', resp?.status(), JSON.stringify(info), 'errs', errs.length, 'cerr', cerr.length, 'failed', failed.length);
if (errs.length) console.log(' pageerrors', JSON.stringify(errs.slice(0,2)));
if (cerr.length) console.log(' console', JSON.stringify(cerr.slice(0,3)));
await b.close();
}
@@ -0,0 +1,21 @@
import { chromium, webkit } from 'playwright';
for (const [name, engine] of [['chromium', chromium], ['webkit', webkit]]) {
const b = await engine.launch();
const ctx = await b.newContext({ viewport: { width: 1280, height: 900 }, javaScriptEnabled: false });
const p = await ctx.newPage();
await p.goto('https://www.novalon.cn/about', { waitUntil: 'domcontentloaded', timeout: 60000 }).catch(()=>{});
await p.waitForTimeout(1500);
const vis = await p.evaluate(() => {
const els = [...document.querySelectorAll('main *')];
let visibleText = 0, hidden = 0;
for (const el of els) {
const cs = getComputedStyle(el);
if (parseFloat(cs.opacity) === 0) hidden++;
if (el.children.length === 0 && (el.textContent||'').trim() && parseFloat(cs.opacity) > 0) visibleText++;
}
return { hiddenByOpacity: hidden, visibleLeafText: visibleText, bodyTextLen: (document.body.innerText||'').trim().length };
});
await p.screenshot({ path: `docs/acceptance/2026-10-20-prod-about/about-nojs-${name}.png`, fullPage: true });
console.log(name, 'JS禁用:', JSON.stringify(vis));
await b.close();
}
@@ -0,0 +1,10 @@
import { webkit } from 'playwright';
const b = await webkit.launch();
const ctx = await b.newContext({ viewport:{width:1280,height:900}, reducedMotion:'reduce' });
const p = await ctx.newPage();
await p.goto('https://www.novalon.cn/about', { waitUntil:'networkidle', timeout:60000 }).catch(()=>{});
await p.waitForTimeout(2500);
await p.screenshot({ path:'docs/acceptance/2026-10-20-prod-about/about-reduced-motion.png', fullPage:true });
const t = await p.evaluate(() => [...document.querySelectorAll('main *')].filter(e=>parseFloat(getComputedStyle(e).opacity)===0).map(e=>({tag:e.tagName, cls:(e.className||'').toString().slice(0,50), text:(e.innerText||'').slice(0,24)})));
console.log('隐藏元素:', JSON.stringify(t, null, 1));
await b.close();
@@ -0,0 +1,26 @@
import { chromium } from 'playwright';
const url = process.argv[2] ?? 'https://www.novalon.cn/about';
const b = await chromium.launch();
const ctx = await b.newContext({ viewport: { width: 1280, height: 900 } });
const p = await ctx.newPage();
const consoleMsgs = [], pageErrors = [], failed = [];
p.on('console', (m) => { if (['error','warning'].includes(m.type())) consoleMsgs.push(`${m.type()}: ${m.text()}`.slice(0, 300)); });
p.on('pageerror', (e) => pageErrors.push(String(e).slice(0, 400)));
p.on('requestfailed', (r) => failed.push(`${r.failure()?.errorText} ${r.url()}`.slice(0, 220)));
const resp = await p.goto(url, { waitUntil: 'networkidle', timeout: 60000 }).catch((e) => { console.log('GOTO_ERR', e.message); return null; });
await p.waitForTimeout(2000);
const info = await p.evaluate(() => ({
title: document.title,
bodyTextLen: (document.body?.innerText ?? '').trim().length,
bodyHtmlLen: document.body?.innerHTML.length ?? 0,
mainLen: document.querySelector('main')?.innerHTML.length ?? -1,
h1: [...document.querySelectorAll('h1')].map((h) => h.innerText.trim()).slice(0, 3),
nextErr: !!document.querySelector('nextjs-portal, [data-nextjs-dialog]'),
}));
await p.screenshot({ path: 'docs/acceptance/2026-10-20-prod-about/about-live.png', fullPage: true });
console.log('status', resp?.status());
console.log(JSON.stringify(info, null, 1));
console.log('pageErrors', JSON.stringify(pageErrors, null, 1));
console.log('console', JSON.stringify(consoleMsgs.slice(0, 12), null, 1));
console.log('failedRequests', JSON.stringify(failed.slice(0, 12), null, 1));
await b.close();
+48
View File
@@ -1213,3 +1213,51 @@ webkit/mobile 的 Tab 引擎差异取证法、`pollBoundingBox` 的二次读取
1. Jenkins 触发器缺失(15.1)——需管理员配置,或确认手动发布为正式路径。
2. 生产侧案例门槛字段已进库,但**尚未有真实案例数据**(0 条),所以"业务可发布案例"这条端到端路径仍未在真实内容上验证过。
3. 视觉基线的逐张读图追认(§14.8 / `baseline-audit.md`)仍是决策人动作。
---
## §16 2026-10-20 · 线上 `/about` 白屏排查:系统性测试结论与一个真缺陷
### 16.1 复现矩阵(先证伪"整站/该页坏了")
| 维度 | 读数 |
|---|---|
| sitemap 全量路由(30 条)逐条真实渲染 | **0 条异常**(正文长度 / `main` 高度 / h1 / pageerror 全部正常) |
| `/about` 直连 | 200;42KB 正文、`main` 26KB、h1「新起点…」、无 pageerror、无 console error |
| 引擎 × 环境 | chromium / webkit / iPhone14(chromium+webkit) / dark / 3G 限速 ⇒ 全部正常、h1 可见 |
| HTML 引用的 18 个 `_next` 资源 | **全部 200**(逐个探测);nginx 访问日志 `/_next/static` **0 个 404** |
| 变体 URL | `/about/` → 308、http → 301、裸域 → 200,均落到同一页 |
| SSR 隐藏初值 | 16 处 `opacity:0`,但**首屏 h1 不在其中**;禁用 JS 时 19 个元素不可见(均为下半页) |
### 16.2 找到的真缺陷:`prefers-reduced-motion` 下 hydration 不匹配(React #418),大片元素停在 opacity:0
- 复现:`webkit + reducedMotion:'reduce'` ⇒ **pageerror `Minified React error #418`**,
且 `main` 内 **14** 个元素 opacity 恒为 0(正常环境只有 3 个,且都是首屏以下的滚动入场项)。
- 根因:`src/hooks/use-reduced-motion.ts` 用 `window.matchMedia` 作 `useState` 初值 ⇒
**SSR 恒 false、客户端首帧 true**;而 `scroll-reveal.tsx` / `template.tsx` / `page-transition.tsx`
用它决定 `initial` / `variants` / 甚至**早返回不同树结构** ⇒ 与 SSR HTML 不一致。
更糟的是 reduce 时 `whileInView` 被清空 ⇒ 元素停在 `initial` 的 `opacity:0`。
- 修法(三处同改,结构恒定):
1. hook 首帧恒 `false`,挂载后 effect 同步真实偏好(过 hydration 后改值安全);
2. `ScrollReveal`/`StaggerReveal` 的 `initial`/`whileInView`/`variants` **不再按 reduce 清空**,
减少动效改为 `duration: 0` / `stagger: 0`(一步到位);
3. `template.tsx` 与 `StaggerChildren` **去掉早返回裸结构**,改为空 variants(树结构恒定)。
- 回归守卫:`e2e/reduced-motion-hydration.spec.ts`(`/about` 与 `/`)断言
①`matchMedia` 自证 reduce 生效 ②无 hydration 类错误 ③h1 与末段标题 opacity=1。
**变异验证**:把 hook 改回 matchMedia 初值 ⇒ 2 条全红;恢复 ⇒ 2 条绿。
### 16.3 用户侧白屏最可能的原因与已做的缓解
- 生产窗口:07:45 上传 → 07:48 容器重启。**在该窗口内访问**会拿到半套资源 ⇒ 白屏,刷新即好。
- 另一条我引入的风险:我最初对 `dist/_next/static` 用了 `--delete`,删掉了上一代 chunk;
回访者若持有旧 HTML(浏览器缓存/bfcache),会请求已删除的 chunk ⇒ hydration 失败。
**已缓解**:从 `dist_backup_20261020_074545` 用 `--ignore-existing` 合并回上一代(101 个文件),
并把 runbook 改成**禁止对 `_next/static` 用 `--delete`**(保留 N-1 代)。
- 仍建议用户端做一次**强制刷新**(⌘⇧R / Ctrl+F5);若仍白屏,需要其浏览器与版本或一张截图才能继续定位。
### 16.4 未复现的部分(如实记录)
「整页纯白」在我这边**未复现**(6 种环境 + 30 条路由全正常)。已修的 reduce 缺陷会让下半页不可见,
但不至于整页白;真正整页白只可能来自"资源半套/旧 chunk 404 后客户端崩溃"这条路径,
与本轮的上传窗口与 `--delete` 吻合。若用户仍复现,下一步是取 `navigator.userAgent`、
`performance.getEntriesByType('resource')` 里的 4xx/5xx 与 console 首条错误。
+3 -1
View File
@@ -68,6 +68,8 @@ docker start novalon-website
- 合并方式与 `#29` 一致:`main` 是 `dev` 的严格祖先时用 **fast-forward-only**,保住 sha 可引用。
- 发布后产物要点:`dist/_next/static` 镜像必须存在(见 §3.2 步骤 3);
缺它 = 全站 CSS/JS 404 而 HTML 全 200。
**不要对 `_next/static` 用 `--delete`**:回访者的 HTML 可能来自旧缓存,仍在引用上一代 chunk;
删掉会让这些人 hydration 失败(表现为白屏)。用 `--ignore-existing` 合并旧代,或保留 N-1 代。
### 3.2 手动路径(2026-10-20 实际执行并验证)
@@ -81,7 +83,7 @@ ssh root@139.155.109.62 'cd /home/novalon/docker-app/novalon-website \
# 2) 增量上传(node_modules 基本不变 ⇒ rsync 只传差异,150MB 原始内容线上只走 3.4MB)
rsync -az dist/standalone/ root@…:/home/novalon/docker-app/novalon-website/dist/standalone/
rsync -az dist/static/ root@…:/home/novalon/docker-app/novalon-website/dist/static/
rsync -az --delete dist/static/ root@…:/home/novalon/docker-app/novalon-website/dist/_next/static/ # nginx 站点根镜像
rsync -az dist/static/ root@…:/home/novalon/docker-app/novalon-website/dist/_next/static/ # nginx 站点根镜像(**不要 --delete**)
rsync -az public/ root@…:/home/novalon/docker-app/novalon-website/public/
rsync -az public/ root@…:/home/novalon/docker-app/novalon-website/dist/ # 根级静态资产
# 3) 重建镜像并重启(compose 是 v1 ⇒ docker-compose)
+68
View File
@@ -0,0 +1,68 @@
import { test, expect } from './fixtures';
/**
* 减少动效(prefers-reduced-motion: reduce)下的 hydration 与可见性回归。
*
* 缺陷原型(2026-10-20 从生产排查出来):`useReducedMotion` 用 `window.matchMedia` 作 useState 初值,
* 于是 SSR 恒 false、客户端首帧 true;组件再用它决定 `initial`/`variants`,
* 导致 ①React #418(hydration 不匹配)②减少动效用户看到大片元素停在 opacity:0。
*
* 断言两条,都不依赖像素:
* ① 页面加载与滚动过程中**不得出现 hydration 相关错误**(console.error 或 pageerror);
* ② 滚到底部后,末段标题的 opacity 必须为 1(内容真的可见,而不是停在初始隐藏态)。
*
* 敏感性:把 hooks/use-reduced-motion.ts 的 `useState(false)` 改回 matchMedia 初值,
* 或把 scroll-reveal 的 `initial={…}` 改回 `shouldReduceMotion ? {} : …` ⇒ 本例应转红。
*/
// 用 contextOptions(BrowserContextOptions 的正式字段)而不是 test.use 的便捷项:
// 后者不在本仓自定义 fixtures 的 TestOptions 推导里(type-check:e2e 会拦),且等价。
test.use({ contextOptions: { reducedMotion: 'reduce' } });
const HYDRATION_HINTS = [/hydrat/i, /did not match/i, /#418/, /Minified React error/];
function collectErrors(page: import('@playwright/test').Page) {
const hits: string[] = [];
page.on('pageerror', (e) => {
const s = String(e);
if (HYDRATION_HINTS.some((r) => r.test(s))) hits.push(`pageerror: ${s.slice(0, 240)}`);
});
page.on('console', (m) => {
if (m.type() !== 'error') return;
const s = m.text();
if (HYDRATION_HINTS.some((r) => r.test(s))) hits.push(`console: ${s.slice(0, 240)}`);
});
return hits;
}
const CASES = [
{ path: '/about', lateHeading: /准备好开始了吗/ },
{ path: '/', lateHeading: /现在有什么卡住你了/ },
];
for (const { path, lateHeading } of CASES) {
test(`${path} 在 reduce 下无 hydration 错误且末段可见`, async ({ page }) => {
const errors = collectErrors(page);
await page.goto(path, { waitUntil: 'networkidle', timeout: 60000 });
// 自证:确实处在 reduce 偏好下,否则本用例什么都没测到
expect(
await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches),
'reducedMotion 未生效',
).toBe(true);
const h1 = page.locator('h1').first();
await expect(h1).toBeVisible({ timeout: 15000 });
const h1Opacity = await h1.evaluate((el) => Number(getComputedStyle(el).opacity));
expect(h1Opacity, '首屏 h1 不得停在 opacity:0').toBe(1);
// 滚到底部,让 whileInView 触发;reduce 下应「一步到位」变可见
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForTimeout(1000);
const late = page.getByRole('heading', { name: lateHeading }).first();
await expect(late, '末段标题应存在(页面完整)').toBeVisible({ timeout: 10000 });
await expect
.poll(async () => late.evaluate((el) => Number(getComputedStyle(el).opacity)), { timeout: 5000 })
.toBe(1);
expect(errors, `出现 hydration 错误:\n${errors.join('\n')}`).toEqual([]);
});
}
+7 -4
View File
@@ -36,16 +36,19 @@ export default function MarketingTemplate({
}) {
const shouldReduceMotion = useReducedMotion();
if (shouldReduceMotion) {
return <>{children}</>;
}
// 2026-10-20:**不再早返回 `<>{children}</>`** —— 那会让树结构与 SSR 不同
// (服务端永远渲染 motion.div,客户端 reduce 用户渲染裸 Fragment)⇒ React #418。
// 改为结构恒定,只在挂载后把 variants 换成空组(时长 0、无位移)。
const variants = shouldReduceMotion
? { initial: {}, enter: {}, exit: {} }
: pageVariants;
return (
<motion.div
initial="initial"
animate="enter"
exit="exit"
variants={pageVariants}
variants={variants}
>
{children}
</motion.div>
+4 -6
View File
@@ -91,10 +91,8 @@ export function StaggerChildren({
}) {
const shouldReduceMotion = useReducedMotion();
if (shouldReduceMotion) {
return <div className={className}>{children}</div>;
}
// 2026-10-20:不再早返回裸 div —— 结构必须与 SSR 一致(否则减少动效用户挂载后会整棵树重挂,
// 与 use-reduced-motion 的 hydration 修复同一原则)。减少动效只把 stagger 压到 0。
return (
<motion.div
className={className}
@@ -103,8 +101,8 @@ export function StaggerChildren({
variants={{
visible: {
transition: {
staggerChildren: 0.06,
delayChildren: 0.05,
staggerChildren: shouldReduceMotion ? 0 : 0.06,
delayChildren: shouldReduceMotion ? 0 : 0.05,
},
},
}}
+11 -5
View File
@@ -79,12 +79,16 @@ export function ScrollReveal({
return (
<motion.div
className={className}
initial={shouldReduceMotion ? {} : getInitialState(variant, yOffset, xOffset)}
whileInView={shouldReduceMotion ? {} : getAnimateState(variant)}
// 2026-10-20:initial/whileInView **不随 reduce 清空**。
// 清空只会让元素停在 initial 的 opacity:0 上(减少动效用户看到空白),
// 而且与 SSR HTML 不一致会触发 React #418。减少动效用「时长 0」表达:
// 元素照常从 initial 走到 animate,只是一步到位。
initial={getInitialState(variant, yOffset, xOffset)}
whileInView={getAnimateState(variant)}
viewport={{ once, margin, amount }}
transition={{
duration: shouldReduceMotion ? 0 : duration,
delay,
delay: shouldReduceMotion ? 0 : delay,
ease: EASE_OUT,
}}
>
@@ -131,8 +135,10 @@ export function StaggerReveal({
};
const itemVariants = {
hidden: shouldReduceMotion ? {} : getInitialState(variant, yOffset, xOffset),
visible: shouldReduceMotion ? {} : getAnimateState(variant),
// 同 ScrollReveal:状态本身不随 reduce 清空(清空会让元素停在 opacity:0,
// 且与 SSR 首帧不一致 ⇒ React #418)。减少动效只把 stagger/时长压到 0。
hidden: getInitialState(variant, yOffset, xOffset),
visible: getAnimateState(variant),
};
return (
+8 -6
View File
@@ -1,12 +1,12 @@
import { useEffect, useState } from 'react';
export function useReducedMotion() {
const [shouldReduceMotion, setShouldReduceMotion] = useState(() => {
if (typeof window !== 'undefined') {
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
}
return false;
});
// 2026-10-20(生产白屏排查):**首帧必须与服务器一致**。
// 浏览器里用 `window.matchMedia` 作 useState 初值时,SSR 恒为 false、客户端首帧为 true
// ⇒ 任何依赖它的 initial/variants 都会与 SSR HTML 不同 ⇒ React #418(hydration 不匹配),
// 且减少动效用户会看到大片元素停在 opacity:0(实测 /about 上 14 个)。
// 改为:首帧恒 false,挂载后用 effect 同步真实偏好(此时已过 hydration,改值安全)。
const [shouldReduceMotion, setShouldReduceMotion] = useState(false);
useEffect(() => {
if (typeof window === 'undefined') {
@@ -14,6 +14,8 @@ export function useReducedMotion() {
}
const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
// 立即同步一次:挂载后才生效,不会影响 hydration
setShouldReduceMotion(mediaQuery.matches);
const handleChange = (event: MediaQueryListEvent) => {
setShouldReduceMotion(event.matches);