Makes Reveal, deferred images and the first row work from the HTML
Reveal content is visible in the HTML and only content below the viewport hides after hydration. Deferred photos get a noscript twin, and the first row of the portfolio loads eagerly per column count. Some old tests still expect the former behaviour; they are rewritten next, so this commit's test run is not fully green. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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>
|
||||
|
||||
@@ -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)}
|
||||
/>
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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 })]
|
||||
: [];
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user