Hero uit het CMS met ingebakken terugval #21
@@ -17,4 +17,4 @@
|
||||
| Feature | asf-packages-cms | ✅ Complete (closed 2026-11-16; PR to master after the CMS PR; no production release) | feature/asf-packages-cms (worktree ../AndreaSlopFotografie-packages, based on feature/contact-form-cms) | web/config (offerings, fetchOfferings), web/src/content (packages, snapshot, types), Pricing + PriceBanner + PriceTopBar (two banners, centred card rows), PackagesProvider (live refresh), CI build-test job and nightly test build, docs/ (CMS integration, deploy and CI, go-live checklist) | 2026-11-12 |
|
||||
| Feature | asf-cms-host-injection | ✅ Complete on the ASF side (2026-11-16, delivered with asf-packages-cms; host side by SMC) | feature/asf-packages-cms | web (PackagesProvider, build markers, neutral HTML), preview server stand-in injector, e2e/contract tests; host side in the SlpModularCms repo | 2026-11-15 |
|
||||
| Feature | asf-translation-files | ✅ Complete on the ASF side (2026-11-16, delivered with asf-packages-cms) | feature/asf-packages-cms | web/src/i18n (nl.json, helpers), content modules, components, ESLint rules, baseline tool, docs/translations.md | 2026-11-15 |
|
||||
| Feature | hero-module | 🔵 Inception (requirements questions to Bryan) | (none yet) | Hero as a manageable CMS module (SMC builds the module, ASF consumes it); LCP in the first HTML via host injection or prerender; static hero texts move into it | 2026-11-16 |
|
||||
| Feature | hero-module | ✅ Complete on the ASF side (2026-11-17; branch ready to merge, no production) | feature/hero-module | Hero as a manageable CMS module (SMC builds the module, ASF consumes it); LCP in the first HTML via host injection or prerender; static hero texts move into it | 2026-11-16 |
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# AI-DLC State Tracking
|
||||
|
||||
## Project Information
|
||||
|
||||
- **Feature Name**: Hero as a manageable CMS module (ASF side)
|
||||
- **Feature Slug**: hero-module
|
||||
- **Project Type**: Brownfield (cross-repo: SMC builds the module and the host injection of the hero; this repo consumes it, supplies markers, contract and golden files)
|
||||
- **Start Date**: 2026-11-16
|
||||
- **Current Stage**: COMPLETE on the ASF side (closed 2026-11-17); branch feature/hero-module, to be merged to master by SLS-Main. No production deploy.
|
||||
|
||||
## Language Configuration
|
||||
|
||||
- **Documentation Language**: English
|
||||
- **Conversation Language**: User Language (Dutch)
|
||||
|
||||
## Stage Progress
|
||||
|
||||
- [x] INCEPTION - requirements and contract agreed with SMC (`web/contract/host-injection/hero/README.md`, model B: wide 3:2 and tall 4:5 variants, `<picture>`, preload per orientation)
|
||||
- [x] CONSTRUCTION - Code Generation: markers HERO-HTML and HERO-PRELOAD, `hero` key in `#cms-data`, `useHero` with baked fallback, plain-HTML first photo that survives hydration, slider on top, hero texts in `nl.json`, stand-in host and preview server, e2e tests, docs
|
||||
- [x] CONSTRUCTION - Build and Test: [build-and-test-summary.md](construction/build-and-test/build-and-test-summary.md)
|
||||
- [x] OPERATIONS - part of the joint production checklist ([docs/go-live-checklist.md](../../../docs/go-live-checklist.md), section "Hero"); production follows via the IIS pipeline, later
|
||||
|
||||
## Scope decisions
|
||||
|
||||
- **Planning (from/to dates) and a hero-wide on/off switch are deliberately not built.** The hero is always there; a hero without usable slides leaves the baked hero in place (for ASF the host setting `Hero:TextOnlyRegion` is off). Adding them later is a CMS change plus a `204`, which the site already handles.
|
||||
- The ASF test seed holds the 8 existing hero photos with focus estimates (`web/contract/host-injection/hero/seed.json`); Bryan runs the seed himself (admin password).
|
||||
|
||||
## Assumptions
|
||||
|
||||
[assumptions-and-open-questions.md](assumptions-and-open-questions.md): what Bryan has to check later.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Hero module: assumptions and deferred questions (ASF side)
|
||||
|
||||
Written while Bryan was away; he decides later. Each point: question, assumption, what changes with another answer, where in the code.
|
||||
|
||||
| # | Question | Assumption | If the answer differs | Where |
|
||||
| --- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
|
||||
| 1 | Focus points of the 8 photos | Estimates from the seed (e.g. hero-8 0.50/0.55) | Change x/y in the seed (CMS) and in the baked values | `web/src/content/heroContent.ts`, `web/contract/host-injection/hero/seed.json` |
|
||||
| 2 | Is the baked hero cropped around the focus point too? | Yes: object-position from the estimates, so baked and live look the same | Pass `focus: null` for the baked slides to get plain centre crop | `heroContent.ts` |
|
||||
| 3 | Button target `#anchor` and https: plain link, `/path`: router link | As said | Make all plain links | `web/src/components/Hero/HeroButton.tsx` |
|
||||
| 4 | Single display (one photo) or slideshow with one slide | No arrows, pause or progress bar for one slide | Show controls anyway | `Hero.tsx` (`shown.length > 1`) |
|
||||
| 5 | Title with a new line | `<br>` in the plain HTML, `pre-line` in the slider | One line only | `heroHtml.ts`, `Hero.tsx` |
|
||||
| 6 | Where does the head preload marker come from | Build step adds it to the finished HTML (React cannot write a head comment) | Host adds the head region itself | `web/config/heroPreload.ts` |
|
||||
| 7 | Hero texts (aria, baked title, alts) | In `nl.json`, block `hero` | Other wording: edit the file | `web/src/i18n/nl.json` |
|
||||
| 8 | Without a host block the site asks `/api/v1/hero` (8 s time-out) | Yes, like packages and banners | Remove the call: baked only | `web/src/components/Hero/useHero.ts` |
|
||||
| 9 | Style of the plain hero before hydration | Matches the slider's first frame (checked by screenshot at 1280 and 390 px) | Adjust CSS | `.cms-hero-*` in `web/src/theme.ts` |
|
||||
| 10 | AVIF for slides 2..n only | As agreed with the CMS session | Add AVIF to the first photo and its preload (then two fetches) | `Hero.tsx` (`SlidePicture`) |
|
||||
| 11 | The first photo, title and buttons stay the plain HTML after hydration (never replaced); the slider adds the other photos on top | Yes: replacing the nodes at hydration risks a late LCP. Side effect: the first photo has no slow zoom and is not in a role=group slide | Go back to a full slider render (one component), accepting the DOM replacement | `Hero.tsx` (`HeroFrame`), `useHero.ts` (`regionHero`) |
|
||||
| 12 | Planning (from/to dates) and a hero-wide on/off switch | Deliberately not built: the hero is always there, a hero without usable slides keeps the baked one | Add in the CMS; the site already handles a 204 and an empty hero | CMS (module), `useHero.ts` |
|
||||
| 13 | Content of the ASF test seed | The 8 existing photos with focus estimates (#1), texts like the baked ones | Edit in the CMS admin; update `heroContent.ts` if the baked fallback should match | `web/contract/host-injection/hero/seed.json` |
|
||||
| 14 | Baked hero after a CMS change | The baked hero is only a fallback and is not rebuilt from the CMS any more (no nightly build) | Re-bake by hand in `heroContent.ts` when the real hero changes for good | `heroContent.ts` |
|
||||
|
||||
## What Bryan has to check later
|
||||
|
||||
- Look at the home page on ASF-test after the seed, on phone and desktop: crop around the focus points (#1, #2), the first frame before the slider starts (#9, #11), the title and buttons (#3, #5).
|
||||
- Does the first photo without slow zoom (#11) bother you? Then choose the full slider render and accept the later LCP.
|
||||
- Wording of the hero texts in `nl.json` (#7).
|
||||
- Whether planning and an on/off switch are wanted (#12).
|
||||
- Keep an eye on the LCP of `/` in the Lighthouse run on test (the host measures it after the seed).
|
||||
@@ -0,0 +1,22 @@
|
||||
# Build and Test summary: hero-module (ASF side)
|
||||
|
||||
## What was built
|
||||
|
||||
- `src/lib/hero.ts` (mapping and validation of `/api/v1/hero`), `src/lib/heroHtml.ts` (HTML between the markers and the preload links), golden files shared with SMC in `web/contract/host-injection/hero/`.
|
||||
- `config/heroPreload.ts` adds the HERO-PRELOAD region to the head of the finished HTML; `config/hostInjector.ts`, `normalizeInjected.ts` and `previewServer.ts` know the hero (stand-in host, `/api/v1/hero` answers 204).
|
||||
- `src/components/Hero/`: `useHero` (host block, else `/api/v1/hero`, else baked), `Hero.tsx` (the region div is never replaced; the slider adds slides 2..n, scrim, arrows, pause, progress and announcement after hydration), `HeroButton`, `HeroArrows`, `HeroPauseButton`.
|
||||
- Baked hero in `src/content/heroContent.ts` (8 photos, real sizes, focus estimates); texts in `nl.json` block `hero`.
|
||||
|
||||
## Verification
|
||||
|
||||
- Unit and property tests: 100% thresholds on `src/lib/**`, `src/i18n/**`, `seo.ts`, `sitemap.ts` hold; golden files match for all hero inputs.
|
||||
- e2e (`pnpm e2e`): host injection with the hero (3 tests), no-JS, display HTML (priority image), reveal. The two frame-sampling reveal tests got retries (2 on CI, 1 locally) after a flaky failure in run #110 on a page without a hero.
|
||||
- Lighthouse (local, noisy machine): the LCP element of the home page is the h1 on master and on this branch; master 0.71, branch 0.69-0.70. Keeping the region after hydration (commit 3d7bb2d) removed the late LCP the first design had.
|
||||
- Visual check against the slider at 1280 and 390 px.
|
||||
- Final run before merge: see the audit trail of the closing commit; lint, format, tests, build and e2e were run as CI runs them.
|
||||
|
||||
## Not verified here (needs the CMS or Bryan)
|
||||
|
||||
- The real host output on ASF-test after the seed (SMC verified it byte-equal to the golden files locally).
|
||||
- LCP measurement on ASF-test (SMC, after the seed).
|
||||
- IIS pass-through and a production CMS for ASF: later, separate feature.
|
||||
@@ -32,6 +32,16 @@ Both follow the same rules as the packages: baked into the HTML at build time, r
|
||||
|
||||
**Layout shift:** a banner that was not active at the last build is not in the HTML. When it appears live, the content below it moves down by its height once (for the top bar, the cards move). Behind the CMS host the host injection writes the banner into the HTML, so there is no shift; without the host a rebuild with the banner active removes it. The same holds in reverse when a baked banner is switched off.
|
||||
|
||||
## Hero (CMS module)
|
||||
|
||||
The hero of the homepage comes from the CMS hero module (`GET /api/v1/hero`); the build bakes one in as the fallback (`web/src/content/heroContent.ts`, texts in `nl.json` under `hero.baked`).
|
||||
|
||||
- **Markers.** `index.html` has `<!--CMS:HERO-HTML-->…<!--/CMS:HERO-HTML-->` (first photo as `<picture>`, the `h1` with tagline and title, the buttons) and, in the head, `<!--CMS:HERO-PRELOAD-->…<!--/CMS:HERO-PRELOAD-->` (the preload links). The head markers are added to the finished HTML by `config/heroPreload.ts` (React cannot write a comment into the head), as part of `config/externalizeInlineScripts.ts`. The host rewrites both from live data; the contract is `web/contract/host-injection/hero/` (README, seed, golden files shared with the CMS repo). Code: `src/lib/hero.ts` (mapping), `src/lib/heroHtml.ts` (HTML and preload).
|
||||
- **Data block.** `#cms-data` gets a `hero` key (the answer of `/api/v1/hero`). After hydration `src/components/Hero/useHero.ts` takes it; without a host block the site asks `/api/v1/hero` itself (8 s time-out). A missing block, a 204, an error or an answer without a usable slide keeps the baked hero (fail open).
|
||||
- **Until hydration** the hero is the plain HTML between the markers, styled by the global CSS `.cms-hero-*` in `src/theme.ts`; the slider (arrows, pause, progress) only exists after hydration, so a visitor without JavaScript sees the first photo and no dead controls. Slides after the first also get AVIF `<source>`s; the first and the preload are WebP only.
|
||||
- **Images.** Ratios `wide` (3:2) and `tall` (4:5; portrait screens), chosen by `(orientation: portrait)`; the focus point is `object-position`. Alt texts and the slider's aria texts are in `nl.json` (`hero`); a decorative photo has `alt=""`.
|
||||
- **Stand-in host.** `config/hostInjector.ts` (preview server and e2e) writes the hero regions and the `hero` key like the real host; `e2e/hostInjection.e2e.ts` covers it.
|
||||
|
||||
## Contact form
|
||||
|
||||
`GET /api/v1/contact-messages/token` and `POST /api/v1/contact-messages` through the headless `web/src/cms-client`. The form is behind the switch `contactForm.enabled` in `web/src/content/siteContent.ts` (off means the "Binnenkort" gate and no request to the server). Details and the go-live conditions are in `aidlc-docs/features/contact-form-cms/` and [go-live-checklist.md](go-live-checklist.md). Friendly Captcha is off at go-live.
|
||||
|
||||
@@ -13,6 +13,12 @@ What must be true before the CMS-driven parts of the site go to production. Brya
|
||||
- [ ] `web/src/content/offerings.snapshot.json` holds the real, current packages (production builds use it).
|
||||
- [ ] The production CMS holds the real packages. The test CMS prices must never end up in the production artifact (it is built without `OFFERINGS_URL`).
|
||||
|
||||
## Hero
|
||||
|
||||
- [ ] The hero module is on `master` and the CMS host of the target environment has the hero module and the injection (`HERO-HTML`, `HERO-PRELOAD`, `hero` in the data block).
|
||||
- [ ] ASF-test: the hero is seeded (Bryan runs the seed, admin password) and the home page checked on phone and desktop; the assumption list `aidlc-docs/features/hero-module/assumptions-and-open-questions.md` is read.
|
||||
- [ ] Production: ASF-production is served by the CMS host (the IIS pipeline, later) and holds the real hero. Until then production shows the baked hero in `src/content/heroContent.ts`; check that it is the one you want.
|
||||
|
||||
## Contact form
|
||||
|
||||
- [ ] All conditions in the contact-form production readiness checklist (server module, recipient, sender, retention 1 year / 30 days spam, proxies, CSP `frame-src`, a real mail from the production host).
|
||||
|
||||
@@ -4,12 +4,12 @@ The texts of the site live in language files, not in the components. Dutch is th
|
||||
|
||||
## Where things are
|
||||
|
||||
- `web/src/i18n/nl.json`: all Dutch texts of the site in one file, in blocks per area in the order of the site: `common`, `site`, `home`, `about`, `contact`, `shoots`, `portfolio`, `instagram`, `testimonials`, `seo`, `cmsClient`. The file is the source of the types. A second language is `web/src/i18n/en.json` with the same keys.
|
||||
- `web/src/i18n/nl.json`: all Dutch texts of the site in one file, in blocks per area in the order of the site: `common`, `site`, `hero`, `home`, `about`, `contact`, `shoots`, `portfolio`, `instagram`, `testimonials`, `seo`, `cmsClient`. The file is the source of the types. A second language is `web/src/i18n/en.json` with the same keys.
|
||||
- `web/src/i18n/index.ts`: `t(key, params?)` for a text, `tList(key)` for a list of texts, `tPlural(key, count, params?)` for a text with a singular and a plural form, `locales`, `locale` and `Messages`.
|
||||
- `web/src/i18n/compare.ts`: the checks the tests use (same keys and parameters, nothing empty).
|
||||
- The typed content modules in `web/src/content` keep their structure, images and paths; the words come from the language files.
|
||||
|
||||
Not in the language files: the hero (becomes a CMS module), the privacy statement (separate feature), and everything that comes from the CMS (packages, banners, later the gallery).
|
||||
Not in the language files: the privacy statement (separate feature), and everything that comes from the CMS (packages, banners, later the gallery).
|
||||
|
||||
## Keys
|
||||
|
||||
@@ -42,7 +42,7 @@ Dotted paths: the block (`common`, `home`, ...), then the page or section, then
|
||||
|
||||
The block `cmsClient` holds the texts of the shared `src/cms-client` package, per part of the package: `cmsClient.contact` has the form's field errors, fallback, waiting time (`rateLimited.one/other` with `{minutes}`), too-large, captcha-required, failure (`{address}`) and the sending label. `src/i18n/cmsClientMessages.ts` builds the `ContactMessages` object from it and `ContactForm` passes it to `useContactForm({ messages })`. The package keeps its own Dutch defaults (`messages.nl.ts`) as a fallback and a test checks that both say the same. Parts that come later (offerings) get their own part of the block.
|
||||
|
||||
Not here: the hero, the privacy statement and everything from the CMS.
|
||||
Not here: the privacy statement and everything from the CMS.
|
||||
|
||||
## Importing the language files
|
||||
|
||||
|
||||
@@ -17,3 +17,4 @@ src/cms-client
|
||||
|
||||
# Golden files of the host injection contract: exact text, never reformatted
|
||||
contract/host-injection/*.expected.html
|
||||
contract/host-injection/hero/*.html
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
externalizeInlineScripts,
|
||||
findExecutableInlineScripts,
|
||||
} from './inlineScripts.ts';
|
||||
import { injectHeroPreload } from './heroPreload.ts';
|
||||
import { NOT_FOUND_FILE, pageFile } from './pageFiles.ts';
|
||||
|
||||
export type ViolationCode =
|
||||
@@ -179,7 +180,7 @@ export function planExternalization(
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = scripts.externalize(html);
|
||||
result = scripts.externalize(injectHeroPreload(html));
|
||||
} catch (error) {
|
||||
if (!(error instanceof ScriptError)) throw error;
|
||||
add(file, error.code, detailOf(error));
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { injectHeroPreload } from './heroPreload.ts';
|
||||
|
||||
const page = (body: string, head = '<title>t</title>') =>
|
||||
`<html><head>${head}</head><body>${body}</body></html>`;
|
||||
|
||||
describe('injectHeroPreload', () => {
|
||||
it('writes the preload of the first photo between markers before </head>', () => {
|
||||
const out = injectHeroPreload(
|
||||
page(
|
||||
'<img class="cms-hero-image" src="/assets/hero-8-abc.jpg" width="1" height="1" alt="">',
|
||||
),
|
||||
);
|
||||
expect(out).toContain(
|
||||
'<title>t</title><!--CMS:HERO-PRELOAD--><link rel="preload" as="image" href="/assets/hero-8-abc.jpg" fetchpriority="high"><!--/CMS:HERO-PRELOAD--></head>',
|
||||
);
|
||||
});
|
||||
|
||||
it('finds the image when src comes before class', () => {
|
||||
const out = injectHeroPreload(
|
||||
page('<img src="/a.jpg" alt="" class="cms-hero-image">'),
|
||||
);
|
||||
expect(out).toContain('href="/a.jpg"');
|
||||
});
|
||||
|
||||
it('leaves a page without a hero, without a head and a done page alone', () => {
|
||||
const plain = page('<img src="/a.jpg" alt="">');
|
||||
expect(injectHeroPreload(plain)).toBe(plain);
|
||||
const noHead = '<img class="cms-hero-image" src="/a.jpg">';
|
||||
expect(injectHeroPreload(noHead)).toBe(noHead);
|
||||
const once = injectHeroPreload(
|
||||
page('<img class="cms-hero-image" src="/a.jpg" alt="">'),
|
||||
);
|
||||
expect(injectHeroPreload(once)).toBe(once);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { heroPreloadHtml } from '../src/lib/heroHtml.ts';
|
||||
|
||||
// The preload link of the hero in the head of a prerendered page, between the
|
||||
// markers the CMS host rewrites (<!--CMS:HERO-PRELOAD-->). React cannot write
|
||||
// a comment into the head, so the build step adds it to the finished HTML,
|
||||
// from the baked first photo of the page. Pages without a hero stay as they
|
||||
// are, and so does a page that already has the markers (running twice is fine).
|
||||
|
||||
const MARK = '<!--CMS:HERO-PRELOAD-->';
|
||||
const HERO_IMAGE =
|
||||
/<img\b[^>]*\bclass="cms-hero-image"[^>]*\bsrc="([^"]+)"|<img\b[^>]*\bsrc="([^"]+)"[^>]*\bclass="cms-hero-image"/;
|
||||
|
||||
export function injectHeroPreload(html: string): string {
|
||||
if (html.includes(MARK)) return html;
|
||||
const found = HERO_IMAGE.exec(html);
|
||||
const src = found?.[1] ?? found?.[2];
|
||||
const end = html.indexOf('</head>');
|
||||
if (src === undefined || end === -1) return html;
|
||||
// The src is already escaped in the HTML; the link is built from the same
|
||||
// text, so it is written back unchanged
|
||||
const link = heroPreloadHtml({
|
||||
display: 'single',
|
||||
title: '',
|
||||
buttons: [],
|
||||
slides: [
|
||||
{
|
||||
id: 'baked',
|
||||
alt: '',
|
||||
decorative: false,
|
||||
image: {
|
||||
width: 1,
|
||||
height: 1,
|
||||
focus: null,
|
||||
src: '',
|
||||
variants: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
}).replace('href=""', `href="${src}"`);
|
||||
return (
|
||||
html.slice(0, end) +
|
||||
`${MARK}${link}<!--/CMS:HERO-PRELOAD-->` +
|
||||
html.slice(end)
|
||||
);
|
||||
}
|
||||
@@ -54,6 +54,45 @@ describe('injectCms regions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('injectCms hero', () => {
|
||||
const hero = {
|
||||
title: 'Titel',
|
||||
slides: [
|
||||
{
|
||||
id: 'a',
|
||||
alt: 'Alt',
|
||||
decorative: false,
|
||||
image: { width: 10, height: 8, src: '/m/a.webp' },
|
||||
},
|
||||
],
|
||||
};
|
||||
const regions =
|
||||
'<!--CMS:HERO-PRELOAD-->old<!--/CMS:HERO-PRELOAD--><!--CMS:HERO-HTML-->old<!--/CMS:HERO-HTML-->';
|
||||
|
||||
it('writes the hero and its preload and puts the hero in the data block', () => {
|
||||
const out = run(
|
||||
page(
|
||||
regions +
|
||||
'<!--CMS:DATA--><script type="application/json" id="cms-data">{}</script>',
|
||||
),
|
||||
{ ...live([]), hero },
|
||||
);
|
||||
expect(out).toContain('<h1 class="cms-hero-title">');
|
||||
expect(out).toContain(
|
||||
'<link rel="preload" as="image" href="/m/a.webp"',
|
||||
);
|
||||
expect(out).not.toContain('old');
|
||||
expect(out).toContain('"hero":{"title":"Titel"');
|
||||
});
|
||||
|
||||
it('keeps the baked hero when there is no usable one', () => {
|
||||
for (const data of [live([]), { ...live([]), hero: { title: 'x' } }]) {
|
||||
const out = run(page(regions), data);
|
||||
expect(out).toBe(page(regions));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('injectCms data block', () => {
|
||||
const baked =
|
||||
'<!--CMS:DATA--><script type="application/json" id="cms-data">{"source":"build"}</script>';
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
// matches that code.
|
||||
import { bannerHtml, offeringsHtml } from '../src/lib/cmsHtml.ts';
|
||||
import { scriptJson } from '../src/lib/cmsData.ts';
|
||||
import { mapHero } from '../src/lib/hero.ts';
|
||||
import { heroHtml, heroPreloadHtml } from '../src/lib/heroHtml.ts';
|
||||
import { formatPrice } from '../src/lib/formatPrice.ts';
|
||||
import { mapBanner, mapOfferings, mapTopBanner } from '../src/lib/offerings.ts';
|
||||
|
||||
@@ -16,6 +18,8 @@ export interface LiveData {
|
||||
// The answers as the public API gives them
|
||||
offerings: unknown;
|
||||
banners: { top: unknown; bottom: unknown };
|
||||
// The answer of GET /api/v1/hero; absent or unusable leaves the baked hero
|
||||
hero?: unknown;
|
||||
}
|
||||
|
||||
export interface InjectOptions {
|
||||
@@ -33,7 +37,7 @@ const jsonLd = (value: unknown) =>
|
||||
.replace(/&/g, '\\u0026');
|
||||
|
||||
const REGION =
|
||||
/<!--CMS:(OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->[\s\S]*?<!--\/CMS:\1-->/g;
|
||||
/<!--CMS:(OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML|HERO-HTML|HERO-PRELOAD)-->[\s\S]*?<!--\/CMS:\1-->/g;
|
||||
const DATA_BLOCK =
|
||||
/<!--CMS:DATA-->(?:<script type="application\/json" id="cms-data">[\s\S]*?<\/script>)?/g;
|
||||
const OFFER_JSON_LD =
|
||||
@@ -64,19 +68,23 @@ export function injectCms(html: string, options: InjectOptions): string {
|
||||
const { data } = options;
|
||||
const mapped = mapOfferings(data.offerings);
|
||||
const packages = mapped ? mapped.packages : [];
|
||||
const hero = mapHero(data.hero);
|
||||
const prices: Price = new Map(packages.map((pkg) => [pkg.id, pkg.price]));
|
||||
const regions: Record<string, string> = {
|
||||
'OFFERINGS-HTML': offeringsHtml(packages),
|
||||
'BANNER-TOP-HTML': bannerHtml(mapTopBanner(data.banners.top)),
|
||||
'BANNER-BOTTOM-HTML': bannerHtml(mapBanner(data.banners.bottom)),
|
||||
'HERO-HTML': heroHtml(hero),
|
||||
'HERO-PRELOAD': heroPreloadHtml(hero),
|
||||
};
|
||||
const siteUrl = options.publicBaseUrl ?? options.authoredBaseUrl;
|
||||
|
||||
let out = html
|
||||
.replace(
|
||||
REGION,
|
||||
(_match, name: string) =>
|
||||
`<!--CMS:${name}-->${regions[name]}<!--/CMS:${name}-->`,
|
||||
.replace(REGION, (match, name: string) =>
|
||||
// No usable hero: the baked one stays (fail open)
|
||||
name.startsWith('HERO') && !hero
|
||||
? match
|
||||
: `<!--CMS:${name}-->${regions[name]}<!--/CMS:${name}-->`,
|
||||
)
|
||||
.replace(
|
||||
DATA_BLOCK,
|
||||
@@ -86,6 +94,7 @@ export function injectCms(html: string, options: InjectOptions): string {
|
||||
...(siteUrl ? { siteUrl } : {}),
|
||||
offerings: data.offerings,
|
||||
banners: data.banners,
|
||||
...(data.hero === undefined ? {} : { hero: data.hero }),
|
||||
})}</script>`,
|
||||
)
|
||||
.replace(OFFER_JSON_LD, (match, slug: string, json: string) => {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
|
||||
const REGION =
|
||||
/(<!--CMS:(?:OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->)[\s\S]*?(<!--\/CMS:(?:OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->)/g;
|
||||
/(<!--CMS:(?:OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML|HERO-HTML|HERO-PRELOAD)-->)[\s\S]*?(<!--\/CMS:(?:OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML|HERO-HTML|HERO-PRELOAD)-->)/g;
|
||||
const DATA_BLOCK =
|
||||
/(?:<!--CMS:DATA-->)?<script type="application\/json" id="cms-data">[\s\S]*?<\/script>|<!--CMS:DATA-->/g;
|
||||
const OFFER_MARKER = /<!--CMS:OFFER-JSON-LD slug="[a-z0-9-]+"-->/g;
|
||||
|
||||
@@ -672,6 +672,7 @@ describe('startPreviewServer', () => {
|
||||
// Live pakketten: geen gegevens, zonder 404
|
||||
expect((await ask(port, '/api/v1/offerings')).status).toBe(204);
|
||||
expect((await ask(port, '/api/v1/offerings/banner')).status).toBe(204);
|
||||
expect((await ask(port, '/api/v1/hero')).status).toBe(204);
|
||||
// Al het andere blijft zoals het was
|
||||
expect((await ask(port, '/api/v1/andere')).status).toBe(404);
|
||||
expect((await ask(port, '/api/v1/contact-messages')).status).toBe(404);
|
||||
|
||||
@@ -227,7 +227,9 @@ export function contactStubResponse(
|
||||
// asks once per page load)
|
||||
if (
|
||||
method === 'GET' &&
|
||||
(path === '/api/v1/offerings' || path === '/api/v1/offerings/banner')
|
||||
(path === '/api/v1/offerings' ||
|
||||
path === '/api/v1/offerings/banner' ||
|
||||
path === '/api/v1/hero')
|
||||
) {
|
||||
return { status: 204, body: '' };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# Hero contract (ASF site and CMS host)
|
||||
|
||||
Golden files for the hero regions that the CMS host fills, model B (decided 2026-11-16): the host cuts a `wide` (3:2) and a `tall` (4:5) variant per photo around the focus point, and the site uses `<picture>`. Same idea as the packages (`../README.md`): for every `NAME.input.json` the host's template must give exactly `NAME.expected.html` (between `<!--CMS:HERO-HTML-->` and `<!--/CMS:HERO-HTML-->`) and `NAME.expected-preload.html` (between `<!--CMS:HERO-PRELOAD-->` and `<!--/CMS:HERO-PRELOAD-->` in the head). The file ends with one newline that is not part of the HTML. The ASF repo tests its own implementation (`src/lib/hero.ts`, `src/lib/heroHtml.ts`) against the same files; to change the contract, change the code and run `UPDATE_GOLDEN=1 pnpm test src/lib/heroHtml.test.ts`, then send the new files to the CMS session. The ASF commit is in `git log -1 -- web/contract/host-injection/hero`.
|
||||
|
||||
## Input
|
||||
|
||||
The answer of `GET /api/v1/hero` (an object). A 204 (no hero) is `null`: the output is empty and the baked hero stays.
|
||||
|
||||
## Rules
|
||||
|
||||
1. Usable hero: an object with a non-empty `title` (trimmed) and at least one usable slide; otherwise both outputs are empty strings (fail open: the baked page stays).
|
||||
2. A slide is kept when: `id` is non-empty; `image.src` is a path of our host (starts with one `/`, not `//`, no backslash); `image.width` and `image.height` are whole numbers above 0; and it has an `alt` (non-empty after trimming) or `decorative` is `true`. Other slides are skipped. Order is the given order. Only the FIRST kept slide is written; the client takes the rest from the data block.
|
||||
3. A decorative slide writes `alt=""`.
|
||||
4. Variants: kept when `ratio`, `type` and `url` are non-empty, `width` is a whole number above 0 and `url` is a path of our host. Only `image/webp` variants are used here (a preload cannot say "AVIF if supported", so a second format would be fetched twice). `wide` variants make the `img` `srcset`, `tall` variants the `source` `srcset`; sorted by width ascending, written `URL WIDTHw`, joined by `, `.
|
||||
5. `focus` (`x` and `y` both between 0 and 1) is written as `style="object-position:X% Y%"` on the `img` (percentages without trailing zeros, at most two decimals); without a valid focus there is no `style`.
|
||||
6. Buttons: at most 2 (the first two valid ones). A button is valid with a non-empty `label` and a `target` that is an anchor (`#name`), a path (one leading `/`, not `//`, no backslash) or an `https://` address that parses. `lead` and `display` are not written in the HTML.
|
||||
7. Escape every text and attribute (`&` `&`, `<` `<`, `>` `>`, `"` `"`, `'` `'`). A new line in the title becomes `<br>` (after escaping).
|
||||
|
||||
## Output, HERO-HTML
|
||||
|
||||
`<picture class="cms-hero-picture">` + (when a `tall` webp variant exists: `<source media="(orientation: portrait)" srcset="TALL" sizes="100vw" type="image/webp">`) + `<img class="cms-hero-image" src="SRC"` + (when a `wide` webp variant exists: ` srcset="WIDE" sizes="100vw"`) + ` width="W" height="H" alt="ALT"` + (focus: ` style="object-position:X% Y%"`) + ` fetchpriority="high">` + `</picture>` + `<h1 class="cms-hero-title">` + (tagline: `<span class="cms-hero-tagline">TAGLINE</span> `) + `<span class="cms-hero-name">TITLE</span></h1>` + (when there are buttons: `<p class="cms-hero-buttons">` + `<a class="cms-hero-button" href="TARGET">LABEL</a>`... + `</p>`).
|
||||
|
||||
`src` is `image.src`; `W` and `H` are `image.width` and `image.height`. Selection is by orientation, not width, because the hero is as high as the screen.
|
||||
|
||||
## Output, HERO-PRELOAD
|
||||
|
||||
With a `tall` variant: `<link rel="preload" as="image" imagesrcset="TALL" imagesizes="100vw" media="(orientation: portrait)" fetchpriority="high">` followed by the landscape link with `media="(orientation: landscape)"`. The landscape link has `imagesrcset="WIDE" imagesizes="100vw"`, or `href="SRC"` when there is no wide set. Without a tall variant there is one link without `media`. The `srcset`, `sizes` and `media` values are byte for byte the same as in the picture; the golden files check this.
|
||||
|
||||
## Files
|
||||
|
||||
`hero-standard` (two slides, wide and tall, AVIF ignored), `hero-minimal` (no variants, no tagline, no button), `hero-two-lines` (line break, anchor, https and a third button that is cut, decorative slide), `hero-hostile` (escaping, unsafe buttons, unusable slides skipped), `hero-no-alt` and `hero-none` (empty). `seed.json` holds the seed for the ASF test CMS with a first focus estimate per photo.
|
||||
|
||||
URL scheme suggestion for the variants (the CMS decides): `/media/hero/<hash>/wide-1600.webp`, `/media/hero/<hash>/tall-960.avif`.
|
||||
@@ -0,0 +1 @@
|
||||
<link rel="preload" as="image" imagesrcset="/media/hero/a"b/w800.webp 800w" imagesizes="100vw" fetchpriority="high">
|
||||
@@ -0,0 +1 @@
|
||||
<picture class="cms-hero-picture"><img class="cms-hero-image" src="/media/hero/a"b/w1600.webp" srcset="/media/hero/a"b/w800.webp 800w" sizes="100vw" width="1600" height="1067" alt="Een "foto" <script>" fetchpriority="high"></picture><h1 class="cms-hero-title"><span class="cms-hero-tagline"><i>x</i></span> <span class="cms-hero-name"><b>"Andrea" & 'Slop'</b></span></h1><p class="cms-hero-buttons"><a class="cms-hero-button" href="/a?b=1&c="2""><Goed></a></p>
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"display": "slideshow",
|
||||
"title": "<b>\"Andrea\" & 'Slop'</b>",
|
||||
"tagline": "<i>x</i>",
|
||||
"buttons": [
|
||||
{ "label": "javascript", "target": "javascript:alert(1)" },
|
||||
{ "label": "Protocolvrij", "target": "//evil.example/x" },
|
||||
{ "label": "<Goed>", "target": "/a?b=1&c=\"2\"" }
|
||||
],
|
||||
"slides": [
|
||||
{
|
||||
"id": "skip1",
|
||||
"alt": "",
|
||||
"decorative": false,
|
||||
"image": { "width": 10, "height": 10, "src": "/media/x.webp" }
|
||||
},
|
||||
{
|
||||
"id": "skip2",
|
||||
"alt": "extern",
|
||||
"decorative": false,
|
||||
"image": {
|
||||
"width": 10,
|
||||
"height": 10,
|
||||
"src": "https://evil.example/x.webp"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "skip3",
|
||||
"alt": "geen afmeting",
|
||||
"decorative": false,
|
||||
"image": { "width": 0, "height": 10, "src": "/media/x.webp" }
|
||||
},
|
||||
{
|
||||
"id": "a1",
|
||||
"alt": "Een \"foto\" <script>",
|
||||
"decorative": false,
|
||||
"image": {
|
||||
"width": 1600,
|
||||
"height": 1067,
|
||||
"src": "/media/hero/a\"b/w1600.webp",
|
||||
"variants": [
|
||||
{
|
||||
"ratio": "wide",
|
||||
"width": 800,
|
||||
"type": "image/webp",
|
||||
"url": "/media/hero/a\"b/w800.webp"
|
||||
},
|
||||
{
|
||||
"ratio": "wide",
|
||||
"width": 400,
|
||||
"type": "image/webp",
|
||||
"url": "https://evil.example/w400.webp"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<link rel="preload" as="image" href="/media/hero/abc123/w2560.webp" fetchpriority="high">
|
||||
@@ -0,0 +1 @@
|
||||
<picture class="cms-hero-picture"><img class="cms-hero-image" src="/media/hero/abc123/w2560.webp" width="2560" height="1702" alt="Lifestyle fotografie" fetchpriority="high"></picture><h1 class="cms-hero-title"><span class="cms-hero-name">Andrea Slop</span></h1>
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"display": "single",
|
||||
"title": "Andrea Slop",
|
||||
"buttons": [],
|
||||
"slides": [
|
||||
{
|
||||
"id": "a1",
|
||||
"alt": "Lifestyle fotografie",
|
||||
"decorative": false,
|
||||
"image": {
|
||||
"width": 2560,
|
||||
"height": 1702,
|
||||
"src": "/media/hero/abc123/w2560.webp"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"display": "slideshow",
|
||||
"title": "Titel",
|
||||
"buttons": [],
|
||||
"slides": [
|
||||
{
|
||||
"id": "x",
|
||||
"alt": "",
|
||||
"decorative": false,
|
||||
"image": { "width": 1, "height": 1, "src": "/m.webp" }
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
null
|
||||
@@ -0,0 +1 @@
|
||||
<link rel="preload" as="image" imagesrcset="/media/hero/3f9a1c/tall-640.webp 640w, /media/hero/3f9a1c/tall-960.webp 960w" imagesizes="100vw" media="(orientation: portrait)" fetchpriority="high"><link rel="preload" as="image" imagesrcset="/media/hero/3f9a1c/wide-960.webp 960w, /media/hero/3f9a1c/wide-1600.webp 1600w" imagesizes="100vw" media="(orientation: landscape)" fetchpriority="high">
|
||||
@@ -0,0 +1 @@
|
||||
<picture class="cms-hero-picture"><source media="(orientation: portrait)" srcset="/media/hero/3f9a1c/tall-640.webp 640w, /media/hero/3f9a1c/tall-960.webp 960w" sizes="100vw" type="image/webp"><img class="cms-hero-image" src="/media/hero/3f9a1c/wide-1600.webp" srcset="/media/hero/3f9a1c/wide-960.webp 960w, /media/hero/3f9a1c/wide-1600.webp 1600w" sizes="100vw" width="1600" height="1067" alt="Zwangerschapsfoto in de duinen" style="object-position:50% 55%" fetchpriority="high"></picture><h1 class="cms-hero-title"><span class="cms-hero-tagline">Lifestyle fotograaf · Huizen</span> <span class="cms-hero-name">Andrea Slop</span></h1><p class="cms-hero-buttons"><a class="cms-hero-button" href="/over-mij">Lees meer</a></p>
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"display": "slideshow",
|
||||
"title": "Andrea Slop",
|
||||
"tagline": "Lifestyle fotograaf · Huizen",
|
||||
"lead": null,
|
||||
"buttons": [{ "label": "Lees meer", "target": "/over-mij" }],
|
||||
"slides": [
|
||||
{
|
||||
"id": "11111111-1111-1111-1111-111111111111",
|
||||
"alt": "Zwangerschapsfoto in de duinen",
|
||||
"decorative": false,
|
||||
"image": {
|
||||
"width": 1600,
|
||||
"height": 1067,
|
||||
"focus": { "x": 0.5, "y": 0.55 },
|
||||
"src": "/media/hero/3f9a1c/wide-1600.webp",
|
||||
"variants": [
|
||||
{
|
||||
"ratio": "wide",
|
||||
"width": 1600,
|
||||
"type": "image/webp",
|
||||
"url": "/media/hero/3f9a1c/wide-1600.webp"
|
||||
},
|
||||
{
|
||||
"ratio": "wide",
|
||||
"width": 960,
|
||||
"type": "image/webp",
|
||||
"url": "/media/hero/3f9a1c/wide-960.webp"
|
||||
},
|
||||
{
|
||||
"ratio": "wide",
|
||||
"width": 1600,
|
||||
"type": "image/avif",
|
||||
"url": "/media/hero/3f9a1c/wide-1600.avif"
|
||||
},
|
||||
{
|
||||
"ratio": "wide",
|
||||
"width": 960,
|
||||
"type": "image/avif",
|
||||
"url": "/media/hero/3f9a1c/wide-960.avif"
|
||||
},
|
||||
{
|
||||
"ratio": "tall",
|
||||
"width": 960,
|
||||
"type": "image/webp",
|
||||
"url": "/media/hero/3f9a1c/tall-960.webp"
|
||||
},
|
||||
{
|
||||
"ratio": "tall",
|
||||
"width": 640,
|
||||
"type": "image/webp",
|
||||
"url": "/media/hero/3f9a1c/tall-640.webp"
|
||||
},
|
||||
{
|
||||
"ratio": "tall",
|
||||
"width": 960,
|
||||
"type": "image/avif",
|
||||
"url": "/media/hero/3f9a1c/tall-960.avif"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "22222222-2222-2222-2222-222222222222",
|
||||
"alt": "Knusse newbornfoto met de familie",
|
||||
"decorative": false,
|
||||
"image": {
|
||||
"width": 1600,
|
||||
"height": 1067,
|
||||
"focus": { "x": 0.45, "y": 0.5 },
|
||||
"src": "/media/hero/7b2e90/wide-1600.webp",
|
||||
"variants": []
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<link rel="preload" as="image" href="/media/hero/abc123/w1600.webp" fetchpriority="high">
|
||||
@@ -0,0 +1 @@
|
||||
<picture class="cms-hero-picture"><img class="cms-hero-image" src="/media/hero/abc123/w1600.webp" width="1600" height="1067" alt="" fetchpriority="high"></picture><h1 class="cms-hero-title"><span class="cms-hero-tagline">Fotografie</span> <span class="cms-hero-name">Andrea<br>Slop</span></h1><p class="cms-hero-buttons"><a class="cms-hero-button" href="#contact">Boek een shoot</a><a class="cms-hero-button" href="https://andreaslop.nl/portfolio">Portfolio</a></p>
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"display": "slideshow",
|
||||
"title": "Andrea\nSlop",
|
||||
"tagline": "Fotografie",
|
||||
"buttons": [
|
||||
{ "label": "Boek een shoot", "target": "#contact" },
|
||||
{ "label": "Portfolio", "target": "https://andreaslop.nl/portfolio" },
|
||||
{ "label": "Derde knop", "target": "/derde" }
|
||||
],
|
||||
"slides": [
|
||||
{
|
||||
"id": "a1",
|
||||
"alt": "",
|
||||
"decorative": true,
|
||||
"image": {
|
||||
"width": 1600,
|
||||
"height": 1067,
|
||||
"src": "/media/hero/abc123/w1600.webp",
|
||||
"variants": []
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"note": "Seed for the ASF hero on the test CMS. Focus points are a first estimate from looking at the photos (x and y between 0 and 1, from the top left); Bryan adjusts them in the admin. Sources are the existing exports in web/src/assets (not camera originals; never upscale).",
|
||||
"display": "slideshow",
|
||||
"title": "Andrea Slop",
|
||||
"tagline": "Lifestyle fotograaf · Huizen",
|
||||
"buttons": [{ "label": "Lees meer", "target": "/over-mij" }],
|
||||
"slides": [
|
||||
{
|
||||
"file": "hero-8.jpg",
|
||||
"width": 1600,
|
||||
"height": 1067,
|
||||
"alt": "Zwangerschapsfoto in de duinen",
|
||||
"focus": { "x": 0.5, "y": 0.55 },
|
||||
"subject": "belly and hands"
|
||||
},
|
||||
{
|
||||
"file": "hero-7.jpg",
|
||||
"width": 1600,
|
||||
"height": 1067,
|
||||
"alt": "Knusse newbornfoto met de familie",
|
||||
"focus": { "x": 0.45, "y": 0.5 },
|
||||
"subject": "the kiss on the baby"
|
||||
},
|
||||
{
|
||||
"file": "hero-1.jpg",
|
||||
"width": 2560,
|
||||
"height": 1702,
|
||||
"alt": "Lifestyle fotografie",
|
||||
"focus": { "x": 0.55, "y": 0.6 },
|
||||
"subject": "tattoo and heather"
|
||||
},
|
||||
{
|
||||
"file": "hero-2.jpg",
|
||||
"width": 1600,
|
||||
"height": 1067,
|
||||
"alt": "Zwangerschapsshoot in de buitenlucht",
|
||||
"focus": { "x": 0.45, "y": 0.45 },
|
||||
"subject": "the couple"
|
||||
},
|
||||
{
|
||||
"file": "hero-3.jpg",
|
||||
"width": 1600,
|
||||
"height": 1067,
|
||||
"alt": "Newbornshoot van een pasgeboren baby",
|
||||
"focus": { "x": 0.45, "y": 0.4 },
|
||||
"subject": "the baby's face"
|
||||
},
|
||||
{
|
||||
"file": "hero-4.jpg",
|
||||
"width": 2048,
|
||||
"height": 1362,
|
||||
"alt": "Spontaan portret buiten",
|
||||
"focus": { "x": 0.45, "y": 0.35 },
|
||||
"subject": "the face"
|
||||
},
|
||||
{
|
||||
"file": "hero-5.jpg",
|
||||
"width": 1600,
|
||||
"height": 1067,
|
||||
"alt": "Natuurlijke lifestylefoto",
|
||||
"focus": { "x": 0.5, "y": 0.55 },
|
||||
"subject": "the hands with the ring"
|
||||
},
|
||||
{
|
||||
"file": "hero-6.jpg",
|
||||
"width": 2048,
|
||||
"height": 1362,
|
||||
"alt": "Portret in de natuur",
|
||||
"focus": { "x": 0.5, "y": 0.35 },
|
||||
"subject": "the face"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -155,7 +155,13 @@ describe.each(priorityPages)('prioriteitsfoto van %s', (path) => {
|
||||
for (const node of body.querySelectorAll('noscript')) node.remove();
|
||||
const prioritized = [
|
||||
...body.querySelectorAll('img[fetchpriority="high"][src]'),
|
||||
].filter((image) => !image.closest('picture'));
|
||||
// The hero photo sits in a <picture> but has no <source> for the
|
||||
// baked page, so its preload is the plain one (config/heroPreload)
|
||||
].filter(
|
||||
(image) =>
|
||||
!image.closest('picture') ||
|
||||
image.classList.contains('cms-hero-image'),
|
||||
);
|
||||
expect(prioritized.length).toBeGreaterThan(0);
|
||||
for (const image of prioritized) {
|
||||
const links = preloads(document).filter(
|
||||
|
||||
@@ -74,6 +74,8 @@ describe('markers in de gebouwde pagina', () => {
|
||||
'OFFERINGS-HTML',
|
||||
'BANNER-TOP-HTML',
|
||||
'BANNER-BOTTOM-HTML',
|
||||
'HERO-HTML',
|
||||
'HERO-PRELOAD',
|
||||
]) {
|
||||
expect(home.split(`<!--CMS:${marker}-->`)).toHaveLength(2);
|
||||
expect(home.split(`<!--/CMS:${marker}-->`)).toHaveLength(2);
|
||||
@@ -337,3 +339,86 @@ describe('zonder host die injecteert', () => {
|
||||
expect(messages).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
const hostHero = (extra: Record<string, unknown> = {}) => ({
|
||||
display: 'slideshow',
|
||||
title: 'Nieuwe titel',
|
||||
tagline: 'Nieuw label',
|
||||
buttons: [{ label: 'Boek nu', target: '#contact' }],
|
||||
slides: ['een', 'twee'].map((name) => ({
|
||||
id: name,
|
||||
alt: `Alt ${name}`,
|
||||
decorative: false,
|
||||
image: {
|
||||
width: 100,
|
||||
height: 80,
|
||||
focus: { x: 0.25, y: 0.75 },
|
||||
src: '/favicon.png',
|
||||
variants: [],
|
||||
},
|
||||
})),
|
||||
...extra,
|
||||
});
|
||||
|
||||
describe('de hero van de host', () => {
|
||||
it('schrijft de eerste foto, de titel en de preload in de HTML', async () => {
|
||||
inject({ offerings: FIVE, banners: NO_BANNERS, hero: hostHero() });
|
||||
const home = await html('/');
|
||||
const region = home.slice(
|
||||
home.indexOf('<!--CMS:HERO-HTML-->'),
|
||||
home.indexOf('<!--/CMS:HERO-HTML-->'),
|
||||
);
|
||||
expect(region).toContain('Nieuwe titel');
|
||||
expect(region).toContain('alt="Alt een"');
|
||||
expect(region).not.toContain('Alt twee');
|
||||
expect(region).toContain('style="object-position:25% 75%"');
|
||||
expect(region).toContain('href="#contact"');
|
||||
expect(home).toContain(
|
||||
'<!--CMS:HERO-PRELOAD--><link rel="preload" as="image" href="/favicon.png" fetchpriority="high"><!--/CMS:HERO-PRELOAD-->',
|
||||
);
|
||||
});
|
||||
|
||||
it('toont na hydratatie de slides van de host, zonder API-verzoek', async () => {
|
||||
inject({ offerings: FIVE, banners: NO_BANNERS, hero: hostHero() });
|
||||
const requested: string[] = [];
|
||||
const { page, messages } = await openPage(server.origin + '/', {
|
||||
prepare: async (p) => {
|
||||
p.on('request', (request) => {
|
||||
if (request.url().includes('/api/v1/hero')) {
|
||||
requested.push(request.url());
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
await waitForHydration(page);
|
||||
await eventually(() =>
|
||||
page.locator('[aria-roledescription="carousel"] h1').textContent(),
|
||||
).toContain('Nieuwe titel');
|
||||
expect(
|
||||
await page
|
||||
.locator('[aria-roledescription="carousel"] img')
|
||||
.first()
|
||||
.getAttribute('alt'),
|
||||
).toBe('Alt een');
|
||||
expect(requested).toEqual([]);
|
||||
expect(messages).toEqual([]);
|
||||
});
|
||||
|
||||
it('laat de gebakken hero staan als de data niet bruikbaar is', async () => {
|
||||
inject({
|
||||
offerings: FIVE,
|
||||
banners: NO_BANNERS,
|
||||
hero: hostHero({ slides: [] }),
|
||||
});
|
||||
const home = await html('/');
|
||||
// The data block still holds what the host sent; the region keeps the
|
||||
// baked hero
|
||||
const region = home.slice(
|
||||
home.indexOf('<!--CMS:HERO-HTML-->'),
|
||||
home.indexOf('<!--/CMS:HERO-HTML-->'),
|
||||
);
|
||||
expect(region).not.toContain('Nieuwe titel');
|
||||
expect(region).toContain('Andrea Slop');
|
||||
expect(home).toContain('<!--CMS:HERO-PRELOAD--><link');
|
||||
});
|
||||
});
|
||||
|
||||
+2
-1
@@ -128,7 +128,8 @@ describe.each(widths)('zonder JavaScript op %i px', (width) => {
|
||||
.count(),
|
||||
).resolves.toBe(0);
|
||||
}
|
||||
const hero = page.locator('[aria-roledescription="carousel"]');
|
||||
// De platte hero (tussen de CMS-markers), geen carrousel
|
||||
const hero = page.locator('[data-cms-region="HERO-HTML"]');
|
||||
await expect(
|
||||
hero.locator('img:visible').count(),
|
||||
).resolves.toBeGreaterThan(0);
|
||||
|
||||
+26
-15
@@ -9,6 +9,12 @@ import {
|
||||
} from './support/browser.ts';
|
||||
import { startServer } from './support/server.ts';
|
||||
|
||||
// The tests sample every animation frame for a few seconds. On the slow CI
|
||||
// runner (Raspberry Pi) the sampler sometimes has not caught up with the page
|
||||
// when the wait ends (for example 0 of 14 hidden elements seen as hidden), a
|
||||
// false failure that passes on a new run. A real fault fails every attempt.
|
||||
const timing = { retry: inCi ? 2 : 1 };
|
||||
|
||||
// FR-PR-09, FR-PR-10, V-D6: Reveal is zichtbaar in de HTML en in de eerste
|
||||
// render; na de hydratatie verbergt alleen een element dat helemaal onder het
|
||||
// scherm staat zich, zonder overgang, en het verschijnt bij het scrollen.
|
||||
@@ -112,6 +118,7 @@ async function settle(page: Page) {
|
||||
describe.each(sizes)('Reveal bij het laden op $width x $height', (size) => {
|
||||
it.each(pages)(
|
||||
'%s: wat in beeld staat blijft op elke frame 1, de rest gaat zonder overgang naar 0',
|
||||
timing,
|
||||
async (path) => {
|
||||
const { page, ...opened } = await open(path, size);
|
||||
await settle(page);
|
||||
@@ -141,22 +148,26 @@ describe.each(sizes)('Reveal bij het laden op $width x $height', (size) => {
|
||||
},
|
||||
);
|
||||
|
||||
it('met verminderde beweging is elke Reveal op elke frame zichtbaar', async () => {
|
||||
for (const path of pages) {
|
||||
const { page } = await open(path, size, 'reduce');
|
||||
await settle(page);
|
||||
const entries = await samples(page);
|
||||
expect(entries.length).toBeGreaterThan(0);
|
||||
for (const entry of entries) {
|
||||
expect(entry.opacities.every((value) => value === 1)).toBe(
|
||||
true,
|
||||
);
|
||||
it(
|
||||
'met verminderde beweging is elke Reveal op elke frame zichtbaar',
|
||||
timing,
|
||||
async () => {
|
||||
for (const path of pages) {
|
||||
const { page } = await open(path, size, 'reduce');
|
||||
await settle(page);
|
||||
const entries = await samples(page);
|
||||
expect(entries.length).toBeGreaterThan(0);
|
||||
for (const entry of entries) {
|
||||
expect(entry.opacities.every((value) => value === 1)).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
await expect(
|
||||
page.locator('[data-reveal="hidden"]').count(),
|
||||
).resolves.toBe(0);
|
||||
}
|
||||
await expect(
|
||||
page.locator('[data-reveal="hidden"]').count(),
|
||||
).resolves.toBe(0);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('Reveal bij het scrollen', () => {
|
||||
|
||||
@@ -41,7 +41,7 @@ describe('Hero', () => {
|
||||
[...container.querySelectorAll('img')].map((img) =>
|
||||
img.getAttribute('src'),
|
||||
);
|
||||
const slide = (i: number) => heroContent.slides[i].src;
|
||||
const slide = (i: number) => heroContent.slides[i].image.src;
|
||||
const last = heroContent.slides.length - 1;
|
||||
|
||||
expect(sources()).toEqual([slide(0)]);
|
||||
|
||||
+210
-116
@@ -1,42 +1,126 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Box,
|
||||
chakra,
|
||||
Container,
|
||||
Heading,
|
||||
Image,
|
||||
VisuallyHidden,
|
||||
} from '@chakra-ui/react';
|
||||
import LinkButton from '../LinkButton';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Box, chakra, Image, VisuallyHidden } from '@chakra-ui/react';
|
||||
import HeroArrows from './HeroArrows';
|
||||
import HeroPauseButton from './HeroPauseButton';
|
||||
import HeroSocials from './HeroSocials';
|
||||
import useHeroSlider, { type HeroAnnouncement } from './useHeroSlider';
|
||||
import type { HeroContent, SocialLink } from '@/content/types';
|
||||
import useHero from './useHero';
|
||||
import type { SocialLink } from '@/content/types';
|
||||
import useHydrated from '@/hooks/useHydrated';
|
||||
import { t } from '@/i18n';
|
||||
import { regionMarkers } from '@/lib/cmsHtml';
|
||||
import type { HeroData, HeroSlide } from '@/lib/hero';
|
||||
import { heroHtml, variantSrcset } from '@/lib/heroHtml';
|
||||
import { slidesToLoad } from '@/lib/slidesToLoad';
|
||||
|
||||
const SLIDE_DURATION = '6s';
|
||||
const SIZES = '100vw';
|
||||
const PORTRAIT = '(orientation: portrait)';
|
||||
|
||||
function announcementText(announcement: HeroAnnouncement, slide: string) {
|
||||
switch (announcement) {
|
||||
case 'slide':
|
||||
return slide;
|
||||
case 'paused':
|
||||
return 'Diavoorstelling gepauzeerd';
|
||||
return t('hero.paused');
|
||||
case 'playing':
|
||||
return 'Diavoorstelling speelt weer af';
|
||||
return t('hero.playing');
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// Where the subject of the photo is; the picture is cropped around it
|
||||
const objectPosition = (slide: HeroSlide): string | undefined => {
|
||||
const { focus } = slide.image;
|
||||
return focus
|
||||
? `${Number((focus.x * 100).toFixed(2))}% ${Number((focus.y * 100).toFixed(2))}%`
|
||||
: undefined;
|
||||
};
|
||||
|
||||
type HeroProps = {
|
||||
content: HeroContent;
|
||||
content: HeroData;
|
||||
socials: SocialLink[];
|
||||
};
|
||||
|
||||
// The hero of the homepage. The plain HTML between the CMS markers (first
|
||||
// photo, title, buttons, styled by .cms-hero-* in the theme) is what the
|
||||
// browser paints first and it is never replaced: React leaves it alone, so the
|
||||
// photo the browser already has stays the largest paint of the page (replacing
|
||||
// it at hydration made the LCP wait for the hydration). After hydration the
|
||||
// slider is laid around it: the other photos on top of the first, the arrows,
|
||||
// the pause button and so on, from the hero of the host, the API or the build.
|
||||
export default function Hero({ content, socials }: HeroProps) {
|
||||
const { title, tagline, cta, slides } = content;
|
||||
const { hero, regionHero } = useHero(content);
|
||||
return (
|
||||
<HeroFrame
|
||||
content={hero}
|
||||
regionHtml={heroHtml(regionHero)}
|
||||
socials={socials}
|
||||
hydrated={useHydrated()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// One photo after the first: a picture with a source for portrait screens
|
||||
// and AVIF where there is one (the first photo is only WebP, because the
|
||||
// browser preloads exactly that file)
|
||||
function SlidePicture({
|
||||
slide,
|
||||
visible,
|
||||
scaled,
|
||||
}: {
|
||||
slide: HeroSlide;
|
||||
visible: boolean;
|
||||
scaled: boolean;
|
||||
}) {
|
||||
const { image } = slide;
|
||||
const tall = ['image/avif', 'image/webp'].map((type) => ({
|
||||
type,
|
||||
srcset: variantSrcset(image.variants, 'tall', type),
|
||||
}));
|
||||
const wide = variantSrcset(image.variants, 'wide');
|
||||
const wideAvif = variantSrcset(image.variants, 'wide', 'image/avif');
|
||||
return (
|
||||
<chakra.picture display="block" w="100%" h="100%">
|
||||
{tall.map(
|
||||
({ type, srcset }) =>
|
||||
srcset && (
|
||||
<source
|
||||
key={type}
|
||||
media={PORTRAIT}
|
||||
srcSet={srcset}
|
||||
sizes={SIZES}
|
||||
type={type}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
{wideAvif && (
|
||||
<source srcSet={wideAvif} sizes={SIZES} type="image/avif" />
|
||||
)}
|
||||
<Image
|
||||
src={image.src}
|
||||
srcSet={wide || undefined}
|
||||
sizes={wide ? SIZES : undefined}
|
||||
width={image.width}
|
||||
height={image.height}
|
||||
alt={slide.alt}
|
||||
w="100%"
|
||||
h="100%"
|
||||
objectFit="cover"
|
||||
objectPosition={objectPosition(slide)}
|
||||
transform={scaled || visible ? 'scale(1)' : 'scale(1.06)'}
|
||||
transition="transform 9s linear"
|
||||
/>
|
||||
</chakra.picture>
|
||||
);
|
||||
}
|
||||
|
||||
type FrameProps = HeroProps & { regionHtml: string; hydrated: boolean };
|
||||
|
||||
function HeroFrame({ content, socials, regionHtml, hydrated }: FrameProps) {
|
||||
const { slides, display } = content;
|
||||
const shown = display === 'single' ? slides.slice(0, 1) : slides;
|
||||
const {
|
||||
active,
|
||||
announcement,
|
||||
@@ -49,25 +133,54 @@ export default function Hero({ content, socials }: HeroProps) {
|
||||
prev,
|
||||
advance,
|
||||
handlers,
|
||||
} = useHeroSlider(slides.length);
|
||||
} = useHeroSlider(shown.length);
|
||||
const section = useRef<HTMLElement>(null);
|
||||
// De slides liggen op elkaar in beeld, dus loading="lazy" stelt niets uit.
|
||||
// Eerst alleen de actieve foto; zodra die binnen en getekend is (twee
|
||||
// Eerst alleen de eerste foto; zodra die binnen en getekend is (twee
|
||||
// frames later, dus na de eerste paint) ook de volgende en de vorige.
|
||||
// Verder weg laden we pas als de slider in de buurt komt (BR-HERO-01).
|
||||
const [firstPainted, setFirstPainted] = useState(false);
|
||||
const onFirstLoaded = () =>
|
||||
requestAnimationFrame(() =>
|
||||
requestAnimationFrame(() => setFirstPainted(true)),
|
||||
);
|
||||
const loaded = firstPainted
|
||||
? slidesToLoad(active, slides.length)
|
||||
: [active];
|
||||
|
||||
// The first photo is part of the plain HTML, so React has no onLoad on it:
|
||||
// listen to it here
|
||||
useEffect(() => {
|
||||
const image =
|
||||
section.current?.querySelector<HTMLImageElement>('.cms-hero-image');
|
||||
if (!image || firstPainted) return;
|
||||
const painted = () =>
|
||||
requestAnimationFrame(() =>
|
||||
requestAnimationFrame(() => setFirstPainted(true)),
|
||||
);
|
||||
if (image.complete && image.naturalWidth > 0) {
|
||||
painted();
|
||||
return;
|
||||
}
|
||||
image.addEventListener('load', painted);
|
||||
image.addEventListener('error', painted);
|
||||
return () => {
|
||||
image.removeEventListener('load', painted);
|
||||
image.removeEventListener('error', painted);
|
||||
};
|
||||
}, [firstPainted]);
|
||||
|
||||
// The first photo is hidden from screen readers while another one is on
|
||||
// top of it
|
||||
useEffect(() => {
|
||||
const picture = section.current?.querySelector('.cms-hero-picture');
|
||||
if (active === 0) picture?.removeAttribute('aria-hidden');
|
||||
else picture?.setAttribute('aria-hidden', 'true');
|
||||
}, [active]);
|
||||
|
||||
const loaded = firstPainted ? slidesToLoad(active, shown.length) : [active];
|
||||
const current = shown[active];
|
||||
|
||||
return (
|
||||
<Box
|
||||
as="section"
|
||||
aria-label="Uitgelicht werk"
|
||||
aria-roledescription="carousel"
|
||||
ref={section}
|
||||
aria-label={t('hero.ariaLabel')}
|
||||
aria-roledescription={hydrated ? 'carousel' : undefined}
|
||||
suppressHydrationWarning
|
||||
position="relative"
|
||||
// Eigen stacking context: de z-indexen hieronder gelden alleen
|
||||
// binnen de hero en botsen niet met de navigatiebalk.
|
||||
@@ -77,111 +190,92 @@ export default function Hero({ content, socials }: HeroProps) {
|
||||
overflow="hidden"
|
||||
bg="ink"
|
||||
touchAction="pan-y"
|
||||
{...handlers}
|
||||
{...(hydrated ? handlers : {})}
|
||||
>
|
||||
{/* Slides: crossfade met een langzame inzoom */}
|
||||
<Box position="absolute" inset={0}>
|
||||
{slides.map((slide, i) => (
|
||||
<Box
|
||||
key={slide.id}
|
||||
role="group"
|
||||
aria-roledescription="slide"
|
||||
aria-label={`${i + 1} van ${slides.length}`}
|
||||
aria-hidden={i !== active}
|
||||
position="absolute"
|
||||
inset={0}
|
||||
opacity={i === active ? 1 : 0}
|
||||
transitionProperty="opacity"
|
||||
transitionDuration="fade"
|
||||
transitionTimingFunction="smooth"
|
||||
>
|
||||
{loaded.includes(i) && (
|
||||
<Image
|
||||
src={slide.src}
|
||||
alt={slide.alt}
|
||||
fetchPriority={i === 0 ? 'high' : undefined}
|
||||
onLoad={
|
||||
firstPainted ? undefined : onFirstLoaded
|
||||
}
|
||||
onError={
|
||||
firstPainted ? undefined : onFirstLoaded
|
||||
}
|
||||
w="100%"
|
||||
h="100%"
|
||||
objectFit="cover"
|
||||
transform={
|
||||
reducedMotion || i === active
|
||||
? 'scale(1)'
|
||||
: 'scale(1.06)'
|
||||
}
|
||||
transition="transform 9s linear"
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
{/* Eerste foto, titel en knoppen: gewone HTML tussen de CMS-markers.
|
||||
Dezelfde tekst als bij het prerenderen, dus React laat hem staan. */}
|
||||
<div
|
||||
data-cms-region="HERO-HTML"
|
||||
suppressHydrationWarning
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: regionMarkers('HERO-HTML', regionHtml),
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* De volgende slides liggen boven de eerste: crossfade met een
|
||||
langzame inzoom */}
|
||||
{hydrated && (
|
||||
<Box position="absolute" inset={0} zIndex={0}>
|
||||
{shown.map((slide, i) =>
|
||||
i === 0 ? null : (
|
||||
<Box
|
||||
key={slide.id}
|
||||
role="group"
|
||||
aria-roledescription="slide"
|
||||
aria-label={t('hero.slideLabel', {
|
||||
position: i + 1,
|
||||
count: shown.length,
|
||||
})}
|
||||
aria-hidden={i !== active}
|
||||
position="absolute"
|
||||
inset={0}
|
||||
opacity={i === active ? 1 : 0}
|
||||
transitionProperty="opacity"
|
||||
transitionDuration="fade"
|
||||
transitionTimingFunction="smooth"
|
||||
>
|
||||
{loaded.includes(i) && (
|
||||
<SlidePicture
|
||||
slide={slide}
|
||||
visible={i === active}
|
||||
scaled={reducedMotion}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
),
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Scrim */}
|
||||
<Box aria-hidden position="absolute" inset={0} bgGradient="scrim" />
|
||||
|
||||
<Container
|
||||
position="relative"
|
||||
zIndex={1}
|
||||
h="100%"
|
||||
pt="header"
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
alignItems="center"
|
||||
justifyContent="center"
|
||||
textAlign="center"
|
||||
color="white"
|
||||
>
|
||||
{/* Tagline en naam samen in één h1: zo staan de zoekwoorden
|
||||
(wat en waar) in de belangrijkste kop van de pagina */}
|
||||
<Heading as="h1" mb={9} color="white">
|
||||
<chakra.span
|
||||
display="block"
|
||||
mb={4}
|
||||
fontFamily="body"
|
||||
textStyle="eyebrow"
|
||||
// Zelfde regelhoogte als lopende tekst, niet die van de kop
|
||||
lineHeight="1.5"
|
||||
color="white/80"
|
||||
>
|
||||
{tagline}
|
||||
</chakra.span>{' '}
|
||||
<chakra.span display="block" textStyle="display">
|
||||
{title}
|
||||
</chakra.span>
|
||||
</Heading>
|
||||
<LinkButton to={cta.to} variant="light">
|
||||
{cta.label}
|
||||
</LinkButton>
|
||||
</Container>
|
||||
|
||||
{slides.length > 1 && <HeroArrows onPrev={prev} onNext={next} />}
|
||||
{hydrated && shown.length > 1 && (
|
||||
<HeroArrows onPrev={prev} onNext={next} />
|
||||
)}
|
||||
<HeroSocials socials={socials} />
|
||||
{autoplay && (
|
||||
{hydrated && autoplay && shown.length > 1 && (
|
||||
<HeroPauseButton stopped={stopped} onToggle={toggleStopped} />
|
||||
)}
|
||||
|
||||
{/* Meldt een wissel of pauze door de bezoeker; staat er altijd, want een
|
||||
live-gebied moet al bestaan voordat de tekst verandert. Leeg na
|
||||
een automatische wissel, zodat er geen oude melding blijft. */}
|
||||
<VisuallyHidden
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
data-testid="hero-announcement"
|
||||
>
|
||||
{announcementText(
|
||||
announcement,
|
||||
`Foto ${active + 1} van ${slides.length}: ${slides[active].alt}`,
|
||||
)}
|
||||
</VisuallyHidden>
|
||||
{hydrated && (
|
||||
<VisuallyHidden
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
data-testid="hero-announcement"
|
||||
>
|
||||
{announcementText(
|
||||
announcement,
|
||||
t(
|
||||
current.alt
|
||||
? 'hero.announcement'
|
||||
: 'hero.announcementPlain',
|
||||
{
|
||||
position: active + 1,
|
||||
count: shown.length,
|
||||
alt: current.alt,
|
||||
},
|
||||
),
|
||||
)}
|
||||
</VisuallyHidden>
|
||||
)}
|
||||
|
||||
{/* Voortgangsbalk: als de animatie klaar is, schuift de slider door.
|
||||
Door de key start hij opnieuw bij elke slidewissel. */}
|
||||
{autoplay && (
|
||||
{hydrated && autoplay && shown.length > 1 && (
|
||||
<Box
|
||||
key={active}
|
||||
aria-hidden
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { chakra, useRecipe } from '@chakra-ui/react';
|
||||
import { t } from '@/i18n';
|
||||
import { Icon } from '@iconify/react/offline';
|
||||
import leftOutlined from '@iconify-icons/ant-design/left-outlined';
|
||||
import rightOutlined from '@iconify-icons/ant-design/right-outlined';
|
||||
@@ -14,7 +15,7 @@ export default function HeroArrows({ onPrev, onNext }: HeroArrowsProps) {
|
||||
<>
|
||||
<ArrowButton
|
||||
side="left"
|
||||
aria-label="Vorige foto"
|
||||
aria-label={t('hero.prev')}
|
||||
data-testid="hero-prev-button"
|
||||
data-requires-js
|
||||
onClick={onPrev}
|
||||
@@ -23,7 +24,7 @@ export default function HeroArrows({ onPrev, onNext }: HeroArrowsProps) {
|
||||
</ArrowButton>
|
||||
<ArrowButton
|
||||
side="right"
|
||||
aria-label="Volgende foto"
|
||||
aria-label={t('hero.next')}
|
||||
data-testid="hero-next-button"
|
||||
data-requires-js
|
||||
onClick={onNext}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { chakra, useRecipe } from '@chakra-ui/react';
|
||||
import LinkButton from '../LinkButton';
|
||||
|
||||
// A button of the hero: a path of the site goes through the router, an anchor
|
||||
// or an https address is a plain link in the same style.
|
||||
export default function HeroButton({
|
||||
label,
|
||||
target,
|
||||
}: {
|
||||
label: string;
|
||||
target: string;
|
||||
}) {
|
||||
const recipe = useRecipe({ key: 'linkButton' });
|
||||
if (target.startsWith('/')) {
|
||||
return (
|
||||
<LinkButton to={target} variant="light">
|
||||
{label}
|
||||
</LinkButton>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<chakra.a href={target} css={recipe({ variant: 'light' })}>
|
||||
{label}
|
||||
</chakra.a>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { chakra, useRecipe } from '@chakra-ui/react';
|
||||
import { t } from '@/i18n';
|
||||
import { Icon } from '@iconify/react/offline';
|
||||
import caretRightOutlined from '@iconify-icons/ant-design/caret-right-outlined';
|
||||
import pauseOutlined from '@iconify-icons/ant-design/pause-outlined';
|
||||
@@ -19,11 +20,7 @@ export default function HeroPauseButton({
|
||||
return (
|
||||
<chakra.button
|
||||
type="button"
|
||||
aria-label={
|
||||
stopped
|
||||
? 'Diavoorstelling afspelen'
|
||||
: 'Diavoorstelling pauzeren'
|
||||
}
|
||||
aria-label={stopped ? t('hero.play') : t('hero.pause')}
|
||||
data-testid="hero-pause-button"
|
||||
data-requires-js
|
||||
onClick={onToggle}
|
||||
|
||||
@@ -4,23 +4,33 @@ 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)
|
||||
// The prerendered hero is the plain HTML between the CMS markers: the first
|
||||
// photo, the title and the buttons. The slider controls only exist after
|
||||
// hydration, so a visitor without JavaScript never sees a dead control.
|
||||
describe('Hero in the prerendered HTML', () => {
|
||||
it('marks the arrows, the pause button and the progress bar', async () => {
|
||||
it('is the first photo between the markers, without slider controls', async () => {
|
||||
const html = await serverHtml(
|
||||
<Hero content={heroContent} socials={siteContent.socials} />,
|
||||
);
|
||||
expect(html).toContain('<!--CMS:HERO-HTML-->');
|
||||
expect(html).toContain('<!--/CMS:HERO-HTML-->');
|
||||
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);
|
||||
const images = doc.querySelectorAll('img.cms-hero-image');
|
||||
expect(images).toHaveLength(1);
|
||||
expect(images[0].getAttribute('src')).toBe(
|
||||
heroContent.slides[0].image.src,
|
||||
);
|
||||
expect(images[0].getAttribute('fetchpriority')).toBe('high');
|
||||
expect(doc.querySelector('h1.cms-hero-title')?.textContent).toContain(
|
||||
heroContent.title,
|
||||
);
|
||||
for (const id of [
|
||||
'hero-prev-button',
|
||||
'hero-next-button',
|
||||
'hero-pause-button',
|
||||
'hero-progress',
|
||||
]) {
|
||||
expect(doc.querySelector(`[data-testid="${id}"]`)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import heroContent from '@/content/heroContent';
|
||||
import { renderWithProviders } from '@/test/renderWithProviders';
|
||||
import type { LoadJson } from '@/components/PackagesProvider/PackagesProvider';
|
||||
import useHero from './useHero';
|
||||
|
||||
const answer = (title: string) => ({
|
||||
title,
|
||||
slides: [
|
||||
{
|
||||
id: 'a',
|
||||
alt: 'Alt',
|
||||
decorative: false,
|
||||
image: { width: 10, height: 8, src: '/m/a.webp' },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
function Title({ load }: { load: LoadJson }) {
|
||||
return <p data-testid="title">{useHero(heroContent, load).hero.title}</p>;
|
||||
}
|
||||
|
||||
const block = (data: unknown) => {
|
||||
const script = document.createElement('script');
|
||||
script.type = 'application/json';
|
||||
script.id = 'cms-data';
|
||||
script.textContent = JSON.stringify(data);
|
||||
document.body.append(script);
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
document.getElementById('cms-data')?.remove();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('useHero', () => {
|
||||
it('takes the hero of the data block and asks nothing', async () => {
|
||||
block({ hero: answer('Van de host') });
|
||||
const load = vi.fn<LoadJson>();
|
||||
await renderWithProviders(<Title load={load} />);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('title')).toHaveTextContent(
|
||||
'Van de host',
|
||||
),
|
||||
);
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the baked hero when the block has no usable one', async () => {
|
||||
block({ hero: { title: 'x' } });
|
||||
await renderWithProviders(<Title load={vi.fn<LoadJson>()} />);
|
||||
expect(screen.getByTestId('title')).toHaveTextContent(
|
||||
heroContent.title,
|
||||
);
|
||||
});
|
||||
|
||||
it('asks the API without a block and shows a usable answer', async () => {
|
||||
const load = vi.fn<LoadJson>().mockResolvedValue(answer('Van de API'));
|
||||
await renderWithProviders(<Title load={load} />);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('title')).toHaveTextContent('Van de API'),
|
||||
);
|
||||
expect(load.mock.calls[0][0]).toBe('/api/v1/hero');
|
||||
});
|
||||
|
||||
it('keeps the baked hero on a 204, an error or an unusable answer', async () => {
|
||||
for (const load of [
|
||||
vi.fn<LoadJson>().mockResolvedValue(undefined),
|
||||
vi.fn<LoadJson>().mockRejectedValue(new Error('status 500')),
|
||||
vi.fn<LoadJson>().mockResolvedValue({ title: 'x' }),
|
||||
]) {
|
||||
const { unmount } = await renderWithProviders(
|
||||
<Title load={load} />,
|
||||
);
|
||||
await waitFor(() => expect(load).toHaveBeenCalled());
|
||||
await Promise.resolve();
|
||||
expect(screen.getByTestId('title')).toHaveTextContent(
|
||||
heroContent.title,
|
||||
);
|
||||
unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it('gives up after the time-out', async () => {
|
||||
vi.useFakeTimers();
|
||||
const load = vi.fn<LoadJson>(
|
||||
(_path, signal) =>
|
||||
new Promise((_resolve, reject) =>
|
||||
signal.addEventListener('abort', () =>
|
||||
reject(new Error('aborted')),
|
||||
),
|
||||
),
|
||||
);
|
||||
await renderWithProviders(<Title load={load} />);
|
||||
await vi.advanceTimersByTimeAsync(8001);
|
||||
expect(load.mock.calls[0][1].aborted).toBe(true);
|
||||
expect(screen.getByTestId('title')).toHaveTextContent(
|
||||
heroContent.title,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
loadFromApi,
|
||||
type LoadJson,
|
||||
} from '@/components/PackagesProvider/PackagesProvider';
|
||||
import useHydrated from '@/hooks/useHydrated';
|
||||
import { hostCmsData } from '@/lib/cmsData';
|
||||
import { mapHero, type HeroData } from '@/lib/hero';
|
||||
|
||||
const HERO_PATH = '/api/v1/hero';
|
||||
const TIMEOUT_MS = 8000;
|
||||
|
||||
// The hero to show: the one in the data block the CMS host wrote, else the
|
||||
// one the API gives, else the baked one. Failing safe is the rule: a missing
|
||||
// block, a network error, a 204, a time-out or an answer that cannot be used
|
||||
// leaves the baked hero on screen. The block is only read after hydration,
|
||||
// so the first render equals the prerendered HTML.
|
||||
export default function useHero(
|
||||
baked: HeroData,
|
||||
load: LoadJson = loadFromApi,
|
||||
): { hero: HeroData; regionHero: HeroData } {
|
||||
const hydrated = useHydrated();
|
||||
const fromBlock = useMemo(() => {
|
||||
const block = hydrated ? hostCmsData(document) : null;
|
||||
return block?.hero === undefined ? null : mapHero(block.hero);
|
||||
}, [hydrated]);
|
||||
const [fetched, setFetched] = useState<HeroData | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// The host sent the data: nothing to ask
|
||||
if (hostCmsData(document)) return;
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
load(HERO_PATH, signal)
|
||||
.then((answer) => {
|
||||
const mapped = mapHero(answer);
|
||||
if (mapped && !signal.aborted) setFetched(mapped);
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.finally(() => clearTimeout(timer));
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
// regionHero is what the plain HTML region of the page holds: the baked
|
||||
// hero, or the one the API gave. The block of the host does not count: the
|
||||
// host wrote that region itself and it must not be written over (that
|
||||
// would replace the photo the browser has painted).
|
||||
return {
|
||||
hero: fromBlock ?? fetched ?? baked,
|
||||
regionHero: fetched ?? baked,
|
||||
};
|
||||
}
|
||||
@@ -33,7 +33,7 @@ const TIMEOUT_MS = 8000;
|
||||
// The JSON answer; undefined for 204; throws for anything else
|
||||
export type LoadJson = (path: string, signal: AbortSignal) => Promise<unknown>;
|
||||
|
||||
const loadFromApi: LoadJson = async (path, signal) => {
|
||||
export const loadFromApi: LoadJson = async (path, signal) => {
|
||||
const response = await fetch(path, {
|
||||
signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { HeroContent } from './types';
|
||||
import { t } from '../i18n/index.ts';
|
||||
import type { HeroData, HeroSlide } from '../lib/hero.ts';
|
||||
|
||||
// Images
|
||||
import hero1 from '../assets/hero-1.jpg';
|
||||
@@ -10,32 +11,104 @@ import hero6 from '../assets/hero-6.jpg';
|
||||
import hero7 from '../assets/hero-7.jpg';
|
||||
import hero8 from '../assets/hero-8.jpg';
|
||||
|
||||
// Statische content tot de CMS-API er is. Daarna komt dit object uit de API.
|
||||
const heroContent: HeroContent = {
|
||||
title: 'Andrea Slop',
|
||||
tagline: 'Lifestyle fotograaf · Huizen',
|
||||
cta: { label: 'Lees meer', to: '/over-mij' },
|
||||
// The hero the build bakes into the page: what the visitor sees until the CMS
|
||||
// host (or the API) gives another one, and again when that fails. The same
|
||||
// shape as what the CMS gives (lib/hero), so one component shows both. The
|
||||
// photos have no wide/tall variants: the plain file is used everywhere.
|
||||
// focus: where the subject is (0..1), used as object-position.
|
||||
const slide = (
|
||||
id: string,
|
||||
src: string,
|
||||
alt: string,
|
||||
width: number,
|
||||
height: number,
|
||||
x: number,
|
||||
y: number,
|
||||
): HeroSlide => ({
|
||||
id,
|
||||
alt,
|
||||
decorative: false,
|
||||
image: { width, height, focus: { x, y }, src, variants: [] },
|
||||
});
|
||||
|
||||
const heroContent: HeroData = {
|
||||
display: 'slideshow',
|
||||
title: t('hero.baked.title'),
|
||||
tagline: t('hero.baked.tagline'),
|
||||
buttons: [{ label: t('hero.baked.button'), target: '/over-mij' }],
|
||||
slides: [
|
||||
{ id: 'hero-8', src: hero8, alt: 'Zwangerschapsfoto in de duinen' },
|
||||
{ id: 'hero-7', src: hero7, alt: 'Knusse newbornfoto met de familie' },
|
||||
{
|
||||
id: 'hero-1',
|
||||
src: hero1,
|
||||
alt: 'Lifestyle fotografie',
|
||||
},
|
||||
{
|
||||
id: 'hero-2',
|
||||
src: hero2,
|
||||
alt: 'Zwangerschapsshoot in de buitenlucht',
|
||||
},
|
||||
{
|
||||
id: 'hero-3',
|
||||
src: hero3,
|
||||
alt: 'Newbornshoot van een pasgeboren baby',
|
||||
},
|
||||
{ id: 'hero-4', src: hero4, alt: 'Spontaan portret buiten' },
|
||||
{ id: 'hero-5', src: hero5, alt: 'Natuurlijke lifestylefoto' },
|
||||
{ id: 'hero-6', src: hero6, alt: 'Portret in de natuur' },
|
||||
slide(
|
||||
'hero-8',
|
||||
hero8,
|
||||
t('hero.baked.alt.hero8'),
|
||||
1600,
|
||||
1067,
|
||||
0.5,
|
||||
0.55,
|
||||
),
|
||||
slide(
|
||||
'hero-7',
|
||||
hero7,
|
||||
t('hero.baked.alt.hero7'),
|
||||
1600,
|
||||
1067,
|
||||
0.45,
|
||||
0.5,
|
||||
),
|
||||
slide(
|
||||
'hero-1',
|
||||
hero1,
|
||||
t('hero.baked.alt.hero1'),
|
||||
2560,
|
||||
1702,
|
||||
0.55,
|
||||
0.6,
|
||||
),
|
||||
slide(
|
||||
'hero-2',
|
||||
hero2,
|
||||
t('hero.baked.alt.hero2'),
|
||||
1600,
|
||||
1067,
|
||||
0.45,
|
||||
0.45,
|
||||
),
|
||||
slide(
|
||||
'hero-3',
|
||||
hero3,
|
||||
t('hero.baked.alt.hero3'),
|
||||
1600,
|
||||
1067,
|
||||
0.45,
|
||||
0.4,
|
||||
),
|
||||
slide(
|
||||
'hero-4',
|
||||
hero4,
|
||||
t('hero.baked.alt.hero4'),
|
||||
2048,
|
||||
1362,
|
||||
0.45,
|
||||
0.35,
|
||||
),
|
||||
slide(
|
||||
'hero-5',
|
||||
hero5,
|
||||
t('hero.baked.alt.hero5'),
|
||||
1600,
|
||||
1067,
|
||||
0.5,
|
||||
0.55,
|
||||
),
|
||||
slide(
|
||||
'hero-6',
|
||||
hero6,
|
||||
t('hero.baked.alt.hero6'),
|
||||
2048,
|
||||
1362,
|
||||
0.5,
|
||||
0.35,
|
||||
),
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
@@ -363,23 +363,3 @@ export interface ShootPageContent {
|
||||
offer: { eyebrow: string; title: string };
|
||||
closing: { title: string; lead: RichText; buttonLabel: string };
|
||||
}
|
||||
|
||||
export interface HeroSlide {
|
||||
id: string;
|
||||
src: string;
|
||||
alt: string;
|
||||
}
|
||||
|
||||
export interface HeroCta {
|
||||
label: string;
|
||||
to: string;
|
||||
}
|
||||
|
||||
export interface HeroContent {
|
||||
title: string;
|
||||
// Klein label in hoofdletters boven de titel: wat en waar, voor bezoekers
|
||||
// en zoekmachines (bv. "Lifestyle fotograaf · Huizen")
|
||||
tagline: string;
|
||||
cta: HeroCta;
|
||||
slides: HeroSlide[];
|
||||
}
|
||||
|
||||
@@ -88,6 +88,7 @@ describe('nl.json', () => {
|
||||
expect(Object.keys(nl)).toEqual([
|
||||
'common',
|
||||
'site',
|
||||
'hero',
|
||||
'home',
|
||||
'about',
|
||||
'contact',
|
||||
|
||||
@@ -121,6 +121,33 @@
|
||||
"instagramHandle": "@andreaslopfotografie"
|
||||
}
|
||||
},
|
||||
"hero": {
|
||||
"ariaLabel": "Uitgelicht werk",
|
||||
"slideLabel": "{position} van {count}",
|
||||
"announcement": "Foto {position} van {count}: {alt}",
|
||||
"announcementPlain": "Foto {position} van {count}",
|
||||
"paused": "Diavoorstelling gepauzeerd",
|
||||
"playing": "Diavoorstelling speelt weer af",
|
||||
"play": "Diavoorstelling afspelen",
|
||||
"pause": "Diavoorstelling pauzeren",
|
||||
"prev": "Vorige foto",
|
||||
"next": "Volgende foto",
|
||||
"baked": {
|
||||
"title": "Andrea Slop",
|
||||
"tagline": "Lifestyle fotograaf · Huizen",
|
||||
"button": "Lees meer",
|
||||
"alt": {
|
||||
"hero8": "Zwangerschapsfoto in de duinen",
|
||||
"hero7": "Knusse newbornfoto met de familie",
|
||||
"hero1": "Lifestyle fotografie",
|
||||
"hero2": "Zwangerschapsshoot in de buitenlucht",
|
||||
"hero3": "Newbornshoot van een pasgeboren baby",
|
||||
"hero4": "Spontaan portret buiten",
|
||||
"hero5": "Natuurlijke lifestylefoto",
|
||||
"hero6": "Portret in de natuur"
|
||||
}
|
||||
}
|
||||
},
|
||||
"home": {
|
||||
"intro": {
|
||||
"title": "Lifestyle fotografie",
|
||||
|
||||
@@ -43,6 +43,13 @@ describe('parseCmsData', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('passes the hero answer on unchecked', () => {
|
||||
expect(
|
||||
parseCmsData(JSON.stringify({ hero: { title: 'T' } }))?.hero,
|
||||
).toEqual({ title: 'T' });
|
||||
expect(parseCmsData('{}')?.hero).toBeUndefined();
|
||||
});
|
||||
|
||||
it('falls back to production for an address that is not an origin', () => {
|
||||
expect(
|
||||
parseCmsData(JSON.stringify({ siteUrl: 'ftp://x' }))?.siteUrl,
|
||||
|
||||
@@ -25,6 +25,9 @@ export interface CmsData {
|
||||
offerings?: unknown;
|
||||
// undefined: not in the block; null: no active banner
|
||||
banners?: { top?: unknown; bottom?: unknown };
|
||||
// The answer of GET /api/v1/hero, not yet checked (lib/hero mapHero);
|
||||
// undefined: not in the block
|
||||
hero?: unknown;
|
||||
}
|
||||
|
||||
const isObject = (value: unknown): value is Record<string, unknown> =>
|
||||
@@ -50,6 +53,7 @@ export function parseCmsData(text: string | null | undefined): CmsData | null {
|
||||
: undefined,
|
||||
offerings: Array.isArray(raw.offerings) ? raw.offerings : undefined,
|
||||
banners,
|
||||
hero: raw.hero,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { isSafeBannerUrl } from './offerings.ts';
|
||||
|
||||
// Turns the answer of GET /api/v1/hero (the CMS) into what the site uses. Pure
|
||||
// functions, tested without a network. Anything that is not clearly valid is
|
||||
// dropped; an answer without a usable slide gives null, so the caller keeps
|
||||
// the hero that was baked into the page (fail open).
|
||||
|
||||
export interface HeroButton {
|
||||
label: string;
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface HeroImageVariant {
|
||||
ratio: string;
|
||||
width: number;
|
||||
type: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface HeroSlide {
|
||||
id: string;
|
||||
alt: string;
|
||||
decorative: boolean;
|
||||
image: {
|
||||
width: number;
|
||||
height: number;
|
||||
// Where the subject is, 0..1; the site uses it as object-position
|
||||
focus: { x: number; y: number } | null;
|
||||
src: string;
|
||||
variants: HeroImageVariant[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface HeroData {
|
||||
display: 'single' | 'slideshow';
|
||||
title: string;
|
||||
tagline?: string;
|
||||
buttons: HeroButton[];
|
||||
slides: HeroSlide[];
|
||||
}
|
||||
|
||||
type Raw = Record<string, unknown>;
|
||||
|
||||
const isObject = (value: unknown): value is Raw =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
|
||||
const asText = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
|
||||
|
||||
const asSize = (value: unknown): number | undefined =>
|
||||
typeof value === 'number' && Number.isInteger(value) && value > 0
|
||||
? value
|
||||
: undefined;
|
||||
|
||||
const BACKSLASH = String.fromCharCode(92);
|
||||
|
||||
// An image address of our own host: a path with one leading slash
|
||||
const isOwnPath = (url: string): boolean =>
|
||||
url.startsWith('/') && !url.startsWith('//') && !url.includes(BACKSLASH);
|
||||
|
||||
// A button goes to an anchor, a path or an https address
|
||||
const isSafeTarget = (target: string): boolean =>
|
||||
/^#[A-Za-z][\w-]*$/.test(target) || isSafeBannerUrl(target);
|
||||
|
||||
function toButton(raw: unknown): HeroButton | null {
|
||||
if (!isObject(raw)) return null;
|
||||
const label = asText(raw.label);
|
||||
const target = asText(raw.target);
|
||||
return label && target && isSafeTarget(target) ? { label, target } : null;
|
||||
}
|
||||
|
||||
function toVariant(raw: unknown): HeroImageVariant | null {
|
||||
if (!isObject(raw)) return null;
|
||||
const ratio = asText(raw.ratio);
|
||||
const type = asText(raw.type);
|
||||
const url = asText(raw.url);
|
||||
const width = asSize(raw.width);
|
||||
return ratio && type && url && width && isOwnPath(url)
|
||||
? { ratio, width, type, url }
|
||||
: null;
|
||||
}
|
||||
|
||||
const inUnit = (value: unknown): value is number =>
|
||||
typeof value === 'number' && value >= 0 && value <= 1;
|
||||
|
||||
function toFocus(raw: unknown): { x: number; y: number } | null {
|
||||
if (!isObject(raw) || !inUnit(raw.x) || !inUnit(raw.y)) return null;
|
||||
return { x: raw.x, y: raw.y };
|
||||
}
|
||||
|
||||
function toSlide(raw: unknown): HeroSlide | null {
|
||||
if (!isObject(raw) || !isObject(raw.image)) return null;
|
||||
const id = asText(raw.id);
|
||||
const decorative = raw.decorative === true;
|
||||
// A photo that says something needs its alt text; a decorative one has none
|
||||
const alt = decorative ? '' : asText(raw.alt);
|
||||
const src = asText(raw.image.src);
|
||||
const width = asSize(raw.image.width);
|
||||
const height = asSize(raw.image.height);
|
||||
if (!id || !src || !isOwnPath(src) || !width || !height) return null;
|
||||
if (alt === undefined) return null;
|
||||
const variants = Array.isArray(raw.image.variants)
|
||||
? raw.image.variants.map(toVariant).filter((v) => v !== null)
|
||||
: [];
|
||||
return {
|
||||
id,
|
||||
alt,
|
||||
decorative,
|
||||
image: {
|
||||
width,
|
||||
height,
|
||||
focus: toFocus(raw.image.focus),
|
||||
src,
|
||||
variants,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function mapHero(answer: unknown): HeroData | null {
|
||||
if (!isObject(answer)) return null;
|
||||
const title = asText(answer.title);
|
||||
const slides = Array.isArray(answer.slides)
|
||||
? answer.slides.map(toSlide).filter((slide) => slide !== null)
|
||||
: [];
|
||||
if (!title || slides.length === 0) return null;
|
||||
const buttons = Array.isArray(answer.buttons)
|
||||
? answer.buttons
|
||||
.map(toButton)
|
||||
.filter((button) => button !== null)
|
||||
.slice(0, 2)
|
||||
: [];
|
||||
return {
|
||||
display: answer.display === 'single' ? 'single' : 'slideshow',
|
||||
title,
|
||||
tagline: asText(answer.tagline),
|
||||
buttons,
|
||||
slides,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mapHero } from './hero';
|
||||
import { heroHtml, heroPreloadHtml } from './heroHtml';
|
||||
|
||||
// The contract with the CMS host: for every hero-*.input.json in
|
||||
// contract/host-injection/hero there is an *.expected.html (the region between
|
||||
// <!--CMS:HERO-HTML--> markers) and an *.expected-preload.html (the links
|
||||
// between <!--CMS:HERO-PRELOAD--> markers). Regenerate after a deliberate change
|
||||
// with UPDATE_GOLDEN=1 and send the files to the CMS session.
|
||||
const DIR = join(process.cwd(), 'contract', 'host-injection', 'hero');
|
||||
const inputs = readdirSync(DIR).filter((name) => name.endsWith('.input.json'));
|
||||
|
||||
describe('hero golden files', () => {
|
||||
it('has inputs', () => {
|
||||
expect(inputs.length).toBeGreaterThanOrEqual(6);
|
||||
});
|
||||
|
||||
it.each(inputs)('%s gives the expected HTML and preload', (file) => {
|
||||
const name = file.replace('.input.json', '');
|
||||
const hero = mapHero(JSON.parse(readFileSync(join(DIR, file), 'utf8')));
|
||||
const outputs = [
|
||||
[`${name}.expected.html`, heroHtml(hero)],
|
||||
[`${name}.expected-preload.html`, heroPreloadHtml(hero)],
|
||||
];
|
||||
for (const [expectedName, html] of outputs) {
|
||||
const path = join(DIR, expectedName);
|
||||
if (process.env.UPDATE_GOLDEN === '1') {
|
||||
writeFileSync(path, html + '\n');
|
||||
}
|
||||
expect(html + '\n').toBe(readFileSync(path, 'utf8'));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const slide = (image: object, extra: object = {}) => ({
|
||||
id: 's',
|
||||
alt: 'Alt',
|
||||
decorative: false,
|
||||
image: { width: 10, height: 8, src: '/m/a.webp', ...image },
|
||||
...extra,
|
||||
});
|
||||
|
||||
const answer = (slides: unknown[], extra: object = {}) => ({
|
||||
title: 'T',
|
||||
slides,
|
||||
...extra,
|
||||
});
|
||||
|
||||
describe('mapHero', () => {
|
||||
it('rejects what is not a usable hero', () => {
|
||||
expect(mapHero(null)).toBeNull();
|
||||
expect(mapHero([])).toBeNull();
|
||||
expect(mapHero({ title: 'T' })).toBeNull();
|
||||
expect(mapHero(answer([]))).toBeNull();
|
||||
expect(mapHero({ slides: [slide({})] })).toBeNull();
|
||||
expect(mapHero(answer([slide({})], { title: ' ' }))).toBeNull();
|
||||
});
|
||||
|
||||
it('drops slides that cannot be used', () => {
|
||||
const bad = [
|
||||
null,
|
||||
{ id: 's' },
|
||||
slide({}, { id: '' }),
|
||||
slide({ src: '' }),
|
||||
slide({ src: 'https://evil.example/a.webp' }),
|
||||
slide({ src: '//evil.example/a.webp' }),
|
||||
slide({ src: '/a\\b.webp' }),
|
||||
slide({ width: 0 }),
|
||||
slide({ height: 1.5 }),
|
||||
slide({}, { alt: ' ' }),
|
||||
];
|
||||
expect(mapHero(answer(bad))).toBeNull();
|
||||
expect(mapHero(answer([...bad, slide({})]))?.slides).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps a decorative slide with an empty alt', () => {
|
||||
const hero = mapHero(
|
||||
answer([slide({}, { decorative: true, alt: 'ignored' })]),
|
||||
);
|
||||
expect(hero?.slides[0].alt).toBe('');
|
||||
expect(hero?.slides[0].decorative).toBe(true);
|
||||
});
|
||||
|
||||
it('reads the display, the tagline and at most two safe buttons', () => {
|
||||
const hero = mapHero(
|
||||
answer([slide({})], {
|
||||
display: 'single',
|
||||
tagline: ' Label ',
|
||||
buttons: [
|
||||
null,
|
||||
{ label: 'x', target: 'javascript:1' },
|
||||
{ label: '', target: '/a' },
|
||||
{ label: 'A', target: '#contact' },
|
||||
{ label: 'B', target: '/b' },
|
||||
{ label: 'C', target: 'https://a.example/c' },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(hero?.display).toBe('single');
|
||||
expect(hero?.tagline).toBe('Label');
|
||||
expect(hero?.buttons.map((b) => b.label)).toEqual(['A', 'B']);
|
||||
expect(mapHero(answer([slide({})]))?.display).toBe('slideshow');
|
||||
expect(
|
||||
mapHero(answer([slide({})], { buttons: 'nope' }))?.buttons,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps only valid variants and a focus point inside the picture', () => {
|
||||
const hero = mapHero(
|
||||
answer([
|
||||
slide({
|
||||
focus: { x: 0.25, y: 1 },
|
||||
variants: [
|
||||
null,
|
||||
{
|
||||
ratio: 'wide',
|
||||
width: 100,
|
||||
type: 'image/webp',
|
||||
url: '/a.webp',
|
||||
},
|
||||
{
|
||||
ratio: 'wide',
|
||||
width: 0,
|
||||
type: 'image/webp',
|
||||
url: '/b.webp',
|
||||
},
|
||||
{
|
||||
ratio: 'wide',
|
||||
width: 100,
|
||||
type: 'image/webp',
|
||||
url: 'https://x.example/c.webp',
|
||||
},
|
||||
],
|
||||
}),
|
||||
slide({ focus: { x: 2, y: 0 } }),
|
||||
slide({ focus: 'middle', variants: 'none' }),
|
||||
]),
|
||||
);
|
||||
expect(hero?.slides[0].image.variants).toHaveLength(1);
|
||||
expect(hero?.slides[0].image.focus).toEqual({ x: 0.25, y: 1 });
|
||||
expect(hero?.slides[1].image.focus).toBeNull();
|
||||
expect(hero?.slides[2].image.focus).toBeNull();
|
||||
expect(hero?.slides[2].image.variants).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('heroHtml and heroPreloadHtml', () => {
|
||||
it('write nothing for no hero', () => {
|
||||
expect(heroHtml(null)).toBe('');
|
||||
expect(heroPreloadHtml(null)).toBe('');
|
||||
});
|
||||
|
||||
it('leave out what is not there', () => {
|
||||
const hero = mapHero(answer([slide({})]));
|
||||
const html = heroHtml(hero);
|
||||
expect(html).not.toContain('<source');
|
||||
expect(html).not.toContain('srcset');
|
||||
expect(html).not.toContain('style=');
|
||||
expect(html).not.toContain('cms-hero-buttons');
|
||||
expect(html).not.toContain('cms-hero-tagline');
|
||||
expect(heroPreloadHtml(hero)).toBe(
|
||||
'<link rel="preload" as="image" href="/m/a.webp" fetchpriority="high">',
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the same srcset, sizes and media in the picture and the preload', () => {
|
||||
const hero = mapHero(
|
||||
answer([
|
||||
slide({
|
||||
variants: [
|
||||
{
|
||||
ratio: 'wide',
|
||||
width: 20,
|
||||
type: 'image/webp',
|
||||
url: '/w20.webp',
|
||||
},
|
||||
{
|
||||
ratio: 'tall',
|
||||
width: 8,
|
||||
type: 'image/webp',
|
||||
url: '/t8.webp',
|
||||
},
|
||||
],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const html = heroHtml(hero);
|
||||
const preload = heroPreloadHtml(hero);
|
||||
for (const part of [
|
||||
'srcset="/t8.webp 8w"',
|
||||
'srcset="/w20.webp 20w"',
|
||||
'media="(orientation: portrait)"',
|
||||
]) {
|
||||
expect(html).toContain(part);
|
||||
}
|
||||
expect(preload).toContain('imagesrcset="/t8.webp 8w"');
|
||||
expect(preload).toContain('imagesrcset="/w20.webp 20w"');
|
||||
expect(preload).toContain('media="(orientation: portrait)"');
|
||||
expect(preload).toContain('media="(orientation: landscape)"');
|
||||
});
|
||||
|
||||
it('preloads the plain image for landscape when only a tall variant has a set', () => {
|
||||
const hero = mapHero(
|
||||
answer([
|
||||
slide({
|
||||
variants: [
|
||||
{
|
||||
ratio: 'tall',
|
||||
width: 8,
|
||||
type: 'image/webp',
|
||||
url: '/t8.webp',
|
||||
},
|
||||
],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(heroPreloadHtml(hero)).toContain(
|
||||
'href="/m/a.webp" media="(orientation: landscape)"',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps one preload without media when there is no tall variant', () => {
|
||||
const hero = mapHero(
|
||||
answer([
|
||||
slide({
|
||||
variants: [
|
||||
{
|
||||
ratio: 'wide',
|
||||
width: 20,
|
||||
type: 'image/webp',
|
||||
url: '/w20.webp',
|
||||
},
|
||||
],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(heroPreloadHtml(hero)).toBe(
|
||||
'<link rel="preload" as="image" imagesrcset="/w20.webp 20w" imagesizes="100vw" fetchpriority="high">',
|
||||
);
|
||||
});
|
||||
|
||||
it('writes the focus point as object-position', () => {
|
||||
const hero = mapHero(answer([slide({ focus: { x: 0.333333, y: 0 } })]));
|
||||
expect(heroHtml(hero)).toContain('style="object-position:33.33% 0%"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { escapeHtml } from './cmsHtml.ts';
|
||||
import type { HeroData, HeroImageVariant, HeroSlide } from './hero.ts';
|
||||
|
||||
// The neutral HTML of the hero between the CMS markers, and the preload links
|
||||
// in the head. The host (SLP Modular CMS) writes the same markup from live
|
||||
// data; the golden files in contract/host-injection/hero are the contract.
|
||||
//
|
||||
// Only the FIRST slide is written (it is the LCP image); the client takes the
|
||||
// rest from the data block. The picture holds one <source> for portrait
|
||||
// screens (ratio "tall") and the <img> itself is the landscape one (ratio
|
||||
// "wide"). Selection is by orientation, because the hero is as high as the
|
||||
// screen. The preload links repeat exactly the same srcset, sizes and media,
|
||||
// so the browser starts the very file the picture will pick.
|
||||
//
|
||||
// Only WebP is used here: a preload cannot say "AVIF if supported", so a
|
||||
// second format would be fetched twice. Later slides may use AVIF.
|
||||
|
||||
const PORTRAIT = '(orientation: portrait)';
|
||||
const LANDSCAPE = '(orientation: landscape)';
|
||||
const SIZES = '100vw';
|
||||
|
||||
// The srcset of one ratio and format ("tall" or "wide"; WebP unless said)
|
||||
export const variantSrcset = (
|
||||
variants: HeroImageVariant[],
|
||||
ratio: string,
|
||||
type = 'image/webp',
|
||||
): string =>
|
||||
variants
|
||||
.filter((v) => v.ratio === ratio && v.type === type)
|
||||
.sort((a, b) => a.width - b.width)
|
||||
.map((v) => `${escapeHtml(v.url)} ${v.width}w`)
|
||||
.join(', ');
|
||||
|
||||
const percent = (unit: number): string => `${Number((unit * 100).toFixed(2))}%`;
|
||||
|
||||
const focusStyle = (slide: HeroSlide): string => {
|
||||
const { focus } = slide.image;
|
||||
return focus
|
||||
? ` style="object-position:${percent(focus.x)} ${percent(focus.y)}"`
|
||||
: '';
|
||||
};
|
||||
|
||||
function pictureHtml(slide: HeroSlide): string {
|
||||
const { image } = slide;
|
||||
const tall = variantSrcset(image.variants, 'tall');
|
||||
const wide = variantSrcset(image.variants, 'wide');
|
||||
const source = tall
|
||||
? `<source media="${PORTRAIT}" srcset="${tall}" sizes="${SIZES}" type="image/webp">`
|
||||
: '';
|
||||
const img =
|
||||
`<img class="cms-hero-image" src="${escapeHtml(image.src)}"` +
|
||||
(wide ? ` srcset="${wide}" sizes="${SIZES}"` : '') +
|
||||
` width="${image.width}" height="${image.height}"` +
|
||||
` alt="${escapeHtml(slide.alt)}"${focusStyle(slide)}` +
|
||||
' fetchpriority="high">';
|
||||
return `<picture class="cms-hero-picture">${source}${img}</picture>`;
|
||||
}
|
||||
|
||||
function headingHtml(hero: HeroData): string {
|
||||
const tagline = hero.tagline
|
||||
? `<span class="cms-hero-tagline">${escapeHtml(hero.tagline)}</span> `
|
||||
: '';
|
||||
// A new line in the title is a line break
|
||||
const name = escapeHtml(hero.title).replace(/\r?\n/g, '<br>');
|
||||
return `<h1 class="cms-hero-title">${tagline}<span class="cms-hero-name">${name}</span></h1>`;
|
||||
}
|
||||
|
||||
function buttonsHtml(hero: HeroData): string {
|
||||
if (hero.buttons.length === 0) return '';
|
||||
const links = hero.buttons
|
||||
.map(
|
||||
(button) =>
|
||||
`<a class="cms-hero-button" href="${escapeHtml(button.target)}">${escapeHtml(button.label)}</a>`,
|
||||
)
|
||||
.join('');
|
||||
return `<p class="cms-hero-buttons">${links}</p>`;
|
||||
}
|
||||
|
||||
// Between <!--CMS:HERO-HTML--> and <!--/CMS:HERO-HTML-->; nothing for no hero
|
||||
export function heroHtml(hero: HeroData | null): string {
|
||||
if (!hero) return '';
|
||||
return pictureHtml(hero.slides[0]) + headingHtml(hero) + buttonsHtml(hero);
|
||||
}
|
||||
|
||||
// Between <!--CMS:HERO-PRELOAD--> and <!--/CMS:HERO-PRELOAD--> in the head: one
|
||||
// link for portrait screens (when a tall variant exists) and one for the
|
||||
// others. Without a tall variant a single link without media is enough.
|
||||
export function heroPreloadHtml(hero: HeroData | null): string {
|
||||
if (!hero) return '';
|
||||
const { image } = hero.slides[0];
|
||||
const tall = variantSrcset(image.variants, 'tall');
|
||||
const wide = variantSrcset(image.variants, 'wide');
|
||||
const link = (target: string, media: string): string =>
|
||||
`<link rel="preload" as="image" ${target}` +
|
||||
`${media ? ` media="${media}"` : ''} fetchpriority="high">`;
|
||||
const wideTarget = wide
|
||||
? `imagesrcset="${wide}" imagesizes="${SIZES}"`
|
||||
: `href="${escapeHtml(image.src)}"`;
|
||||
if (!tall) return link(wideTarget, '');
|
||||
return (
|
||||
link(`imagesrcset="${tall}" imagesizes="${SIZES}"`, PORTRAIT) +
|
||||
link(wideTarget, LANDSCAPE)
|
||||
);
|
||||
}
|
||||
@@ -28,6 +28,77 @@ const config = defineConfig({
|
||||
'[tabindex="-1"]:focus': {
|
||||
outline: 'none',
|
||||
},
|
||||
// The hero as the page first shows it: the plain HTML between the CMS
|
||||
// markers (lib/heroHtml, components/Hero). Looks like the slider's first
|
||||
// frame: the photo fills the hero, title and buttons are centred over
|
||||
// it, the scrim (a later sibling) sits between them.
|
||||
'[data-cms-region="HERO-HTML"]': {
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
textAlign: 'center',
|
||||
color: 'white',
|
||||
pt: 'header',
|
||||
px: 'gutter',
|
||||
},
|
||||
'.cms-hero-picture': {
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
zIndex: 0,
|
||||
display: 'block',
|
||||
},
|
||||
'.cms-hero-image': {
|
||||
display: 'block',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
objectFit: 'cover',
|
||||
},
|
||||
'.cms-hero-title': {
|
||||
position: 'relative',
|
||||
zIndex: 1,
|
||||
margin: 0,
|
||||
marginBottom: 9,
|
||||
fontFamily: 'heading',
|
||||
// Same as the Heading component the slider uses
|
||||
fontWeight: '500',
|
||||
letterSpacing: '0.2px',
|
||||
color: 'white',
|
||||
},
|
||||
'.cms-hero-tagline': {
|
||||
display: 'block',
|
||||
marginBottom: 4,
|
||||
fontFamily: 'body',
|
||||
textStyle: 'eyebrow',
|
||||
lineHeight: '1.5',
|
||||
color: 'white/80',
|
||||
},
|
||||
'.cms-hero-name': { display: 'block', textStyle: 'display' },
|
||||
'.cms-hero-buttons': {
|
||||
position: 'relative',
|
||||
zIndex: 1,
|
||||
margin: 0,
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
justifyContent: 'center',
|
||||
gap: 4,
|
||||
},
|
||||
'.cms-hero-button': {
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: 3,
|
||||
px: '2.4rem',
|
||||
py: '1.05rem',
|
||||
borderWidth: '1px',
|
||||
borderStyle: 'solid',
|
||||
borderColor: 'white/70',
|
||||
color: 'white',
|
||||
textStyle: 'eyebrow',
|
||||
fontWeight: '400',
|
||||
textDecoration: 'none',
|
||||
},
|
||||
// The plain HTML between the CMS markers (components/CmsRegion): what
|
||||
// the CMS host writes, shown until the styled cards take over after
|
||||
// hydration. Looks like the cards (white, hairline border, centred),
|
||||
|
||||
Reference in New Issue
Block a user