From 2f86c4419a188a296e695443dfd6070b40510e00 Mon Sep 17 00:00:00 2001 From: zhangxiang Date: Tue, 20 Oct 2026 14:00:41 +0800 Subject: [PATCH] =?UTF-8?q?fix(motion):=20=E7=AB=99=E5=86=85=E8=B7=B3?= =?UTF-8?q?=E8=BD=AC=E7=99=BD=E5=B1=8F=E2=80=94=E2=80=94=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E5=86=85=E5=AE=B9=E4=B8=8D=E5=86=8D=E8=B5=B0=20AnimatePresence?= =?UTF-8?q?=20wait=20=E9=80=80=E5=9C=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 现象:生产环境所有站内跳转白屏,地址与标题已切换,刷新才恢复。 根因:AnimatePresence mode="wait" 要求新页等旧页退场完成才挂载;App Router 导航期间的重复渲染会重置退场完成标记,切换 state 的窗口被错过, motion.div 永久停在 exit 变体(opacity:0; translateY(-8px))。 修法:路由内容只保留 key={pathname} 的 280ms 入场;首屏仍由 mounted 渲染 裸 children;reduce 变体改为显式可见终值,避免切到空变体时冻结在半透明。 守卫:新增 client-navigation-visibility(导航后落定再读祖先链乘积); 首屏用例改逐帧采样;视觉用例改逐屏滚动触发 whileInView。 验证:E2E 20/20(四浏览器)、视觉 125/125、单测 1815、type-check/lint 0 error。 --- docs/lessons-learned.md | 27 ++++++++++++ e2e/client-navigation-visibility.spec.ts | 52 ++++++++++++++++++++++ e2e/first-paint-visibility.spec.ts | 45 +++++++++++++++---- e2e/reduced-motion-hydration.spec.ts | 8 ++-- e2e/visual-regression.spec.ts | 22 +++++++--- src/app/(marketing)/template.tsx | 12 ++++-- src/components/ui/page-transition.tsx | 55 ++++++++++-------------- 7 files changed, 167 insertions(+), 54 deletions(-) create mode 100644 e2e/client-navigation-visibility.spec.ts diff --git a/docs/lessons-learned.md b/docs/lessons-learned.md index 4756e9d..66d7984 100644 --- a/docs/lessons-learned.md +++ b/docs/lessons-learned.md @@ -896,3 +896,30 @@ if [ "$A" -eq 0 ] && [ "$B" -eq 0 ]; then git add … && git commit … && git p ⇒ 通用判据:**当 DOM 祖先可以整体降透明度时,「元素 opacity=1」不构成可见性证明; 仪器必须先证明页面处于终态,再解释对比度。** + +### 5.50 AnimatePresence mode="wait" 会让新页永久停在 exit 态(2026-10-20) + +**现象**:生产环境所有站内跳转白屏,地址栏与标题已变,刷新(冷加载)才正常。 +**复现**:production standalone 产物,首页点「关于我们」;`main#main-content` 的父级 motion.div +内联停在 `opacity:0; transform:translateY(-8px)`(exit 变体)且不再变化,祖先链有效 opacity 恒 0。 + +**机理**:`` 要等旧子树的 exit 完成才挂载新子树。App Router 导航期间 +本组件会多次重渲染,每次 `children` 引用变化都会让 AnimatePresence 重跑 diff 并把退场完成标记 +重置为 false,200ms 后切换 state 的窗口被错过。保留 `exit` 也不能只靠 sync 模式兜底:实测旧 +`main` 节点常驻(`mains: 2`),因为注销同样依赖这套 presence bookkeeping。 + +**修法**:路由内容不再包 AnimatePresence,`` 只保留入场动画 +(280ms,令牌层不变);首屏仍由 `mounted` 门控渲染裸 children。不要用「去掉 exit」或 +「mode=popLayout」折中——前者留下常驻旧子树,后者留下绝对定位的隐形残影。 + +**连带修正(同一条因果链)**: +- 移除 presence 的 `initial={false}` 上下文后,子树恢复各自入场,屏下的 ScrollReveal 在全页截图时 + 仍处 opacity:0。视觉用例的「直接跳到底」会跳过中间各屏(IntersectionObserver 只回调当前视口), + 改为**逐屏滚动**;视觉全量 125/125。 +- 首屏可见性断言改为**逐帧采样**:并行负载下,单点读 h1 会与「水合后子树重挂、入场重新开始」竞争。 + +**回归守卫**:`e2e/client-navigation-visibility.spec.ts` —— 点页脚链接后等 800ms(退场+入场落定) +再读祖先链乘积;`E2E_TARGET=production` 下四浏览器通过。 + +⇒ 通用判据:**跨路由的「等旧页退场再挂新页」不能依赖 framer 的 presence 状态机; +新页面挂载不得以旧页面的动画完成作为前置条件。** diff --git a/e2e/client-navigation-visibility.spec.ts b/e2e/client-navigation-visibility.spec.ts new file mode 100644 index 0000000..25cd55a --- /dev/null +++ b/e2e/client-navigation-visibility.spec.ts @@ -0,0 +1,52 @@ +import { test, expect } from './fixtures'; + +/** + * 客户端导航可见性回归(2026-10-20 生产白屏)。 + * + * 缺陷原型:首页点击导航后 URL 与正文都已切换,但 PageTransition 的 motion.div 停在 + * exit 变体(inline opacity:0; translateY(-8px)),新页面永不进入 ⇒ 整页白屏,刷新才恢复。 + * 只看 h1 自身 opacity 读不到(恒为 1),必须读祖先链的乘积累积。 + * + * 复核:`E2E_TARGET=production npx playwright test client-navigation-visibility`。 + */ +const NAV_STEPS = [ + { href: '/about', label: '关于我们' }, + { href: '/products', label: '产品矩阵' }, + { href: '/methodology', label: '方法论' }, + { href: '/insights', label: '洞察' }, + { href: '/about/brand', label: '品牌故事' }, +]; + +function effectiveOpacity(page: import('@playwright/test').Page) { + return page.evaluate(() => { + const main = document.querySelector('main#main-content'); + let opacity = 1; + let node: Element | null = main; + while (node) { + opacity *= Number(getComputedStyle(node).opacity); + node = node.parentElement; + } + return opacity; + }); +} + +test('首页经客户端导航到各栏目后内容必须可见', async ({ page }) => { + await page.goto('/', { waitUntil: 'networkidle', timeout: 60000 }); + await expect + .poll(() => effectiveOpacity(page), { timeout: 15000 }) + .toBeGreaterThan(0.99); + + for (const step of NAV_STEPS) { + await page.getByTestId('footer').locator(`a[href="${step.href}"]`).first().click(); + await page.waitForURL(`**${step.href}`, { timeout: 15000 }); + // 退场 200ms + 入场 280ms 都在 URL 变化之后才落定;URL 一变就采样会读到退场前的 1(假绿)。 + await page.waitForTimeout(800); + + await expect + .poll(() => effectiveOpacity(page), { + timeout: 5000, + message: `导航到 ${step.href}(${step.label})后整页有效 opacity 未回到 1(白屏)`, + }) + .toBeGreaterThan(0.99); + } +}); diff --git a/e2e/first-paint-visibility.spec.ts b/e2e/first-paint-visibility.spec.ts index 563d83b..e26439f 100644 --- a/e2e/first-paint-visibility.spec.ts +++ b/e2e/first-paint-visibility.spec.ts @@ -1,5 +1,11 @@ import { test, expect } from './fixtures'; +declare global { + interface Window { + __firstPaint?: Array<{ ready: string | null; opacity: number }>; + } +} + /** * 冷首访可见性守卫(2026-10-20)。 * @@ -10,13 +16,16 @@ import { test, expect } from './fixtures'; * * 断言两条,都能失败: * ① 禁用 JS(等价"脚本没跑起来"):h1 的内联样式仍是 opacity:0,但**计算值必须为 1**; - * ② 正常加载:水合后置位 data-content-ready,且 h1 仍可见(交接不闪回 0)。 + * ② 正常加载:水合后置位 data-content-ready,且 h1 在交接前后每一帧都可见(不闪回 0)。 */ test.describe('首屏可见性(无 JS / 水合交接)', () => { test('禁用 JS 时 h1 计算 opacity 为 1(内联仍是 0,靠兜底规则)', async ({ browser }) => { const ctx = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 1280, height: 900 } }); const page = await ctx.newPage(); await page.goto('/about', { waitUntil: 'domcontentloaded', timeout: 60000 }); + // JS 关闭时 CSS 仍可能晚于 DOM 到达;不等到 load 就取 computed style, + // 会把「样式表还没到」误读成「兜底规则失效」(2026-10-20 并行跑实测)。 + await page.waitForLoadState('load', { timeout: 30000 }); const snap = await page.evaluate(() => { const h1 = document.querySelector('h1') as HTMLElement | null; return { @@ -29,12 +38,26 @@ test.describe('首屏可见性(无 JS / 水合交接)', () => { await ctx.close(); }); - test('水合后 800ms 置位 data-content-ready 且 h1 仍可见', async ({ page }) => { + test('水合后 800ms 置位 data-content-ready 且 h1 始终可见', async ({ page }) => { + // 单点读 h1 会与「水合后子树重挂、入场动画重新开始」的瞬间竞争(并行跑偶发读到 0)。 + // 改为逐帧采样:交接前(data-content-ready 未置位)每一帧都必须可见,交接后也必须可见。 + await page.addInitScript(() => { + const samples: Array<{ ready: string | null; opacity: number }> = []; + window.__firstPaint = samples; + const tick = () => { + const h1 = document.querySelector('h1'); + if (h1) { + samples.push({ + ready: document.documentElement.getAttribute('data-content-ready'), + opacity: Number(getComputedStyle(h1).opacity), + }); + } + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + }); await page.goto('/about', { waitUntil: 'domcontentloaded', timeout: 60000 }); - const h1 = page.locator('h1').first(); - await expect(h1).toBeVisible({ timeout: 10000 }); - const early = await h1.evaluate((el) => Number(getComputedStyle(el).opacity)); - expect(early, '首帧(水合前后)h1 必须是可见的').toBe(1); + await expect(page.locator('h1').first()).toBeVisible({ timeout: 10000 }); await expect .poll(() => page.evaluate(() => document.documentElement.getAttribute('data-content-ready')), { @@ -44,7 +67,13 @@ test.describe('首屏可见性(无 JS / 水合交接)', () => { .toBe('1'); await page.waitForTimeout(400); - const after = await h1.evaluate((el) => Number(getComputedStyle(el).opacity)); - expect(after, '交接后不得闪回 opacity:0').toBe(1); + const samples = await page.evaluate(() => window.__firstPaint ?? []); + const beforeHandoff = samples.filter((s) => s.ready === null); + expect(beforeHandoff.length, '采样必须覆盖交接前(否则本用例什么都没测到)').toBeGreaterThan(0); + expect( + Math.min(...beforeHandoff.map((s) => s.opacity)), + '交接前 h1 任一帧都不得为 0', + ).toBe(1); + expect(samples.at(-1)?.opacity, '交接后不得闪回 opacity:0').toBe(1); }); }); diff --git a/e2e/reduced-motion-hydration.spec.ts b/e2e/reduced-motion-hydration.spec.ts index fe296ef..02f5389 100644 --- a/e2e/reduced-motion-hydration.spec.ts +++ b/e2e/reduced-motion-hydration.spec.ts @@ -64,11 +64,13 @@ for (const { path, lateHeading } of CASES) { }); expect(h1Opacity, '首屏 h1 的祖先链不得停在半透明/0').toBeGreaterThan(0.99); - // 滚到底部,让 whileInView 触发;reduce 下应「一步到位」变可见 - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - await page.waitForTimeout(1000); + // 把目标滚进视口,让 whileInView 触发;reduce 下应「一步到位」变可见。 + // 不能 `window.scrollTo(0, scrollHeight)` 直接跳底:reduce 会禁用平滑滚动(瞬时跳转), + // 目标从视口外被越过、IntersectionObserver 永不回调 ⇒ 探针自设条件造成假红。 const late = page.getByRole('heading', { name: lateHeading }).first(); await expect(late, '末段标题应存在(页面完整)').toBeVisible({ timeout: 10000 }); + await late.scrollIntoViewIfNeeded(); + await page.waitForTimeout(1000); await expect .poll( async () => diff --git a/e2e/visual-regression.spec.ts b/e2e/visual-regression.spec.ts index a0d99a6..e6bf705 100644 --- a/e2e/visual-regression.spec.ts +++ b/e2e/visual-regression.spec.ts @@ -46,14 +46,22 @@ async function waitForPageStable(page: Page) { await page.waitForLoadState('networkidle'); await page.waitForTimeout(2000); - // 触发全页 ScrollReveal / StaggerReveal:先滚到底再回顶,让所有 below-the-fold + // 触发全页 ScrollReveal / StaggerReveal:逐屏滚到底再回顶,让所有 below-the-fold // 模块的 whileInView 动画进入最终态,避免全页截图时内容停在 opacity:0 初始态。 - // 视觉回归项目已统一 reducedMotion:'reduce',此滚动作为双保险,覆盖任何媒体查询 - // 在 viewport resize 期间短暂失真的边界情况。 - await page.evaluate(() => window.scrollTo({ top: document.body.scrollHeight, behavior: 'instant' })); - await page.waitForTimeout(800); - await page.evaluate(() => window.scrollTo({ top: 0, behavior: 'instant' })); - await page.waitForTimeout(200); + // 不能直接 `scrollTo(scrollHeight)` 一跳到底:IntersectionObserver 只会回调当前视口 + // 内的目标,中间各屏被跳过 ⇒ 截图出来是空白段(2026-10-20 移除路由级 AnimatePresence + // 后首屏不再替子树屏蔽 initial,这条路径才真正被走到)。 + await page.evaluate(async () => { + const step = Math.max(400, Math.floor(window.innerHeight * 0.8)); + for (let y = 0; y <= document.body.scrollHeight; y += step) { + window.scrollTo({ top: y, behavior: 'instant' }); + await new Promise((resolve) => setTimeout(resolve, 120)); + } + window.scrollTo({ top: document.body.scrollHeight, behavior: 'instant' }); + await new Promise((resolve) => setTimeout(resolve, 400)); + window.scrollTo({ top: 0, behavior: 'instant' }); + await new Promise((resolve) => setTimeout(resolve, 200)); + }); await page.evaluate(() => { document.querySelectorAll('img').forEach(img => { diff --git a/src/app/(marketing)/template.tsx b/src/app/(marketing)/template.tsx index b164078..cef57e7 100644 --- a/src/app/(marketing)/template.tsx +++ b/src/app/(marketing)/template.tsx @@ -48,14 +48,20 @@ export default function MarketingTemplate({ // 2026-10-20:**不再早返回 `<>{children}`** —— 那会让树结构与 SSR 不同 // (服务端永远渲染 motion.div,客户端 reduce 用户渲染裸 Fragment)⇒ React #418。 - // 改为结构恒定,只在挂载后把 variants 换成空组(时长 0、无位移)。 + // 2026-10-20(导航白屏修复的连带回归):reduce 变体不能写成 `{}`。motion.div 挂载时 + // hook 仍是 false(首帧与 SSR 一致),它按 pageVariants 开始 0→1 的入场;effect 切到 + // reduce 后 `animate="enter"` 若映射到空变体,framer 会停在当前帧(实测 opacity 0.2) + // 而不是「一步到位」。改为显式给可见终值 + 0 时长。 const variants = shouldReduceMotion - ? { initial: {}, enter: {}, exit: {} } + ? { + initial: { opacity: 1, y: 0 }, + enter: { opacity: 1, y: 0, transition: { duration: 0 } }, + } : pageVariants; return ( {children}; } - // 2026-10-20(多端复核):reduce 下**不能**在 mounted 之后切回裸 children。 - // 原先 `if (!mounted || shouldReduceMotion) return children` 会让已挂载的 motion.div - // 在 reduce 状态落地的瞬间被 AnimatePresence 的 exit 链接管,而在 headless/移动仿真里 - // exit 链没有稳定落点,实测整页祖先停在 opacity 0.15–0.35(桌面 1440 甚至 0)。 - // 现在无论是否 reduce 都保留同一个 motion.div,只用零时长 + 可见变体把动画「一步到位」。 + // 2026-10-20(生产导航白屏):**不再用 AnimatePresence 包裹路由内容**。 + // 原写法 `` 会让新页面 + // 等旧页面退场完成后才挂载;而 Next App Router 在导航过程中会多次重渲染本组件,每次新的 + // children 引用都会让 AnimatePresence 重跑 diff 并把退场完成标记重置,200ms 退场动画结束后 + // 切换 state 的机会被错过 ⇒ 同一个 motion.div 永久停在 exit 变体(实测 inline opacity:0; + // translateY(-8px)),整页白屏,刷新(走 mounted=false 的裸 children 路径)才恢复。 + // 现在只保留入场:key 随 pathname 变化触发重挂,入场动画仍按令牌层 280ms 播放。 + // 回归守卫:e2e/client-navigation-visibility.spec.ts。 const reducedVariants = { initial: { opacity: 1, y: 0, scale: 1 }, animate: { opacity: 1, y: 0, scale: 1, transition: { duration: 0 } }, - exit: { opacity: 1, transition: { duration: 0 } }, }; const variants = shouldReduceMotion ? reducedVariants : pageVariants; return ( - - - {children} - - + + {children} + ); } @@ -125,8 +115,7 @@ export function StaggerChildren({ {child} )) - : children - } + : children} ); }