Prerenders every page as HTML #14

Merged
Sluijsens merged 49 commits from feature/prerendering into master 2026-11-03 18:44:31 +01:00
19 changed files with 422 additions and 70 deletions
Showing only changes of commit 44125155bc - Show all commits
@@ -5,7 +5,7 @@
- **Feature Slug**: prerendering
- **Project Type**: Brownfield
- **Start Date**: 2026-10-31T14:15:01Z
- **Current Stage**: CONSTRUCTION - Code Generation (unit 2: display-fallbacks): plan approved; batch B0 running
- **Current Stage**: CONSTRUCTION - Code Generation (unit 2: display-fallbacks): B0 and B1 done; B2, B3 and B4 running
- **Branch**: feature/prerendering (from master c4c2f83); commits and pushes allowed for this feature (owner, 2026-10-31)
- **Worktree**: K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-prerendering
@@ -0,0 +1,23 @@
# Baseline checks: display fallbacks (unit 2), Step 1
- Commit: `4139c8f732f3861be48469b6b0bfe700c44389be`
- Branch: `feature/prerendering` (checked, matches)
- Date: 2026-10-31 (test run started 22:44, e2e started 22:45)
- Node: v24.16.0; pnpm: 12.11.2
- `git status --short` before the run: empty output (clean tree)
## Results
| Command | Result |
|---|---|
| `pnpm lint` | ESLint: No issues found (exit 0) |
| `pnpm format:check` | All matched files use Prettier code style (exit 0) |
| `pnpm test` | 123 test files passed (123), 1179 tests passed (1179); coverage: statements 96.04 %, branches 94.14 %, functions 97.38 %, lines 96.53 % (exit 0) |
| `pnpm build && pnpm e2e` | Build: 12 pages prerendered, 16 inline scripts moved, 28 files written (exit 0). e2e: 4 test files passed (4), 77 tests passed (77) |
fast-check seed of the baseline `pnpm test` run: `915664407`
(`FC_SEED=915664407 pnpm test` replays it).
Logs (outside the repository): `%TEMP%\prerendering-b0-test.log`, `%TEMP%\prerendering-b0-build.log`, `%TEMP%\prerendering-b0-build2.log`, `%TEMP%\prerendering-b0-e2e.log`.
e2e files: `e2e/hydration.e2e.ts`, `e2e/interaction.e2e.ts`, `e2e/rawHtml.e2e.ts`, `e2e/smoke.e2e.ts`.
@@ -0,0 +1,25 @@
# Proof report: display fallbacks, early proofs
Details and evidence per point: [verification-log.md](verification-log.md).
## Outcomes
- **V-D1 OK.** `Reveal` with a layout effect hydrates cleanly under StrictMode (unit test) and in Chrome: elements in view stay at opacity 1 in every frame, elements below the fold go to 0 after hydration without an intermediate value, reduced motion hides nothing. The `/portfolio` grid on a phone is now visible.
- **V-D2 OK.** With JavaScript on the noscript twin is never requested: requested URLs equal the displayed photos, each once; Emotion writes the shared class once.
- **V-D3 OK for head and twin.** The `noscript` with the CSS stays in the head, the browser holds the same number of `noscript` elements as the HTML, no hydration error. Header and panel are settled with the menu links. Without JavaScript every shown image has loaded and every empty deferred image is `display: none`.
- **V-D13 OK.** The `<picture>` tiles keep their box to the pixel at six widths, hover zoom and focus ring work, 1, 2 and 3 grid photos load before `load` at phone, tablet and desktop, each photo once, no hydration error. Router link types accept `media` and `fetchPriority`.
## Files changed so far
New: `web/src/lib/revealPhase.ts`, `web/src/lib/firstRow.ts`, `web/src/components/NoScript/noScriptCss.ts`, `web/src/components/NoScript/NoScriptStyles.tsx`, `web/src/displayHydration.test.tsx`.
Changed: `web/src/hooks/useReveal.ts`, `web/src/components/Reveal/Reveal.tsx`, `web/src/components/DeferredImage/DeferredImage.tsx`, `web/src/routes/__root.tsx`, `web/src/seo.ts`, `web/src/components/PortfolioGrid/PortfolioGrid.tsx`, `web/src/components/portfolio/PortfolioGallery/PortfolioGallery.tsx`, `web/src/routes/portfolio.tsx`, `web/src/components/PortfolioGrid/PortfolioGrid.test.tsx` (one line, see below).
## Deviations from the design
- `PortfolioGrid.test.tsx`: `eagerCount={3}` became `eagerFirstRow`, only so `tsc` and `pnpm build` compile (the build runs `tsc` over the tests). Its assertions are untouched and still pass; Step 14 rewrites the test.
- `firstRow.ts` imports `preloadImage` from `../seo.ts` (relative with `.ts`, like the other files in `src/lib`) instead of `@/seo`.
- `PortfolioGrid` keeps its literal `gridTemplateColumns` (as the step says); `GRID_COLUMNS` is a parallel constant with the same values.
## Checks
`tsc --noEmit`, `pnpm lint`, `pnpm format:check` (src), `pnpm build` green. `pnpm test`: 124 files, 1180 tests, 5 failures, all in tests named in the plan: four `useReveal.test.tsx` cases and `PortfolioGallery.test.tsx` ("none eager").
@@ -0,0 +1,21 @@
# Verification log: display fallbacks (unit 2)
Status values: `open` (not yet settled), `OK`, `BLOCKED`, `DEVIATION`.
| V-D# | Point | Step | Outcome | Evidence | Status |
|---|---|---|---|---|---|
| V-D1 | `useLayoutEffect` in `Reveal` during `renderToString`, `hydrateRoot` and StrictMode (double effect): no warning, no mismatch, the hide step runs once visibly. | 2 | No warning, no mismatch, hide step visible once. | Unit test src/displayHydration.test.tsx (hydrate() under StrictMode, rectangles stubbed): no recoverable error, in-view Reveal stays visible, below-the-fold becomes hidden after hydration and visible after the fake observer fires; no console warning in the run. Browser probe on the built site (rAF sampling of getComputedStyle opacity from the first frame, 2.5 s; /over-mij, /soorten-fotoshoots, /portfolio at 412x823; /, /over-mij at 1350x940; / at 412x823): elements in view at the first sample (2, 2, 1, 0, 2, 0 of 5, 11, 3, 14, 5, 14) were 1 in every frame; elements below the fold (3, 9, 2, 14, 3, 14) ended hidden with opacity values only 0 or 1, never an intermediate value; no console error or warning. /soorten-fotoshoots: first frame with a 0 is frame 16 of 456 (the hide happens after hydration, no transition). reducedMotion reduce (/ and /over-mij at 412x823, /soorten-fotoshoots): every sample 1, nothing hidden. /portfolio grid wrapper at 412x823 now stays visible (the BR-RVL-13 defect). | OK |
| V-D2 | With JavaScript on, the twin image is never requested (request log on `/soorten-fotoshoots` and `/portfolio` before any scroll), and the preload scanner does not read inside `noscript`. Also that Emotion writes the shared class once (one `<style>` for the two images). | 3 | Twin never requested with JavaScript on; one Emotion class. | Built dist, Chrome, 1350x940, JavaScript on. /soorten-fotoshoots: 12 image requests in total, 12 distinct URLs, none twice; 4 before load + 500 ms (both logos, newborn, newborn-detail: photos in or near view); set of requested URLs equals the set of currentSrc of the displayed img elements. /portfolio: 18 requests, 18 distinct, none twice, 8 before load + 500 ms (logos and 6 photos near the viewport), requested set equals the displayed set. No console message. Raw HTML: no preload link for a twin. Emotion: one style block data-emotion="css qvpj2z" (soorten) and one for css-1qa5q9y (portfolio tile class), shared by the deferred image and its twin. | OK |
| V-D3 | `<noscript>` inside `<head>` and inside the header and the panel hydrate without a mismatch in `hydrateRoot(document)` (the shell hydrates `<html>`), and the head hoisting of `HeadContent` keeps the CSS in the head. | 3 (head, twin), 7 (header and panel) | Head and twin part OK; header and panel part is settled in the menu step. | Raw dist/client/soorten-fotoshoots.html and portfolio.html: the noscript with the style sits inside head (after HeadContent); document.head.querySelector("noscript") exists in the browser with the CSS as text; document.querySelectorAll("noscript").length equals the raw HTML count (10 on /soorten-fotoshoots, 17 on /portfolio). No hydration error or console message in the browser. JavaScript off: every displayed img has complete and naturalWidth > 0 (12 of 22 and 18 of 35 images displayed, matching the request counts), every img[data-deferred] is display none and has no src, noscript is display: contents; screenshots of both pages looked at, no broken-image box. | OK (head, twin); header and panel open until the menu step |
| V-D4 | Fragment navigation to a fixed element does not scroll in Firefox and Safari, and Chrome on Android (only desktop Chrome was probed). If one scrolls, the fixed `header` target moves to a zero-size fixed element. | 18 (Chrome part) | | | open |
| V-D5 | The comparison of BR-DMS-05 (E against D on mobile, three runs each, same machine) and its report to the owner when E is below 0.9 or below D. | 26 | | | open |
| V-D6 | Height of every `Reveal` at 320, 360, 412, 768, 1350 px wide against the limit of BR-RVL-13. | 18 | | | open |
| V-D7 | After the gate measurement: whether `loading="lazy"` on the light logo and the contact portrait changes score and LCP as estimated; that the logo does not flash on `/` or on a client navigation from `/` to another page and back. | 24, 25 | | | open |
| V-D8 | The raw-HTML e2e tests that count `img` or links (`rawHtml.e2e.ts`) with `noscript` content present. | 20 | | | open |
| V-D9 | The visible focus ring of the two menu links in Chakra's reset (a bare `a` outside Chakra components). | 17 | | | open |
| V-D10 | Whether Chrome really excludes the viewport-filling hero photo from LCP (so text is the candidate on `/`), by a trace. Only explains `/`; changes no rule. | 25 (only if a trace exists) | | | open |
| V-D11 | The first React 19 upgrade: the hoisting facts of BR-PRE-01 (tested by BR-PRE-04). | 15 | | | open |
| V-D12 | Visual check without JavaScript on every page at 390 and 1280 px (screenshots through `E2E_SCREENSHOT_DIR`, looked at, not compared): header, hero, nav, footer, empty areas left by hidden controls (`mb` of the filter bar, the gate's margin). | 16 | | | open |
| V-D13 | `<picture>` with `display: contents` around the grid tile `DeferredImage`: the tile keeps its size, the hover zoom, the focus ring and the reading order; the `<source>` photo is requested once when `src` is set later; hydration is clean for tiles 2 and 3 (`<picture>` and `noscript` children). | 4 (proof), 14 (test), 19 (e2e) | Tile keeps size, zoom and focus; one request per photo; clean hydration in the browser. | Boxes of all portfolio tiles before and after at 320x568, 412x823, 768x1024, 1023x768, 1024x768, 1350x940: identical to 0.01 px (baseline taken from the dist built after Steps 2 and 3, which change no box). Photo requests before the load event: 1 at 320, 390, 412 px; 2 at 768 and 1023; 3 at 1024 and 1350; each URL once, none for tiles 4 and up. After a scroll to the bottom each of the 10 grid photos was requested exactly once at every width. Distinct x positions in the first row: 1, 1, 1, 2, 2, 3, 3 at 320, 390, 412, 768, 1023, 1024, 1350 = column count. Hover and keyboard focus (Tab): tile image transform matrix(1.05 ...), zIndex 1, outline solid 2px on tile 2 at 768 and tiles 2 and 3 at 1350. dist/client/portfolio.html head: React preload for tile 1 (f41a1916, no media), f41a1922 with media (min-width: 48em), f41a7883 with media (min-width: 64em), no other photo preload. No hydration error or console message at any width (production build). | OK |
| V-D14 | Which tiles Chrome reports as the largest paint at 412, 768 and 1350 px after the change (the probe saw `f41a1916` at 412, `f41a1922` at 768 and `f41a7883` at 1350 without the eager row), and that these are first-row tiles. | 25 | | | open |
| V-D15 | `/portfolio?shoot=gezin`: the preloads of unfiltered tiles 2 and 3 and the remounted first row of the filtered list do not fetch the same photo twice. | 19 | | | open |
@@ -144,7 +144,7 @@ P23 of the design is an example test on one constant, not a property: Step 8 (BR
## Part A: Setup and baseline (batch B0, Haiku, exclusive)
### Step 1: Confirm a green baseline and create the log [ ]
### Step 1: Confirm a green baseline and create the log [x]
- Executor: Haiku.
- Implements: NFR-PR-Q-01 (baseline), setup.
@@ -161,7 +161,7 @@ P23 of the design is an example test on one constant, not a property: Step 8 (BR
The three riskiest mechanisms are built in their real form and proven in a real browser first. If a proof fails, STOP: the design needs a decision before mechanical work starts.
### Step 2: `Reveal` with a layout effect (V-D1) [ ]
### Step 2: `Reveal` with a layout effect (V-D1) [x]
- Executor: Sonnet.
- Implements: BR-RVL-01 to 09, 11, 12; FR-PR-09, FR-PR-10; V-D1.
@@ -175,7 +175,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
- Done when: the probe shows the expected behaviour; `pnpm exec tsc --noEmit`, `pnpm lint` clean; `pnpm exec vitest run src/displayHydration.test.tsx` green. The existing `useReveal.test.tsx` cases listed in § 6 fail as expected (they are rewritten in Step 14); no other test fails.
- Record: verification log V-D1 with the probe output summary. If hydration reports an error, a flash is sampled, or React warns about `useLayoutEffect`, STOP.
### Step 3: `DeferredImage` twin and the head CSS (V-D2, V-D3) [ ]
### Step 3: `DeferredImage` twin and the head CSS (V-D2, V-D3) [x]
- Executor: Sonnet.
- Implements: BR-IMG-01 to 04, 10; BR-NAV-01, 02 (head placement); V-D2, V-D3.
@@ -192,7 +192,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
- Done when: V-D2 and V-D3 are OK; `tsc`, lint clean; `src/components/DeferredImage/DeferredImage.test.tsx` still passes unchanged (client render shows no `noscript` content).
- Record: verification log V-D2, V-D3 with evidence. A hydration error caused by the head `noscript`, a request for a twin with JavaScript on, or the CSS leaving the head: STOP.
### Step 4: First row of the portfolio grid (V-D13) [ ]
### Step 4: First row of the portfolio grid (V-D13) [x]
- Executor: Sonnet.
- Implements: BR-PRE-03, 08, 10, 11, 12; BR-IMG-10; FR-PR-21; V-D13.
@@ -208,7 +208,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
- Done when: V-D13 is OK; `tsc`, lint clean; `pnpm build` green. `PortfolioGrid.test.tsx` is expected to fail on the removed prop only (Step 14).
- Record: verification log V-D13 with evidence (request counts per width, box comparison). A `<picture>` that changes a tile's box, a double request, a request below the media query, or a hydration error: STOP.
### Step 5: Proof report and decision to continue [ ]
### Step 5: Proof report and decision to continue [x]
- Executor: Sonnet.
- Do: write `aidlc-docs/features/prerendering/construction/display-fallbacks/code/proof-report.md` (max one page): per V-D1, V-D2, V-D3, V-D13 the outcome in one or two sentences with evidence; the list of files changed so far; deviations from the design (none expected). Run `pnpm exec tsc --noEmit`, `pnpm lint`, `pnpm build`, `pnpm test` and list which tests fail (expected: the `useReveal.test.tsx` cases and `PortfolioGrid.test.tsx` named in § 6, nothing else).
@@ -35,16 +35,37 @@ export default function DeferredImage({
});
const load = pageLoaded && (near ?? inView);
// The twin is for visitors without JavaScript: the parser reads noscript
// content as text when scripting is on, so it is never fetched, and React
// ignores it when hydrating. It has the same style props, so the same
// class and box, and leaves out what must stay unique.
const twinProps: Record<string, unknown> = { ...rest };
delete twinProps.id;
delete twinProps['data-testid'];
return (
<Image
ref={ref}
src={load ? image.src : undefined}
alt={image.alt}
htmlWidth={image.width}
htmlHeight={image.height}
loading="lazy"
decoding="async"
{...rest}
/>
<>
<Image
ref={ref}
src={load ? image.src : undefined}
alt={image.alt}
htmlWidth={image.width}
htmlHeight={image.height}
loading="lazy"
decoding="async"
data-deferred
{...rest}
/>
<noscript>
<Image
src={image.src}
alt={image.alt}
htmlWidth={image.width}
htmlHeight={image.height}
decoding="async"
{...twinProps}
/>
</noscript>
</>
);
}
@@ -0,0 +1,11 @@
import { NO_SCRIPT_CSS } from './noScriptCss';
// Rendered in the head by the root shell. The browser ignores the children
// when scripting is on, on the server and when hydrating alike.
export default function NoScriptStyles() {
return (
<noscript>
<style>{NO_SCRIPT_CSS}</style>
</noscript>
);
}
@@ -0,0 +1,10 @@
// The CSS of every fallback for a visitor without JavaScript. It sits in a
// <noscript><style> in the head, so a browser with scripting on never parses
// it. No `</`, `url(` or `@import`: it must not end the noscript early or
// fetch anything (BR-NAV-02).
export const NO_SCRIPT_CSS = [
// The wrapper takes no part in flex, grid or positioning of its twin
'noscript{display:contents}',
// The empty deferred photo would draw as a broken-image box
'img[data-deferred]:not([src]){display:none!important}',
].join('');
@@ -35,7 +35,7 @@ describe('PortfolioGrid', () => {
await renderWithProviders(
<PortfolioGrid
items={galleryItems}
eagerCount={3}
eagerFirstRow
onOpen={() => {}}
/>,
);
@@ -1,8 +1,15 @@
import { useRef, type MouseEvent } from 'react';
import { Box, chakra, Image, VisuallyHidden } from '@chakra-ui/react';
import {
Box,
chakra,
Image,
VisuallyHidden,
type ImageProps,
} from '@chakra-ui/react';
import DeferredImage from '@/components/DeferredImage/DeferredImage';
import Reveal from '@/components/Reveal/Reveal';
import type { GalleryItem } from '@/content/types';
import { firstRow } from '@/lib/firstRow';
import {
GAP_ROWS,
masonryRowSpan,
@@ -11,9 +18,10 @@ import {
type PortfolioGridProps = {
items: readonly GalleryItem[];
// How many photos at the start load straight away (the first row on
// desktop); the rest wait until the page has loaded and they are near
eagerCount?: number;
// The photos of the first row (one column per screen width, see firstRow)
// load straight away; the rest wait until the page has loaded and they
// are near
eagerFirstRow?: boolean;
onOpen: (index: number) => void;
// First hover or focus on a photo: a good moment to load the lightbox
onIntent?: () => void;
@@ -29,7 +37,7 @@ type PortfolioGridProps = {
// to open the lightbox instead.
export default function PortfolioGrid({
items,
eagerCount = 3,
eagerFirstRow = true,
onOpen,
onIntent,
'data-testid': testId = 'portfolio-grid',
@@ -59,6 +67,40 @@ export default function PortfolioGrid({
onOpen(index);
};
const tile = (item: GalleryItem, index: number, imageStyle: ImageProps) => {
const row = eagerFirstRow ? firstRow(index) : null;
if (row === 'always') {
return (
<Image
src={item.thumb.src}
alt={item.thumb.alt}
htmlWidth={item.thumb.width}
htmlHeight={item.thumb.height}
fetchPriority="high"
decoding="async"
{...imageStyle}
/>
);
}
if (row) {
// From this width the source loads the photo at once, to be in
// step with its preload; below it nothing loads until the image
// is near. The src set later is the same file.
return (
<chakra.picture display="contents">
<source media={row.media} srcSet={item.thumb.src} />
<DeferredImage
image={item.thumb}
{...imageStyle}
loading="eager"
fetchPriority="high"
/>
</chakra.picture>
);
}
return <DeferredImage image={item.thumb} {...imageStyle} />;
};
return (
<Box containerType="inline-size">
<Reveal>
@@ -132,22 +174,7 @@ export default function PortfolioGrid({
onPointerEnter={reportIntent}
onFocus={reportIntent}
>
{index < eagerCount ? (
<Image
src={item.thumb.src}
alt={item.thumb.alt}
htmlWidth={item.thumb.width}
htmlHeight={item.thumb.height}
fetchPriority="high"
decoding="async"
{...imageStyle}
/>
) : (
<DeferredImage
image={item.thumb}
{...imageStyle}
/>
)}
{tile(item, index, imageStyle)}
{/* The alt names the photo; this says what
the link does */}{' '}
<VisuallyHidden>
+20 -8
View File
@@ -6,11 +6,12 @@ type RevealProps = BoxProps & {
delay?: number;
};
// Fades its content in and up once it scrolls into view (design .reveal).
// The content is always in the DOM and readable by assistive technology;
// only its opacity and position change.
// Fades its content in and up once it scrolls into view (design .reveal),
// when it started wholly below the viewport; content in view is simply
// shown. The content is always in the DOM and readable by assistive
// technology; only its opacity and position change.
export default function Reveal({ delay = 0, children, ...rest }: RevealProps) {
const { ref, visible } = useReveal<HTMLDivElement>();
const { ref, visible, animated } = useReveal<HTMLDivElement>();
return (
<Box
@@ -18,10 +19,21 @@ export default function Reveal({ delay = 0, children, ...rest }: RevealProps) {
data-reveal={visible ? 'visible' : 'hidden'}
opacity={visible ? 1 : 0}
transform={visible ? 'none' : 'translateY(24px)'}
transitionProperty="opacity, transform"
transitionDuration="reveal"
transitionTimingFunction="smooth"
transitionDelay={`${delay}s`}
{...(animated
? {
transitionProperty: 'opacity, transform',
transitionDuration: 'reveal',
transitionTimingFunction: 'smooth',
transitionDelay: `${delay}s`,
}
: { transition: 'none' })}
// A preference that changes while elements are hidden shows them
// at once
_motionReduce={{
opacity: 1,
transform: 'none',
transition: 'none',
}}
{...rest}
>
{children}
@@ -105,11 +105,12 @@ export default function PortfolioGallery({
<Box ref={grid}>
<PortfolioGrid
items={items}
// No photo loads before the page has: the grid fades in, so
// its photos are never the largest paint, and loading them
// early only slowed the fonts and the intro text (measured
// 0.80 vs 0.91 on mobile; decision 2026-10-27)
eagerCount={0}
// The first row loads eagerly, with preloads, because it
// is in view and is the largest paint; later rows wait for
// the page and for proximity. An earlier measurement
// (2026-10-27, 0.80 eager against 0.91 deferred on mobile)
// was made while the grid still faded in; it is repeated
// before this is final.
onOpen={open}
onIntent={() => setLightboxRequested(true)}
/>
+53
View File
@@ -0,0 +1,53 @@
import { StrictMode } from 'react';
import { act } from '@testing-library/react';
import { ChakraProvider } from '@chakra-ui/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import Reveal from '@/components/Reveal/Reveal';
import { FakeIntersectionObserver as FakeObserver } from '@/test/fakeIntersectionObserver';
import { hydrate } from '@/test/hydrate';
import system from './theme';
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
FakeObserver.reset();
});
// jsdom has no layout: place the elements by their test id
function stubTops(tops: Record<string, number>) {
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(
function (this: Element) {
const top = tops[this.getAttribute('data-testid') ?? ''] ?? 0;
return { top } as DOMRect;
},
);
}
describe('Reveal while hydrating (BR-RVL-01, 02)', () => {
const page = (
<StrictMode>
<ChakraProvider value={system}>
<Reveal data-testid="in-view">in view</Reveal>
<Reveal data-testid="below-fold">below the fold</Reveal>
</ChakraProvider>
</StrictMode>
);
it('keeps an element in view visible and hides one below the fold only after hydration', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
stubTops({ 'in-view': innerHeight - 1, 'below-fold': innerHeight });
const { container, errors } = hydrate(page);
const inView = container.querySelector('[data-testid="in-view"]')!;
const belowFold = container.querySelector(
'[data-testid="below-fold"]',
)!;
expect(errors).toEqual([]);
expect(inView).toHaveAttribute('data-reveal', 'visible');
expect(belowFold).toHaveAttribute('data-reveal', 'hidden');
act(() => FakeObserver.instances.at(-1)!.trigger(true));
expect(belowFold).toHaveAttribute('data-reveal', 'visible');
expect(inView).toHaveAttribute('data-reveal', 'visible');
});
});
+42 -8
View File
@@ -1,17 +1,51 @@
import { useMediaQuery } from '@chakra-ui/react';
import { useLayoutEffect, useState } from 'react';
import {
nextRevealPhase,
startsHidden,
type RevealPhase,
} from '@/lib/revealPhase';
import useInView from './useInView';
// Tells whether an element has scrolled into view, once, using the design's
// initReveal trigger: a little of the element must be on screen, and not
// right at the bottom edge. When the visitor prefers reduced motion the
// element counts as visible right away.
// Tells whether an element is shown, and whether it fades in. The first
// render is settled (visible), on the server and in the browser, so the
// prerendered HTML shows the content with and without JavaScript. After
// hydration an element wholly below the viewport is hidden, without a
// transition, and fades in once when it scrolls into view with the design's
// initReveal trigger: a little of it on screen, and not right at the bottom
// edge. Reduced motion and a missing IntersectionObserver hide nothing.
export default function useReveal<T extends Element>() {
const [reducedMotion] = useMediaQuery(['(prefers-reduced-motion: reduce)']);
const [phase, setPhase] = useState<RevealPhase>('settled');
const { ref, inView } = useInView<T>({
threshold: 0.12,
rootMargin: '0px 0px -60px 0px',
skip: reducedMotion,
skip: phase !== 'hidden',
});
return { ref, visible: inView };
// A layout effect runs after the commit and before the next paint, so
// hiding an element is never painted as a flash. It reads the media query
// itself: Chakra's useMediaQuery still holds its server-safe value here.
useLayoutEffect(() => {
const element = ref.current;
if (
!element ||
typeof IntersectionObserver === 'undefined' ||
window.matchMedia('(prefers-reduced-motion: reduce)').matches
) {
return;
}
if (startsHidden(element.getBoundingClientRect().top, innerHeight)) {
setPhase((current) => nextRevealPhase(current, 'belowViewport'));
}
}, [ref]);
const effective =
phase === 'hidden' && inView
? nextRevealPhase(phase, 'intersected')
: phase;
return {
ref,
visible: effective !== 'hidden',
animated: effective === 'revealed',
};
}
+45
View File
@@ -0,0 +1,45 @@
import type { ContentImage } from '../content/types.ts';
import { preloadImage, type HeadLink } from '../seo.ts';
// Columns of the portfolio grid per screen width, narrowest first: the values
// of PortfolioGrid's gridTemplateColumns (base, md, lg)
export const GRID_COLUMNS = [
{ media: null, columns: 1 },
{ media: '(min-width: 48em)', columns: 2 },
{ media: '(min-width: 64em)', columns: 3 },
] as const;
type GridColumns = readonly {
media: string | null;
columns: number;
}[];
// 'always': in the first row at every width. { media }: in the first row from
// that width on. null: never in the first row.
export type FirstRow = 'always' | { media: string } | null;
// Whether the tile at this index is in the first row of the grid, and from
// which width on. The column count is CSS only, so the build cannot know the
// width: it names the media query instead.
export function firstRow(
index: number,
columns: GridColumns = GRID_COLUMNS,
): FirstRow {
if (index < columns[0].columns) return 'always';
const breakpoint = columns.find((entry) => index < entry.columns);
return breakpoint?.media ? { media: breakpoint.media } : null;
}
// The preloads React cannot write itself: the first-row tiles that sit in a
// <picture>, each bound to the query of its <source>
export function firstRowPreloads(
items: readonly { thumb: ContentImage }[],
columns: GridColumns = GRID_COLUMNS,
): HeadLink[] {
return items.flatMap((item, index) => {
const row = firstRow(index, columns);
return row && row !== 'always'
? [preloadImage(item.thumb, { media: row.media })]
: [];
});
}
+26
View File
@@ -0,0 +1,26 @@
// The phases of a Reveal. `settled` is what the server and the hydrating
// render show: visible, nothing to animate. After hydration only an element
// wholly below the viewport becomes `hidden`, and it becomes `revealed` once
// it scrolls into view (BR-RVL-09).
export type RevealPhase = 'settled' | 'hidden' | 'revealed';
export type RevealEvent = 'belowViewport' | 'inView' | 'intersected';
// An element whose top edge is at or below the bottom edge of the viewport was
// not painted from the HTML, so it may be hidden without a flash. Anything
// else, also an element above the viewport or one taller than it, stays.
export function startsHidden(top: number, viewportHeight: number): boolean {
return top >= viewportHeight;
}
// One way only: settled stays settled, hidden becomes revealed, revealed
// stays. Applying an event twice (StrictMode runs effects twice) gives the
// same phase as once.
export function nextRevealPhase(
phase: RevealPhase,
event: RevealEvent,
): RevealPhase {
if (phase === 'settled' && event === 'belowViewport') return 'hidden';
if (phase === 'hidden' && event === 'intersected') return 'revealed';
return phase;
}
+2
View File
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';
import { createRootRoute, HeadContent, Scripts } from '@tanstack/react-router';
import { ChakraProvider } from '@chakra-ui/react';
import AppShell from '../components/AppShell';
import NoScriptStyles from '../components/NoScript/NoScriptStyles';
import ErrorPage from '../components/StatusPage/ErrorPage';
import NotFound from '../components/StatusPage/NotFound';
import siteContent from '../content/siteContent';
@@ -29,6 +30,7 @@ const RootDocument = ({ children }: { children: ReactNode }) => (
<html lang="nl">
<head>
<HeadContent />
<NoScriptStyles />
</head>
<body>
{/* De site is alleen licht; de _dark-waarden in het thema blijven
+26 -11
View File
@@ -7,7 +7,12 @@ import portfolioContent from '../content/portfolioContent';
import shootTypes from '../content/shootTypes';
import siteContent from '../content/siteContent';
import type { ShootTypeId } from '../content/types';
import { isShootTypeId } from '../lib/portfolioFilters';
import { firstRowPreloads } from '../lib/firstRow';
import {
filterPhotos,
isShootTypeId,
toGalleryItems,
} from '../lib/portfolioFilters';
import { visibleSocials } from '../lib/visibleSocials';
import useHydrated from '../hooks/useHydrated';
import { galleryImages, pageHead, structuredDataScript, webPage } from '../seo';
@@ -27,16 +32,26 @@ export const Route = createFileRoute('/portfolio')({
: undefined;
return isShootTypeId(value, shootTypeIds) ? { shoot: value } : {};
},
head: () => ({
...pageHead('/portfolio'),
scripts: [
structuredDataScript(
webPage('ImageGallery', '/portfolio', {
associatedMedia: galleryImages(portfolioContent.photos),
}),
),
],
}),
head: () => {
const base = pageHead('/portfolio');
// The unfiltered list the page renders: ?shoot= only applies after
// hydration
const items = toGalleryItems(
filterPhotos(portfolioContent.photos, undefined),
shootTypes,
);
return {
...base,
links: [...base.links, ...firstRowPreloads(items)],
scripts: [
structuredDataScript(
webPage('ImageGallery', '/portfolio', {
associatedMedia: galleryImages(portfolioContent.photos),
}),
),
],
};
},
component: Portfolio,
});
+26
View File
@@ -2,6 +2,7 @@
// Titels en beschrijvingen staan in het pagina-register (sitePages.ts).
import type {
AboutPageContent,
ContentImage,
FaqItem,
PortfolioPhoto,
PricingPackage,
@@ -65,6 +66,31 @@ export function pageHead(path: RoutePath) {
};
}
export type HeadLink = {
rel: 'preload';
as: 'image';
href: string;
fetchPriority: 'high';
media?: string;
};
// Preload van een foto die React zelf niet naar de head haalt, omdat hij in
// een <picture> staat. Zonder `media` geldt hij voor elke breedte; een foto
// die vanaf een breakpoint zichtbaar is krijgt dezelfde query als zijn
// <source>, zodat er nooit iets wordt opgehaald dat niet getoond wordt.
export function preloadImage(
image: ContentImage,
options?: { media?: string },
): HeadLink {
return {
rel: 'preload',
as: 'image',
href: image.src,
fetchPriority: 'high',
...(options?.media ? { media: options.media } : {}),
};
}
// JSON voor een <script type="application/ld+json">. <, > en & worden
// ge-escaped, zodat content het script-element nooit kan afsluiten (BR-SEO-05).
export function jsonLdScript(data: unknown): string {