Adds the fallbacks for visitors without JavaScript

The mobile menu works through CSS, and controls that need JavaScript are hidden
without it. The contact photo gets its own preload, and the tests cover the new
Reveal behaviour, the first row and the noscript markup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 23:09:33 +01:00
co-authored by Claude Opus 5.5
parent 44125155bc
commit 01fcfeefea
38 changed files with 1510 additions and 67 deletions
@@ -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): B0 and B1 done; B2, B3 and B4 running
- **Current Stage**: CONSTRUCTION - Code Generation (unit 2: display-fallbacks): B0 to B4 done; B5 browser tests 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
@@ -6,7 +6,7 @@ Status values: `open` (not yet settled), `OK`, `BLOCKED`, `DEVIATION`.
|---|---|---|---|---|---|
| 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-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: hydratePage of NavigationBar with the noscript links hydrates with no recoverable error (NoScriptNav.test.tsx); browser check on a current build is left to Step 21 |
| 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 |
@@ -218,7 +218,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
## Part C: No-JavaScript menu and CSS (batch B2, Sonnet; parallel with B3 and B4)
### Step 6: The complete no-JavaScript CSS [ ]
### Step 6: The complete no-JavaScript CSS [x]
- Executor: Sonnet.
- Implements: BR-NAV-03 to 06, 08, 09; BR-NJS-01, 02, 09; BR-IMG-02, 04.
@@ -232,7 +232,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
Use the Chakra CSS variables the site already uses where a token is needed (`var(--slp-...)`), no hard-coded colours except `currentColor`. Build the ids in the selectors from the exported constants.
- Done when: `tsc`, lint clean; the CSS has no `</`, `url(` or `@import`, balanced braces (Step 8 tests it).
### Step 7: The two menu links and the attributes [ ]
### Step 7: The two menu links and the attributes [x]
- Executor: Sonnet.
- Implements: BR-NAV-03, 04, 06, 07, 09, 10; BR-PRE-05 (light logo); V-D3 (header and panel).
@@ -244,7 +244,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
4. `MobileNavGroup.tsx`: `data-requires-js` on the chevron button. `NavSubmenu.tsx`: `data-submenu` on the wrapper `Box` (the one with the `ref` and `onBlur`), `data-submenu-panel` on the panel `Box`, `data-requires-js` on the chevron button.
- Done when: `tsc`, lint clean; the existing tests of the folder (`NavigationBar.test`, `MobileNav.test`, `NavSubmenu.test`, `NavLink.test`, `activeOptions.test`, `src/navSubmenu.test.tsx`) pass unchanged (client render shows no `noscript` content); `renderToString` of the navigation contains both links.
### Step 8: Tests for the menu and the CSS [ ]
### Step 8: Tests for the menu and the CSS [x]
- Executor: Sonnet.
- Implements: BR-DTS-02; BR-NAV-02; NFR-PR-SEC-01, S-01; PBT: "No PBT properties identified" (constant markup).
@@ -256,7 +256,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
## Part D: Markers and preload hygiene (batch B3, Sonnet; parallel with B2 and B4)
### Step 9: `data-requires-js` and the footer column [ ]
### Step 9: `data-requires-js` and the footer column [x]
- Executor: Sonnet.
- Implements: BR-NJS-01 to 04, 06; BR-NJS-02 (footer); FR-PR-13, FR-PR-22.
@@ -264,7 +264,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
- Do: `data-requires-js` on each arrow `ArrowButton`, on the pause button, on the hero progress bar `Box`, on the `FilterBar` root `div`, on the 48 px controls spacer `Box` in `CarouselPlaceholder`. `FooterColumn` takes an optional `requiresJs?: boolean` prop that sets `data-requires-js` on its root `Box`; the Contact column in `Footer.tsx` passes `requiresJs`. The `data-email-pending` placeholders already exist (unit 1); do not change them. Nothing else changes: the review copies stay hidden, `aria-hidden` and `inert` (BR-NJS-04).
- Done when: `tsc`, lint clean; the existing tests of these folders pass unchanged.
### Step 10: Preload hygiene for the contact page [ ]
### Step 10: Preload hygiene for the contact page [x]
- Executor: Sonnet.
- Implements: BR-PRE-02, 05; V-D11.
@@ -272,7 +272,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
- Do: `loading="lazy"` on the portrait `Image` of `ContactDetails` (it is `display: none` from `lg`; a lazy image is neither fetched while hidden nor hoisted by React). `routes/contact.tsx`: import `ASIDE_MEDIA` from `../components/contact/ContactAside/ContactAside` and `preloadImage` from `../seo`; `head()` returns `links: [...base.links, preloadImage(contactContent.image, { media: ASIDE_MEDIA })]` with `base = pageHead('/contact')`, keeping the existing `scripts`.
- Done when: `tsc`, lint clean; `ContactDetails.test.tsx` and the contact route tests pass unchanged; `pnpm exec vitest run src/seo.test.ts` still green.
### Step 11: Tests for markers and preload hygiene [ ]
### Step 11: Tests for markers and preload hygiene [x]
- Executor: Sonnet.
- Implements: BR-DTS-02; PBT: "No PBT properties identified" (attribute additions).
@@ -284,7 +284,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
## Part E: Reveal, image and first-row tests (batch B4, Sonnet; parallel with B2 and B3)
### Step 12: Generators [ ]
### Step 12: Generators [x]
- Executor: Sonnet.
- Implements: PBT-07; BR-DTS-05.
@@ -292,7 +292,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
- Do: `revealArbitraries.ts`: `viewportHeight` (finite positive floats, integers and a few phone and desktop heights mixed), `elementTop` (finite floats and integers, negative, zero, equal to the viewport height, far below), `revealPhase`, `revealEvent` (`belowViewport`, `inView`, `intersected`), `revealEvents` (arrays up to 20). `firstRowArbitraries.ts`: `columnMap` (1 to 4 breakpoints, strictly increasing column counts starting at the base, media strings of the form `(min-width: Nem)` with strictly increasing N), `tileIndex` (0 to 12), and a `galleryItemsWithThumbs` built from `galleryItems` in `arbitraries.ts`. Do not add anything to `arbitraries.ts`.
- Done when: `tsc` clean; the files are used by Step 13 (check with `grep`).
### Step 13: Properties P18 to P25 [ ]
### Step 13: Properties P18 to P25 [x]
- Executor: Sonnet.
- Implements: BR-RVL-12; BR-PRE-03, 08, 11; BR-DTS-05; PBT-01 to 10.
@@ -308,7 +308,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
- Example tests for every branch of `revealPhase.ts`, `firstRow.ts` (the real `GRID_COLUMNS`: tile 1 always, tile 2 `48em`, tile 3 `64em`, tile 4 null) and `preloadImage` with and without `media`, so `src/lib/**` and `src/seo.ts` stay at 100 %.
- Done when: `pnpm exec vitest run src/lib/revealPhase.test.ts src/lib/firstRow.test.ts src/seo.test.ts` green; a coverage run of those files shows 100 % for `revealPhase.ts`, `firstRow.ts` and the new `seo.ts` code.
### Step 14: Component, hydration and prerender tests [ ]
### Step 14: Component, hydration and prerender tests [x]
- Executor: Sonnet.
- Implements: BR-DTS-01, 02, 05; BR-RVL-01 to 09; BR-IMG-01, 03, 10; BR-PRE-08, 10; V-D1, V-D13 (test); PBT: "No PBT properties identified" for components (decisions are in P18 to P25).
@@ -323,6 +323,7 @@ The three riskiest mechanisms are built in their real form and proven in a real
- `displayPrerender.test.tsx` (`// @vitest-environment node`, in the style of `src/prerender.test.tsx`): for every `sitePages` path, the prerendered HTML contains one noscript twin per `data-deferred` image and no `data-reveal="hidden"`.
- Done when: **CP2** (after B2 and B3 are also done): `pnpm test` green with coverage thresholds, `pnpm lint`, `pnpm format:check`, `pnpm exec tsc --noEmit`, `pnpm build` green.
- Record: list every existing test changed, with the reason.
- Record (B4): changed existing tests, all named in section 6. `useReveal.test.tsx`: the six cases rewritten (server render visible; stubbed rectangle for the hidden, observing and disconnecting cases; reduced motion creates no observer; hydration case follows the new layout effect). `PortfolioGrid.test.tsx`: `eagerCount={3}` test replaced by the first-row test (`eagerFirstRow`), plus server-markup, hydration and column tests. `PortfolioGallery.test.tsx`: only the loop that expected no eager photo ("none eager") now expects tile 1 plain and high priority, tiles 2 and 3 eager, the rest lazy.
---
@@ -175,4 +175,14 @@ describe('ContactDetails in the prerendered HTML', () => {
);
expect(html).not.toContain('data-testid="details"');
});
it('loads the small portrait lazily, so a hidden one is never fetched', async () => {
const html = await serverHtml(card({ portrait }));
const doc = new DOMParser().parseFromString(html, 'text/html');
expect(
doc
.querySelector('[data-testid="contact-details-portrait"]')
?.getAttribute('loading'),
).toBe('lazy');
});
});
@@ -70,6 +70,7 @@ export default function ContactDetails({
rounded="full"
objectFit="cover"
flexShrink={0}
loading="lazy"
data-testid="contact-details-portrait"
/>
)}
@@ -1,7 +1,11 @@
import { ChakraProvider } from '@chakra-ui/react';
import { act, screen } from '@testing-library/react';
import { prerender } from 'react-dom/static';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { FakeIntersectionObserver } from '@/test/fakeIntersectionObserver';
import { hydratePage, serverHtml } from '@/test/hydrate';
import { renderWithProviders } from '@/test/renderWithProviders';
import system from '@/theme';
import DeferredImage, { DEFERRED_LOAD_MARGIN } from './DeferredImage';
const image = {
@@ -73,3 +77,80 @@ describe('DeferredImage', () => {
expect(FakeIntersectionObserver.instances).toHaveLength(0);
});
});
describe('DeferredImage without JavaScript', () => {
const imgTags = (html: string) => html.match(/<img\b[^>]*>/g) ?? [];
const attribute = (tag: string, name: string) =>
new RegExp(` ${name}="([^"]*)"`).exec(tag)?.[1];
const hasAttribute = (tag: string, name: string) =>
new RegExp(` ${name}[ =/>]`).test(tag);
it('renders the empty image and, in a noscript, a twin with the photo', async () => {
const html = await serverHtml(
<DeferredImage image={image} id="foto" data-testid="foto" />,
);
const [first = '', twin = '', ...others] = imgTags(html);
expect(others).toEqual([]);
expect(html.match(/<noscript>/g)).toHaveLength(1);
expect(html).toMatch(/<noscript><img\b[^>]*src="\/foto\.jpg"/);
expect(hasAttribute(first, 'data-deferred')).toBe(true);
expect(hasAttribute(first, 'src')).toBe(false);
expect(attribute(first, 'loading')).toBe('lazy');
expect(attribute(first, 'id')).toBe('foto');
expect(attribute(first, 'data-testid')).toBe('foto');
expect(attribute(twin, 'src')).toBe('/foto.jpg');
expect(attribute(twin, 'alt')).toBe('Een foto');
expect(attribute(twin, 'width')).toBe('800');
expect(attribute(twin, 'height')).toBe('1200');
expect(hasAttribute(twin, 'loading')).toBe(false);
expect(hasAttribute(twin, 'id')).toBe(false);
expect(hasAttribute(twin, 'data-testid')).toBe(false);
expect(hasAttribute(twin, 'data-deferred')).toBe(false);
});
it('gives the twin the class of the first image, so it has the same box', async () => {
const html = await serverHtml(
<DeferredImage image={image} w="100%" objectFit="cover" />,
);
const [first = '', twin = ''] = imgTags(html);
expect(attribute(first, 'class')).toBeTruthy();
expect(attribute(twin, 'class')).toBe(attribute(first, 'class'));
});
it('adds no preload for the twin when it is rendered in a document', async () => {
const { prelude } = await prerender(
<html lang="nl">
<head />
<body>
<ChakraProvider value={system}>
<DeferredImage image={image} />
<img src="/gewoon.jpg" alt="" />
</ChakraProvider>
</body>
</html>,
);
const html = await new Response(prelude).text();
const preloads = html.match(/<link\b[^>]*rel="preload"[^>]*>/g) ?? [];
// React hoists the plain photo, which shows the check can see a preload
expect(preloads).toHaveLength(1);
expect(preloads[0]).toContain('href="/gewoon.jpg"');
expect(html).toMatch(/<noscript><img\b[^>]*src="\/foto\.jpg"/);
});
it('hydrates the pair without a mismatch and renders no twin in the browser', async () => {
const { container, errors } = await hydratePage(
<DeferredImage image={image} />,
);
expect(errors).toEqual([]);
expect(container.querySelectorAll('img')).toHaveLength(1);
});
it('renders an empty noscript when the browser renders it', async () => {
const { container } = await renderWithProviders(
<DeferredImage image={image} />,
);
expect(container.querySelector('noscript')).toBeEmptyDOMElement();
});
});
@@ -2,6 +2,7 @@ import { screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { axeResults } from '@/test/axe';
import { serverHtml } from '@/test/hydrate';
import { renderWithProviders } from '@/test/renderWithProviders';
import FilterBar from './FilterBar';
@@ -101,4 +102,21 @@ describe('FilterBar', () => {
0,
);
});
it('is marked as needing JavaScript in the prerendered HTML', async () => {
const html = await serverHtml(
<FilterBar
options={options}
value="alles"
onChange={() => {}}
label={LABEL}
/>,
);
const doc = new DOMParser().parseFromString(html, 'text/html');
expect(
doc
.querySelector('[data-testid="filter-bar"]')
?.hasAttribute('data-requires-js'),
).toBe(true);
});
});
@@ -28,6 +28,7 @@ export default function FilterBar({
role="group"
aria-label={label}
data-testid="filter-bar"
data-requires-js
display="flex"
// One row, always: when the web font replaces the fallback, a
// wrapping row could gain or lose a line and push the photos
+10
View File
@@ -220,4 +220,14 @@ describe('Footer in the prerendered HTML', () => {
vi.unstubAllEnvs();
}
});
it('marks only the Contact column as needing JavaScript in the prerendered HTML', async () => {
const html = await serverHtml(<Footer content={siteContent} />);
const doc = new DOMParser().parseFromString(html, 'text/html');
const marked = doc.querySelectorAll('[data-requires-js]');
expect(marked).toHaveLength(1);
expect(marked[0].querySelector('h2')?.getAttribute('aria-label')).toBe(
'Contact',
);
});
});
+1 -1
View File
@@ -106,7 +106,7 @@ export default function Footer({ content }: FooterProps) {
)}
{available && (
<FooterColumn title="Contact">
<FooterColumn title="Contact" requiresJs>
{address === null ? (
// Even hoog als FooterLink (44px onder lg, daarna
// een tekstregel), zodat de kolom niet verspringt
+8 -2
View File
@@ -3,14 +3,20 @@ import { Box, Heading, Stack } from '@chakra-ui/react';
type FooterColumnProps = {
title: string;
// Hidden without JavaScript, for a column that only holds items that need it
requiresJs?: boolean;
children: ReactNode;
};
// Kolom in de footer: kopje als label, daaronder een lijst. De kop is een h2,
// want de kolommen zijn hoofdsecties van de pagina (BR-SEO-09).
export default function FooterColumn({ title, children }: FooterColumnProps) {
export default function FooterColumn({
title,
requiresJs,
children,
}: FooterColumnProps) {
return (
<Box>
<Box data-requires-js={requiresJs || undefined}>
<Heading
as="h2"
// Mobiele schermlezers lezen de CSS-hoofdletters ("SOCIALS") als
+1
View File
@@ -186,6 +186,7 @@ export default function Hero({ content, socials }: HeroProps) {
key={active}
aria-hidden
data-testid="hero-progress"
data-requires-js
data-state={paused ? 'paused' : 'running'}
position="absolute"
left={0}
+2
View File
@@ -16,6 +16,7 @@ export default function HeroArrows({ onPrev, onNext }: HeroArrowsProps) {
side="left"
aria-label="Vorige foto"
data-testid="hero-prev-button"
data-requires-js
onClick={onPrev}
>
<Icon icon={leftOutlined} aria-hidden />
@@ -24,6 +25,7 @@ export default function HeroArrows({ onPrev, onNext }: HeroArrowsProps) {
side="right"
aria-label="Volgende foto"
data-testid="hero-next-button"
data-requires-js
onClick={onNext}
>
<Icon icon={rightOutlined} aria-hidden />
@@ -25,6 +25,7 @@ export default function HeroPauseButton({
: 'Diavoorstelling pauzeren'
}
data-testid="hero-pause-button"
data-requires-js
onClick={onToggle}
css={iconControl()}
position="absolute"
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest';
import heroContent from '@/content/heroContent';
import siteContent from '@/content/siteContent';
import { serverHtml } from '@/test/hydrate';
import Hero from './Hero';
// Controls that do nothing without JavaScript carry the marker the head CSS
// hides (BR-NJS-01, BR-NJS-03)
describe('Hero in the prerendered HTML', () => {
it('marks the arrows, the pause button and the progress bar', async () => {
const html = await serverHtml(
<Hero content={heroContent} socials={siteContent.socials} />,
);
const doc = new DOMParser().parseFromString(html, 'text/html');
const marked = (testId: string) =>
doc
.querySelector(`[data-testid="${testId}"]`)
?.hasAttribute('data-requires-js');
expect(marked('hero-prev-button')).toBe(true);
expect(marked('hero-next-button')).toBe(true);
expect(marked('hero-pause-button')).toBe(true);
expect(marked('hero-progress')).toBe(true);
expect(doc.querySelectorAll('[data-requires-js]')).toHaveLength(4);
});
});
@@ -4,6 +4,7 @@ import type { NavMenuEvent } from '@/lib/navMenuState';
import { hasChildren, mainNav } from '@/navigation';
import RouterLink from '../RouterLink';
import MobileNavGroup from './MobileNavGroup';
import { NoScriptMenuClose } from './NoScriptNav';
// Exact, like the submenu: no link counts as current on an unknown URL
// (BR-404-05)
@@ -82,6 +83,7 @@ export default function MobileNav({
{/* Automatische marges centreren een kort menu en laten een hoog
menu bovenaan beginnen (centreren zou de bovenkant afknippen) */}
<Box marginBlock="auto">
<NoScriptMenuClose />
<nav aria-label="Mobiel menu">
<Stack as="ul" gap={5} listStyleType="none">
{mainNav.map((item) => (
@@ -46,6 +46,7 @@ export default function MobileNavGroup({
</RouterLink>
<chakra.button
type="button"
data-requires-js
aria-expanded={open}
aria-controls={id}
aria-label={`Submenu ${item.label}`}
@@ -54,6 +54,7 @@ export default function NavSubmenu({
return (
<Box
ref={wrapper}
data-submenu
position="relative"
display="flex"
alignItems="center"
@@ -80,6 +81,7 @@ export default function NavSubmenu({
<chakra.button
ref={toggleRef}
type="button"
data-requires-js
aria-expanded={open}
aria-controls={id}
aria-label={`Submenu ${item.label}`}
@@ -102,6 +104,7 @@ export default function NavSubmenu({
</chakra.button>
<Box
id={id}
data-submenu-panel
position="absolute"
top="calc(100% + 0.75rem)"
left="4"
@@ -8,10 +8,12 @@ import {
} from '@chakra-ui/react';
import NavLink from './NavLink';
import MobileNav from './MobileNav';
import { NoScriptMenuOpen } from './NoScriptNav';
import NavSubmenu from './NavSubmenu';
import { hasChildren, mainNav } from '@/navigation';
import RouterLink from '../RouterLink';
import useScrolledPast from '@/hooks/useScrolledPast';
import { HEADER_ID, MOBILE_NAV_ID } from '../NoScript/noScriptCss';
import { isSectionCurrent } from '@/lib/navCurrent';
import { initialNavMenuState, navMenuReducer } from '@/lib/navMenuState';
import { useEffect, useReducer, useRef } from 'react';
@@ -79,6 +81,7 @@ export default function NavigationBar() {
return (
<>
<chakra.header
id={HEADER_ID}
position="fixed"
top={0}
insetX={0}
@@ -135,6 +138,9 @@ export default function NavigationBar() {
alt=""
htmlWidth={500}
htmlHeight={500}
// Not shown on pages with a solid header, so
// not fetched there (BR-PRE-05)
loading={isHome ? undefined : 'lazy'}
display={overlay('none', 'block')}
/>
</RouterLink>
@@ -183,8 +189,10 @@ export default function NavigationBar() {
display="flex"
justifyContent="flex-end"
>
<NoScriptMenuOpen />
<chakra.button
ref={hamburgerRef}
data-requires-js
onClick={() =>
dispatch({
type: 'toggleMenu',
@@ -202,7 +210,7 @@ export default function NavigationBar() {
: 'Menu openen'
}
aria-expanded={state.menuOpen}
aria-controls="mobile-nav"
aria-controls={MOBILE_NAV_ID}
data-open={state.menuOpen || undefined}
// Op desktop opent deze knop straks het info-menu (side area)
display={{ base: 'block', lg: 'none' }}
@@ -253,7 +261,7 @@ export default function NavigationBar() {
</Container>
</chakra.header>
<MobileNav
id="mobile-nav"
id={MOBILE_NAV_ID}
open={state.menuOpen}
groupOpen={state.groupOpen}
pathname={pathname}
@@ -0,0 +1,91 @@
import { describe, expect, it } from 'vitest';
import { hydratePage, renderToString, serverHtml } from '@/test/hydrate';
import NavigationBar from './NavigationBar';
import { NoScriptMenuClose, NoScriptMenuOpen } from './NoScriptNav';
// The noscript wrappers are dropped first: this document runs scripts, so the
// parser would keep their content as text
function parse(markup: string) {
const container = document.createElement('div');
container.innerHTML = markup.replaceAll(/<\/?noscript>/g, '');
return container;
}
const FOLLOWING = Node.DOCUMENT_POSITION_FOLLOWING;
describe('NoScriptMenuOpen', () => {
it('renders one link to the panel inside a noscript', () => {
const markup = renderToString(<NoScriptMenuOpen />);
expect(markup.startsWith('<noscript>')).toBe(true);
expect(markup.endsWith('</noscript>')).toBe(true);
const links = parse(markup).querySelectorAll('a');
expect(links).toHaveLength(1);
expect(links[0]).toHaveAttribute('href', '#mobile-nav');
expect(links[0]).toHaveAttribute('aria-label', 'Menu openen');
expect(links[0]).toHaveAttribute('class', 'ns-menu-open');
expect(links[0]).toHaveAttribute('data-testid', 'nav-noscript-open');
expect(
links[0].querySelectorAll('span[aria-hidden="true"]'),
).toHaveLength(3);
});
it('has no style element inside the noscript', () => {
expect(renderToString(<NoScriptMenuOpen />)).not.toContain('<style');
});
});
describe('NoScriptMenuClose', () => {
it('renders one link to the header inside a noscript', () => {
const markup = renderToString(<NoScriptMenuClose />);
expect(markup.startsWith('<noscript>')).toBe(true);
const links = parse(markup).querySelectorAll('a');
expect(links).toHaveLength(1);
expect(links[0]).toHaveAttribute('href', '#site-header');
expect(links[0]).toHaveAttribute('class', 'ns-menu-close');
expect(links[0]).toHaveAttribute('data-testid', 'nav-noscript-close');
expect(links[0]).toHaveTextContent('Menu sluiten');
});
it('has no style element inside the noscript', () => {
expect(renderToString(<NoScriptMenuClose />)).not.toContain('<style');
});
});
describe('NavigationBar server markup', () => {
it('puts the open link before the hamburger and the close link first in the panel', async () => {
const navigation = parse(await serverHtml(<NavigationBar />));
const open = navigation.querySelector('.ns-menu-open')!;
const hamburger = navigation.querySelector(
'[data-testid="nav-menu-toggle"]',
)!;
expect(
open.compareDocumentPosition(hamburger) & FOLLOWING,
).toBeTruthy();
const panel = navigation.querySelector('#mobile-nav')!;
const close = panel.querySelector('.ns-menu-close')!;
const list = panel.querySelector('nav')!;
expect(list.contains(close)).toBe(false);
expect(close.compareDocumentPosition(list) & FOLLOWING).toBeTruthy();
});
it('makes the light logo lazy except on the home page (BR-PRE-05)', async () => {
const logos = async (path: string) =>
parse(await serverHtml(<NavigationBar />, path)).querySelectorAll(
'header img',
);
const inner = await logos('/over-mij');
expect(inner[1]).toHaveAttribute('loading', 'lazy');
expect(inner[0]).not.toHaveAttribute('loading');
const home = await logos('/');
expect(home[1]).not.toHaveAttribute('loading');
expect(home[0]).not.toHaveAttribute('loading');
});
it('hydrates without a mismatch with the noscript links in place', async () => {
const { errors, container } = await hydratePage(<NavigationBar />);
expect(errors).toEqual([]);
expect(
container.querySelector('[data-testid="nav-menu-toggle"]'),
).not.toBeNull();
});
});
@@ -0,0 +1,35 @@
import { HEADER_ID, MOBILE_NAV_ID } from '../NoScript/noScriptCss';
// Menu links for a visitor without JavaScript. Plain elements: a browser with
// scripting on ignores the noscript content, and the CSS in the head
// (noScriptCss.ts) styles them.
export function NoScriptMenuOpen() {
return (
<noscript>
<a
className="ns-menu-open"
href={`#${MOBILE_NAV_ID}`}
aria-label="Menu openen"
data-testid="nav-noscript-open"
>
<span aria-hidden="true" />
<span aria-hidden="true" />
<span aria-hidden="true" />
</a>
</noscript>
);
}
export function NoScriptMenuClose() {
return (
<noscript>
<a
className="ns-menu-close"
href={`#${HEADER_ID}`}
data-testid="nav-noscript-close"
>
Menu sluiten
</a>
</noscript>
);
}
@@ -0,0 +1,112 @@
import { describe, expect, it } from 'vitest';
import siteContent from '@/content/siteContent';
import { emailAddress } from '@/lib/emailAddress';
import { serverHtml } from '@/test/hydrate';
import NavigationBar from '../NavigationBar/NavigationBar';
import { HEADER_ID, MOBILE_NAV_ID, NO_SCRIPT_CSS } from './noScriptCss';
// The navigation as the prerender writes it, without the noscript wrappers:
// this document runs scripts, so the parser would keep their content as text
async function navigationDocument(path = '/') {
const container = document.createElement('div');
container.innerHTML = (
await serverHtml(<NavigationBar />, path)
).replaceAll(/<\/?noscript>/g, '');
return container;
}
describe('NO_SCRIPT_CSS', () => {
it('cannot end the noscript early or fetch anything (BR-NAV-02)', () => {
expect(NO_SCRIPT_CSS).not.toContain('</');
expect(NO_SCRIPT_CSS).not.toContain('url(');
expect(NO_SCRIPT_CSS).not.toContain('@import');
});
it('has balanced braces and no empty rule', () => {
const opening = NO_SCRIPT_CSS.match(/\{/g)?.length ?? 0;
const closing = NO_SCRIPT_CSS.match(/\}/g)?.length ?? 0;
expect(opening).toBeGreaterThan(0);
expect(opening).toBe(closing);
expect(NO_SCRIPT_CSS).not.toContain('{}');
});
it('holds no e-mail address', () => {
expect(NO_SCRIPT_CSS).not.toContain(emailAddress(siteContent.email)!);
});
it.each([
['wrapper', 'noscript{display:contents}'],
[
'empty photo',
'img[data-deferred]:not([src]){display:none!important}',
],
[
'hidden controls',
'[data-requires-js],[data-email-pending]{display:none!important}',
],
['open link', '.ns-menu-open{'],
[
'open link hidden from lg',
'@media (min-width:64rem){.ns-menu-open{display:none}}',
],
['close link', '.ns-menu-close{'],
[
'focus ring',
'.ns-menu-open:focus-visible,.ns-menu-close:focus-visible{outline:',
],
[
'panel open',
'#mobile-nav:target{clip-path:inset(0);visibility:visible}',
],
[
'group expanded',
'#mobile-nav [id^="mobile-group-"]{grid-template-rows:1fr;visibility:visible;transition:none}',
],
[
'desktop submenu',
'[data-submenu]:focus-within>[data-submenu-panel]{visibility:visible;opacity:1;transform:none;pointer-events:auto;transition:none}',
],
])('has the %s rule', (_group, rule) => {
expect(NO_SCRIPT_CSS).toContain(rule);
});
it('does not set display on the panel, so it stays hidden from lg', () => {
const panelRule = NO_SCRIPT_CSS.match(
/#mobile-nav:target\{[^}]*\}/,
)![0];
expect(panelRule).not.toContain('display');
});
});
describe('what the CSS names exists in the navigation', () => {
it('uses the ids the components render', async () => {
expect(MOBILE_NAV_ID).toBe('mobile-nav');
expect(HEADER_ID).toBe('site-header');
const navigation = await navigationDocument();
expect(navigation.querySelector(`header#${HEADER_ID}`)).not.toBeNull();
expect(navigation.querySelector(`#${MOBILE_NAV_ID}`)).not.toBeNull();
expect(
navigation.querySelector('[id^="mobile-group-"]'),
).not.toBeNull();
});
it('marks the buttons that do nothing without JavaScript', async () => {
const navigation = await navigationDocument();
const marked = [...navigation.querySelectorAll('[data-requires-js]')];
// Hamburger, desktop chevron, mobile chevron
expect(marked).toHaveLength(3);
expect(marked.every((element) => element.tagName === 'BUTTON')).toBe(
true,
);
expect(
navigation.querySelector('[data-testid="nav-menu-toggle"]'),
).toHaveAttribute('data-requires-js');
});
it('marks the desktop submenu wrapper and its panel', async () => {
const navigation = await navigationDocument();
const wrapper = navigation.querySelector('[data-submenu]')!;
const panel = wrapper.querySelector('[data-submenu-panel]')!;
expect(panel).toHaveAttribute('id', 'submenu-soorten-fotoshoots');
});
});
+54 -5
View File
@@ -2,9 +2,58 @@
// <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}',
// Ids the menu links point at; the components render the same constants
export const MOBILE_NAV_ID = 'mobile-nav';
export const HEADER_ID = 'site-header';
// The wrapper takes no part in flex, grid or positioning of its twin
const WRAPPER = 'noscript{display:contents}';
// The empty deferred photo would draw as a broken-image box
const EMPTY_PHOTO = 'img[data-deferred]:not([src]){display:none!important}';
// Controls that do nothing without JavaScript. !important: the style props of
// these elements set display, and Emotion's rules come later in the document.
const HIDDEN_CONTROLS =
'[data-requires-js],[data-email-pending]{display:none!important}';
// The open link takes the place of the hamburger: same 44px box, same bars
const OPEN_LINK = [
'.ns-menu-open{display:block;position:relative;width:44px;height:44px;color:inherit}',
'.ns-menu-open>span{position:absolute;left:10px;width:24px;height:2px;border-radius:1px;background:currentColor}',
'.ns-menu-open>span:nth-of-type(1){top:15px}',
'.ns-menu-open>span:nth-of-type(2){top:21px}',
'.ns-menu-open>span:nth-of-type(3){top:27px}',
'@media (min-width:64rem){.ns-menu-open{display:none}}',
].join('');
const CLOSE_LINK =
'.ns-menu-close{display:inline-block;min-height:44px;padding:0.5rem 0;color:inherit;font:inherit}';
const FOCUS_RING =
'.ns-menu-open:focus-visible,.ns-menu-close:focus-visible{outline:2px solid currentColor;outline-offset:2px}';
// Id selectors outweigh Emotion's single-class rules. No display: the panel
// stays hidden from lg up, even when the address ends in the fragment.
const PANEL_OPEN = `#${MOBILE_NAV_ID}:target{clip-path:inset(0);visibility:visible}`;
// The shoot group is always expanded
const GROUP_EXPANDED = `#${MOBILE_NAV_ID} [id^="mobile-group-"]{grid-template-rows:1fr;visibility:visible;transition:none}`;
// The desktop submenu opens on keyboard focus. transition none: a Tab pressed
// while the visibility transition starts would skip the panel.
const SUBMENU_FOCUS =
'[data-submenu]:focus-within>[data-submenu-panel]{visibility:visible;opacity:1;transform:none;pointer-events:auto;transition:none}';
export const NO_SCRIPT_CSS = [
WRAPPER,
EMPTY_PHOTO,
HIDDEN_CONTROLS,
OPEN_LINK,
CLOSE_LINK,
FOCUS_RING,
PANEL_OPEN,
GROUP_EXPANDED,
SUBMENU_FOCUS,
].join('');
@@ -1,9 +1,12 @@
import { fireEvent, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { GRID_COLUMNS } from '@/lib/firstRow';
import { masonryRowSpan } from '@/lib/masonryRowSpan';
import { axeResults } from '@/test/axe';
import { cssRulesFor } from '@/test/cssRules';
import { galleryItems } from '@/test/galleryFixtures';
import { hydratePage, serverHtml } from '@/test/hydrate';
import { renderWithProviders } from '@/test/renderWithProviders';
import PortfolioGrid from './PortfolioGrid';
@@ -31,13 +34,9 @@ describe('PortfolioGrid', () => {
expect(await axeResults(container)).toHaveNoViolations();
});
it('loads the first photos straight away and defers the rest', async () => {
it('loads the first row straight away and defers the rest', async () => {
await renderWithProviders(
<PortfolioGrid
items={galleryItems}
eagerFirstRow
onOpen={() => {}}
/>,
<PortfolioGrid items={galleryItems} onOpen={() => {}} />,
);
const images = screen.getAllByRole('img');
images.forEach((image, index) => {
@@ -56,6 +55,28 @@ describe('PortfolioGrid', () => {
String(galleryItems[index].thumb.width),
);
});
// Only tile 1 is plain; tiles 2 and 3 have a source of their own
expect(images[0].closest('picture')).toBeNull();
expect(images[1].closest('picture')).not.toBeNull();
expect(images[2].closest('picture')).not.toBeNull();
expect(images[3].closest('picture')).toBeNull();
});
it('defers every photo when the first row is not eager', async () => {
await renderWithProviders(
<PortfolioGrid
items={galleryItems}
eagerFirstRow={false}
onOpen={() => {}}
/>,
);
const images = screen.getAllByRole('img');
expect(images).toHaveLength(galleryItems.length);
for (const image of images) {
expect(image).not.toHaveAttribute('fetchpriority');
expect(image).toHaveAttribute('loading', 'lazy');
expect(image.closest('picture')).toBeNull();
}
});
it('asks to open the lightbox on a plain click or Enter', async () => {
@@ -107,3 +128,112 @@ describe('PortfolioGrid', () => {
expect(screen.getByTestId('portfolio-grid')).toBeEmptyDOMElement();
});
});
describe('PortfolioGrid in the prerendered HTML', () => {
const tileOf = (page: HTMLElement, number: number) =>
page.querySelector(`[data-testid="portfolio-tile-${number}"]`)!;
const prerendered = async (eagerFirstRow?: boolean) => {
const page = document.createElement('div');
page.innerHTML = await serverHtml(
<PortfolioGrid
items={galleryItems}
eagerFirstRow={eagerFirstRow}
onOpen={() => {}}
/>,
);
return page;
};
it('gives tile 1 a plain photo with its src, whatever the screen width', async () => {
const image = tileOf(await prerendered(), 1).querySelector('img')!;
expect(image.closest('picture')).toBeNull();
expect(image).toHaveAttribute('src', galleryItems[0].thumb.src);
expect(image).toHaveAttribute('fetchpriority', 'high');
expect(image).not.toHaveAttribute('data-deferred');
});
it('puts tiles 2 and 3 in a picture whose source starts at the width of their column (BR-PRE-10)', async () => {
const page = await prerendered();
[1, 2].forEach((index) => {
const tile = tileOf(page, index + 1);
const source = tile.querySelector('picture > source')!;
expect(source).toHaveAttribute('media', GRID_COLUMNS[index].media);
expect(source).toHaveAttribute(
'srcset',
galleryItems[index].thumb.src,
);
const image = tile.querySelector('picture > img')!;
expect(image).toHaveAttribute('data-deferred');
expect(image).not.toHaveAttribute('src');
expect(image).toHaveAttribute('loading', 'eager');
expect(image).toHaveAttribute('fetchpriority', 'high');
});
});
it('leaves tile 4 and up deferred, without a src', async () => {
const page = await prerendered();
expect(galleryItems.length).toBeGreaterThan(3);
for (let number = 4; number <= galleryItems.length; number++) {
const tile = tileOf(page, number);
const image = tile.querySelector('img')!;
expect(tile.querySelector('picture')).toBeNull();
expect(image).toHaveAttribute('data-deferred');
expect(image).not.toHaveAttribute('src');
expect(image).toHaveAttribute('loading', 'lazy');
}
});
it('defers every tile when the first row is not eager', async () => {
const page = await prerendered(false);
for (let number = 1; number <= galleryItems.length; number++) {
const tile = tileOf(page, number);
const image = tile.querySelector('img')!;
expect(tile.querySelector('picture, source')).toBeNull();
expect(image).toHaveAttribute('data-deferred');
expect(image).not.toHaveAttribute('src');
}
});
it('hydrates without a mismatch, with the first row and without it', async () => {
const eager = await hydratePage(
<PortfolioGrid items={galleryItems} onOpen={() => {}} />,
);
expect(eager.errors).toEqual([]);
eager.unmount();
const deferred = await hydratePage(
<PortfolioGrid
items={galleryItems}
eagerFirstRow={false}
onOpen={() => {}}
/>,
);
expect(deferred.errors).toEqual([]);
});
});
describe('PortfolioGrid columns', () => {
it('lays out as many columns per width as GRID_COLUMNS names, the ones the first row follows', async () => {
await renderWithProviders(
<PortfolioGrid items={galleryItems} onOpen={() => {}} />,
);
const rules = cssRulesFor(screen.getByTestId('portfolio-grid'));
const [base, ...wider] = GRID_COLUMNS;
const unqueried = rules.filter((rule) => !rule.startsWith('@media'));
expect(unqueried.join()).toContain('grid-template-columns: 1fr');
expect(unqueried.join()).toContain(`--cols: ${base.columns}`);
for (const { media, columns } of wider) {
// Chakra writes its breakpoints in rem, the first row in em; both
// are relative to the browser's font size
const query = media.replace('em)', 'rem)');
const inQuery = rules
.filter((rule) => rule.startsWith(`@media screen and ${query}`))
.join();
expect(inQuery).toContain(
`grid-template-columns: repeat(${columns}, 1fr)`,
);
expect(inQuery).toContain(`--cols: ${columns}`);
}
});
});
@@ -9,13 +9,20 @@ import {
import DeferredImage from '@/components/DeferredImage/DeferredImage';
import Reveal from '@/components/Reveal/Reveal';
import type { GalleryItem } from '@/content/types';
import { firstRow } from '@/lib/firstRow';
import { firstRow, GRID_COLUMNS } from '@/lib/firstRow';
import {
GAP_ROWS,
masonryRowSpan,
ROWS_PER_COLUMN_WIDTH,
} from '@/lib/masonryRowSpan';
const [BASE_COLUMNS, MD_COLUMNS, LG_COLUMNS] = GRID_COLUMNS.map(
(entry) => entry.columns,
);
const columnTemplate = (columns: number) =>
columns === 1 ? '1fr' : `repeat(${columns}, 1fr)`;
type PortfolioGridProps = {
items: readonly GalleryItem[];
// The photos of the first row (one column per screen width, see firstRow)
@@ -109,17 +116,17 @@ export default function PortfolioGrid({
listStyleType="none"
display="grid"
gridTemplateColumns={{
base: '1fr',
md: 'repeat(2, 1fr)',
lg: 'repeat(3, 1fr)',
base: columnTemplate(BASE_COLUMNS),
md: columnTemplate(MD_COLUMNS),
lg: columnTemplate(LG_COLUMNS),
}}
columnGap="gridGap"
// One implicit row = column width / ROWS_PER_COLUMN_WIDTH
gridAutoRows="var(--row)"
css={{
'--cols': '1',
md: { '--cols': '2' },
lg: { '--cols': '3' },
'--cols': String(BASE_COLUMNS),
md: { '--cols': String(MD_COLUMNS) },
lg: { '--cols': String(LG_COLUMNS) },
'--row': `calc((100cqi - (var(--cols) - 1) * {spacing.gridGap}) / var(--cols) / ${ROWS_PER_COLUMN_WIDTH})`,
}}
>
+69 -2
View File
@@ -1,8 +1,29 @@
import { screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { act, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cssRulesFor } from '@/test/cssRules';
import { FakeIntersectionObserver } from '@/test/fakeIntersectionObserver';
import { renderWithProviders } from '@/test/renderWithProviders';
import Reveal from './Reveal';
afterEach(() => {
vi.unstubAllGlobals();
FakeIntersectionObserver.reset();
});
// The rules of the element outside media queries, as one text
const baseRules = (element: Element) =>
cssRulesFor(element)
.filter((rule) => !rule.startsWith('@media'))
.join(' ');
// jsdom has no layout: put the element below the bottom edge of the viewport
function startBelowFold() {
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({
top: innerHeight,
} as DOMRect);
}
describe('Reveal', () => {
it('renders its content visibly when IntersectionObserver is missing', async () => {
await renderWithProviders(
@@ -25,4 +46,50 @@ describe('Reveal', () => {
);
expect(screen.getByTestId('reveal').tagName).toBe('FIGURE');
});
it('stays visible, without a transition, when it is in view at load', async () => {
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
await renderWithProviders(
<Reveal delay={0.4} data-testid="reveal">
<p>Inhoud</p>
</Reveal>,
);
const reveal = screen.getByTestId('reveal');
expect(reveal).toHaveAttribute('data-reveal', 'visible');
expect(reveal).toHaveStyle({ opacity: '1' });
expect(baseRules(reveal)).toContain('transition: none');
});
it('is hidden without a transition when it starts below the fold', async () => {
startBelowFold();
await renderWithProviders(
<Reveal delay={0.4} data-testid="reveal">
<p>Inhoud</p>
</Reveal>,
);
const reveal = screen.getByTestId('reveal');
expect(reveal).toHaveAttribute('data-reveal', 'hidden');
expect(reveal).toHaveStyle({
opacity: '0',
transform: 'translateY(24px)',
});
expect(baseRules(reveal)).toContain('transition: none');
});
it('fades in with its delay once it scrolls into view', async () => {
startBelowFold();
await renderWithProviders(
<Reveal delay={0.4} data-testid="reveal">
<p>Inhoud</p>
</Reveal>,
);
act(() => FakeIntersectionObserver.instances[0].trigger(true));
const reveal = screen.getByTestId('reveal');
expect(reveal).toHaveAttribute('data-reveal', 'visible');
expect(reveal).toHaveStyle({ opacity: '1', transform: 'none' });
const rules = baseRules(reveal);
expect(rules).toContain('transition-property: opacity,transform');
expect(rules).toContain('transition-delay: 0.4s');
expect(rules).not.toContain('transition: none');
});
});
@@ -262,4 +262,20 @@ describe('Testimonials in the prerendered HTML', () => {
expect(html.match(/data-testid="testimonial-/g)).toHaveLength(1);
expect(html).not.toContain('inert');
});
it('marks the controls spacer and keeps the other copies hidden in the prerendered HTML', async () => {
const html = await serverHtml(
<Testimonials content={content} testimonials={testimonials} />,
);
const doc = new DOMParser().parseFromString(html, 'text/html');
const marked = doc.querySelectorAll('[data-requires-js]');
expect(marked).toHaveLength(1);
expect(marked[0].textContent).toBe('');
const copies = [...doc.querySelectorAll('[aria-hidden="true"]')].filter(
(element) => element.querySelector('blockquote'),
);
expect(copies.length).toBeGreaterThan(0);
for (const copy of copies)
expect(copy.hasAttribute('inert')).toBe(true);
});
});
@@ -98,7 +98,7 @@ function CarouselPlaceholder({
</VisuallyHidden>
))}
{/* The control bar: 48px buttons below the same margin */}
<Box mt="clamp(2.5rem, 5vw, 4rem)" h="48px" />
<Box mt="clamp(2.5rem, 5vw, 4rem)" h="48px" data-requires-js />
</Box>
);
}
@@ -64,11 +64,20 @@ describe('PortfolioGallery', () => {
screen.getByRole('button', { name: 'Alles', pressed: true }),
).toBeInTheDocument();
expect(tiles()).toHaveLength(10);
// Every photo waits until the page has loaded (none eager)
for (const image of screen.getAllByRole('img')) {
expect(image).not.toHaveAttribute('fetchpriority');
expect(image).toHaveAttribute('loading', 'lazy');
}
// The first row loads straight away, every later photo waits until
// the page has loaded
screen.getAllByRole('img').forEach((image, index) => {
if (index === 0) {
expect(image).toHaveAttribute('fetchpriority', 'high');
expect(image).not.toHaveAttribute('loading');
} else if (index < 3) {
expect(image).toHaveAttribute('fetchpriority', 'high');
expect(image).toHaveAttribute('loading', 'eager');
} else {
expect(image).not.toHaveAttribute('fetchpriority');
expect(image).toHaveAttribute('loading', 'lazy');
}
});
expect(await axeResults(container)).toHaveNoViolations();
});
+157 -3
View File
@@ -1,10 +1,12 @@
import { StrictMode } from 'react';
import { act } from '@testing-library/react';
import { act, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ChakraProvider } from '@chakra-ui/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import portfolioContent from '@/content/portfolioContent';
import Reveal from '@/components/Reveal/Reveal';
import { FakeIntersectionObserver as FakeObserver } from '@/test/fakeIntersectionObserver';
import { hydrate } from '@/test/hydrate';
import { hydrate, hydrateAppAsStart } from '@/test/hydrate';
import system from './theme';
afterEach(() => {
@@ -51,3 +53,155 @@ describe('Reveal while hydrating (BR-RVL-01, 02)', () => {
expect(inView).toHaveAttribute('data-reveal', 'visible');
});
});
// The pages the way Start hands them over: Router's own hydrate() runs first
// (BR-HYD-01). IntersectionObserver is a fake, so Reveal can hide what is
// below the fold.
describe('pages hydrate with the display fallbacks in place', () => {
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
Element.prototype.scrollTo = () => {};
});
afterEach(() => {
// @ts-expect-error -- jsdom has no Element.scrollTo of its own
delete Element.prototype.scrollTo;
});
it.each([
'/',
'/over-mij',
'/portfolio',
'/contact',
'/soorten-fotoshoots/loveshoot',
])('hydrates %s without a recoverable error', async (path) => {
const { errors } = await hydrateAppAsStart(path, path);
expect(
await screen.findByRole('heading', { level: 1 }),
).toBeInTheDocument();
if (path === '/contact') {
await screen.findByTestId('contact-form', undefined, {
timeout: 10_000,
});
}
expect(errors).toEqual([]);
});
it('hydrates the first-row picture tiles of /portfolio, which keep their source', async () => {
const { container, errors } = await hydrateAppAsStart(
'/portfolio',
'/portfolio',
);
expect(
await screen.findByRole('button', { name: 'Alles', pressed: true }),
).toBeInTheDocument();
const media = (number: number) =>
container
.querySelector(
`[data-testid="portfolio-tile-${number}"] picture > source`,
)
?.getAttribute('media');
expect(media(1)).toBeUndefined();
expect(media(2)).toBe('(min-width: 48em)');
expect(media(3)).toBe('(min-width: 64em)');
expect(
container.querySelector('[data-testid="portfolio-tile-4"] picture'),
).toBeNull();
expect(errors).toEqual([]);
});
it('applies ?shoot=gezin after hydrating, with a first row of its own', async () => {
const { container, errors } = await hydrateAppAsStart(
'/portfolio',
'/portfolio?shoot=gezin',
);
await waitFor(() =>
expect(
within(screen.getByTestId('portfolio-grid')).getAllByRole(
'link',
),
).toHaveLength(2),
);
const first = container.querySelector(
'[data-testid="portfolio-tile-1"] img',
)!;
expect(first.closest('picture')).toBeNull();
expect(first).toHaveAttribute('fetchpriority', 'high');
expect(first).not.toHaveAttribute('data-deferred');
expect(
container
.querySelector(
'[data-testid="portfolio-tile-2"] picture > source',
)
?.getAttribute('media'),
).toBe('(min-width: 48em)');
expect(errors).toEqual([]);
});
it('remounts the photos of the filtered list as its first row', async () => {
const { container, errors } = await hydrateAppAsStart(
'/portfolio',
'/portfolio',
);
const user = userEvent.setup();
await screen.findByRole('button', { name: 'Alles', pressed: true });
const gezinHref = portfolioContent.photos.find(
(photo) => photo.shootType === 'gezin',
)!.full.src;
const imageOf = (href: string) =>
container.querySelector(`a[href="${href}"] img`)!;
const before = imageOf(gezinHref);
expect(before).toHaveAttribute('data-deferred');
await user.click(screen.getByRole('button', { name: 'Gezin' }));
await waitFor(() =>
expect(
within(screen.getByTestId('portfolio-grid')).getAllByRole(
'link',
),
).toHaveLength(2),
);
const after = imageOf(gezinHref);
expect(after).not.toBe(before);
expect(after).toHaveAttribute('src');
expect(errors).toEqual([]);
});
it('keeps the Reveals that are in view visible through hydration', async () => {
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(
function (this: Element) {
if (!this.hasAttribute('data-reveal')) {
return { top: 0 } as DOMRect;
}
const [inView] = document.querySelectorAll('[data-reveal]');
return {
top: this === inView ? 0 : innerHeight + 100,
} as DOMRect;
},
);
const changes = new MutationObserver(() => {});
changes.observe(document.body, {
subtree: true,
attributes: true,
attributeFilter: ['data-reveal'],
attributeOldValue: true,
});
const { container, errors } = await hydrateAppAsStart(
'/over-mij',
'/over-mij',
);
await screen.findByRole('heading', { level: 1 });
const reveals = [...container.querySelectorAll('[data-reveal]')];
const [inView, ...below] = reveals;
expect(below.length).toBeGreaterThan(0);
expect(inView).toHaveAttribute('data-reveal', 'visible');
expect(
changes.takeRecords().filter((record) => record.target === inView),
).toEqual([]);
for (const reveal of below) {
expect(reveal).toHaveAttribute('data-reveal', 'hidden');
}
changes.disconnect();
expect(errors).toEqual([]);
});
});
+76
View File
@@ -0,0 +1,76 @@
// @vitest-environment node
import { ChakraProvider } from '@chakra-ui/react';
import {
createMemoryHistory,
createRouter,
HeadContent,
RouterProvider,
rootRouteId,
} from '@tanstack/react-router';
import type { ReactNode } from 'react';
import { prerender } from 'react-dom/static';
import { describe, expect, it } from 'vitest';
import { routerOptions } from './router';
import sitePages from './sitePages';
import system from './theme';
// What the HTML of every page holds for visitors without JavaScript: all
// content visible, and every empty deferred photo next to a twin that shows
// it (BR-RVL-01, BR-IMG-01). Rendered like src/prerender.test.tsx does.
const TestShell = ({ children }: { children: ReactNode }) => (
<>
<HeadContent />
{children}
</>
);
async function prerenderPath(path: string) {
const router = createRouter({
...routerOptions(),
history: createMemoryHistory({ initialEntries: [path] }),
});
const rootOptions = router.routesById[rootRouteId].options as {
shellComponent?: typeof TestShell;
};
rootOptions.shellComponent = TestShell;
await router.load();
const { prelude } = await prerender(
<ChakraProvider value={system}>
<RouterProvider router={router} />
</ChakraProvider>,
);
return new Response(prelude).text();
}
const count = (html: string, pattern: RegExp) =>
html.match(pattern)?.length ?? 0;
describe('prerendered display fallbacks', () => {
it.each([...Object.keys(sitePages), '/onbekend'])(
'shows %s with one noscript twin per deferred photo and nothing hidden',
async (path) => {
const html = await prerenderPath(path);
const deferred = count(html, /<img\b[^>]*\bdata-deferred\b[^>]*>/g);
const twins = count(html, /<noscript><img\b[^>]*\bsrc="[^"]+"/g);
expect(twins).toBe(deferred);
expect(html).not.toContain('data-reveal="hidden"');
},
30_000,
);
it.each(['/', '/portfolio', '/over-mij'])(
'writes the content of %s as visible Reveals',
async (path) => {
const html = await prerenderPath(path);
expect(count(html, /data-reveal="visible"/g)).toBeGreaterThan(0);
},
30_000,
);
it('has deferred photos on the pages that show many', async () => {
const html = await prerenderPath('/portfolio');
expect(
count(html, /<img\b[^>]*\bdata-deferred\b[^>]*>/g),
).toBeGreaterThan(3);
});
});
+95 -16
View File
@@ -1,3 +1,4 @@
import { StrictMode } from 'react';
import { act, render, screen } from '@testing-library/react';
import { ChakraProvider } from '@chakra-ui/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -7,9 +8,13 @@ import system from '../theme';
import useReveal from './useReveal';
function Probe() {
const { ref, visible } = useReveal<HTMLDivElement>();
const { ref, visible, animated } = useReveal<HTMLDivElement>();
return (
<div ref={ref} data-testid="probe">
<div
ref={ref}
data-testid="probe"
data-animated={animated ? 'yes' : 'no'}
>
{visible ? 'visible' : 'hidden'}
</div>
);
@@ -37,6 +42,15 @@ const mockReducedMotion = () =>
}) as MediaQueryList,
);
// jsdom has no layout, so every element sits at the top. Place it above or
// below the bottom edge of the viewport.
const placeAt = (top: number) =>
vi
.spyOn(Element.prototype, 'getBoundingClientRect')
.mockReturnValue({ top } as DOMRect);
const placeInView = () => placeAt(innerHeight - 1);
const placeBelowFold = () => placeAt(innerHeight);
afterEach(() => {
vi.unstubAllGlobals();
FakeObserver.reset();
@@ -48,25 +62,50 @@ describe('useReveal', () => {
expect(screen.getByTestId('probe')).toHaveTextContent('visible');
});
it('is visible right away when the visitor prefers reduced motion', () => {
it('stays visible below the fold without IntersectionObserver', () => {
placeBelowFold();
renderProbe();
expect(screen.getByTestId('probe')).toHaveTextContent('visible');
});
it('stays visible and creates no observer when it is in view at load', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
placeInView();
renderProbe();
expect(screen.getByTestId('probe')).toHaveTextContent('visible');
expect(screen.getByTestId('probe')).toHaveAttribute(
'data-animated',
'no',
);
expect(FakeObserver.instances).toHaveLength(0);
});
it('stays visible when it starts above the viewport', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
placeAt(-3000);
renderProbe();
expect(screen.getByTestId('probe')).toHaveTextContent('visible');
expect(FakeObserver.instances).toHaveLength(0);
});
it('is visible and creates no observer when the visitor prefers reduced motion', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
placeBelowFold();
mockReducedMotion();
renderProbe();
expect(screen.getByTestId('probe')).toHaveTextContent('visible');
// The first render still assumes motion is fine (as the prerendered
// HTML does), so an observer may start; it is stopped again at once
expect(
FakeObserver.instances.every((observer) => observer.disconnected),
).toBe(true);
expect(FakeObserver.instances).toHaveLength(0);
});
it('stays hidden until the element scrolls into view, then stops observing', () => {
it('is hidden below the fold until the element scrolls into view, then stops observing', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
placeBelowFold();
renderProbe();
const probe = screen.getByTestId('probe');
const [observer] = FakeObserver.instances;
expect(probe).toHaveTextContent('hidden');
expect(probe).toHaveAttribute('data-animated', 'no');
expect(observer.observed).toEqual([probe]);
expect(observer.options).toEqual({
threshold: 0.12,
@@ -78,16 +117,41 @@ describe('useReveal', () => {
act(() => observer.trigger(true));
expect(probe).toHaveTextContent('visible');
expect(probe).toHaveAttribute('data-animated', 'yes');
expect(observer.disconnected).toBe(true);
expect(FakeObserver.instances).toHaveLength(1);
});
it('disconnects when the element unmounts before it was seen', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
placeBelowFold();
const { unmount } = renderProbe();
expect(FakeObserver.instances[0].disconnected).toBe(false);
unmount();
expect(FakeObserver.instances[0].disconnected).toBe(true);
});
it('gives the same result when StrictMode runs the effects twice', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
placeBelowFold();
render(
<StrictMode>
<ChakraProvider value={system}>
<Probe />
</ChakraProvider>
</StrictMode>,
);
const probe = screen.getByTestId('probe');
expect(probe).toHaveTextContent('hidden');
const live = FakeObserver.instances.filter(
(observer) => !observer.disconnected,
);
expect(live).toHaveLength(1);
act(() => live[0].trigger(true));
expect(probe).toHaveTextContent('visible');
expect(probe).toHaveAttribute('data-animated', 'yes');
});
});
describe('useReveal while hydrating', () => {
@@ -97,22 +161,26 @@ describe('useReveal while hydrating', () => {
</ChakraProvider>
);
it('is hidden in the server render', () => {
it('is visible in the server render', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
expect(renderToString(page)).toContain('hidden');
const markup = renderToString(page);
expect(markup).toContain('>visible<');
expect(markup).not.toContain('hidden');
expect(FakeObserver.instances).toHaveLength(0);
});
it('assumes no reduced motion in the hydrating render, then follows the preference', () => {
it('stays visible through hydration when it is in view, without an observer', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
mockReducedMotion();
const markup = renderToString(page);
const { container, errors } = hydrate(page, markup);
placeInView();
const { container, errors } = hydrate(page);
expect(container).toHaveTextContent('visible');
expect(errors).toEqual([]);
expect(FakeObserver.instances).toHaveLength(0);
});
it('stays hidden after hydrating until the element scrolls into view', () => {
it('hides itself after hydrating below the fold, until the element scrolls into view', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
placeBelowFold();
const { container, errors } = hydrate(page);
expect(container).toHaveTextContent('hidden');
expect(errors).toEqual([]);
@@ -120,4 +188,15 @@ describe('useReveal while hydrating', () => {
act(() => FakeObserver.instances.at(-1)!.trigger(true));
expect(container).toHaveTextContent('visible');
});
it('hydrates what the server rendered when the visitor prefers reduced motion, and hides nothing', () => {
vi.stubGlobal('IntersectionObserver', FakeObserver);
placeBelowFold();
mockReducedMotion();
const markup = renderToString(page);
const { container, errors } = hydrate(page, markup);
expect(container).toHaveTextContent('visible');
expect(errors).toEqual([]);
expect(FakeObserver.instances).toHaveLength(0);
});
});
+160
View File
@@ -0,0 +1,160 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import {
columnMap,
galleryItemsWithThumbs,
tileIndex,
type ColumnMap,
} from '../test/firstRowArbitraries';
import { firstRow, firstRowPreloads, GRID_COLUMNS } from './firstRow';
const widthOf = (media: string | null) =>
media === null ? 0 : Number(/\(min-width: (\d+)em\)/.exec(media)![1]);
const columnsAt = (map: ColumnMap, width: number) =>
map.filter((entry) => widthOf(entry.media) <= width).at(-1)!.columns;
// Whether a tile is in the first row at a screen width, as the CSS shows it
const eagerAt = (map: ColumnMap, index: number, width: number) => {
const row = firstRow(index, map);
return row === 'always' || (row !== null && widthOf(row.media) <= width);
};
const widths = (map: ColumnMap) =>
[...new Set([...map.map((entry) => widthOf(entry.media)), 0, 200])].sort(
(a, b) => a - b,
);
describe('firstRow', () => {
it('knows the columns of the portfolio grid', () => {
expect(GRID_COLUMNS.map((entry) => entry.columns)).toEqual([1, 2, 3]);
expect(GRID_COLUMNS.map((entry) => entry.media)).toEqual([
null,
'(min-width: 48em)',
'(min-width: 64em)',
]);
});
it('puts tile 1 in the first row always, tile 2 from 48em, tile 3 from 64em and the rest never', () => {
expect(firstRow(0)).toBe('always');
expect(firstRow(1)).toEqual({ media: '(min-width: 48em)' });
expect(firstRow(2)).toEqual({ media: '(min-width: 64em)' });
expect(firstRow(3)).toBeNull();
expect(firstRow(11)).toBeNull();
});
it('answers for another column map', () => {
const map = [
{ media: null, columns: 2 },
{ media: '(min-width: 30em)', columns: 4 },
];
expect(firstRow(1, map)).toBe('always');
expect(firstRow(2, map)).toEqual({ media: '(min-width: 30em)' });
expect(firstRow(4, map)).toBeNull();
});
it('is always below the base count, never from the largest count, and else the first breakpoint that fits (invariant)', () => {
fc.assert(
fc.property(columnMap, tileIndex, (map, index) => {
const row = firstRow(index, map);
const largest = map.at(-1)!.columns;
if (index < map[0].columns) {
expect(row).toBe('always');
} else if (index >= largest) {
expect(row).toBeNull();
} else {
const first = map.find((entry) => index < entry.columns)!;
expect(row).toEqual({ media: first.media });
}
}),
);
});
it('keeps a tile in the first row at every wider screen, and fills exactly the columns (metamorphic, monotonic)', () => {
fc.assert(
fc.property(columnMap, (map) => {
const indexes = Array.from(
{ length: map.at(-1)!.columns + 3 },
(_, index) => index,
);
const screens = widths(map);
for (const [position, width] of screens.entries()) {
const eager = indexes.filter((index) =>
eagerAt(map, index, width),
);
expect(eager).toHaveLength(columnsAt(map, width));
for (const wider of screens.slice(position + 1)) {
for (const index of eager) {
expect(eagerAt(map, index, wider)).toBe(true);
}
}
}
}),
);
});
});
describe('firstRowPreloads', () => {
const thumb = (id: string) => ({
src: `/${id}.jpg`,
alt: id,
width: 400,
height: 600,
});
it('binds the preload of tiles 2 and 3 to the query of their source', () => {
const items = ['a', 'b', 'c', 'd', 'e'].map((id) => ({
thumb: thumb(id),
}));
expect(firstRowPreloads(items)).toEqual([
{
rel: 'preload',
as: 'image',
href: '/b.jpg',
fetchPriority: 'high',
media: '(min-width: 48em)',
},
{
rel: 'preload',
as: 'image',
href: '/c.jpg',
fetchPriority: 'high',
media: '(min-width: 64em)',
},
]);
});
it('has fewer links when the list is short, and none for an empty one', () => {
expect(firstRowPreloads([{ thumb: thumb('a') }])).toEqual([]);
expect(
firstRowPreloads([{ thumb: thumb('a') }, { thumb: thumb('b') }]),
).toHaveLength(1);
expect(firstRowPreloads([])).toEqual([]);
});
it('makes one link per tile with a media, none for the other tiles, and no duplicates (metamorphic, monotonic)', () => {
fc.assert(
fc.property(galleryItemsWithThumbs, columnMap, (items, map) => {
const links = firstRowPreloads(items, map);
const expected = items.flatMap((item, index) => {
const row = firstRow(index, map);
return row && row !== 'always'
? [{ href: item.thumb.src, media: row.media }]
: [];
});
expect(
links.map((link) => ({
href: link.href,
media: link.media,
})),
).toEqual(expected);
expect(links.length).toBeLessThanOrEqual(
map.at(-1)!.columns - map[0].columns,
);
expect(new Set(links.map((link) => link.href)).size).toBe(
links.length,
);
}),
);
});
});
+126
View File
@@ -0,0 +1,126 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import {
elementTop,
revealEvent,
revealEvents,
revealPhase,
topNearViewportEdge,
viewportHeight,
} from '../test/revealArbitraries';
import { nextRevealPhase, startsHidden, type RevealPhase } from './revealPhase';
describe('startsHidden', () => {
it('hides an element wholly below the viewport only', () => {
expect(startsHidden(823, 823)).toBe(true);
expect(startsHidden(5000, 823)).toBe(true);
expect(startsHidden(822.5, 823)).toBe(false);
expect(startsHidden(0, 823)).toBe(false);
// Above the viewport (scroll restoration, #anchor jump)
expect(startsHidden(-300, 823)).toBe(false);
});
it('is hidden exactly when the top is at or below the viewport height (invariant)', () => {
fc.assert(
fc.property(elementTop, viewportHeight, (top, height) => {
expect(startsHidden(top, height)).toBe(top >= height);
}),
);
fc.assert(
fc.property(topNearViewportEdge, ({ top, viewportHeight }) => {
expect(startsHidden(top, viewportHeight)).toBe(
top >= viewportHeight,
);
}),
);
});
it('stays hidden further down the page (metamorphic, monotonic)', () => {
fc.assert(
fc.property(
elementTop,
fc.double({ min: 0, max: 50000, noNaN: true }),
viewportHeight,
(top, distance, height) => {
if (startsHidden(top, height)) {
expect(startsHidden(top + distance, height)).toBe(true);
}
},
),
);
});
it('does not change when the page is shifted as a whole (metamorphic, translation)', () => {
fc.assert(
fc.property(
fc.integer({ min: -20000, max: 20000 }),
fc.integer({ min: 1, max: 4000 }),
fc.integer({ min: -5000, max: 5000 }),
(top, height, offset) => {
expect(startsHidden(top + offset, height + offset)).toBe(
startsHidden(top, height),
);
},
),
);
});
});
describe('nextRevealPhase', () => {
it('hides a settled element that is below the viewport and keeps one in view', () => {
expect(nextRevealPhase('settled', 'belowViewport')).toBe('hidden');
expect(nextRevealPhase('settled', 'inView')).toBe('settled');
expect(nextRevealPhase('settled', 'intersected')).toBe('settled');
});
it('reveals a hidden element once it intersects', () => {
expect(nextRevealPhase('hidden', 'intersected')).toBe('revealed');
expect(nextRevealPhase('hidden', 'belowViewport')).toBe('hidden');
expect(nextRevealPhase('hidden', 'inView')).toBe('hidden');
});
it('never leaves revealed', () => {
for (const event of [
'belowViewport',
'inView',
'intersected',
] as const) {
expect(nextRevealPhase('revealed', event)).toBe('revealed');
}
});
it('never goes back, and never reveals an element that was not hidden (invariant, state machine)', () => {
fc.assert(
fc.property(
fc.constantFrom<RevealPhase[]>('settled', 'hidden'),
revealEvents,
(start, events) => {
let phase = start;
let hasBeenHidden = start === 'hidden';
let hasBeenRevealed = false;
for (const event of events) {
phase = nextRevealPhase(phase, event);
if (phase === 'hidden') hasBeenHidden = true;
if (hasBeenRevealed) expect(phase).toBe('revealed');
if (phase === 'revealed') {
hasBeenRevealed = true;
expect(hasBeenHidden).toBe(true);
}
if (start === 'settled' && !hasBeenHidden) {
expect(phase).toBe('settled');
}
}
},
),
);
});
it('gives the same phase when an event is applied twice (idempotent)', () => {
fc.assert(
fc.property(revealPhase, revealEvent, (phase, event) => {
const once = nextRevealPhase(phase, event);
expect(nextRevealPhase(once, event)).toBe(once);
}),
);
});
});
+21 -6
View File
@@ -1,7 +1,9 @@
import { useEffect } from 'react';
import { Box, Grid, Heading, VisuallyHidden } from '@chakra-ui/react';
import { createFileRoute, useNavigate } from '@tanstack/react-router';
import ContactAside from '../components/contact/ContactAside/ContactAside';
import ContactAside, {
ASIDE_MEDIA,
} from '../components/contact/ContactAside/ContactAside';
import ContactDetails from '../components/ContactDetails/ContactDetails';
import ContactPanel from '../components/ContactPanel/ContactPanel';
import PageIntro from '../components/PageIntro/PageIntro';
@@ -12,7 +14,12 @@ import packages from '../content/packages';
import siteContent from '../content/siteContent';
import { withReplyTime } from '../lib/withReplyTime';
import useHydrated from '../hooks/useHydrated';
import { contactPage, pageHead, structuredDataScript } from '../seo';
import {
contactPage,
pageHead,
preloadImage,
structuredDataScript,
} from '../seo';
// ?pakket= from a link elsewhere on the site. Only text is kept; the panel
// checks it against the shown packages (BR-CP-10).
@@ -23,10 +30,18 @@ const FORM_TITLE_ID = 'contact-form-title';
export const Route = createFileRoute('/contact')({
validateSearch: (search: Record<string, unknown>): ContactSearch =>
typeof search.pakket === 'string' ? { pakket: search.pakket } : {},
head: () => ({
...pageHead('/contact'),
scripts: [structuredDataScript(contactPage('/contact'))],
}),
head: () => {
const base = pageHead('/contact');
return {
...base,
// The aside photo sits in a <picture>, which React does not hoist
links: [
...base.links,
preloadImage(contactContent.image, { media: ASIDE_MEDIA }),
],
scripts: [structuredDataScript(contactPage('/contact'))],
};
},
component: Contact,
});
+59
View File
@@ -29,6 +29,7 @@ import {
pageHead,
person,
personId,
preloadImage,
professionalService,
shootPageGraph,
shootService,
@@ -43,6 +44,7 @@ import {
import sitePages from './sitePages';
import {
anySiteContent,
contentImage,
faqItems,
knownRoutePath,
knowsAboutEntries,
@@ -971,3 +973,60 @@ describe('galleryImages', () => {
expect(script).not.toMatch(/@[a-z0-9-]+\.[a-z]/i);
});
});
describe('preloadImage', () => {
const photo = {
src: '/assets/contact-abc.jpg',
alt: 'Een foto',
width: 800,
height: 1200,
};
it('preloads the photo at high priority for every width', () => {
expect(preloadImage(photo)).toEqual({
rel: 'preload',
as: 'image',
href: '/assets/contact-abc.jpg',
fetchPriority: 'high',
});
});
it('binds the preload to a media query when given one', () => {
expect(preloadImage(photo, { media: '(min-width: 64em)' })).toEqual({
rel: 'preload',
as: 'image',
href: '/assets/contact-abc.jpg',
fetchPriority: 'high',
media: '(min-width: 64em)',
});
});
it('leaves out an empty options object and an empty media', () => {
expect(preloadImage(photo, {})).toEqual(preloadImage(photo));
expect(preloadImage(photo, { media: '' })).toEqual(preloadImage(photo));
});
it('points at the image with the fixed link fields, and adds media only when given (invariant)', () => {
fc.assert(
fc.property(
contentImage,
fc.option(fc.stringMatching(/^\(min-width: \d{1,3}em\)$/), {
nil: undefined,
}),
(image, media) => {
const link = preloadImage(image, { media });
expect(link.href).toBe(image.src);
expect(link.rel).toBe('preload');
expect(link.as).toBe('image');
expect(link.fetchPriority).toBe('high');
expect(link.media).toBe(media);
expect(Object.keys(link).sort()).toEqual(
media
? ['as', 'fetchPriority', 'href', 'media', 'rel']
: ['as', 'fetchPriority', 'href', 'rel'],
);
},
),
);
});
});
+41
View File
@@ -0,0 +1,41 @@
import fc from 'fast-check';
import type { ContentImage } from '@/content/types';
import { galleryItems } from './arbitraries';
export type ColumnMap = {
media: string | null;
columns: number;
}[];
// Column counts per screen width as a grid can have them: a base count and up
// to three breakpoints, the counts and the widths both strictly increasing
export const columnMap: fc.Arbitrary<ColumnMap> = fc
.tuple(
fc.integer({ min: 1, max: 3 }),
fc.uniqueArray(fc.integer({ min: 20, max: 120 }), {
minLength: 0,
maxLength: 3,
}),
fc.array(fc.integer({ min: 1, max: 3 }), {
minLength: 3,
maxLength: 3,
}),
)
.map(([base, widths, steps]) => {
const sorted = [...widths].sort((a, b) => a - b);
let columns = base;
return [
{ media: null, columns },
...sorted.map((width, index) => {
columns += steps[index];
return { media: `(min-width: ${width}em)`, columns };
}),
];
});
// The position of a tile in the grid, a little beyond the widest row
export const tileIndex: fc.Arbitrary<number> = fc.integer({ min: 0, max: 12 });
// Unfiltered grid photos, in the shape the preloads are built from
export const galleryItemsWithThumbs: fc.Arbitrary<{ thumb: ContentImage }[]> =
galleryItems.map((items) => items.map(({ thumb }) => ({ thumb })));
+45
View File
@@ -0,0 +1,45 @@
import fc from 'fast-check';
import type { RevealEvent, RevealPhase } from '@/lib/revealPhase';
// Heights of real screens, so the shrunk examples read like phones and desktops
const screenHeights = [568, 640, 667, 740, 823, 844, 900, 940, 1024, 1080];
export const viewportHeight: fc.Arbitrary<number> = fc.oneof(
fc.constantFrom(...screenHeights),
fc.integer({ min: 1, max: 4000 }),
fc.double({ min: 1, max: 4000, noNaN: true }),
);
// The top edge of an element relative to the viewport: above it (negative),
// at its top, anywhere on screen and far below. `display: none` and jsdom
// give zero.
export const elementTop: fc.Arbitrary<number> = fc.oneof(
fc.constant(0),
fc.integer({ min: -20000, max: 20000 }),
fc.double({ min: -20000, max: 20000, noNaN: true }),
fc.integer({ min: 4000, max: 100000 }),
);
// An element top given relative to the viewport height, for the cases where
// the edge itself matters: just above, exactly at and just below it
export const topNearViewportEdge: fc.Arbitrary<{
viewportHeight: number;
top: number;
}> = fc
.tuple(viewportHeight, fc.constantFrom(-1000, -1, -0.5, 0, 0.5, 1, 1000))
.map(([height, offset]) => ({
viewportHeight: height,
top: height + offset,
}));
export const revealPhase: fc.Arbitrary<RevealPhase> = fc.constantFrom<
RevealPhase[]
>('settled', 'hidden', 'revealed');
export const revealEvent: fc.Arbitrary<RevealEvent> = fc.constantFrom<
RevealEvent[]
>('belowViewport', 'inView', 'intersected');
export const revealEvents: fc.Arbitrary<RevealEvent[]> = fc.array(revealEvent, {
maxLength: 20,
});