diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 689d143..2106c75 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -12,7 +12,15 @@ concurrency: cancel-in-progress: false jobs: + validate: + uses: ./.github/workflows/validate.yml + with: + upload-dist: true + secrets: + UMAMI_API_KEY: ${{ secrets.UMAMI_API_KEY }} + deploy: + needs: validate runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -21,38 +29,14 @@ jobs: with: persist-credentials: false - - name: Enable Corepack - run: corepack enable - - - name: Setup Node.js - uses: actions/setup-node@v5 - with: - node-version: '24.13.0' - cache: 'pnpm' - - - name: Install dependencies - run: pnpm install --frozen-lockfile - - - name: Cache Astro assets - uses: actions/cache@v5 + - name: Download the tested production site + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2, Node 24 with: - path: node_modules/.astro - key: ${{ runner.os }}-astro-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} - restore-keys: | - ${{ runner.os }}-astro-${{ hashFiles('pnpm-lock.yaml') }}- - ${{ runner.os }}-astro- - - - name: Validate source and content - run: | - pnpm test:unit - pnpm type-check - pnpm test:markdown + name: validated-dist + path: dist - - name: Build and package site - env: - UMAMI_API_KEY: ${{ secrets.UMAMI_API_KEY }} + - name: Package committed source with validated site run: | - pnpm build git archive --format=tar --output=site-source.tar HEAD tar -rf site-source.tar dist diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..b915757 --- /dev/null +++ b/.github/workflows/validate.yml @@ -0,0 +1,99 @@ +name: Validate blog + +on: + pull_request: + branches: [main] + workflow_dispatch: + inputs: + extended: + description: Also test Firefox and WebKit + type: boolean + default: true + schedule: + - cron: '20 20 * * 0' # Monday 04:20 in Singapore + workflow_call: + inputs: + upload-dist: + type: boolean + default: false + extended: + type: boolean + default: false + secrets: + UMAMI_API_KEY: + required: false + +permissions: + contents: read + +concurrency: + group: validate-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + checks: + # Goldens and compositor captures use Windows, matching local reviewed baselines. + # Deploy still runs on Linux and consumes this exact validated static directory. + runs-on: windows-2025 + timeout-minutes: 30 + env: + BROWSER_MATRIX: ${{ (github.event_name == 'schedule' || inputs.extended) && 'extended' || 'primary' }} + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1, Node 24 + with: + persist-credentials: false + - name: Enable Corepack + run: corepack enable + - name: Setup Node.js + uses: actions/setup-node@v5 + with: + node-version: '24.13.0' + cache: pnpm + - name: Install dependencies + run: pnpm install --frozen-lockfile + - name: Cache Astro assets + uses: actions/cache@v5 + with: + path: node_modules/.astro + key: ${{ runner.os }}-astro-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-astro-${{ hashFiles('pnpm-lock.yaml') }}- + - name: Unit tests + run: pnpm test:unit + - name: Astro type checks + run: pnpm type-check + - name: Markdown and MDX integration + run: pnpm test:markdown + # Both commands write dist: this clean build must follow integration, never overlap it. + - name: Build production site and verify output + env: + UMAMI_API_KEY: ${{ secrets.UMAMI_API_KEY }} + run: pnpm build + - name: Install Chromium + run: pnpm exec playwright install chromium + - name: Install additional engines + if: env.BROWSER_MATRIX == 'extended' + run: pnpm exec playwright install firefox webkit + - name: Browser interaction, motion and visual regression + run: pnpm test:browser + - name: Preserve browser diagnostics + if: ${{ !cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7, Node 24 + with: + name: browser-report-${{ github.run_id }}-${{ github.run_attempt }} + path: | + playwright-report/ + test-results/ + if-no-files-found: ignore + retention-days: 7 + compression-level: 0 # PNG/video/trace files are already compressed. + - name: Preserve validated site for deployment + if: inputs.upload-dist + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7, Node 24 + with: + name: validated-dist + path: dist/ + if-no-files-found: error + retention-days: 1 + compression-level: 0 diff --git a/.gitignore b/.gitignore index 8e615ba..6e2a4f7 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,10 @@ dist/ /audit/ *.log +# browser regression diagnostics (reviewed golden images live in tests/browser/snapshots) +/playwright-report/ +/test-results/ + # private config .env .env.* diff --git a/AGENTS.md b/AGENTS.md index 2a1b8af..39e625c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,3 +10,20 @@ reduced motion, browser return navigation, and failure states. Run the project's pnpm unit, Markdown/MDX integration, type, and production build checks before delivery. Integration tests and production builds both write dist: run them sequentially. Retain theme/upstream attribution and local font licenses. + +Read [MAINTENANCE.md](MAINTENANCE.md) for module ownership, motion history and +deployment constraints. Run `pnpm test:browser` against the normal production +build; [tests/browser/README.md](tests/browser/README.md) explains the browser +matrix, animation probes, screenshots and diagnostics. Source-pattern unit +tests alone do not establish visual correctness. Never update screenshot +baselines just to make a failing test pass; inspect actual/expected/diff images. + +Keep Home title motion exclusively in `voyage.ts`. Incoming CSS preparation, +after-swap title animation and post-transition interaction setup serve different +lifecycle phases. Preserve the narrowly scoped Home root opacity fix, real-sky +additive blending, planet grain and generation/abort guards. Consult the motion +decision history before simplifying these paths. + +Changes to architecture, lifecycle, dependencies, commands, tests or deployment +must update the affected maintenance/test documentation in the same change. +Report checks actually run, browser/viewport coverage and remaining limitations. diff --git a/CMS_SETUP.md b/CMS_SETUP.md index 7588d3a..34c260d 100644 --- a/CMS_SETUP.md +++ b/CMS_SETUP.md @@ -88,3 +88,5 @@ GitHub OAuth 应用设置: 认证服务仅在 Docker 内网开放,Nginx 转发 /oauth 与 /oauth/callback;/oauth/health 可检查服务是否已读取凭据。登录只允许 Chen017,并检查目标仓库写权限。OAuth 的 public_repo 授权范围并不只限这一个公开仓库;改私有仓库或增加编辑账号需相应调整并复核。 部署会同步代码删除,保留服务器 .env、Git、依赖和缓存目录。缺少 rsync 时,root 权限的 Debian/Ubuntu 主机会自动安装;其他系统需自行提供 rsync。 + +main 推送先调用共享验证流程,依次完成单元、类型、Markdown/MDX、正常生产构建与浏览器回归检查;验证通过后,部署下载同一次运行的 `validated-dist`,不在服务器重复构建。检查失败时网站不会进入后续部署步骤。工作流触发条件、必要 Secrets、诊断产物与回退方法统一记录在 [MAINTENANCE.md](MAINTENANCE.md) 的 CI/CD 部分。 diff --git a/DESIGN_SYSTEM.md b/DESIGN_SYSTEM.md index b3949c9..341214a 100644 --- a/DESIGN_SYSTEM.md +++ b/DESIGN_SYSTEM.md @@ -139,6 +139,12 @@ One short homepage opening may run on the first visit of a browser session; keep all content immediately visible, skip it on history return and reduced motion, without a replay control. Scroll-linked decoration follows native scrolling and never captures wheel or touch input. +The shorter Home return entrance is separate from that first-session opening: +both `Etalib’s` and `Space.` start from their prepared poses during the incoming +slide. Preserve the existing stagger (110ms + 580ms and 190ms + 820ms), without +restarting at transition completion. CSS must establish the initial poses before +snapshot capture; removing that preparation creates a visible downward jump. +See `MAINTENANCE.md` for ownership and the historical regression decisions. Parallax photography must overscan by at least its full travel on every screen width; use explicit 20px horizontal / 14px vertical overscan rather than a scale factor whose margin becomes insufficient in a narrow window. diff --git a/MAINTENANCE.md b/MAINTENANCE.md index a25c5d4..8afbe10 100644 --- a/MAINTENANCE.md +++ b/MAINTENANCE.md @@ -26,13 +26,18 @@ Keep functional article fields in the schema. Unreferenced tags/attribution meta ## Verification -- `pnpm check` -- `pnpm type-check` uses the same Astro-aware checker, including `.astro` imports. +- Use Node.js **24.13.0** and the package's Corepack-managed **pnpm 10.29.2** to reproduce CI. The supported Node minimum remains in `package.json`. +- `corepack enable`, then `pnpm install --frozen-lockfile`. Use `pnpm dev` for authoring, `pnpm cms:local` for local CMS editing. Development search intentionally reports unavailable; test Pagefind in the production preview. +- `pnpm type-check` runs the Astro-aware checker, including `.astro` imports. `pnpm check` is an alias; do not run both in CI. - `pnpm test:unit` - `pnpm test:markdown` exercises temporary Markdown and MDX, then removes the fixtures. - `pnpm build` generates `dist`, Pagefind and validates required/removed paths. +- `pnpm exec playwright install chromium` once, then `pnpm test:browser` against that normal build. The runner starts and stops its own production preview on port 4321; stop other servers on this port first. After `test:markdown`, run a normal build before packaging so temporary test pages cannot enter the release. Integration fixtures are created and removed by the test runner. +Run integration and production builds **sequentially**, with browser tests after the final build. Browser tests never build implicitly. `pnpm verify:build` rechecks existing output without rebuilding. `pnpm lint` and `pnpm format` **write source files**; they are not read-only verification commands. + +[Browser testing guide](tests/browser/README.md) covers the matrix, natural animation observations, compositor screenshots, baseline review and failure artifacts. Run all these checks for upgrades to Astro, Svelte, browser revisions, assets or lifecycle code; for focused iteration use `pnpm test:motion` and Playwright's `--project` / `--grep`, then complete the delivery gate. Keep performance measurements separate from correctness tests. Keep regression coverage for canonical article routes, empty encryption passwords and public excerpts, escaped TOC/JSON-LD content, MDX rendering and relative images, single comment initialization, and image lightboxes after decryption. Use the maintained tests for verification; historical one-off probe scripts are not regression test entrypoints. @@ -42,7 +47,7 @@ The production site is static and generated in `dist/`. `.astro/` is Astro's gen Parse `twilight.config.yaml` at production build time through the `twilight-build-config` Vite plugin. Keep the YAML fallback for Astro configuration loading and development updates, so browsers do not download the YAML parser. Keep the configuration validation and normalization paths shared. -Preserve responsive AVIF/WebP pictures, eager high-priority loading for the banner, deferred post covers, and interaction-triggered search loading. Only the interface Regular and display Italic Latin subsets are preloaded. Do not restore the complete Chinese font to the active font stack; its public URL remains available for compatibility. Cache hashed `/_astro/` assets for one year with `immutable`, revalidate HTML, and keep Pagefind entry files uncached so new deployments use the matching index. +Preserve responsive AVIF/WebP pictures, eager high-priority loading for the banner, deferred post covers, and interaction-triggered search loading. The shared layout currently preloads three local Latin files: interface Regular and display Regular/Italic. Font definitions live in `astro.config.mjs` and preload selection in `src/layouts/home.astro`; verify emitted preload links when changing either. Do not restore the complete Chinese font to the active font stack; its public URL remains available for compatibility. Cache hashed `/_astro/` assets for one year with `immutable`, revalidate HTML, and keep Pagefind entry files uncached so new deployments use the matching index. The image postprocessor selects AVIF only when every responsive size is smaller than WebP. Deferred covers start loading within 350px of the viewport and fade in after decoding; keep no-JavaScript, missing IntersectionObserver, failure and reduced-motion fallbacks. Navigation icons use local SVG data, and Skills uses the shared static layout. @@ -57,3 +62,83 @@ The existing tracking script stays independent of the optional count display. Wh GitHub Actions passes the optional key from repository secrets to the build step as `UMAMI_API_KEY`. The VPS Docker deployment serves the pre-built `dist/` directly through nginx. Do not pass secrets through build arguments or commit them in the site configuration. `pnpm new-post ` creates a draft at `src/content/posts//index.md` or `index.mdx`; publishing requires explicitly changing `draft` to false. Encrypted articles require a nonblank password both when saved in the CMS and when built. Keep automatic excerpts out of their public cards. + +## Module map and documentation ownership + +| Location | Responsibility / maintenance contract | +| --- | --- | +| `src/layouts/home.astro`, `grid.astro`; `src/components/site/` | Shared shell, ClientRouter, header/footer/backdrop; `home.astro` is also used by interior layouts. Initial inline preparation must run before module startup. | +| `src/pages/`, `src/content/` | Static routes and authored content. Writing is `/archive/`; Links is `/friends/`. Preserve `/skills/`, article URLs and aliases. | +| `src/scripts/voyage.ts`, `heading-motion.ts`, `site.ts` | Home interaction/motion, non-hero heading motion, interior enhancement respectively. See lifecycle below. | +| `src/utils/page-lifecycle.ts`, `panel-lifecycle.ts`, `scroll-controls.ts`, `lazy-resource.ts` | Shared events, panel cleanup/focus, article scrolling and demand-loaded resources. Reuse these helpers. | +| `src/styles/voyage.css`, `interior.css`, `transition.css` | Shared Voyage composition, reading surfaces and system motion fallback. Later rules include intentional compatibility constraints; order is significant. | +| `src/plugins/`, `src/components/common/` | Real Markdown/MDX rendering, code controls, image/media and protected-content capabilities. Validate via integration builds, not only editor preview. | +| `src/cms/`, `public/admin/`, `cms/` | Editor parsing/preview, Decap forms and server-side OAuth. Configuration and operation belong in `CMS_SETUP.md`. | +| `scripts/`, `tests/` | Build/image/output validation and unit tests; `tests/browser/` owns production browser verification and reviewed PNG baselines. | +| `.github/workflows/`, Docker/Nginx configuration | Validation, tested static artifact transport, VPS serving and authentication proxy. | + +`README.md` / `README.zh-CN.md` are entry points. `AGENTS.md` is the contributor delivery gate, `DESIGN_SYSTEM.md` the visual contract, this file the implementation/operations guide, `CMS_SETUP.md` the writing/auth guide. Keep command and workflow details here or in the browser guide and link to them instead of copying divergent instructions. Update affected documentation with code changes; state uncertainty rather than documenting an inferred browser guarantee. + +## Motion ownership and historical regressions + +Baseline for this maintenance pass: [`06fbecd`](https://github.com/Chen017/Blog/commit/06fbecd63ecb79bec5e98c59b39d7db134b5ad0b). Historical PR descriptions contain superseded experiments; follow the final code and decisions below. + +1. `NavigationMotion.astro` is a single early inline coordinator. `astro:before-preparation` increments the generation and clears stale identities/flags. Direction follows `Home → Writing → Links → About`; articles belong to Writing. The outgoing header keeps its own `aria-current`; incoming server HTML supplies the new selection. +2. `astro:before-swap` sets **incoming-document** flags before snapshot capture, publishes transition promises and aborts outgoing page work. A normal-motion, previously opened, non-article, hash-free Home return receives `data-voyage-return-prepared`. +3. `voyage.ts` is the **only Home hero animation owner**. Its after-swap initialization restores filters/order/source/scroll and immediately installs both return animations from the CSS-prepared poses. Remove preparation only after both `fill:both` effects exist. Generic `heading-motion.ts` deliberately excludes the hero and handles other headings on page-load. +4. Transition completion clears coordinator-owned fold flags and reveals deferred writing sections. Home interactions and heavier interior enhancements wait separately for completion. Generation, AbortController, connected-root and transition-identity checks reject obsolete results, including rapid A→B→A with the same pathname. + +| Effect | Delay + duration | Initial pose | +| --- | --- | --- | +| First Home `Etalib’s` | 450 + 1800ms | opacity .45, blur 3px, Y 12px | +| First Home `Space.` | 550 + 2100ms | opacity .45, blur 3px, Y 18px | +| First Home horizon | 450 + 2300ms | opacity .4, Y 15px | +| Returning `Etalib’s` | 110 + 580ms | opacity .45, blur 3px, Y 12px | +| Returning `Space.` | 190 + 820ms | Y 8px, rotation −2°, unchanged opacity | + +Initial CSS is not redundant with WAAPI: it covers the interval before the effect exists. The first-session marker stays until the longest opening animation settles; completed filled effects are then released. The inline 5-second fallback keeps content readable if initialization fails. Opening eligibility also depends on URL hash, history state, visibility and system motion. A genuinely fresh browser context is required to reproduce a first visit. +The fallback timer belongs to the initial document and is cancelled on before-swap; its listener is also removed when the timer fires. Astro reuses the HTML element, so an uncancelled initial timer can clear **incoming** preparation while a slow new module is still loading. Preserve the original 5-second recovery for a broken first load without letting it mutate a later page. + +The hero adds 68% neutral white light to the **real sky** with `plus-lighter`; fallback/reduced-transparency rules remain intentional. Adding a stacking context between sky and glyphs can break this even if the computed blend mode is unchanged. The `.nv-page` context contains both foreground and backdrop. The Home-only `::view-transition-new(root)` opacity override suppresses a luminance discontinuity while retaining the 280ms slide; its exclusions protect paired article titles and motion preferences. Planet grain must remain rendered during transitions. + +Article-title morphs are a separate 620ms transition. `voyage:source` pairs one card/title with its route, origin history index and target scroll; shared names must stay unique. Restore filter/order before source lookup and scroll instantly before capture, then restore keyboard focus without scrolling. Similar scroll calculations in the coordinator and Home initializer occur at different lifecycle phases. The pending target survives click-time and teardown saves. Return only the selected/already-loaded covers eagerly; preserve other lazy covers. + +`stopMotion(false)` on abort/pagehide intentionally preserves outgoing parallax until snapshot capture; preference/visibility changes reset it. Touch does not imitate a fine pointer. Persisted pageshow refreshes state/preferences without rerunning the opening. Page-specific styles remain Astro-owned: carrying outgoing interior CSS into Home was removed to prevent leakage. + +| History / reason | Regression protection | +| --- | --- | +| [PR #7](https://github.com/Chen017/Blog/pull/7): competing hero observers restarted `Space.`; outgoing menu was highlighted too early | Sole hero owner; opening marker lifetime; server-rendered current state; `test:motion`, browser fresh opening and directed navigation. | +| [PR #8](https://github.com/Chen017/Blog/pull/8): independent hero snapshot was the wrong approach; hiding grain caused a planet boundary discontinuity | No separate hero capture or transition-time grain hiding; browser filmstrip pixels and natural grain observations. | +| [PR #9](https://github.com/Chen017/Blog/pull/9), `fa04cbe`: departure changed hero blend to normal; incoming root fade caused a bright handoff | Preserve additive blend and narrowly scoped full-opacity Home root; departure/return filmstrips. Never restore the global normal-blend override. | +| [PR #10](https://github.com/Chen017/Blog/pull/10), then `9d1e49f`, `bd42d99`, `bed59ba`, `c44a311` | The original post-transition nod was superseded: one-way `Space.` entrance, pre-snapshot staging and concurrent slide/title motion. | +| `1227bfd`, `21433e3`, `d5a8f3f`, `06fbecd` | Both Home lines use the approved stagger and prepared first poses; browser staging, natural-frame continuity and effect-count assertions. | +| Maintenance browser reproduction: Firefox Enter produced a trusted click with `detail:1`, `pointerType:""` | Detect non-pointer activation using the empty PointerEvent pointer type as well as zero detail. Preserve focused-anchor checks; mouse/touch must not acquire keyboard-return focus. Covered by paired keyboard/pointer entry-history browser scenarios. | +| First cloud run: the initial 5s timer cleared incoming preparation before a delayed page-load; a slow-module browser test reproduced it locally | Cancel the initial fallback at before-swap, retain its direct-load recovery and listener cleanup. Do not extend the delay to move the same race later. | + +## CI/CD and recovery + +`validate.yml` runs on PRs to main, weekly (Monday 04:20 Singapore), manual dispatch and reusable calls. It uses Windows 2025 for the committed screenshot renderer, Node/pnpm from the verification section and lockfile-frozen dependencies. PRs cancel obsolete runs. Each run executes unit → type → Markdown/MDX integration → **normal production build** → browser tests. It installs Chromium for four widths; weekly/manual extended runs add Firefox and WebKit behavior checks. CI uses one browser worker: an initial two-worker cloud run showed simultaneous long touch/navigation stalls, so native captures are serialized instead of hiding them behind longer timeouts. No browser test rebuilds the site. Astro asset cache is optional; correctness never depends on a cache hit. + +`deploy.yml` still runs on pushes to main, including online CMS commits. It calls validation once with the optional `UMAMI_API_KEY`, then downloads the exact tested `validated-dist` artifact on Ubuntu. It does **not** rebuild or reinstall dependencies. Packaging combines `git archive HEAD` (committed source only) and that `dist`. Existing SCP/SSH, preserved `.env`, Docker/Nginx deployment, optional OAuth health check and image/BuildKit pruning remain in place. Main deployments remain serialized and are not cancelled midway. There is no tag or GitHub Release step. + +Required repository Secrets remain `HOST`, `USERNAME`, `PORT`, `SSH_KEY`; optional counts use `UMAMI_API_KEY`; OAuth requires `OAUTH_GITHUB_CLIENT_ID` and `OAUTH_GITHUB_CLIENT_SECRET` together. Validation requires no VPS credentials. Artifact transfer stays inside the originating workflow run. Failed checks block the deploy job; browser reports, diff images, traces, videos and motion JSON are retained for 7 days. Tested deployment output is retained for 1 day. These are diagnostics/artifacts, not public hosting or releases. + +The first GitHub run after a CI change must be checked in Actions: local validation does not prove runner font availability, account permissions, repository required-check settings or live VPS behavior. Branch protection is managed in repository settings, not these YAML files. Prefer requiring the validation check before merging; branch policy is not changed automatically by this project. A weekly failure reports through normal GitHub Actions notifications; it cannot undo an earlier deployment. + +| Symptom | Investigation / recovery | +| --- | --- | +| Remote-image dimension/build failure | Check the exact article image URL and network access. The current build infers dimensions for some external covers; it therefore still depends on those hosts. Retry after recovery; do not bypass output verification. | +| Temporary regression articles in preview | Stop preview, complete/inspect `test:markdown` cleanup, then run a normal `pnpm build`. Do not package its integration output. | +| Port 4321 already in use | Stop the existing dev/preview process. Browser tests deliberately refuse server reuse to avoid testing a stale/dev build. | +| Screenshot failure | Read HTML report and expected/actual/diff, engine/OS and lockfile. Check local font/photo loads and animation timing before any baseline update. See browser guide. | +| Motion timing/flaky retry | Inspect motion JSON, trace and filmstrip. CI treats a passing retry as a failure too; do not dismiss intermittence as success. | +| Search unavailable | Development intentionally has no index. In production verify `dist/pagefind/`, network failures and Retry. Keep Pagefind entry files revalidated. | +| Deploy skipped / artifact missing | Check validation first. Only a successful reusable deploy-validation call uploads `validated-dist`. Do not rebuild on the VPS to bypass the gate. | +| SCP/SSH/OAuth health failure | Inspect the named Actions step, connectivity/Secrets, server disk space, Docker logs and `.env`; never paste credentials into logs. Existing deployment is not transactional: the remote rsync may already have changed files. | +| Need to roll back production | Revert to a known-good committed revision through main and let the same gates rebuild/deploy it. Confirm home/search/OAuth routes after deployment. The workflow does not currently provide an atomic release-directory rollback. | + +## Review coverage and remaining maintenance debt + +This pass examines shared navigation/motion/state restoration, their callers and CSS/history in depth; build/test/CI and deployment transport are reviewed for the validation path. Rendering features and CMS interfaces are sampled through existing unit/integration tests. Auth/OAuth security, every authored document, production host configuration and dependency vulnerability analysis are not a comprehensive security audit. Generated output, binaries, vendored libraries and licensed fonts are not edited. + +Preserve the current runtime while adding safeguards. Splitting the early inline coordinator, consolidating CSS layers or unifying scroll calculations are future changes requiring their own measured browser baseline; code volume alone is not evidence of redundancy. Current risks are: external covers needed at build time, a monolithic inline cache/lifecycle coordinator, source-pattern tests with limited compositor evidence, and non-atomic VPS replacement. Browser probes and screenshots reduce regression risk but cannot certify every GPU or Safari/iOS device. Upgrade one dependency/ownership boundary at a time; keep lockfile and browser snapshots reviewed together. Do not revive removed feed/theme/tag/music-card systems from outdated upstream documentation. diff --git a/README.md b/README.md index 5333374..dd87185 100644 --- a/README.md +++ b/README.md @@ -53,10 +53,11 @@ See [CMS_SETUP.md](CMS_SETUP.md) (Chinese) for the complete writing guide, music ### Write locally -Requires Node.js 22.22+ and pnpm 10.29.2. +Requires Node.js 22.22+ and pnpm 10.29.2; use Node.js 24.13.0 to match CI. ```bash -pnpm install +corepack enable +pnpm install --frozen-lockfile pnpm cms:local ``` @@ -67,17 +68,20 @@ Open . Local saves write articles and images into Blog settings live in `twilight.config.yaml`, site content in `src/content`, and writing-dashboard collections in `public/admin/config.yml`. See [CMS_SETUP.md](CMS_SETUP.md) for the current authentication and deployment configuration. ```bash -pnpm check pnpm test:unit +pnpm type-check pnpm test:markdown pnpm build +pnpm exec playwright install chromium +pnpm test:browser ``` -Run a normal build after the Markdown integration checks so temporary test pages stay out of the release. The production output is `dist/`, including the Pagefind search index. +Run these sequentially: integration and production builds both write `dist/`. Browser tests start their own production preview and compare real animation/interaction behavior and reviewed screenshots. `pnpm check` is an alias of the type check. The production output includes the Pagefind search index. -- [MAINTENANCE.md](MAINTENANCE.md): retained features and maintenance boundaries. +- [MAINTENANCE.md](MAINTENANCE.md): module ownership, motion regression history, development, CI/CD and troubleshooting. +- [Browser testing](tests/browser/README.md): viewport/engine coverage, animation evidence, golden review and failure diagnostics. - [CMS_SETUP.md](CMS_SETUP.md): writing, media uploads, authentication, and deployment. `src/`, `public/`, `cms/`, `scripts/`, and `tests/` contain maintained project files. `dist/`, `.astro/`, and `.vercel/` are generated output or local caches and can be removed when not in use. One-off investigation reports and logs stay out of Git. -OAuth credentials are stored in GitHub Actions encrypted Secrets and delivered to the server's `.env`. Keep local credentials out of Git. The existing VPS deployment uses Docker, Nginx, and GitHub Actions. +OAuth credentials are stored in GitHub Actions encrypted Secrets and delivered to the server's `.env`. Keep local credentials out of Git. PRs run validation; main pushes validate once and deploy the tested static artifact through Docker/Nginx. Weekly/manual checks add browser engines. See the maintenance guide for workflow details and required Secrets. diff --git a/README.zh-CN.md b/README.zh-CN.md index b3c1e71..d3c6179 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -53,10 +53,11 @@ ### 本地写作 -需要 Node.js 22.22 及以上版本,以及 pnpm 10.29.2。 +需要 Node.js 22.22 及以上版本,以及 pnpm 10.29.2;使用 Node.js 24.13.0 可与 CI 保持一致。 ```bash -pnpm install +corepack enable +pnpm install --frozen-lockfile pnpm cms:local ``` @@ -67,17 +68,20 @@ pnpm cms:local 博客配置位于 `twilight.config.yaml`,网站内容位于 `src/content`,后台内容集合配置位于 `public/admin/config.yml`。当前认证与部署配置见 [CMS_SETUP.md](CMS_SETUP.md)。 ```bash -pnpm check pnpm test:unit +pnpm type-check pnpm test:markdown pnpm build +pnpm exec playwright install chromium +pnpm test:browser ``` -Markdown 集成检查完成后,需要再运行一次正常构建,避免临时测试页面进入正式产物。生产输出目录为 `dist/`,其中包含 Pagefind 搜索索引。 +按顺序执行:Markdown 集成检查和生产构建都会写入 `dist/`,不能并行。浏览器测试会自行启动生产预览,验证真实动画、交互和已审查的截图基线。`pnpm check` 是类型检查的别名,无需重复执行。生产产物包含 Pagefind 搜索索引。 -- [MAINTENANCE.md](MAINTENANCE.md)(英文):保留功能与维护边界。 +- [MAINTENANCE.md](MAINTENANCE.md)(英文):模块职责、动画回归历史、开发方式、CI/CD 和故障排查。 +- [浏览器测试指南](tests/browser/README.md)(英文):屏幕尺寸与浏览器覆盖、动画证据、基线审查和失败诊断。 - [CMS_SETUP.md](CMS_SETUP.md):写作、媒体上传、认证与部署说明。 `src/`、`public/`、`cms/`、`scripts/` 和 `tests/` 是持续维护的项目文件。`dist/`、`.astro/` 和 `.vercel/` 是构建产物或本地缓存,不使用时可以删除。一次性排查报告和日志不纳入 Git。 -OAuth 凭据保存在 GitHub Actions 加密 Secrets 中,并在部署时写入服务器的 `.env`。不要把本地凭据提交到 Git。现有 VPS 部署使用 Docker、Nginx 和 GitHub Actions。 +OAuth 凭据保存在 GitHub Actions 加密 Secrets 中,并在部署时写入服务器的 `.env`,不要提交到 Git。PR 自动验证;main 推送只执行一次完整验证,再通过 Docker/Nginx 部署同一份已测试的静态产物。每周和手动扩展检查增加浏览器引擎,具体触发条件、Secrets 和排查方法以维护指南为准。 diff --git a/package.json b/package.json index 837f980..a2b1b74 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,9 @@ "test:unit": "node --test tests/*.test.mjs", "test:motion": "node --test tests/navigation-motion.test.mjs tests/voyage-motion.test.mjs", "test:markdown": "node scripts/test-markdown.mjs", + "test:browser": "playwright test", + "test:browser:update": "playwright test visual.spec.mjs --update-snapshots", + "test:browser:report": "playwright show-report", "verify:build": "node scripts/verify-build.mjs", "type-check": "astro check", "check-stylus": "node scripts/compile-inline-stylus.cjs", @@ -77,6 +80,7 @@ "@astrojs/ts-plugin": "^1.10.12", "@biomejs/biome": "2.3.13", "@iconify-json/mdi": "^1.2.3", + "@playwright/test": "1.64.1", "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "decap-server": "3.11.5", diff --git a/playwright.config.mjs b/playwright.config.mjs new file mode 100644 index 0000000..861fc29 --- /dev/null +++ b/playwright.config.mjs @@ -0,0 +1,52 @@ +import { defineConfig } from '@playwright/test'; + +// Match the committed screenshot environment. Browser revisions come from pnpm-lock.yaml. +const chromium = (name, width, height, touch = false) => ({ + name, + use: { browserName: 'chromium', viewport: { width, height }, hasTouch: touch, isMobile: touch }, +}); + +export default defineConfig({ + testDir: './tests/browser', + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 1 : 0, + failOnFlakyTests: !!process.env.CI, + updateSnapshots: process.env.CI ? 'none' : 'missing', + // Native compositing/touch capture shares runner resources. Serialize CI + // rather than letting concurrent rendering stalls masquerade as regressions. + workers: process.env.CI ? 1 : 3, + timeout: 45_000, + expect: { timeout: 8_000, toHaveScreenshot: { animations: 'allow', threshold: 0.2, maxDiffPixelRatio: 0.003 } }, + reporter: [['list'], ['html', { open: 'never' }]], + outputDir: 'test-results', + snapshotPathTemplate: '{testDir}/snapshots/{platform}/{projectName}/{arg}{ext}', + use: { + baseURL: 'http://127.0.0.1:4321', + locale: 'en-US', + timezoneId: 'Asia/Singapore', + colorScheme: 'dark', + reducedMotion: 'no-preference', + deviceScaleFactor: 1, + trace: 'retain-on-failure', + screenshot: 'only-on-failure', + video: 'retain-on-failure', + }, + webServer: { + // Never rebuild here: Markdown integration and production builds share dist. + command: 'pnpm preview --host 127.0.0.1 --port 4321', + url: 'http://127.0.0.1:4321', + reuseExistingServer: false, + timeout: 30_000, + }, + projects: [ + chromium('desktop', 1440, 900), + chromium('phone', 390, 844, true), + chromium('tablet', 768, 1024, true), + chromium('narrow', 320, 740, true), + ...(process.env.BROWSER_MATRIX === 'extended' ? [ + { name: 'firefox', use: { browserName: 'firefox', viewport: { width: 1440, height: 900 } } }, + { name: 'webkit', use: { browserName: 'webkit', viewport: { width: 1440, height: 900 } } }, + ] : []), + ], +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 60ce90e..8f27a17 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -169,6 +169,9 @@ importers: '@iconify-json/mdi': specifier: ^1.2.3 version: 1.2.3 + '@playwright/test': + specifier: 1.64.1 + version: 1.64.1 '@types/hast': specifier: ^3.0.5 version: 3.0.5 @@ -1036,6 +1039,11 @@ packages: resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} + '@playwright/test@1.64.1': + resolution: {integrity: sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==} + engines: {node: '>=20'} + hasBin: true + '@rolldown/binding-android-arm-eabi@1.2.14': resolution: {integrity: sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3198,6 +3206,16 @@ packages: resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} engines: {node: '>=16.20.0'} + playwright-core@1.64.1: + resolution: {integrity: sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.64.1: + resolution: {integrity: sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==} + engines: {node: '>=20'} + hasBin: true + points-on-curve@0.2.0: resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==} @@ -4944,6 +4962,10 @@ snapshots: '@pkgjs/parseargs@0.11.0': optional: true + '@playwright/test@1.64.1': + dependencies: + playwright: 1.64.1 + '@rolldown/binding-android-arm-eabi@1.2.14': optional: true @@ -7567,6 +7589,12 @@ snapshots: pkce-challenge@5.0.1: {} + playwright-core@1.64.1: {} + + playwright@1.64.1: + dependencies: + playwright-core: 1.64.1 + points-on-curve@0.2.0: {} points-on-path@0.2.1: diff --git a/src/components/site/NavigationMotion.astro b/src/components/site/NavigationMotion.astro index 5296712..066994d 100644 --- a/src/components/site/NavigationMotion.astro +++ b/src/components/site/NavigationMotion.astro @@ -395,7 +395,7 @@ } const transition = event.viewTransition; // Prepare the previously visited Home title before Astro captures its - // incoming snapshot. The post-transition WAAPI reveal starts from this + // incoming snapshot. The after-swap WAAPI reveal starts from this // same pose, avoiding a visible normal-position -> lower-position snap. if (to === '/' && !selected && !hasHash && transition && document.documentElement.dataset?.motion !== 'off' && diff --git a/src/layouts/home.astro b/src/layouts/home.astro index 87694c1..acca24b 100644 --- a/src/layouts/home.astro +++ b/src/layouts/home.astro @@ -52,7 +52,15 @@ const ogImage = siteConfig.generateOgImages && postSlug ? new URL(`/og/${postSlu try { if (location.pathname === '/' && !location.hash && !history.state?.voyage && !sessionStorage.getItem('voyage:opened')) document.documentElement.setAttribute('data-voyage-opening', ''); } catch { /* Keep the opening visible if storage is unavailable. */ } - setTimeout(() => { if (!document.documentElement.hasAttribute('data-voyage-observing')) document.documentElement.removeAttribute('data-voyage-preparing'); document.documentElement.removeAttribute('data-voyage-opening'); }, 5000); + // Astro reuses ; this initial-document recovery timer + // must not clear preparation on a later, still-loading page. + const cancelFallback = () => clearTimeout(fallback); + const fallback = setTimeout(() => { + document.removeEventListener('astro:before-swap', cancelFallback); + if (!document.documentElement.hasAttribute('data-voyage-observing')) document.documentElement.removeAttribute('data-voyage-preparing'); + document.documentElement.removeAttribute('data-voyage-opening'); + }, 5000); + document.addEventListener('astro:before-swap', cancelFallback, { once: true }); } } catch { /* CSS also respects the system preference. */ } diff --git a/src/scripts/voyage.ts b/src/scripts/voyage.ts index 5789c6b..8a55dd9 100644 --- a/src/scripts/voyage.ts +++ b/src/scripts/voyage.ts @@ -409,7 +409,10 @@ function initializeVoyage( scroll: targetScroll, keyboard: document.activeElement === card.querySelector("a") && - (!("detail" in event) || (event as MouseEvent).detail === 0), + // Firefox can report detail=1 for Enter; an empty + // PointerEvent pointerType still identifies non-pointer activation. + (!("detail" in event) || (event as MouseEvent).detail === 0 || + (event as PointerEvent).pointerType === ""), }, }, "", diff --git a/tests/browser/README.md b/tests/browser/README.md new file mode 100644 index 0000000..9549042 --- /dev/null +++ b/tests/browser/README.md @@ -0,0 +1,142 @@ +# Production browser regression tests + +Start with [MAINTENANCE.md](../../MAINTENANCE.md) for setup, ownership/history, +build order, CI/deployment and troubleshooting. [DESIGN_SYSTEM.md](../../DESIGN_SYSTEM.md) +remains the visual contract. This guide owns browser commands and evidence only. + +## Reproduce + +Use Node 24.13.0, pnpm 10.29.2 and frozen dependencies. After `pnpm test:markdown`, +always run `pnpm build` before testing. Do not run either build while preview is +using `dist`. Stop any server on port 4321; the test runner owns its preview. + +```sh +pnpm exec playwright install chromium +pnpm test:browser +pnpm test:browser --project=desktop --grep 'both return' +pnpm test:browser --project=phone --headed +pnpm test:browser --workers=1 +pnpm test:browser:report +``` + +To run additional engines locally: + +```powershell +pnpm exec playwright install firefox webkit +$env:BROWSER_MATRIX = 'extended' +pnpm test:browser +Remove-Item Env:BROWSER_MATRIX +``` + +On POSIX systems use `BROWSER_MATRIX=extended pnpm test:browser`. Functional tests +can run anywhere with `--grep-invert 'composition|filmstrip|opening pixels'`; +committed goldens intentionally use Windows. Do not generate Linux/macOS goldens +and claim they validate the Windows CI renderer. + +| Project | Viewport | Input / scope | +| --- | --- | --- | +| desktop | 1440×900 | Fine pointer, keyboard, full behavior and compositor filmstrips | +| phone | 390×844 | Touch, keyboard, behavior and four resting page screenshots | +| tablet | 768×1024 | Touch, keyboard, behavior and four resting page screenshots | +| narrow | 320×740 | Touch, keyboard, behavior and four resting page screenshots | +| firefox, webkit | 1440×900 | Extended behavior checks; golden pixels stay in Chromium | + +Projects emulate input and viewport; they are not physical phones or a Safari +installation. Native View Transition checks require engine support and assert +that a real transition was observed. A separate fallback test disables that API. +Headless/virtual GPU results cannot establish all physical GPU/OS behavior. + +## What the tests observe + +- `navigation.spec.mjs`: every directed main-tab pair; title/current state/header + position and overflow; keyboard and touch; real Pagefind failure/retry and + focus; filtered/sorted article history and keyboard versus pointer source return; rapid + interrupted anchors; live reduced-motion changes; unavailable APIs/storage; + content without JavaScript. + It also verifies failed speculative HTML warming recovers and Chromium's + emulated reduced-transparency preference uses readable solid lettering. + A real slow-module scenario crosses the initial 5-second safety deadline + between swap and page-load, guarding the old timer against disabling a new + page's heading entrance. Its deliberate timed wait reproduces that boundary; + it is not a generic sleep used to make other tests pass. + A complementary failed-module case keeps the original direct-load recovery. +- `motion.spec.mjs`: actual native WAAPI effects and computed starting poses, + effect counts and original opening/return timing; rAF samples during natural + return animation; no downward restart; return effects created before native + transition completion; actual directional slide effects and their duration. +- `visual.spec.mjs`: production viewport PNGs and selected compositor frames. + Real native animations are paused/searched at selected times for repeatable + screenshots; they are not replaced by mocked animations. Natural playback is + tested separately so seeking cannot hide a late-start bug. + Writing captures the masthead, hiding its changing entry-count kicker; Home + hides only the tiny changing counts. New articles therefore do not require + approving design baselines. Build/behavior tests check real counts and entries. + `screenshot.css` is passed through the assertion API's `stylePath`; it is never + imported by the site and only applies while those resting images are captured. +- `fixtures.mjs`: wraps native `Element.animate` / `startViewTransition` to + observe effects and lifecycle timing while preserving their returned native + objects. The recorder is test-only and never enters the production bundle. + +External analytics/media requests are fulfilled empty to isolate optional +third-party availability. Local production scripts, fonts, background photography +and Pagefind remain real. Expected search failures are injected only within that +scenario. Resting screenshots pause infinite star twinkle at a fixed phase and +decode the real sky; they do not hide the hero, background, texture or blend. +Animation screenshots explicitly use `animations: 'allow'`: Playwright's default +animation disabling would fast-forward the finite effects being protected. + +Timing/effect assertions alone cannot prove real additive compositing, so both +natural samples and raster comparisons are required. A picture alone cannot +prove correct event ordering. Native back/forward is exercised, but no test +claims a confirmed persisted BFCache hit without observing one. Source-pattern +unit tests remain useful for hard-to-trigger branches, not as visual proof. + +## Baseline review + +Goldens live in `snapshots/win32//`. CI uses Windows 2025 and the exact +Playwright/browser versions from the lockfile. OS fonts, browser versions and +renderer differences can affect pixels; a runner/browser upgrade needs a review +of the images, not a larger tolerance to hide changes. The small pixel tolerance +allows raster noise; no masks cover critical lettering or sky. + +```sh +pnpm test:browser:update +pnpm test:browser +``` + +Use the update command only for a deliberate, reviewed visual change. Inspect +the expected/actual/diff images and the complete changed PNG set. The update +command establishes references, it does not prove that they are correct. Review +title pre-poses, simultaneous slide/title movement, real-sky color, the planet +surface and handoff to live DOM. Preserve the original PNGs when debugging a +failure. Never accept baselines generated by a broken/missing font/photo load. + +CI uses `updateSnapshots: 'none'`; no automated run approves its own new images. +CI serializes browsers with one worker; local iteration defaults to three. +Use `--workers=1` to reproduce the cloud resource model. Do not infer animation +smoothness from a multi-worker runner's elapsed time. +One retry collects evidence, and `failOnFlakyTests` keeps passing retries from +turning an intermittent regression green. Do not disable a failing engine/test +merely to unblock deployment; investigate and document any unavoidable gap. + +## Failure evidence and maintenance + +Actions uploads `browser-report--` for 7 days. Download it and open +the extracted `playwright-report/index.html` via `pnpm exec playwright show-report +`. Expected/actual/diff PNGs, retained video and traces are +linked from the report. `browser-diagnostics` contains uncaught errors, failed +requests, native animation calls, lifecycle events and natural frame poses. +Use `pnpm exec playwright show-trace ` to inspect timing and requests. +Reports can contain page/article content; do not publish them to unrelated hosts. + +When a behavior changes, update its browser test and the motion decision table +in `MAINTENANCE.md` if applicable. For an animation change, run a focused natural +timeline scenario and compositor screenshots before the full matrix. When a +snapshot fails, first distinguish a real regression from a missing font/photo, +wrong production build, different renderer or an unstable capture. Keep every +remaining unverified device/deployment claim explicit in the delivery report. + +API references: [Playwright visual comparisons](https://playwright.dev/docs/test-snapshots), +[screenshot animation handling](https://playwright.dev/docs/api/class-page#page-screenshot), +[CI setup](https://playwright.dev/docs/ci-intro), +[trace viewer](https://playwright.dev/docs/trace-viewer-intro). diff --git a/tests/browser/fixtures.mjs b/tests/browser/fixtures.mjs new file mode 100644 index 0000000..51d9471 --- /dev/null +++ b/tests/browser/fixtures.mjs @@ -0,0 +1,168 @@ +import { test as base, expect } from '@playwright/test'; + +export const routes = [ + { name: 'Home', path: '/', heading: '.nv-titleblock h1' }, + { name: 'Writing', path: '/archive/', heading: '.vs-page-head h1' }, + { name: 'Links', path: '/friends/', heading: '.vs-page-head h1' }, + { name: 'About', path: '/about/', heading: '.vs-about-content h1' }, +]; + +export const test = base.extend({ + page: async ({ page }, use, testInfo) => { + const errors = []; + const failedRequests = []; + page.on('pageerror', error => errors.push(error.message)); + page.on('requestfailed', request => failedRequests.push({ url: request.url(), error: request.failure()?.errorText })); + // Analytics and external media are not necessary to navigate the static blog. + // Local scripts, fonts, photos and Pagefind remain real production requests. + await page.route('**/*', route => { + const address = new URL(route.request().url()); + if (['127.0.0.1', 'localhost'].includes(address.hostname)) return route.continue(); + return route.fulfill({ status: 204, body: '' }); + }); + await page.addInitScript(() => { + const probe = window.__motionProbe = { calls: [], events: [], frames: [], transitions: [], activations: [], recording: false }; + const pose = element => { + if (!element) return null; + const css = getComputedStyle(element); + const box = element.getBoundingClientRect(); + return { opacity: Number(css.opacity), translate: css.translate, rotate: css.rotate, + filter: css.filter, blend: css.mixBlendMode, display: css.display, + x: box.x, y: box.y, width: box.width, height: box.height }; + }; + const sample = () => ({ + time: performance.now(), path: location.pathname, + active: document.activeElement?.id || document.activeElement?.className || document.activeElement?.tagName, + first: pose(document.querySelector('.nv-title-first')), + space: pose(document.querySelector('.nv-titleblock h1 em')), + title: pose(document.querySelector('.nv-titleblock h1')), + grain: pose(document.querySelector('.nv-horizon-grain')), + opening: document.documentElement.hasAttribute('data-voyage-opening'), + prepared: document.documentElement.hasAttribute('data-voyage-return-prepared'), + }); + const nativeAnimate = Element.prototype.animate; + document.addEventListener('click', event => { + const link = event.target.closest?.('.nv-entry-link'); + if (link) probe.activations.push({ detail: event.detail, pointerType: event.pointerType, trusted: event.isTrusted, + activeLink: document.activeElement === link, route: link.getAttribute('href') }); + }, true); + Element.prototype.animate = function (...args) { + const animation = nativeAnimate.apply(this, args); + if (this.matches('.nv-title-first, .nv-titleblock h1 em, .nv-horizon, .vs-page-head h1, .vs-page-head h1 em, .vs-about-content h1, .vs-about-content h1 em')) { + probe.calls.push({ path: location.pathname, time: performance.now(), + target: this.matches('.nv-title-first') ? 'first' : this.matches('.nv-titleblock h1 em') ? 'space' : this.className || this.tagName, + timing: animation.effect.getTiming(), frames: animation.effect.getKeyframes(), pose: pose(this) }); + } + return animation; + }; + for (const name of ['astro:before-preparation', 'astro:before-swap', 'astro:after-swap', 'astro:page-load']) { + document.addEventListener(name, event => { + const item = { name, time: performance.now(), path: location.pathname, direction: event.direction, sample: sample(), history: history.state }; + probe.events.push(item); + if (name === 'astro:before-swap') { + // This listener runs before application listeners; read the marker after all of them. + queueMicrotask(() => { item.incomingPrepared = event.newDocument.documentElement.hasAttribute('data-voyage-return-prepared'); }); + } + if (name === 'astro:after-swap') probe.staged = sample(); + }); + } + if (document.startViewTransition) { + const nativeTransition = document.startViewTransition.bind(document); + document.startViewTransition = (...args) => { + const transition = nativeTransition(...args); + const item = { start: performance.now(), path: location.pathname }; + probe.transitions.push(item); + window.__nativeTransition = transition; + void transition.ready.then(() => { + item.ready = performance.now(); + item.animations = document.getAnimations().filter(a => a.effect?.pseudoElement).map(a => ({ + pseudo: a.effect.pseudoElement, name: a.animationName, timing: a.effect.getTiming(), frames: a.effect.getKeyframes(), + })); + }, () => { item.skipped = true; }); + void transition.finished.then(() => { item.end = performance.now(); }, () => { item.end = performance.now(); }); + return transition; + }; + } + function frame() { + if (probe.recording && probe.frames.length < 600) probe.frames.push(sample()); + requestAnimationFrame(frame); + } + requestAnimationFrame(frame); + }); + await use(page); + if (testInfo.status !== testInfo.expectedStatus || errors.length) { + const motion = await page.evaluate(() => ({ ...window.__motionProbe, finalHistory: history.state, finalFocus: document.activeElement?.outerHTML?.slice(0, 500) })).catch(() => null); + await testInfo.attach('browser-diagnostics', { body: JSON.stringify({ errors, failedRequests, motion }, null, 2), contentType: 'application/json' }); + } + expect(errors, 'uncaught browser exceptions').toEqual([]); + }, +}); + +export { expect }; + +export async function settled(page) { + await page.waitForFunction(() => !!document.querySelector('.nv-page') && !document.documentElement.hasAttribute('data-astro-transition') && + !document.documentElement.hasAttribute('data-voyage-home-transition') && + !document.documentElement.hasAttribute('data-voyage-return-prepared') && + !document.documentElement.hasAttribute('data-voyage-opening')); + // IntersectionObserver delivery can follow native transition completion. + await page.waitForFunction(() => { + const heading = document.querySelector('.vs-page-head h1, .vs-about-content h1'); + return !heading || matchMedia('(prefers-reduced-motion: reduce)').matches || heading.hasAttribute('data-motion-ready'); + }); + await page.evaluate(async () => { + await document.fonts.ready; + await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity && a.playState !== 'paused').map(a => a.finished.catch(() => {}))); + }); +} + +export async function visit(page, path = '/', opened = true) { + if (opened) await page.addInitScript(() => sessionStorage.setItem('voyage:opened', 'true')); + await page.goto(path); + await settled(page); +} + +export async function navigate(page, name) { + const route = routes.find(route => route.name === name); + const link = page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name, exact: true }); + if (testTouch(page)) await link.tap(); else await link.click(); + await expect(page).toHaveURL(new RegExp(`${route.path.replaceAll('/', '\\/')}(?:#.*)?$`)); + await settled(page); +} + +// Playwright exposes touch settings through test.info(), not browser sniffing. +function testTouch() { return !!test.info().project.use.hasTouch; } + +export async function armCompositorCapture(page) { + await page.evaluate(() => { + window.__captureReady = new Promise(resolve => { + document.addEventListener('astro:after-swap', () => queueMicrotask(async () => { + await window.__nativeTransition.ready; + window.__capturedAnimations = document.getAnimations().filter(animation => + animation.effect?.pseudoElement || animation.effect?.target?.matches?.('.nv-title-first, .nv-titleblock h1 em')); + for (const animation of window.__capturedAnimations) animation.pause(); + resolve(window.__capturedAnimations.length); + }), { once: true }); + }); + }); +} + +export async function seekCaptured(page, time) { + await page.evaluate(time => { + for (const animation of window.__capturedAnimations) animation.currentTime = time; + }, time); + await freezeDecorations(page); +} + +export async function freezeDecorations(page) { + await page.mouse.move(0, 0); + await page.evaluate(async () => { + await document.fonts.ready; + await Promise.all([...document.querySelectorAll('.nv-sky img')].map(image => image.decode().catch(() => {}))); + for (const animation of document.getAnimations()) { + if (animation.effect?.getComputedTiming().iterations === Infinity) { + animation.pause(); animation.currentTime = 0; + } + } + }); +} diff --git a/tests/browser/motion.spec.mjs b/tests/browser/motion.spec.mjs new file mode 100644 index 0000000..ecde14b --- /dev/null +++ b/tests/browser/motion.spec.mjs @@ -0,0 +1,91 @@ +import { test, expect, visit, navigate, settled } from './fixtures.mjs'; + +test('fresh Home opens each title line once at the established slow timing', async ({ page }) => { + await page.goto('/'); + await settled(page); + const probe = await page.evaluate(() => window.__motionProbe); + for (const [target, duration, delay] of [['first', 1800, 450], ['space', 2100, 550]]) { + const calls = probe.calls.filter(call => call.target === target); + expect(calls).toHaveLength(1); + expect(calls[0].timing).toMatchObject({ duration, delay, fill: 'both' }); + expect(calls[0].pose.opacity).toBeCloseTo(0.45, 2); + } + await expect(page.locator('.nv-title-first')).toHaveCSS('opacity', '1'); + await expect(page.locator('.nv-titleblock h1 em')).toHaveCSS('translate', 'none'); + await navigate(page, 'Writing'); + await navigate(page, 'Home'); + const durations = await page.evaluate(() => window.__motionProbe.calls.filter(call => ['first', 'space'].includes(call.target)).map(call => call.timing.duration)); + expect(durations.filter(duration => duration === 1800 || duration === 2100)).toHaveLength(2); +}); + +test('both return lines are staged before paint and start before the slide finishes', async ({ page }) => { + await visit(page); + for (const name of ['Writing', 'Links', 'About']) { + await navigate(page, name); + await page.evaluate(() => { window.__motionProbe.calls = []; window.__motionProbe.frames = []; window.__motionProbe.recording = true; }); + await navigate(page, 'Home'); + const probe = await page.evaluate(() => { window.__motionProbe.recording = false; return window.__motionProbe; }); + const transition = probe.transitions.at(-1); + // Fallback navigation is covered separately; do not mistake it for native transition evidence. + expect(transition?.ready, 'this scenario requires native View Transitions').toBeGreaterThan(0); + expect(probe.staged.prepared).toBe(true); + expect(probe.staged.first.opacity).toBeCloseTo(0.45, 2); + expect(probe.staged.first.translate).toBe('0px 12px'); + expect(probe.staged.space.translate).toBe('0px 8px'); + expect(probe.staged.space.rotate).toBe('-2deg'); + for (const [target, duration, delay] of [['first', 580, 110], ['space', 820, 190]]) { + const calls = probe.calls.filter(call => call.target === target); + expect(calls).toHaveLength(1); + expect(calls[0].timing).toMatchObject({ duration, delay, fill: 'both' }); + expect(calls[0].time).toBeLessThan(transition.end); + } + const frames = probe.frames.filter(frame => frame.path === '/' && frame.space); + expect(frames.length).toBeGreaterThan(3); + const duringSlide = frames.filter(frame => frame.time < transition.end); + expect(duringSlide.some(frame => frame.first.opacity > 0.46), 'Etalib’s must visibly progress during the slide').toBe(true); + expect(duringSlide.some(frame => (Number.parseFloat(frame.space.translate.split(' ').at(-1)) || 0) < 7.9), + 'Space. must visibly progress before the slide completes').toBe(true); + for (const frame of frames) { + expect(frame.title.blend).toBe('plus-lighter'); + expect(frame.grain.display).not.toBe('none'); + expect(frame.space.opacity).toBe(1); + } + // A normal pose followed by a lower pose would produce a positive Y jump. + const ys = frames.map(frame => Number.parseFloat(frame.space.translate.split(' ').at(-1)) || 0); + for (let i = 1; i < ys.length; i++) expect(ys[i] - ys[i - 1]).toBeLessThan(0.5); + await expect(page.locator('.nv-title-first')).toHaveCSS('opacity', '1'); + await expect(page.locator('.nv-titleblock h1 em')).toHaveCSS('rotate', 'none'); + expect(await page.locator('.nv-titleblock h1').evaluate(el => el.getAnimations({ subtree: true }).length)).toBe(0); + } +}); + +test('native slide direction follows the tab order in both directions', async ({ page }) => { + await visit(page); + for (const [name, slide] of [['About', 'astroSlideFromRight'], ['Writing', 'astroSlideFromLeft'], ['Links', 'astroSlideFromRight'], ['Home', 'astroSlideFromLeft']]) { + await navigate(page, name); + const transition = await page.evaluate(() => window.__motionProbe.transitions.at(-1)); + expect(transition?.ready).toBeGreaterThan(0); + const animation = transition.animations.find(animation => animation.name === slide); + expect(animation, JSON.stringify(transition.animations)).toBeTruthy(); + expect(animation.timing.duration).toBe(280); + const xs = animation.frames.map(frame => frame.transform); + expect(xs[0]).not.toBe(xs.at(-1)); + // Engines serialize translateX as translate when the Y coordinate is zero. + expect(xs[0]).toMatch(slide.endsWith('Right') ? /^translate(?:X)?\(100%\)$/ : /^translate(?:X)?\(-100%\)$/); + } +}); + +test('interior headings keep their separate staggered entrances', async ({ page }) => { + await visit(page); + for (const name of ['Writing', 'Links', 'About']) { + await page.evaluate(() => { window.__motionProbe.calls = []; }); + await navigate(page, name); + const calls = await page.evaluate(() => window.__motionProbe.calls); + const heading = calls.filter(call => call.target === 'H1'); + const flourish = calls.filter(call => call.target === 'EM'); + expect(heading).toHaveLength(1); + expect(flourish).toHaveLength(1); + expect(heading[0].timing).toMatchObject({ duration: 580, delay: 110 }); + expect(flourish[0].timing).toMatchObject({ duration: 820, delay: 190 }); + } +}); diff --git a/tests/browser/navigation.spec.mjs b/tests/browser/navigation.spec.mjs new file mode 100644 index 0000000..0829157 --- /dev/null +++ b/tests/browser/navigation.spec.mjs @@ -0,0 +1,212 @@ +import { test, expect, routes, visit, navigate, settled } from './fixtures.mjs'; + +test('all twelve directed tab routes preserve headings, header and current page', async ({ page }) => { + await visit(page); + // Eulerian tour of the four-tab directed graph: every pair in both directions. + for (const name of ['Writing', 'Home', 'Links', 'Home', 'About', 'Writing', 'Links', 'Writing', 'About', 'Links', 'About', 'Home']) { + const before = await page.locator('.nv-header').boundingBox(); + await navigate(page, name); + const route = routes.find(route => route.name === name); + await expect(page.locator(route.heading)).toBeVisible(); + await expect(page.locator('.nv-nav [aria-current="page"]')).toHaveText(name); + expect((await page.locator('.nv-header').boundingBox()).y).toBeCloseTo(before.y, 0); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + } +}); + +test('keyboard navigation and search failure/retry restore focus and remain usable after history', async ({ page }) => { + await visit(page); + const writing = page.locator('.nv-nav').getByRole('link', { name: 'Writing', exact: true }); + await writing.focus(); + await page.keyboard.press('Enter'); + await expect(page).toHaveURL(/\/archive\/$/); + await settled(page); + await page.route('**/pagefind/**', route => route.abort('failed')); + const trigger = page.getByRole('button', { name: 'Search', exact: true }); + await trigger.focus(); + await page.keyboard.press('Enter'); + await expect(page.locator('#search-input')).toBeFocused(); + await expect(page.locator('#search-panel').getByRole('status')).toContainText('Search could not load'); + await page.unroute('**/pagefind/**'); + await page.getByRole('button', { name: 'Retry loading search' }).click(); + await expect(page.locator('#search-panel').getByRole('status')).toContainText('Search titles and article content'); + await page.locator('#search-input').fill('music'); + await expect(page.locator('.search-result').first()).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(trigger).toBeFocused(); + await expect(page.locator('#search-panel')).toHaveAttribute('inert', ''); + await page.goBack(); + await settled(page); + await trigger.click(); + await expect(page.locator('#search-input')).toBeFocused(); + await page.keyboard.press('Escape'); + await expect(trigger).toBeFocused(); +}); + +for (const activation of ['keyboard', 'pointer']) { +test(`entry history restores filter, sort, source card, scroll and input-specific focus (${activation})`, async ({ page, hasTouch }) => { + await visit(page); + const category = page.locator('.nv-filters button').nth(1); + await category.click(); + const selectedCategory = await category.getAttribute('data-category'); + await page.locator('.nv-order-menu summary').click(); + await page.locator('.nv-order-options [data-order="oldest"]').click(); + const card = page.locator('.nv-entry:not([hidden])').first(); + const cardId = await card.getAttribute('id'); + const link = card.locator('a').first(); + await link.scrollIntoViewIfNeeded(); + if (activation === 'keyboard') await link.focus(); + const scroll = await page.evaluate(() => scrollY); + if (activation === 'keyboard') await page.keyboard.press('Enter'); + else if (hasTouch) await link.tap(); + else await link.click(); + await expect(page).toHaveURL(/\/posts\//); + await settled(page); + await expect(page.locator('.vs-article-head h1')).toBeVisible(); + await page.goBack(); + await expect(page).toHaveURL(/\/$/); + await settled(page); + await expect(page.locator('.nv-filters [aria-pressed="true"]')).toHaveAttribute('data-category', selectedCategory); + await expect(page.locator('.nv-order select')).toHaveValue('oldest'); + if (activation === 'keyboard') await expect(page.locator(`#${cardId} a`).first()).toBeFocused(); + else await expect(page.locator(`#${cardId} a`).first()).not.toBeFocused(); + expect(Math.abs(await page.evaluate(() => scrollY) - scroll)).toBeLessThan(100); + await page.goForward(); + await expect(page).toHaveURL(/\/posts\//); + await settled(page); +}); +} + +test('rapid navigation interrupts old work and the final page remains interactive', async ({ page }) => { + await visit(page); + // Real anchors, with second activation inside a running native transition. + await page.evaluate(async () => { + const click = name => [...document.querySelectorAll('.nv-nav a')].find(a => a.textContent === name).click(); + click('Writing'); + await new Promise(resolve => document.addEventListener('astro:after-swap', resolve, { once: true })); + click('Links'); + await new Promise(resolve => document.addEventListener('astro:after-swap', resolve, { once: true })); + click('Home'); + }); + await expect(page).toHaveURL(/\/$/); + await settled(page); + await expect(page.locator('.nv-nav [aria-current]')).toHaveText('Home'); + await expect(page.locator('html')).not.toHaveAttribute('data-voyage-home-fold-deferred', ''); + await page.locator('.nv-filters button').nth(1).click(); + await expect(page.locator('.nv-filters button').nth(1)).toHaveAttribute('aria-pressed', 'true'); + await navigate(page, 'About'); +}); + +test('reduced motion on entry and while animating cancels decorative motion', async ({ page }) => { + await page.emulateMedia({ reducedMotion: 'reduce' }); + await visit(page, '/', false); + expect(await page.evaluate(() => window.__motionProbe.calls.filter(a => ['first', 'space'].includes(a.target)))).toEqual([]); + await expect(page.locator('[data-binary]')).toBeDisabled(); + await navigate(page, 'Writing'); + await navigate(page, 'Home'); + await expect(page.locator('.nv-title-first')).toHaveCSS('opacity', '1'); + await page.emulateMedia({ reducedMotion: 'no-preference' }); + await expect(page.locator('[data-binary]')).toBeEnabled(); + await page.locator('[data-binary]').focus(); + await page.emulateMedia({ reducedMotion: 'reduce' }); + // Media-query change events are delivered asynchronously by browser engines. + await expect(page.locator('html')).toHaveAttribute('data-motion', 'off'); + await expect.poll(() => page.locator('.nv-dot-a').evaluate(el => el.getAnimations().length)).toBe(0); + await page.goBack(); + await settled(page); + await expect(page.locator('html')).toHaveAttribute('data-motion', 'off'); +}); + +test('missing optional browser APIs and blocked storage keep content navigable', async ({ page }) => { + await page.addInitScript(() => { + Object.defineProperty(window, 'IntersectionObserver', { value: undefined, configurable: true }); + delete window.IntersectionObserver; + Object.defineProperty(document, 'startViewTransition', { value: undefined, configurable: true }); + Object.defineProperty(window, 'sessionStorage', { get() { throw new DOMException('blocked', 'SecurityError'); } }); + }); + await page.goto('/'); + await settled(page); + await expect(page.locator('.nv-titleblock h1')).toBeVisible(); + await navigate(page, 'Links'); + await navigate(page, 'Home'); + await expect(page.locator('.nv-entry').first()).toBeVisible(); +}); + +test('a failed speculative tab fetch is not cached as a successful destination', async ({ page }) => { + let failures = 0; + await page.route('**/archive/', route => { + failures++; + return route.fulfill({ status: 503, contentType: 'text/html', body: 'Temporarily unavailable' }); + }); + await visit(page); + await expect.poll(() => failures).toBeGreaterThan(0); + await page.unroute('**/archive/'); + await navigate(page, 'Writing'); + await expect(page.locator('.vs-page-head h1')).toContainText('years.'); +}); + +test('the initial safety timeout cannot disable a slow incoming heading', async ({ page }) => { + let releaseModule; + let moduleStarted; + const gate = new Promise(resolve => { releaseModule = resolve; }); + const started = new Promise(resolve => { moduleStarted = resolve; }); + // Delay the interior layout's first execution, while HTML and the native swap stay real. + await page.route('**/_astro/grid.*.js', async route => { + if (route.request().resourceType() === 'script') { moduleStarted(); await gate; } + await route.continue(); + }); + await visit(page); + // Cross the real initial 5s recovery deadline after swap but before page-load. + await page.evaluate(() => new Promise(resolve => setTimeout(resolve, Math.max(0, 4400 - performance.now())))); + const activation = page.locator('.nv-nav').getByRole('link', { name: 'Writing', exact: true }).click(); + try { + await started; + await expect(page).toHaveURL(/\/archive\/$/); + await page.evaluate(() => new Promise(resolve => setTimeout(resolve, Math.max(0, 5500 - performance.now())))); + await expect(page.locator('html')).toHaveAttribute('data-voyage-preparing', ''); + } finally { + releaseModule(); + await activation; + } + await settled(page); + await expect(page.locator('.vs-page-head h1')).toHaveAttribute('data-motion-ready', 'true'); +}); + +test('the initial safety timeout still reveals Home when enhancement modules fail', async ({ page }) => { + await page.route('**/_astro/*.js', route => route.request().resourceType() === 'script' ? route.abort('failed') : route.continue()); + await page.goto('/'); + await expect(page.locator('.nv-title-first')).toHaveCSS('opacity', '0.45'); + await expect(page.locator('html')).not.toHaveAttribute('data-voyage-opening', '', { timeout: 6500 }); + await expect(page.locator('html')).not.toHaveAttribute('data-voyage-preparing', ''); + await expect(page.locator('.nv-title-first')).toHaveCSS('opacity', '1'); + await expect(page.locator('.nv-title-first')).toHaveCSS('translate', 'none'); +}); + +test('reduced transparency replaces additive text with solid readable lettering', async ({ page, browserName, context }) => { + test.skip(browserName !== 'chromium', 'CDP media emulation is Chromium-specific.'); + const session = await context.newCDPSession(page); + await session.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-transparency', value: 'reduce' }] }); + await visit(page); + await expect(page.locator('.nv-titleblock h1')).toHaveCSS('mix-blend-mode', 'normal'); + await expect(page.locator('.nv-title-first')).toHaveCSS('color', 'rgb(224, 224, 224)'); + await navigate(page, 'Links'); + await navigate(page, 'Home'); + await expect(page.locator('.nv-titleblock h1')).toHaveCSS('mix-blend-mode', 'normal'); + await session.detach(); +}); + +test('no JavaScript still exposes the four pages and article content', async ({ browser, baseURL, viewport, hasTouch, isMobile }) => { + const context = await browser.newContext({ javaScriptEnabled: false, baseURL, viewport, hasTouch, isMobile }); + await context.route('**/*', route => new URL(route.request().url()).hostname === '127.0.0.1' + ? route.continue() : route.fulfill({ status: 204, body: '' })); + const page = await context.newPage(); + for (const route of routes) { + await page.goto(route.path); + await expect(page.locator(route.heading)).toBeVisible(); + await expect(page.locator('.nv-nav a')).toHaveCount(4); + } + await page.goto('/'); + await page.locator('.nv-entry a').first().click(); + await expect(page.locator('.vs-article-head h1')).toBeVisible(); + await context.close(); +}); diff --git a/tests/browser/screenshot.css b/tests/browser/screenshot.css new file mode 100644 index 0000000..1449539 --- /dev/null +++ b/tests/browser/screenshot.css @@ -0,0 +1,7 @@ +/* Screenshot-only normalization of changing editorial counts. + Never hide the hero, its sky/texture or any animated title. */ +#voyage-afterhours .nv-filters button span, +#voyage-afterhours .nv-count, +#voyage-afterhours .vs-page-head .vs-kicker { + visibility: hidden !important; +} diff --git a/tests/browser/snapshots/win32/desktop/about-rest.png b/tests/browser/snapshots/win32/desktop/about-rest.png new file mode 100644 index 0000000..47ef73b Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/about-rest.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-departure-0ms.png b/tests/browser/snapshots/win32/desktop/home-departure-0ms.png new file mode 100644 index 0000000..16ea1dd Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-departure-0ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-departure-200ms.png b/tests/browser/snapshots/win32/desktop/home-departure-200ms.png new file mode 100644 index 0000000..c342716 Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-departure-200ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-departure-80ms.png b/tests/browser/snapshots/win32/desktop/home-departure-80ms.png new file mode 100644 index 0000000..ebed209 Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-departure-80ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-opening-0ms.png b/tests/browser/snapshots/win32/desktop/home-opening-0ms.png new file mode 100644 index 0000000..6c68280 Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-opening-0ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-opening-1000ms.png b/tests/browser/snapshots/win32/desktop/home-opening-1000ms.png new file mode 100644 index 0000000..d5908b2 Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-opening-1000ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-opening-2740ms.png b/tests/browser/snapshots/win32/desktop/home-opening-2740ms.png new file mode 100644 index 0000000..1d496df Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-opening-2740ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-rest.png b/tests/browser/snapshots/win32/desktop/home-rest.png new file mode 100644 index 0000000..a7ec70d Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-rest.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-return-0ms.png b/tests/browser/snapshots/win32/desktop/home-return-0ms.png new file mode 100644 index 0000000..988b579 Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-return-0ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-return-160ms.png b/tests/browser/snapshots/win32/desktop/home-return-160ms.png new file mode 100644 index 0000000..20892b4 Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-return-160ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-return-270ms.png b/tests/browser/snapshots/win32/desktop/home-return-270ms.png new file mode 100644 index 0000000..7268e1c Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-return-270ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-return-live-1010ms.png b/tests/browser/snapshots/win32/desktop/home-return-live-1010ms.png new file mode 100644 index 0000000..0025b91 Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-return-live-1010ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-return-live-280ms.png b/tests/browser/snapshots/win32/desktop/home-return-live-280ms.png new file mode 100644 index 0000000..2e4501e Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-return-live-280ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/home-return-live-690ms.png b/tests/browser/snapshots/win32/desktop/home-return-live-690ms.png new file mode 100644 index 0000000..c19909d Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/home-return-live-690ms.png differ diff --git a/tests/browser/snapshots/win32/desktop/links-rest.png b/tests/browser/snapshots/win32/desktop/links-rest.png new file mode 100644 index 0000000..52ee679 Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/links-rest.png differ diff --git a/tests/browser/snapshots/win32/desktop/writing-rest.png b/tests/browser/snapshots/win32/desktop/writing-rest.png new file mode 100644 index 0000000..cf2f93b Binary files /dev/null and b/tests/browser/snapshots/win32/desktop/writing-rest.png differ diff --git a/tests/browser/snapshots/win32/narrow/about-rest.png b/tests/browser/snapshots/win32/narrow/about-rest.png new file mode 100644 index 0000000..8df409a Binary files /dev/null and b/tests/browser/snapshots/win32/narrow/about-rest.png differ diff --git a/tests/browser/snapshots/win32/narrow/home-rest.png b/tests/browser/snapshots/win32/narrow/home-rest.png new file mode 100644 index 0000000..e3a53fa Binary files /dev/null and b/tests/browser/snapshots/win32/narrow/home-rest.png differ diff --git a/tests/browser/snapshots/win32/narrow/links-rest.png b/tests/browser/snapshots/win32/narrow/links-rest.png new file mode 100644 index 0000000..665214b Binary files /dev/null and b/tests/browser/snapshots/win32/narrow/links-rest.png differ diff --git a/tests/browser/snapshots/win32/narrow/writing-rest.png b/tests/browser/snapshots/win32/narrow/writing-rest.png new file mode 100644 index 0000000..e91c4bf Binary files /dev/null and b/tests/browser/snapshots/win32/narrow/writing-rest.png differ diff --git a/tests/browser/snapshots/win32/phone/about-rest.png b/tests/browser/snapshots/win32/phone/about-rest.png new file mode 100644 index 0000000..86f72ac Binary files /dev/null and b/tests/browser/snapshots/win32/phone/about-rest.png differ diff --git a/tests/browser/snapshots/win32/phone/home-rest.png b/tests/browser/snapshots/win32/phone/home-rest.png new file mode 100644 index 0000000..baf9390 Binary files /dev/null and b/tests/browser/snapshots/win32/phone/home-rest.png differ diff --git a/tests/browser/snapshots/win32/phone/links-rest.png b/tests/browser/snapshots/win32/phone/links-rest.png new file mode 100644 index 0000000..a5cac44 Binary files /dev/null and b/tests/browser/snapshots/win32/phone/links-rest.png differ diff --git a/tests/browser/snapshots/win32/phone/writing-rest.png b/tests/browser/snapshots/win32/phone/writing-rest.png new file mode 100644 index 0000000..769aa32 Binary files /dev/null and b/tests/browser/snapshots/win32/phone/writing-rest.png differ diff --git a/tests/browser/snapshots/win32/tablet/about-rest.png b/tests/browser/snapshots/win32/tablet/about-rest.png new file mode 100644 index 0000000..72ee71b Binary files /dev/null and b/tests/browser/snapshots/win32/tablet/about-rest.png differ diff --git a/tests/browser/snapshots/win32/tablet/home-rest.png b/tests/browser/snapshots/win32/tablet/home-rest.png new file mode 100644 index 0000000..7ca02db Binary files /dev/null and b/tests/browser/snapshots/win32/tablet/home-rest.png differ diff --git a/tests/browser/snapshots/win32/tablet/links-rest.png b/tests/browser/snapshots/win32/tablet/links-rest.png new file mode 100644 index 0000000..05cd975 Binary files /dev/null and b/tests/browser/snapshots/win32/tablet/links-rest.png differ diff --git a/tests/browser/snapshots/win32/tablet/writing-rest.png b/tests/browser/snapshots/win32/tablet/writing-rest.png new file mode 100644 index 0000000..89fe108 Binary files /dev/null and b/tests/browser/snapshots/win32/tablet/writing-rest.png differ diff --git a/tests/browser/visual.spec.mjs b/tests/browser/visual.spec.mjs new file mode 100644 index 0000000..ff17896 --- /dev/null +++ b/tests/browser/visual.spec.mjs @@ -0,0 +1,96 @@ +import { test, expect, routes, visit, navigate, freezeDecorations, armCompositorCapture, seekCaptured } from './fixtures.mjs'; +import { fileURLToPath } from 'node:url'; + +const countStyles = fileURLToPath(new URL('./screenshot.css', import.meta.url)); + +test.beforeEach(async ({}, testInfo) => { + test.skip(['firefox', 'webkit'].includes(testInfo.project.name), 'Golden pixels use the pinned Chromium/Windows renderer; behavior still runs across engines.'); +}); + +test('four production page viewports retain the approved composition', async ({ page }) => { + await visit(page); + for (const route of routes) { + if (route.name !== 'Home') await navigate(page, route.name); + await freezeDecorations(page); + // Publishing an article should not require approving new design goldens. + // Counts/lists are verified semantically by build and behavior tests. + const options = {}; + if (route.name === 'Writing') { + const head = await page.locator('.vs-page-head').boundingBox(); + options.clip = { x: 0, y: 0, width: page.viewportSize().width, height: Math.ceil(head.y + head.height) }; + options.stylePath = countStyles; + } else if (route.name === 'Home') options.stylePath = countStyles; + await expect(page).toHaveScreenshot(`${route.name.toLowerCase()}-rest.png`, options); + } +}); + +test('native return filmstrip protects blending, grain and slide/title coordination', async ({ page }, testInfo) => { + test.skip(testInfo.project.name !== 'desktop', 'One full compositor filmstrip; other widths have behavior and resting pixels.'); + await visit(page); + await navigate(page, 'About'); + await freezeDecorations(page); + await armCompositorCapture(page); + await page.locator('.nv-nav').getByRole('link', { name: 'Home', exact: true }).click(); + expect(await page.evaluate(() => window.__captureReady)).toBeGreaterThan(2); + // Pause real browser animations, then seek their actual compositor effects. + // Never use screenshot's default animation disabling: it skips the regression frames. + for (const time of [0, 160, 270]) { + await seekCaptured(page, time); + await expect(page).toHaveScreenshot(`home-return-${time}ms.png`); + } + await page.evaluate(() => { + for (const animation of window.__capturedAnimations) { + if (animation.effect?.pseudoElement) animation.finish(); + else animation.currentTime = 280; + } + }); + await page.evaluate(() => window.__nativeTransition.finished); + await freezeDecorations(page); + await expect(page).toHaveScreenshot('home-return-live-280ms.png'); + for (const time of [690, 1010]) { + await page.evaluate(time => { + for (const animation of window.__capturedAnimations) if (!animation.effect?.pseudoElement) animation.currentTime = time; + }, time); + await expect(page).toHaveScreenshot(`home-return-live-${time}ms.png`); + } + await page.evaluate(() => { + for (const animation of window.__capturedAnimations) if (!animation.effect?.pseudoElement) animation.finish(); + }); +}); + +test('native departure filmstrip protects outgoing additive lettering and planet', async ({ page }, testInfo) => { + test.skip(testInfo.project.name !== 'desktop', 'Full departure capture in the reference compositor.'); + await visit(page); + await freezeDecorations(page); + await armCompositorCapture(page); + await page.locator('.nv-nav').getByRole('link', { name: 'About', exact: true }).click(); + expect(await page.evaluate(() => window.__captureReady)).toBeGreaterThan(2); + for (const time of [0, 80, 200]) { + await seekCaptured(page, time); + await expect(page).toHaveScreenshot(`home-departure-${time}ms.png`); + } + await page.evaluate(() => { + for (const animation of window.__capturedAnimations) animation.finish(); + }); + await page.evaluate(() => window.__nativeTransition.finished); +}); + +test('opening pixels preserve the two slow title reveals and horizon', async ({ page }, testInfo) => { + test.skip(testInfo.project.name !== 'desktop', 'First-entry compositor baseline.'); + await page.goto('/'); + await page.waitForFunction(() => document.querySelector('.nv-horizon')?.getAnimations().length > 0); + await page.evaluate(async () => { + window.__capturedAnimations = document.getAnimations().filter(animation => + animation.effect?.target?.matches?.('.nv-title-first, .nv-titleblock h1 em, .nv-horizon')); + for (const animation of window.__capturedAnimations) animation.pause(); + await document.fonts.ready; + }); + expect(await page.evaluate(() => window.__capturedAnimations.length)).toBe(3); + for (const time of [0, 1000, 2740]) { + await seekCaptured(page, time); + await expect(page).toHaveScreenshot(`home-opening-${time}ms.png`); + } + await page.evaluate(() => { + for (const animation of window.__capturedAnimations) animation.finish(); + }); +});