Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95f16295f2 | ||
|
|
1f087581d4 | ||
|
|
2147fcec35 | ||
|
|
d99b909f9f | ||
|
|
49b1d5f0ba | ||
|
|
6475696709 | ||
|
|
440a298cc7
|
||
|
|
8050072ce5 | ||
|
|
20806692bb | ||
|
|
78d3f594e5
|
||
|
|
358fca0855 | ||
|
|
cce4a2b858 | ||
|
|
efd2aeeb48
|
||
|
|
9e45aca7f3 | ||
|
|
3d7bb2d4a6 | ||
|
|
1a59fc3125 | ||
|
|
ad0b114828 | ||
|
|
13f78c48cd |
@@ -84,13 +84,23 @@ jobs:
|
||||
run: pnpm test
|
||||
|
||||
# Sentry toont bij elke fout uit welke commit de build komt
|
||||
# Dit artefact (dist) is ook wat naar productie gaat: bewust zonder
|
||||
# OFFERINGS_URL, dus met de gecommitte pakketlijst. De testbuild met de
|
||||
# pakketten uit het CMS is job build-test.
|
||||
# Dit artefact (dist) is ook wat naar productie gaat: met de gecommitte
|
||||
# pakketlijst (snapshot), zonder testadres en met dicht formulier. De
|
||||
# CMS-host schrijft de actuele gegevens bij elk verzoek in de HTML.
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
run: |
|
||||
# Zonder deze waarden meet de site stilletjes niets: liever een rode build
|
||||
for name in VITE_SENTRY_DSN VITE_UMAMI_SCRIPT_URL VITE_UMAMI_WEBSITE_ID; do
|
||||
[ -n "${!name}" ] || { echo "$name ontbreekt: stel de Gitea-variabele PROD_${name#VITE_} in"; exit 1; }
|
||||
done
|
||||
pnpm build
|
||||
env:
|
||||
VITE_RELEASE: ${{ github.sha }}
|
||||
# Monitoring van de productiesite (src/monitoring/config.ts)
|
||||
VITE_APP_ENV: production
|
||||
VITE_SENTRY_DSN: ${{ vars.PROD_SENTRY_DSN }}
|
||||
VITE_UMAMI_SCRIPT_URL: ${{ vars.PROD_UMAMI_SCRIPT_URL }}
|
||||
VITE_UMAMI_WEBSITE_ID: ${{ vars.PROD_UMAMI_WEBSITE_ID }}
|
||||
|
||||
- name: Audit (productiepakketten, blokkerend)
|
||||
run: pnpm audit:deps
|
||||
@@ -105,10 +115,10 @@ jobs:
|
||||
path: web/dist/client/
|
||||
retention-days: 7
|
||||
|
||||
# De build voor de testsite: zelfde code als dist, maar met de pakketten uit
|
||||
# het CMS van de testomgeving (OFFERINGS_URL uit de repo-variabele
|
||||
# ASF_OFFERINGS_URL_TEST). Productie krijgt dit artefact nooit: die blijft op
|
||||
# dist met de gecommitte lijst tot er een productie-CMS is.
|
||||
# De build voor de testsite: zelfde code als dist, maar met het eigen adres
|
||||
# van de testsite en het formulier open. De pakketten komen niet meer uit
|
||||
# het CMS bij de build: de CMS-host injecteert ze bij elk verzoek.
|
||||
# Productie krijgt dit artefact nooit.
|
||||
build-test:
|
||||
needs: check
|
||||
if: (github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master')
|
||||
@@ -137,11 +147,20 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build (testomgeving, pakketten uit het CMS)
|
||||
run: pnpm build
|
||||
- name: Build (testomgeving)
|
||||
run: |
|
||||
# Zonder deze waarden meet de site stilletjes niets: liever een rode build
|
||||
for name in VITE_SENTRY_DSN VITE_UMAMI_SCRIPT_URL VITE_UMAMI_WEBSITE_ID; do
|
||||
[ -n "${!name}" ] || { echo "$name ontbreekt: stel de Gitea-variabele TEST_${name#VITE_} in"; exit 1; }
|
||||
done
|
||||
pnpm build
|
||||
env:
|
||||
VITE_RELEASE: ${{ github.sha }}
|
||||
OFFERINGS_URL: ${{ vars.ASF_OFFERINGS_URL_TEST }}
|
||||
# Monitoring van de testsite (src/monitoring/config.ts)
|
||||
VITE_APP_ENV: test
|
||||
VITE_SENTRY_DSN: ${{ vars.TEST_SENTRY_DSN }}
|
||||
VITE_UMAMI_SCRIPT_URL: ${{ vars.TEST_UMAMI_SCRIPT_URL }}
|
||||
VITE_UMAMI_WEBSITE_ID: ${{ vars.TEST_UMAMI_WEBSITE_ID }}
|
||||
# De testsite staat op zichzelf: canonical, og:url, og:image,
|
||||
# JSON-LD en sitemap wijzen naar het eigen adres, zodat een gedeelde
|
||||
# link (WhatsApp, Discord) ook zijn eigen plaatje toont. Alleen in
|
||||
@@ -193,18 +212,26 @@ jobs:
|
||||
- name: Upload naar de testserver
|
||||
env:
|
||||
# Secrets via env, zodat bash tekens als $ of ` niet nog eens uitlegt
|
||||
SSHPASS: ${{ secrets.PI_MAIN_PASSWORD }}
|
||||
SSH_PORT: ${{ secrets.PI_MAIN_PORT }}
|
||||
SSH_USER: ${{ secrets.PI_MAIN_USERNAME }}
|
||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||
DEPLOY_PATH: ${{ vars.DEPLOY_PATH_TEST }}
|
||||
SSH_KEY: ${{ secrets.TEST_HOST_SSH_KEY }}
|
||||
SSH_PORT: ${{ secrets.TEST_HOST_PORT }}
|
||||
SSH_USER: ${{ secrets.TEST_HOST_USERNAME }}
|
||||
SSH_HOST: ${{ secrets.TEST_HOST_ADDRESS }}
|
||||
DEPLOY_PATH: ${{ vars.TEST_DEPLOY_PATH }}
|
||||
run: |
|
||||
case "$DEPLOY_PATH" in
|
||||
''|'/'|*' '*) echo "DEPLOY_PATH_TEST ontbreekt of is ongeldig: '$DEPLOY_PATH'"; exit 1 ;;
|
||||
''|'/'|*' '*) echo "TEST_DEPLOY_PATH ontbreekt of is ongeldig: '$DEPLOY_PATH'"; exit 1 ;;
|
||||
esac
|
||||
sudo apt-get update && sudo apt-get install -y sshpass
|
||||
SSH="sshpass -e ssh -p $SSH_PORT -o StrictHostKeyChecking=accept-new $SSH_USER@$SSH_HOST"
|
||||
$SSH "set -e
|
||||
for name in SSH_KEY SSH_PORT SSH_USER SSH_HOST; do
|
||||
[ -n "${!name}" ] || { echo "Secret TEST_HOST_${name#SSH_} ontbreekt"; exit 1; }
|
||||
done
|
||||
# Inloggen met de deploysleutel, geen wachtwoord. De sleutel gaat naar
|
||||
# een tijdelijk bestand dat na afloop verdwijnt.
|
||||
KEY_FILE="$(mktemp)"
|
||||
trap 'rm -f "$KEY_FILE"' EXIT
|
||||
printf '%s\n' "$SSH_KEY" > "$KEY_FILE"
|
||||
chmod 600 "$KEY_FILE"
|
||||
SSH_OPTS=(-i "$KEY_FILE" -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=accept-new)
|
||||
ssh -p "$SSH_PORT" "${SSH_OPTS[@]}" "$SSH_USER@$SSH_HOST" "set -e
|
||||
if [ -e '$DEPLOY_PATH/wp-config.php' ] || [ -d '$DEPLOY_PATH/wp-content' ]; then
|
||||
echo 'Geweigerd: $DEPLOY_PATH bevat WordPress'; exit 1
|
||||
fi
|
||||
@@ -215,7 +242,7 @@ jobs:
|
||||
# mag. Zo zijn groeps-schrijfrechten op de doelmap genoeg.
|
||||
# dotglob: ook bestanden die met een punt beginnen gaan mee.
|
||||
shopt -s dotglob
|
||||
sshpass -e scp -P "$SSH_PORT" -o StrictHostKeyChecking=accept-new -r dist/* "$SSH_USER@$SSH_HOST:$DEPLOY_PATH/"
|
||||
scp -P "$SSH_PORT" "${SSH_OPTS[@]}" -r dist/* "$SSH_USER@$SSH_HOST:$DEPLOY_PATH/"
|
||||
echo "Gedeployd naar test: ${GITHUB_REF_NAME} (${GITHUB_SHA::7})"
|
||||
|
||||
# Vergelijkt wat de server teruggeeft met dist. Met de oude nginx-config
|
||||
@@ -223,18 +250,17 @@ jobs:
|
||||
# dus staan voor de deploy (zie pi-install-instructions.md).
|
||||
- name: Controle na deploy
|
||||
env:
|
||||
HEALTH_URL: ${{ vars.HEALTH_CHECK_URL_TEST }}
|
||||
# 'true' zodra test.andreaslop.nl door de CMS-host (Api.AndreaSlopFotografie)
|
||||
# wordt bediend in plaats van nginx: dan controleert het script ook de
|
||||
# exacte CSP en de CMS-routes. Zet hem om samen met de proxy-route.
|
||||
SERVED_BY_CMS: ${{ vars.ASF_TEST_SERVED_BY_CMS }}
|
||||
HEALTH_URL: ${{ vars.TEST_HEALTH_URL }}
|
||||
# De CSP komt uit dezelfde bron als de build (Umami en Sentry)
|
||||
VITE_APP_ENV: test
|
||||
VITE_SENTRY_DSN: ${{ vars.TEST_SENTRY_DSN }}
|
||||
VITE_UMAMI_SCRIPT_URL: ${{ vars.TEST_UMAMI_SCRIPT_URL }}
|
||||
VITE_UMAMI_WEBSITE_ID: ${{ vars.TEST_UMAMI_WEBSITE_ID }}
|
||||
run: |
|
||||
if [ -z "$HEALTH_URL" ]; then echo "Geen HEALTH_CHECK_URL_TEST ingesteld; overgeslagen"; exit 0; fi
|
||||
if [ "$SERVED_BY_CMS" = "true" ]; then
|
||||
EXPECTED_CSP="$(node config/printCsp.ts)" bash deploy/verify-deployment.sh "$HEALTH_URL" dist --test --cms
|
||||
else
|
||||
bash deploy/verify-deployment.sh "$HEALTH_URL" dist --test
|
||||
fi
|
||||
if [ -z "$HEALTH_URL" ]; then echo "Geen TEST_HEALTH_URL ingesteld; overgeslagen"; exit 0; fi
|
||||
# test.andreaslop.nl wordt door de CMS-host bediend: het script
|
||||
# controleert ook de exacte CSP en de CMS-routes
|
||||
EXPECTED_CSP="$(node config/printCsp.ts)" bash deploy/verify-deployment.sh "$HEALTH_URL" dist --test --cms
|
||||
echo "Test bereikbaar en gelijk aan de build"
|
||||
|
||||
# Lighthouse tegen de gebouwde site (mobiel en desktop)
|
||||
@@ -343,17 +369,19 @@ jobs:
|
||||
name: dist
|
||||
path: web/dist
|
||||
|
||||
# FTP met TLS (verplicht) naar de webhoster, in drie rondes (zie
|
||||
# deploy/upload-production.sh): eerst alles behalve HTML en web.config,
|
||||
# dan web.config en alle HTML, en pas daarna oude bestanden opruimen. Zo
|
||||
# verwijst een bezoeker nooit naar een bestand dat er nog niet staat.
|
||||
# Deze job kan pas draaien als er een webhost is.
|
||||
- name: Upload naar productie (FTPS)
|
||||
# Gewone FTP (het productiepakket biedt geen FTPS) naar de map met
|
||||
# voorgerenderde pagina's van de CMS-host, in drie rondes (zie
|
||||
# deploy/upload-production.sh): eerst alles behalve HTML, dan alle HTML,
|
||||
# en pas daarna oude bestanden opruimen. Zo verwijst een bezoeker nooit
|
||||
# naar een bestand dat er nog niet staat. De host zelf en zijn web.config
|
||||
# komen uit de CMS-pijplijn. Deze job kan pas draaien als er een webhost is.
|
||||
- name: Upload naar productie (gewone FTP)
|
||||
env:
|
||||
FTP_HOST: ${{ secrets.FTP_HOST }}
|
||||
FTP_USER: ${{ secrets.FTP_USERNAME }}
|
||||
LFTP_PASSWORD: ${{ secrets.FTP_PASSWORD }}
|
||||
FTP_DIR: ${{ vars.FTP_REMOTE_DIR || 'wwwroot' }}
|
||||
FTP_HOST: ${{ secrets.PROD_HOST_ADDRESS }}
|
||||
FTP_PORT: ${{ secrets.PROD_HOST_PORT }}
|
||||
FTP_USER: ${{ secrets.PROD_HOST_USERNAME }}
|
||||
LFTP_PASSWORD: ${{ secrets.PROD_HOST_PASSWORD }}
|
||||
FTP_DIR: ${{ vars.PROD_DEPLOY_PATH || 'wwwroot' }}
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install -y lftp
|
||||
bash deploy/upload-production.sh dist "$FTP_DIR"
|
||||
@@ -361,8 +389,8 @@ jobs:
|
||||
|
||||
- name: Controle na deploy
|
||||
env:
|
||||
HEALTH_URL: ${{ vars.HEALTH_CHECK_URL_PRODUCTION }}
|
||||
HEALTH_URL: ${{ vars.PROD_HEALTH_URL }}
|
||||
run: |
|
||||
if [ -z "$HEALTH_URL" ]; then echo "Geen HEALTH_CHECK_URL_PRODUCTION ingesteld; overgeslagen"; exit 0; fi
|
||||
if [ -z "$HEALTH_URL" ]; then echo "Geen PROD_HEALTH_URL ingesteld; overgeslagen"; exit 0; fi
|
||||
bash deploy/verify-deployment.sh "$HEALTH_URL" dist
|
||||
echo "Productie bereikbaar en gelijk aan de build"
|
||||
|
||||
@@ -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,30 @@
|
||||
# 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` |
|
||||
| 15 | Pause on mouse hover | Removed on purpose (Bryan, 2026-11-17): a full-screen hero almost always has the pointer over it. Kept: the explicit pause button (WCAG 2.2.2), no autoplay with `prefers-reduced-motion`, pause when the tab is hidden, and pause while keyboard focus is on the controls (a deliberate action; a click on an arrow does not pause). Touch and swipe do not pause either: a swipe restarts the progress bar of the new slide | Add hover back: `onPointerEnter`/`onPointerLeave` in `useHeroSlider.ts` | `web/src/components/Hero/useHeroSlider.ts` |
|
||||
| 16 | Slow zoom on the first photo (supersedes #11 in part; Bryan chose the full slider render, 2026-11-17) | The first photo zooms like the others, without replacing the plain HTML: the plain HTML is painted at scale 1.06 (CSS `.cms-hero-image`), the slider sets `data-zoom` after hydration and it zooms out to 1 over 9 s. Same first frame before and after hydration, so no CLS, and the LCP does not wait for hydration (replacing the nodes made the LCP 5.3 s in the first design). Reduced motion: no scale at all | Replace the nodes at hydration (one component); measure LCP first | `theme.ts`, `Hero.tsx` |
|
||||
|
||||
## 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.
|
||||
+18
-9
@@ -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.
|
||||
@@ -41,7 +51,7 @@ Both follow the same rules as the packages: baked into the HTML at build time, r
|
||||
Decision (Bryan, 2026-11-15): the hosting package has one entry per website. The CMS host (Kestrel) is that entry and serves the website itself (the prerendered pages), `/admin` and `/api/v1/*`. In production IIS (or the proxy) therefore passes **all** requests to the CMS host, not only `/api/v1/*`, and serves no static files or HTML cache of its own. This holds for the test host and for ASF production alike.
|
||||
|
||||
- **Test (ASF):** nginx on the proxy Pi forwards everything for `test.andreaslop.nl` to the CMS host (`web/deploy/nginx/test.andreaslop.nl.proxy.conf`), which serves the site files and the API. Nothing to add.
|
||||
- **Production: not in place yet.** The generated `web/deploy/iis/web.config` and the FTP upload of static files (`web/deploy/upload-production.sh`) still describe the old idea of IIS serving the files. They have to change with the production hosting: IIS keeps only the redirects (www, HTTPS) and the pass-through to the CMS host, and the prerendered `dist/` goes to the CMS host's prerendered-pages folder as on test. Security headers then come from the CMS host (as on test). This is part of the production hosting work, not of the packages feature. Until then production builds use the committed snapshot and the live calls fail safely (the baked list stays; the browser console shows a 404 for the API). Change generated server files only in `web/config/serverConfig.ts` and run `pnpm server-config`.
|
||||
- **Production: not in place yet.** The FTP upload (`web/deploy/upload-production.sh`) is now plain FTP into the CMS host's prerendered-pages folder and no longer puts a `web.config` on the server (the host's own `web.config` comes from the CMS pipeline). The generated `web/deploy/iis/web.config` still describes the old idea of IIS serving the files and has to change with the production hosting: IIS keeps only the redirects (www, HTTPS) and the pass-through to the CMS host, and the prerendered `dist/` goes to the CMS host's prerendered-pages folder as on test. Security headers then come from the CMS host (as on test). This is part of the production hosting work, not of the packages feature. Until then production builds use the committed snapshot and the live calls fail safely (the baked list stays; the browser console shows a 404 for the API). Change generated server files only in `web/config/serverConfig.ts` and run `pnpm server-config`.
|
||||
- **Host injection (built in the site; the host side is the CMS repo's work):** the build leaves markers in the prerendered pages and the CMS host fills them from live data, so a CMS change is visible to search engines at once without a rebuild. Contract and plan: `aidlc-docs/features/asf-cms-host-injection/plan.md`; golden files for the list HTML: `web/contract/host-injection/`.
|
||||
- Markers: `<!--CMS:DATA-->` + `<script type="application/json" id="cms-data">` (root document, every page), `<!--CMS:OFFERINGS-HTML-->`, `<!--CMS:BANNER-TOP-HTML-->` and `<!--CMS:BANNER-BOTTOM-HTML-->` regions (home page), `<!--CMS:OFFER-JSON-LD slug="...">` before the ld+json block of the newborn, zwangerschap and gezin pages, and `<span data-cms-price="slug">` in their price block.
|
||||
- In the page: `CmsRegion` renders the plain HTML between the markers (`lib/cmsHtml.ts`, styled by `.cms-*` rules in `theme.ts`) and React leaves it alone until hydration, so a host that wrote different data causes no hydration mismatch; after hydration the styled components take over. `PackagesProvider` reads the data block in the first render after hydration (`hostCmsData`); a block with `"source":"build"` is the baked one and counts as "no host data", so the page asks the API as before. The site address comes from `siteUrl` in the block (`setSiteUrl` in `client.tsx`), because the script files cannot be rewritten per host.
|
||||
@@ -49,12 +59,11 @@ Decision (Bryan, 2026-11-15): the hosting package has one entry per website. The
|
||||
|
||||
## Environment and variables
|
||||
|
||||
| Name | Where | Meaning |
|
||||
| --------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `OFFERINGS_URL` | build env | Site address that serves the API (for example `https://test.andreaslop.nl`). Unset gives the snapshot. |
|
||||
| `ASF_OFFERINGS_URL_TEST` | Gitea repo variable | Value of `OFFERINGS_URL` for the test build. Set by SLS, not by feature sessions. |
|
||||
| `API_PROXY_TARGET` | dev env | Forwards `/api` in `pnpm dev` to a CMS host. |
|
||||
| `VITE_SITE_URL` | build env | Address the site presents itself under (canonical, og:*, JSON-LD, sitemap). Only the test build sets it (`https://test.andreaslop.nl`); unset gives `https://andreaslop.nl`. |
|
||||
| `VITE_CONTACT_FORM_ENABLED` | build env | Opens the contact form when exactly `true`. Only the test build sets it; unset keeps the form closed (production). Opening it in production needs Bryan's explicit go, after the captcha decision ([go-live-checklist.md](go-live-checklist.md)). |
|
||||
| Name | Where | Meaning |
|
||||
| --------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `OFFERINGS_URL` | build env | Site address that serves the API (for example `https://test.andreaslop.nl`). Unset gives the snapshot. |
|
||||
| `API_PROXY_TARGET` | dev env | Forwards `/api` in `pnpm dev` to a CMS host. |
|
||||
| `VITE_SITE_URL` | build env | Address the site presents itself under (canonical, og:*, JSON-LD, sitemap). Only the test build sets it (`https://test.andreaslop.nl`); unset gives `https://andreaslop.nl`. |
|
||||
| `VITE_CONTACT_FORM_ENABLED` | build env | Opens the contact form when exactly `true`. Only the test build sets it; unset keeps the form closed (production). Opening it in production needs Bryan's explicit go, after the captcha decision ([go-live-checklist.md](go-live-checklist.md)). |
|
||||
|
||||
The production artifact is built without `OFFERINGS_URL` on purpose: production must never carry the prices of the test CMS.
|
||||
No build sets `OFFERINGS_URL` any more (since the host injection, 2026-11-18): the CMS host writes the current data into the HTML. The variable stays supported for a local build against a CMS. The production artifact never carries the prices of the test CMS.
|
||||
|
||||
+26
-3
@@ -20,8 +20,8 @@ Dispatch from the CLI (the token comes from your git credentials, never print it
|
||||
|
||||
## Jobs
|
||||
|
||||
1. `check`: lint, format, unit/property/axe tests (coverage threshold 100% on `src/lib/**`), build **without** `OFFERINGS_URL` (so with the committed snapshot), audit. Uploads artifact `dist` (this is what production gets).
|
||||
2. `build-test`: builds again with `OFFERINGS_URL=${{ vars.ASF_OFFERINGS_URL_TEST }}` (packages and banners from the test CMS) and `VITE_SITE_URL=https://test.andreaslop.nl` (see "Own address of the test site") and uploads `dist-test`.
|
||||
1. `check`: lint, format, unit/property/axe tests (coverage threshold 100% on `src/lib/**`), build (with the committed package snapshot), audit. Uploads artifact `dist` (this is what production gets).
|
||||
2. `build-test`: builds again with `VITE_CONTACT_FORM_ENABLED=true` and `VITE_SITE_URL=https://test.andreaslop.nl` (see "Own address of the test site") and uploads `dist-test`.
|
||||
3. `deploy-test`: needs `check` and `build-test`, downloads `dist-test`, uploads to the ASF test host and runs the deployment check (served by the CMS host, admin files, POST status).
|
||||
4. `lighthouse`: against the built site with the preview stub (`--audit-route --contact-stub`).
|
||||
5. `deploy-production`: manual, from `release/*` only, uses artifact `dist`.
|
||||
@@ -52,4 +52,27 @@ The test site stands on its own: in the test build `VITE_SITE_URL` is `https://t
|
||||
|
||||
There used to be a nightly test build (`schedule`, 03:15 UTC) that baked the CMS data into the HTML for search engines. It is gone: the CMS host writes the packages, banners and hero into the first HTML of every request (cache 60 s, refreshed at once on a change; NFR-10), so a content change is visible without a rebuild. A rebuild is only needed for code and design. The nightly run also put `master` over ASF-test every night, which would undo a feature branch deployed there.
|
||||
|
||||
The production site gets the same only when the ASF production site is served by the CMS host (the IIS pipeline, later; see [go-live-checklist.md](go-live-checklist.md)). Until then production shows the committed snapshot. The test build still sets `OFFERINGS_URL`; removing that (and `VITE_SITE_URL`) is a separate follow-up once host injection is confirmed end to end.
|
||||
The production site gets the same only when the ASF production site is served by the CMS host (the IIS pipeline, later; see [go-live-checklist.md](go-live-checklist.md)). Until then production shows the committed snapshot. The test build no longer sets `OFFERINGS_URL` (removed 2026-11-18, once the host injection was confirmed on ASF-test); it still sets `VITE_SITE_URL` (own address of the test site) and `VITE_CONTACT_FORM_ENABLED`.
|
||||
|
||||
## Names of the repo variables and secrets
|
||||
|
||||
Format `{ENV}_{GROUP}_{NAME}` with `ENV` = `TEST` or `PROD`, no app part (this repo only deploys the ASF site) and no `VITE` (the pipeline maps a value to `VITE_...` in the build). Decision of Bryan, 2026-11-18; the full list is in the SLS repo (`aidlc-docs/_shared/gitea-naamgeving-variabelen.md`). Repo variables and secrets are created by SLS, not by feature sessions.
|
||||
|
||||
| Name | Kind | Used by |
|
||||
| -------------------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `TEST_DEPLOY_PATH` | variable | `deploy-test`: target folder on the Pi |
|
||||
| `TEST_HEALTH_URL` | variable | `deploy-test`: check after the deploy |
|
||||
| `PROD_DEPLOY_PATH` | variable | `deploy-production`: remote folder (default `wwwroot`) |
|
||||
| `PROD_HEALTH_URL` | variable | `deploy-production`: check after the deploy |
|
||||
| `TEST_SENTRY_DSN`, `TEST_UMAMI_SCRIPT_URL`, `TEST_UMAMI_WEBSITE_ID` | variable | `build-test` and the CSP check in `deploy-test` (as `VITE_SENTRY_DSN`, `VITE_UMAMI_SCRIPT_URL`, `VITE_UMAMI_WEBSITE_ID`, `VITE_APP_ENV=test`) |
|
||||
| `PROD_SENTRY_DSN`, `PROD_UMAMI_SCRIPT_URL`, `PROD_UMAMI_WEBSITE_ID` | variable | `check` (the production artifact; `VITE_APP_ENV=production`) |
|
||||
| `PROD_HOST_ADDRESS`, `PROD_HOST_USERNAME`, `PROD_HOST_PASSWORD` | secrets | `deploy-production`: FTP (plain FTP, no FTPS, at the hosting partner) |
|
||||
| `TEST_HOST_ADDRESS`, `TEST_HOST_PORT`, `TEST_HOST_USERNAME`, `TEST_HOST_SSH_KEY` | secrets | `deploy-test`: SSH key login to the Pi (one shared deploy key; no password) |
|
||||
|
||||
Removed: `PI_MAIN_*` (the SSH password login; the old secrets are deleted by Bryan after a green run), `DEPLOY_PATH_TEST`, `HEALTH_CHECK_URL_TEST`, `HEALTH_CHECK_URL_PRODUCTION`, `FTP_REMOTE_DIR`, `FTP_HOST`, `FTP_USERNAME`, `FTP_PASSWORD` (renamed), `ASF_OFFERINGS_URL_TEST` and `ASF_TEST_SERVED_BY_CMS` (no longer needed). The old names in the repo are removed by SLS after a green run.
|
||||
|
||||
**Monitoring per build.** Sentry and Umami settings are no longer in the code (`src/monitoring/config.ts`): every build gets them for its own environment and measures only on that environment's host (production build on `andreaslop.nl`, test build on `test.andreaslop.nl`; any other host measures nothing). The CSP origins for Umami and Sentry (`config/securityHeaders.ts`) come from the same variables, so a build without them has neither a measurement nor those origins; the build steps fail when a variable is empty. Unit and browser tests use the production values from `config/monitoringTestEnv.ts` (public values, the same as the variables); `pnpm server-config` does too, so the committed generated files carry the production CSP. The CMS host has its own copy of the origins in its environment (CMS repo).
|
||||
|
||||
## Plain FTP to production
|
||||
|
||||
The production package only offers plain FTP, no FTPS or SFTP. `deploy/upload-production.sh` therefore never tries TLS (`ftp:ssl-allow no`, passive mode) and sends the user name, the password and the files unencrypted. Measures: a separate FTP account with rights only on the folder of the prerendered pages, a unique strong password that only exists as the secret `PROD_HOST_PASSWORD`, rotating it after the first rollout, and asking the host whether SFTP or explicit FTPS can be switched on. The script uploads in three rounds (everything except HTML, then all HTML, then cleaning up old files) into the prerendered-pages folder of the CMS host (`PROD_DEPLOY_PATH`, the exact folder is still open, see `aidlc-docs/features/asf-production-iis/plan.md`, A2). It does not put a `web.config` there and deletes nothing outside that folder; the host and its `web.config` come from the CMS pipeline. `PROD_HOST_PORT` is optional (default 21).
|
||||
|
||||
@@ -11,7 +11,13 @@ What must be true before the CMS-driven parts of the site go to production. Brya
|
||||
|
||||
- [ ] Production hosting in place with the CMS host as the one entry of the website: IIS passes ALL requests to the CMS host (not only `/api/v1/*`) and serves no static files itself; the prerendered `dist/` is deployed to the CMS host ([cms-integration.md](cms-integration.md), "Hosting"). The generated IIS config and the production upload script are updated for this. Without it production keeps the committed snapshot and the console shows a 404 per page view for the API.
|
||||
- [ ] `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`).
|
||||
- [ ] The production CMS holds the real packages. The test CMS prices must never end up in the production artifact (no build fetches packages from a CMS any more).
|
||||
|
||||
## 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
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Redirects of the old WordPress addresses (redirects.json)
|
||||
|
||||
The old site of andreaslop.nl was a WordPress site. Its addresses that are still indexed get a redirect (or "gone") on the new site. The site is the source of the list; the CMS host reads it and applies it the same on test and on production. The inventory of the old addresses is in `aidlc-docs/features/asf-production-iis/oude-urls.md`.
|
||||
|
||||
## Where it comes from
|
||||
|
||||
- The list is in code: `web/config/redirectRules.ts` (with tests in `redirectRules.test.ts`).
|
||||
- `pnpm build` ends with `web/config/writeRedirects.ts`, which writes `dist/client/redirects.json`, next to `index.html`. The deploy puts it in the prerendered-pages folder of the host (on test with the rest of `dist-test`, on production with the FTP upload). `deploy/check-artifact.sh` refuses a build without it.
|
||||
- Change the list only in `redirectRules.ts`; the file is never edited by hand.
|
||||
|
||||
## Format (agreed with the CMS session, design of 2026-11-18)
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"redirects": [
|
||||
{ "from": "/portfolio-item/decoration", "to": "/portfolio", "status": 301 },
|
||||
{ "from": "/feed", "status": 410 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `from`: a path with one leading slash, without query string, fragment or `..`. The first segment is never `admin`, `health` or `api`. The host matches it case insensitive and with or without a slash at the end, so a path is given once (both forms count as a duplicate).
|
||||
- `status`: `301`, `404` or `410`.
|
||||
- `to`: required for a 301 (a path of this site, or an absolute `https://` address; this list only uses paths) and not allowed for 404 and 410. It is never the same as `from`, and never itself a rule (no chains).
|
||||
- No patterns, no wildcards, no query-string rules (decision of Bryan: only plain paths). At most 5000 rules and 1 MB.
|
||||
- The host answers a 301 with `Location` and `Cache-Control: max-age=3600`, a 404 or 410 with the 404 page of the site as the body. A rule wins over an existing file. Only GET and HEAD. `redirects.json` itself is not served.
|
||||
|
||||
## What is in the list
|
||||
|
||||
| Old address | Answer |
|
||||
| ---------------------------------------------------------------------------------------- | --------------------- |
|
||||
| `/sitemap_index.xml`, `/wp-sitemap.xml` and the five old sub-sitemaps | 301 to `/sitemap.xml` |
|
||||
| `/portfolio-item` and the 15 items of the old sitemap | 301 to `/portfolio` |
|
||||
| `/portfolio-tag/{homepage,portfolio-gallerij,simple}` | 301 to `/portfolio` |
|
||||
| `/testimonials-category/photo` | 301 to `/` |
|
||||
| `/masonry-gallery-category/test-masonry-gallery` (theme demo), `/feed`, `/comments/feed` | 410 |
|
||||
|
||||
Not in the list on purpose:
|
||||
|
||||
- The real pages (`/over-mij/`, `/portfolio/`, `/soorten-fotoshoots/`, `/contact/`): the host redirects the slash, case and `.html` variants canonically (`web/config/canonicalUrls.ts`); the slugs are the same as on the new site.
|
||||
- Query-string addresses (`/?page_id=17`, `/?s=...`): decision of Bryan.
|
||||
- Addresses that are a 404 anyway: `/wp-admin`, `/wp-login.php`, `/xmlrpc.php`, `/wp-json`, `/wp-content`, `/category`, `/tag`, `/author`. A path without a rule gives the 404 page already.
|
||||
|
||||
## Open
|
||||
|
||||
- Whether to check Google Search Console and external links (Instagram, Google Business Profile) for other old addresses before the old site is switched off; if there are any, add them to `redirectRules.ts`.
|
||||
- After the host reads the file (CMS repo, small PR of SMC): add a check to `deploy/verify-deployment.sh --cms` that `/portfolio-item/decoration/` gives a 301 to `/portfolio`.
|
||||
@@ -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) => {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// De monitoringinstellingen die de tests als productiebuild zien. De echte
|
||||
// waarden komen in de pipeline uit de Gitea-variabelen PROD_SENTRY_DSN,
|
||||
// PROD_UMAMI_SCRIPT_URL en PROD_UMAMI_WEBSITE_ID (en TEST_...); deze openbare
|
||||
// waarden zijn er hetzelfde als, zodat de gegenereerde serverconfiguratie en de
|
||||
// CSP in de tests vergelijkbaar blijven. Zie src/monitoring/config.ts.
|
||||
export const monitoringTestEnv = {
|
||||
VITE_APP_ENV: 'production',
|
||||
VITE_SENTRY_DSN:
|
||||
'https://12ec77dcc3216a98b96d3fb3dac13f66@o4511795618185216.ingest.de.sentry.io/4512282287472720',
|
||||
VITE_UMAMI_SCRIPT_URL: 'https://analytics.slpsoftware.nl/script.js',
|
||||
VITE_UMAMI_WEBSITE_ID: '3edbb7d1-4388-4f2d-9cef-11ade88ace96',
|
||||
};
|
||||
@@ -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,173 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
MAX_REDIRECTS,
|
||||
REDIRECT_FORMAT_VERSION,
|
||||
redirectProblems,
|
||||
redirectRules,
|
||||
redirectTargets,
|
||||
redirectsJson,
|
||||
type RedirectRule,
|
||||
} from './redirectRules';
|
||||
|
||||
// What the host does with the file (the format is in docs/redirect-rules.md);
|
||||
// the host has its own implementation and tests
|
||||
function resolve(rules: readonly RedirectRule[], rawPath: string) {
|
||||
const path = rawPath.toLowerCase().replace(/\/+$/, '') || '/';
|
||||
return rules.find((rule) => rule.from.toLowerCase() === path);
|
||||
}
|
||||
|
||||
describe('redirectRules', () => {
|
||||
it('has no problems', () => {
|
||||
expect(redirectProblems(redirectRules)).toEqual([]);
|
||||
});
|
||||
|
||||
it('sends every 301 to a page of the site or the sitemap', () => {
|
||||
for (const rule of redirectRules.filter((r) => r.status === 301)) {
|
||||
expect(redirectTargets).toContain(rule.to);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['/sitemap_index.xml', 301, '/sitemap.xml'],
|
||||
['/wp-sitemap.xml', 301, '/sitemap.xml'],
|
||||
['/page-sitemap.xml', 301, '/sitemap.xml'],
|
||||
['/portfolio-item-sitemap.xml', 301, '/sitemap.xml'],
|
||||
['/masonry-gallery-category-sitemap.xml', 301, '/sitemap.xml'],
|
||||
['/portfolio-tag-sitemap.xml', 301, '/sitemap.xml'],
|
||||
['/testimonials-category-sitemap.xml', 301, '/sitemap.xml'],
|
||||
['/portfolio-item/', 301, '/portfolio'],
|
||||
['/portfolio-item/decoration/', 301, '/portfolio'],
|
||||
['/portfolio-item/wedding-dress/', 301, '/portfolio'],
|
||||
['/portfolio-item/best-girls/', 301, '/portfolio'],
|
||||
['/portfolio-item/mm-1/', 301, '/portfolio'],
|
||||
['/portfolio-item/wedding-cake/', 301, '/portfolio'],
|
||||
['/portfolio-item/mm2/', 301, '/portfolio'],
|
||||
['/portfolio-item/cake-smash-1/', 301, '/portfolio'],
|
||||
['/portfolio-item/hairstyles/', 301, '/portfolio'],
|
||||
['/portfolio-item/360/', 301, '/portfolio'],
|
||||
['/portfolio-item/366/', 301, '/portfolio'],
|
||||
['/portfolio-item/353/', 301, '/portfolio'],
|
||||
['/portfolio-item/homepage-foto/', 301, '/portfolio'],
|
||||
['/portfolio-item/getting-ready/', 301, '/portfolio'],
|
||||
['/portfolio-item/m1/', 301, '/portfolio'],
|
||||
['/portfolio-item/f1/', 301, '/portfolio'],
|
||||
['/Portfolio-Item/MM1', undefined, undefined],
|
||||
['/portfolio-item/MM-1', 301, '/portfolio'],
|
||||
['/portfolio-tag/homepage/', 301, '/portfolio'],
|
||||
['/portfolio-tag/portfolio-gallerij/', 301, '/portfolio'],
|
||||
['/portfolio-tag/simple/', 301, '/portfolio'],
|
||||
['/testimonials-category/photo/', 301, '/'],
|
||||
['/masonry-gallery-category/test-masonry-gallery/', 410, undefined],
|
||||
['/feed/', 410, undefined],
|
||||
['/comments/feed/', 410, undefined],
|
||||
])('%s gives %s %s', (path, status, to) => {
|
||||
const rule = resolve(redirectRules, path);
|
||||
expect(rule?.status).toBe(status);
|
||||
expect(rule?.to).toBe(to);
|
||||
});
|
||||
|
||||
it('leaves the real pages and their canonical variants to the host', () => {
|
||||
for (const path of [
|
||||
'/',
|
||||
'/over-mij',
|
||||
'/over-mij/',
|
||||
'/portfolio',
|
||||
'/soorten-fotoshoots/newborn',
|
||||
'/contact',
|
||||
'/robots.txt',
|
||||
'/sitemap.xml',
|
||||
'/assets/index-abc.js',
|
||||
'/admin/',
|
||||
'/api/v1/offerings',
|
||||
'/wp-login.php',
|
||||
]) {
|
||||
expect(resolve(redirectRules, path)).toBeUndefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('redirectProblems', () => {
|
||||
const rule = (extra: Partial<RedirectRule>): RedirectRule => ({
|
||||
from: '/a',
|
||||
to: '/b',
|
||||
status: 301,
|
||||
...extra,
|
||||
});
|
||||
|
||||
it.each([
|
||||
[rule({ from: 'a' }), 'not a usable path'],
|
||||
[rule({ from: '/' }), 'not a usable path'],
|
||||
[rule({ from: '//a' }), 'not a usable path'],
|
||||
[rule({ from: '/a/../b' }), 'not a usable path'],
|
||||
[rule({ from: '/a?x=1' }), 'not a usable path'],
|
||||
[rule({ from: '/a#b' }), 'not a usable path'],
|
||||
[rule({ from: '/Admin/x' }), 'answered by the host'],
|
||||
[rule({ from: '/api/v1' }), 'answered by the host'],
|
||||
[rule({ from: '/health' }), 'answered by the host'],
|
||||
[rule({ to: undefined }), 'needs a path'],
|
||||
[rule({ to: 'https://evil.example/' }), 'needs a path'],
|
||||
[rule({ to: '//evil.example' }), 'needs a path'],
|
||||
[rule({ to: '/A/' }), 'the same'],
|
||||
[rule({ status: 410 }), 'only a 301 has a target'],
|
||||
[rule({ status: 404 }), 'only a 301 has a target'],
|
||||
])('flags %j', (bad, text) => {
|
||||
expect(redirectProblems([bad]).join()).toContain(text);
|
||||
});
|
||||
|
||||
it('flags a duplicate, also in another case or with a slash', () => {
|
||||
expect(redirectProblems([rule({}), rule({})]).join()).toContain(
|
||||
'duplicate',
|
||||
);
|
||||
expect(
|
||||
redirectProblems([
|
||||
rule({ from: '/A' }),
|
||||
rule({ from: '/a/' }),
|
||||
]).join(),
|
||||
).toContain('duplicate');
|
||||
});
|
||||
|
||||
it('flags a chain', () => {
|
||||
expect(
|
||||
redirectProblems([
|
||||
rule({ from: '/a', to: '/b' }),
|
||||
rule({ from: '/b', to: '/c' }),
|
||||
]).join(),
|
||||
).toContain('is a rule too');
|
||||
});
|
||||
|
||||
it('flags too many rules', () => {
|
||||
const many = Array.from({ length: MAX_REDIRECTS + 1 }, (_, i) =>
|
||||
rule({ from: `/p${i}`, to: '/x' }),
|
||||
);
|
||||
expect(redirectProblems(many).join()).toContain('more than');
|
||||
});
|
||||
|
||||
it('accepts a 404 and a 410 without a target', () => {
|
||||
expect(
|
||||
redirectProblems([
|
||||
rule({ status: 404, to: undefined }),
|
||||
rule({ from: '/b', status: 410, to: undefined }),
|
||||
]),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('redirectsJson', () => {
|
||||
it('writes the version and the redirects', () => {
|
||||
const parsed = JSON.parse(redirectsJson());
|
||||
expect(parsed.version).toBe(REDIRECT_FORMAT_VERSION);
|
||||
expect(parsed.redirects).toEqual(redirectRules);
|
||||
expect(Object.keys(parsed)).toEqual(['version', 'redirects']);
|
||||
expect(redirectsJson().endsWith('\n')).toBe(true);
|
||||
});
|
||||
|
||||
it('stays far below the size limit of the host', () => {
|
||||
expect(redirectsJson().length).toBeLessThan(100_000);
|
||||
});
|
||||
|
||||
it('refuses a list with problems', () => {
|
||||
expect(() => redirectsJson([{ from: 'x', status: 404 }])).toThrow(
|
||||
'Invalid redirect rules',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
// Redirects for the old WordPress addresses of andreaslop.nl (decision of
|
||||
// Bryan, 2026-11-18; the inventory is aidlc-docs/features/asf-production-iis/
|
||||
// oude-urls.md). The site is the source: this list is written into the build
|
||||
// as redirects.json and the CMS host reads it, the same on test and on
|
||||
// production. The format is the one of the host (design of SMC, 2026-11-18):
|
||||
// exact paths only, no patterns; see docs/redirect-rules.md.
|
||||
//
|
||||
// Not in this list: the slash, case and .html variants of the real pages
|
||||
// (/over-mij/ and so on; the host redirects those canonically, see
|
||||
// config/canonicalUrls.ts), query-string addresses (?page_id=, decision of
|
||||
// Bryan) and addresses that are a 404 anyway (/wp-admin, /wp-login.php,
|
||||
// /xmlrpc.php, /wp-json, /wp-content, /category, /tag, /author, /?s=): an
|
||||
// unknown path gives the 404 page without a rule.
|
||||
import { pagePaths } from './canonicalUrls.ts';
|
||||
|
||||
export type RedirectStatus = 301 | 404 | 410;
|
||||
|
||||
export interface RedirectRule {
|
||||
// A path with one leading slash. The host matches it case insensitive and
|
||||
// with or without a slash at the end (so give it once).
|
||||
from: string;
|
||||
// Only for 301: a path of this site
|
||||
to?: string;
|
||||
status: RedirectStatus;
|
||||
}
|
||||
|
||||
export const REDIRECT_FORMAT_VERSION = 1;
|
||||
export const MAX_REDIRECTS = 5000;
|
||||
|
||||
// The host answers these paths itself; a rule there would never be read
|
||||
const RESERVED_FIRST_SEGMENTS = ['admin', 'health', 'api'];
|
||||
|
||||
const permanent = (from: string, to: string): RedirectRule => ({
|
||||
from,
|
||||
to,
|
||||
status: 301,
|
||||
});
|
||||
const gone = (from: string): RedirectRule => ({ from, status: 410 });
|
||||
|
||||
// The old sitemaps: search engines find the new one
|
||||
const sitemaps = [
|
||||
'/sitemap_index.xml',
|
||||
'/wp-sitemap.xml',
|
||||
'/page-sitemap.xml',
|
||||
'/portfolio-item-sitemap.xml',
|
||||
'/masonry-gallery-category-sitemap.xml',
|
||||
'/portfolio-tag-sitemap.xml',
|
||||
'/testimonials-category-sitemap.xml',
|
||||
];
|
||||
|
||||
// The gallery items of the theme (from the old sitemap, 2026-11-18): the
|
||||
// portfolio is the nearest page
|
||||
const portfolioItems = [
|
||||
'decoration',
|
||||
'wedding-dress',
|
||||
'best-girls',
|
||||
'mm-1',
|
||||
'wedding-cake',
|
||||
'mm2',
|
||||
'cake-smash-1',
|
||||
'hairstyles',
|
||||
'360',
|
||||
'366',
|
||||
'353',
|
||||
'homepage-foto',
|
||||
'getting-ready',
|
||||
'm1',
|
||||
'f1',
|
||||
];
|
||||
const portfolioTags = ['homepage', 'portfolio-gallerij', 'simple'];
|
||||
|
||||
export const redirectRules: readonly RedirectRule[] = [
|
||||
...sitemaps.map((from) => permanent(from, '/sitemap.xml')),
|
||||
permanent('/portfolio-item', '/portfolio'),
|
||||
...portfolioItems.map((name) =>
|
||||
permanent(`/portfolio-item/${name}`, '/portfolio'),
|
||||
),
|
||||
...portfolioTags.map((name) =>
|
||||
permanent(`/portfolio-tag/${name}`, '/portfolio'),
|
||||
),
|
||||
// The theme archive of testimonials: they are on the home page
|
||||
permanent('/testimonials-category/photo', '/'),
|
||||
// Theme demo content and the feeds: no equivalent and no berichten
|
||||
gone('/masonry-gallery-category/test-masonry-gallery'),
|
||||
gone('/feed'),
|
||||
gone('/comments/feed'),
|
||||
];
|
||||
|
||||
const pathPattern = /^\/[A-Za-z0-9._~/%-]*$/;
|
||||
const isPath = (value: string): boolean =>
|
||||
pathPattern.test(value) && !value.startsWith('//') && !value.includes('..');
|
||||
|
||||
// What the host compares: lower case, without a slash at the end
|
||||
const key = (path: string): string =>
|
||||
path.toLowerCase().replace(/\/+$/, '') || '/';
|
||||
|
||||
// The reasons a rule list is not usable; empty when it is. The host validates
|
||||
// the file again; the tests check this list and what is written from it.
|
||||
export function redirectProblems(rules: readonly RedirectRule[]): string[] {
|
||||
const problems: string[] = [];
|
||||
if (rules.length > MAX_REDIRECTS) {
|
||||
problems.push(`more than ${MAX_REDIRECTS} rules`);
|
||||
}
|
||||
const froms = new Map<string, RedirectRule>();
|
||||
rules.forEach((rule, index) => {
|
||||
const label = `rule ${index + 1} (${rule.from})`;
|
||||
if (!isPath(rule.from) || rule.from === '/') {
|
||||
problems.push(`${label}: from is not a usable path`);
|
||||
return;
|
||||
}
|
||||
const first = key(rule.from).split('/')[1];
|
||||
if (RESERVED_FIRST_SEGMENTS.includes(first)) {
|
||||
problems.push(`${label}: ${first} is answered by the host itself`);
|
||||
}
|
||||
if (froms.has(key(rule.from))) problems.push(`${label}: duplicate`);
|
||||
froms.set(key(rule.from), rule);
|
||||
if (rule.status === 301) {
|
||||
if (!rule.to || !isPath(rule.to)) {
|
||||
problems.push(
|
||||
`${label}: a 301 needs a path of this site in to`,
|
||||
);
|
||||
} else if (key(rule.to) === key(rule.from)) {
|
||||
problems.push(`${label}: from and to are the same`);
|
||||
}
|
||||
} else if (rule.to !== undefined) {
|
||||
problems.push(`${label}: only a 301 has a target`);
|
||||
}
|
||||
});
|
||||
// No chains: a target is never itself a rule (the host would flatten it,
|
||||
// or it is gone)
|
||||
for (const rule of rules) {
|
||||
if (rule.status === 301 && rule.to && froms.has(key(rule.to))) {
|
||||
problems.push(
|
||||
`rule ${rule.from}: the target ${rule.to} is a rule too`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// The pages a 301 may point to: every page of the site and the sitemap
|
||||
export const redirectTargets: readonly string[] = [
|
||||
...pagePaths,
|
||||
'/sitemap.xml',
|
||||
];
|
||||
|
||||
export function redirectsJson(
|
||||
rules: readonly RedirectRule[] = redirectRules,
|
||||
): string {
|
||||
const problems = redirectProblems(rules);
|
||||
if (problems.length > 0) {
|
||||
throw new Error(`Invalid redirect rules:\n${problems.join('\n')}`);
|
||||
}
|
||||
return `${JSON.stringify({ version: REDIRECT_FORMAT_VERSION, redirects: rules }, null, 2)}\n`;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { contentSecurityPolicy, securityHeaders } from './securityHeaders';
|
||||
|
||||
const umami = 'https://analytics.slpsoftware.nl';
|
||||
@@ -12,7 +12,17 @@ const captchaFrames = [
|
||||
const directive = (csp: string, name: string) =>
|
||||
csp.split('; ').find((d) => d.startsWith(name + ' ')) ?? '';
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
describe('securityHeaders', () => {
|
||||
it('noemt Umami en Sentry niet zonder monitoringinstellingen in de build', () => {
|
||||
vi.stubEnv('VITE_SENTRY_DSN', '');
|
||||
const csp = contentSecurityPolicy('production');
|
||||
expect(csp).not.toContain(umami);
|
||||
expect(csp).not.toContain(sentry);
|
||||
expect(directive(csp, 'script-src')).toBe("script-src 'self'");
|
||||
});
|
||||
|
||||
it('productie-CSP heeft geen onveilige uitzonderingen voor scripts', () => {
|
||||
const csp = contentSecurityPolicy('production');
|
||||
expect(csp).not.toContain('unsafe-eval');
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// HTTP-securityheaders voor de Vite dev- en preview-server. De productieset is
|
||||
// ook het voorschrift voor de toekomstige host (zie NFR-SEC-01/02).
|
||||
|
||||
import { sentryIngestOrigin, umamiOrigin } from '../src/monitoring/config.ts';
|
||||
import { monitoringOrigins } from '../src/monitoring/config.ts';
|
||||
|
||||
type Mode = 'production' | 'development';
|
||||
|
||||
@@ -21,19 +21,24 @@ export const captchaFrameOrigins = [
|
||||
'https://global1.frcapi.com',
|
||||
];
|
||||
|
||||
const productionCsp: Record<string, string[]> = {
|
||||
'default-src': ["'self'"],
|
||||
'script-src': ["'self'", umamiOrigin],
|
||||
'style-src': ["'self'", "'unsafe-inline'"],
|
||||
'img-src': ["'self'", 'data:'],
|
||||
'font-src': ["'self'"],
|
||||
'connect-src': ["'self'", umamiOrigin, sentryIngestOrigin],
|
||||
'frame-src': captchaFrameOrigins,
|
||||
'object-src': ["'none'"],
|
||||
'base-uri': ["'self'"],
|
||||
'form-action': ["'self'"],
|
||||
'frame-ancestors': ["'none'"],
|
||||
};
|
||||
// De herkomsten van Umami en Sentry komen uit de build-omgeving (zie
|
||||
// src/monitoring/config.ts); zonder die instellingen staan ze er niet in.
|
||||
function productionCsp(): Record<string, string[]> {
|
||||
const origins = monitoringOrigins();
|
||||
return {
|
||||
'default-src': ["'self'"],
|
||||
'script-src': ["'self'", ...origins.umami],
|
||||
'style-src': ["'self'", "'unsafe-inline'"],
|
||||
'img-src': ["'self'", 'data:'],
|
||||
'font-src': ["'self'"],
|
||||
'connect-src': ["'self'", ...origins.umami, ...origins.sentry],
|
||||
'frame-src': captchaFrameOrigins,
|
||||
'object-src': ["'none'"],
|
||||
'base-uri': ["'self'"],
|
||||
'form-action': ["'self'"],
|
||||
'frame-ancestors': ["'none'"],
|
||||
};
|
||||
}
|
||||
|
||||
// Alleen wat de Vite dev-server zelf nodig heeft: een inline script voor
|
||||
// React Refresh en een websocket voor hot reload.
|
||||
@@ -43,7 +48,7 @@ const developmentExtras: Record<string, string[]> = {
|
||||
};
|
||||
|
||||
export function contentSecurityPolicy(mode: Mode): string {
|
||||
return Object.entries(productionCsp)
|
||||
return Object.entries(productionCsp())
|
||||
.map(([directive, sources]) => {
|
||||
const extra =
|
||||
mode === 'development'
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
// Writes redirects.json next to the pages of the build (the last step of
|
||||
// pnpm build, after externalizeInlineScripts). Runs directly with Node.
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { redirectsJson } from './redirectRules.ts';
|
||||
|
||||
const outDir = process.argv[2] ?? join('dist', 'client');
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
writeFileSync(join(outDir, 'redirects.json'), redirectsJson());
|
||||
console.log(`redirects.json written to ${outDir}`);
|
||||
@@ -2,8 +2,15 @@
|
||||
// Draait direct met Node (type stripping), zonder extra tooling.
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
import { monitoringTestEnv } from './monitoringTestEnv.ts';
|
||||
import { serverConfigFiles } from './serverConfig.ts';
|
||||
|
||||
// The committed files carry the CSP of the production build; the origins of
|
||||
// Umami and Sentry come from the environment (src/monitoring/config.ts)
|
||||
for (const [name, value] of Object.entries(monitoringTestEnv)) {
|
||||
process.env[name] ??= value;
|
||||
}
|
||||
|
||||
for (const [path, generate] of Object.entries(serverConfigFiles)) {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, generate());
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -22,7 +22,7 @@ fail() {
|
||||
failures=$((failures + 1))
|
||||
}
|
||||
|
||||
for file in index.html 404.html over-mij.html; do
|
||||
for file in index.html 404.html over-mij.html redirects.json; do
|
||||
if [ -f "$dist/$file" ]; then
|
||||
echo "gevonden: $file"
|
||||
else
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
# Upload naar productie in drie rondes (BR-HST-14, 15; FR-PR-18).
|
||||
# Gebruik: upload-production.sh <dist-map> <doelmap-op-de-server>
|
||||
# Verbinding: FTP_HOST, FTP_USER en LFTP_PASSWORD uit de omgeving (FTPS).
|
||||
# De doelmap is de map met voorgerenderde pagina's van de CMS-host; de host
|
||||
# (en zijn web.config) staat er los van en wordt door de CMS-pijplijn gedeployd.
|
||||
# Verbinding: FTP_HOST, FTP_USER en LFTP_PASSWORD uit de omgeving, optioneel
|
||||
# FTP_PORT. Gewone FTP, geen FTPS: het productiepakket biedt alleen dat. De
|
||||
# gegevens gaan dus onversleuteld over het netwerk (zie docs/deploy-and-ci.md,
|
||||
# "Plain FTP"); daarom nooit TLS proberen en een eigen FTP-account met rechten
|
||||
# alleen op deze map.
|
||||
# Alleen voor de test: LFTP_OPEN (bijvoorbeeld file:///) vervangt de
|
||||
# verbinding, en UPLOAD_PASS=1|2|3 voert maar één ronde uit.
|
||||
set -euo pipefail
|
||||
@@ -36,7 +42,6 @@ done
|
||||
|
||||
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
bash "$here/check-artifact.sh" "$dist"
|
||||
cp "$here/iis/web.config" "$dist/web.config"
|
||||
|
||||
pass="${UPLOAD_PASS:-all}"
|
||||
case "$pass" in
|
||||
@@ -48,7 +53,7 @@ wants() { [ "$pass" = all ] || [ "$pass" = "$1" ]; }
|
||||
# Geen back-ups: lftp zet standaard een kopie met een tijdstempel
|
||||
# (web.config~20261101221045~) naast elk bestand dat het overschrijft. Op de
|
||||
# host zou elke deploy er een achterlaten, bereikbaar voor wie de naam raadt.
|
||||
settings="set ftp:ssl-force true; set ftp:ssl-protect-data true; set net:max-retries 3; set xfer:make-backup no;"
|
||||
settings="set ftp:ssl-allow no; set ftp:passive-mode on; set net:max-retries 3; set xfer:make-backup no;"
|
||||
|
||||
# Elke opdracht krijgt een eigen lftp-sessie, zodat het script bij een mislukte
|
||||
# ronde stopt (set -e) voordat de volgende ronde begint: de HTML gaat nooit
|
||||
@@ -60,22 +65,25 @@ run_lftp() {
|
||||
else
|
||||
: "${FTP_HOST:?FTP_HOST ontbreekt}" "${FTP_USER:?FTP_USER ontbreekt}"
|
||||
: "${LFTP_PASSWORD:?LFTP_PASSWORD ontbreekt}"
|
||||
lftp --env-password -u "$FTP_USER" "$FTP_HOST" -e "$commands"
|
||||
local port=()
|
||||
if [ -n "${FTP_PORT:-}" ]; then
|
||||
[[ "$FTP_PORT" =~ ^[0-9]+$ ]] || { echo "Ongeldige FTP_PORT" >&2; exit 2; }
|
||||
port=(-p "$FTP_PORT")
|
||||
fi
|
||||
lftp --env-password -u "$FTP_USER" "${port[@]}" "$FTP_HOST" -e "$commands"
|
||||
fi
|
||||
}
|
||||
|
||||
# Ronde 1: alles behalve HTML en web.config, dus ook /assets. Nieuwe
|
||||
# bestanden met hash in de naam storen de oude release niet.
|
||||
# Ronde 1: alles behalve HTML, dus ook /assets. Nieuwe bestanden met hash in
|
||||
# de naam storen de oude release niet.
|
||||
if wants 1; then
|
||||
echo "== Ronde 1: alles behalve HTML en web.config"
|
||||
run_lftp "mirror --reverse --verbose --exclude-glob '*.html' --exclude-glob web.config $dist/ $remote/;"
|
||||
echo "== Ronde 1: alles behalve HTML"
|
||||
run_lftp "mirror --reverse --verbose --exclude-glob '*.html' $dist/ $remote/;"
|
||||
fi
|
||||
# Ronde 2: web.config vlak voor de HTML (de regels passen bij de nieuwe
|
||||
# bestanden), dan alle HTML, ook de geneste pagina's en 404.html. Pas nu
|
||||
# verwijst iets naar de nieuwe assets.
|
||||
# Ronde 2: alle HTML, ook de geneste pagina's en 404.html. Pas nu verwijst
|
||||
# iets naar de nieuwe assets.
|
||||
if wants 2; then
|
||||
echo "== Ronde 2: web.config en alle HTML"
|
||||
run_lftp "put -O $remote $dist/web.config;"
|
||||
echo "== Ronde 2: alle HTML"
|
||||
run_lftp "mirror --reverse --verbose --include-glob '*.html' $dist/ $remote/;"
|
||||
fi
|
||||
# Ronde 3: opruimen als laatste, zodat bezoekers met de oude HTML hun oude
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
# headers staan met de exacte waarde op elk antwoord (pagina, asset,
|
||||
# 301, 404, robots.txt), cachebeleid, alleen gzip (nooit br), een
|
||||
# procentgecodeerd pad blijft gecodeerd, en /admin, /health en
|
||||
# /api/v1/System/capabilities (zonder Offerings) antwoorden.
|
||||
# /api/v1/System/capabilities (met Offerings en Hero) antwoorden.
|
||||
set -euo pipefail
|
||||
|
||||
if [ "$#" -lt 2 ] || [ "$#" -gt 4 ]; then
|
||||
@@ -272,7 +272,7 @@ if [ "$cms_mode" -eq 1 ]; then
|
||||
fail "POST /: status $status, verwacht 405"
|
||||
fi
|
||||
|
||||
# De CMS-routes: health, admin, API (zonder Offerings), onbekend API-pad
|
||||
# De CMS-routes: health, admin, API (met Offerings en Hero), onbekend API-pad
|
||||
fetch /health
|
||||
if [ "$status" != "200" ]; then fail "/health: status $status, verwacht 200"; fi
|
||||
|
||||
@@ -301,8 +301,13 @@ if [ "$cms_mode" -eq 1 ]; then
|
||||
fetch /api/v1/System/capabilities
|
||||
if [ "$status" != "200" ]; then
|
||||
fail "/api/v1/System/capabilities: status $status, verwacht 200"
|
||||
elif grep -qi 'offerings' "$work/body"; then
|
||||
fail "/api/v1/System/capabilities noemt Offerings; die module hoort voor ASF uit te staan"
|
||||
else
|
||||
# De site haalt pakketten, banners en de hero uit deze modules
|
||||
for module in Offerings Hero; do
|
||||
if ! grep -qi "\"$module\"" "$work/body"; then
|
||||
fail "/api/v1/System/capabilities noemt $module niet; de site heeft die module nodig"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# Een onbekend API-pad is een API-404, nooit de website
|
||||
|
||||
@@ -539,7 +539,6 @@ describe.skipIf(toolsMissing || lftpMissing)('upload-production.sh', () => {
|
||||
'robots.txt',
|
||||
'soorten-fotoshoots/newborn.html',
|
||||
'stale.txt',
|
||||
'web.config',
|
||||
]);
|
||||
|
||||
const third = await upload(dist, target, '3');
|
||||
@@ -551,7 +550,6 @@ describe.skipIf(toolsMissing || lftpMissing)('upload-production.sh', () => {
|
||||
'over-mij.html',
|
||||
'robots.txt',
|
||||
'soorten-fotoshoots/newborn.html',
|
||||
'web.config',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -567,19 +565,18 @@ describe.skipIf(toolsMissing || lftpMissing)('upload-production.sh', () => {
|
||||
);
|
||||
expect(rounds).toEqual(['1', '2', '3']);
|
||||
|
||||
const expected = [...validFiles, 'web.config'].sort();
|
||||
const expected = [...validFiles].sort();
|
||||
expect(await tree(target)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('laat bij een tweede deploy geen back-upbestanden met ~ achter', async () => {
|
||||
const { dist, target } = await setup();
|
||||
expect((await upload(dist, target)).code).toBe(0);
|
||||
// Nu bestaat web.config al op de host, en alles wordt overschreven
|
||||
// Nu bestaat alles al op de host en wordt het overschreven
|
||||
await write(dist, 'robots.txt', 'nieuwe inhoud');
|
||||
expect((await upload(dist, target)).code).toBe(0);
|
||||
const files = await tree(target);
|
||||
expect(files.filter((file) => file.includes('~'))).toEqual([]);
|
||||
expect(files).toContain('web.config');
|
||||
});
|
||||
|
||||
it('weigert een ongeldige build en uploadt dan niets', async () => {
|
||||
@@ -590,13 +587,12 @@ describe.skipIf(toolsMissing || lftpMissing)('upload-production.sh', () => {
|
||||
expect(await tree(target)).toEqual(['stale.txt']);
|
||||
});
|
||||
|
||||
it('neemt de web.config uit deploy/iis over', async () => {
|
||||
it('zet geen web.config op de server: die hoort bij de CMS-host', async () => {
|
||||
const { dist, target } = await setup();
|
||||
const run = await upload(dist, target);
|
||||
expect(run.code).toBe(0);
|
||||
expect(await readFile(join(target, 'web.config'), 'utf8')).toBe(
|
||||
await readFile(join(deployDir, 'iis/web.config'), 'utf8'),
|
||||
);
|
||||
expect(existsSync(join(target, 'web.config'))).toBe(false);
|
||||
expect(existsSync(join(dist, 'web.config'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -666,7 +662,7 @@ touch '${slash(marker)}'
|
||||
},
|
||||
);
|
||||
|
||||
it('zet in elke lftp-sessie de back-ups uit en de TLS-eisen aan', async () => {
|
||||
it('zet in elke lftp-sessie de back-ups uit en TLS uit (gewone FTP)', async () => {
|
||||
const dist = await makeDist();
|
||||
const bin = await makeTemp('andreaslop-fakebin-');
|
||||
const log = join(bin, 'opdrachten');
|
||||
@@ -690,11 +686,53 @@ printf '%s\\n' "$2" >> '${slash(log)}'
|
||||
const sessions = (await readFile(log, 'utf8'))
|
||||
.split('\n')
|
||||
.filter(Boolean);
|
||||
// Ronde 1, web.config, ronde 2 (HTML) en ronde 3
|
||||
expect(sessions).toHaveLength(4);
|
||||
// Ronde 1, ronde 2 (HTML) en ronde 3
|
||||
expect(sessions).toHaveLength(3);
|
||||
for (const commands of sessions) {
|
||||
expect(commands).toContain('set xfer:make-backup no;');
|
||||
expect(commands).toContain('set ftp:ssl-force true;');
|
||||
expect(commands).toContain('set ftp:ssl-allow no;');
|
||||
expect(commands).toContain('set ftp:passive-mode on;');
|
||||
expect(commands).not.toContain('ssl-force');
|
||||
}
|
||||
});
|
||||
|
||||
it('geeft FTP_PORT door aan lftp en weigert een ongeldige poort', async () => {
|
||||
const dist = await makeDist();
|
||||
const bin = await makeTemp('andreaslop-fakebin-');
|
||||
const log = join(bin, 'argumenten');
|
||||
await writeFile(
|
||||
join(bin, 'lftp'),
|
||||
`#!/bin/sh
|
||||
printf '%s\n' "$*" >> '${slash(log)}'
|
||||
`,
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
const env = {
|
||||
PATH: `${bin}${delimiter}${process.env.PATH ?? ''}`,
|
||||
FTP_HOST: 'ftp.example.test',
|
||||
FTP_USER: 'gebruiker',
|
||||
LFTP_PASSWORD: 'geheim',
|
||||
};
|
||||
const bad = await runScript(
|
||||
'upload-production.sh',
|
||||
[basename(dist), 'wwwroot'],
|
||||
{ ...env, FTP_PORT: '21; rm -rf' },
|
||||
dirname(dist),
|
||||
);
|
||||
expect(bad.code).toBe(2);
|
||||
expect(existsSync(log)).toBe(false);
|
||||
|
||||
const good = await runScript(
|
||||
'upload-production.sh',
|
||||
[basename(dist), 'wwwroot'],
|
||||
{ ...env, FTP_PORT: '2121' },
|
||||
dirname(dist),
|
||||
);
|
||||
expect(good.code).toBe(0);
|
||||
for (const line of (await readFile(log, 'utf8'))
|
||||
.split('\n')
|
||||
.filter(Boolean)) {
|
||||
expect(line).toContain('-u gebruiker -p 2121 ftp.example.test');
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
"packageManager": "pnpm@12.11.2",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "node config/fetchOfferings.ts && tsc && vite build && node config/externalizeInlineScripts.ts",
|
||||
"build": "node config/fetchOfferings.ts && tsc && vite build && node config/externalizeInlineScripts.ts && node config/writeRedirects.ts",
|
||||
"preview": "node config/previewServer.ts",
|
||||
"e2e": "vitest run --config vitest.e2e.config.ts",
|
||||
"postinstall": "chakra typegen ./src/theme.ts",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import UmamiAnalytics from './UmamiAnalytics';
|
||||
|
||||
const umamiScripts = () =>
|
||||
@@ -8,6 +8,7 @@ const umamiScripts = () =>
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
umamiScripts().forEach((script) => script.remove());
|
||||
});
|
||||
|
||||
@@ -18,18 +19,28 @@ describe('UmamiAnalytics', () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
['andreaslop.nl', '3edbb7d1-4388-4f2d-9cef-11ade88ace96'],
|
||||
['test.andreaslop.nl', '7fb301ab-6ecc-4aea-beee-71bcb6009bfe'],
|
||||
])('telt op %s met de juiste website', (hostname, websiteId) => {
|
||||
render(<UmamiAnalytics hostname={hostname} />);
|
||||
['production', 'andreaslop.nl', '3edbb7d1-4388-4f2d-9cef-11ade88ace96'],
|
||||
['test', 'test.andreaslop.nl', 'test-website'],
|
||||
])(
|
||||
'telt in de %s-build op %s met de juiste website',
|
||||
(environment, hostname, websiteId) => {
|
||||
vi.stubEnv('VITE_APP_ENV', environment);
|
||||
vi.stubEnv('VITE_UMAMI_WEBSITE_ID', websiteId);
|
||||
render(<UmamiAnalytics hostname={hostname} />);
|
||||
|
||||
const [script] = umamiScripts();
|
||||
expect(script.defer).toBe(true);
|
||||
expect(script.dataset).toMatchObject({
|
||||
websiteId,
|
||||
domains: hostname,
|
||||
doNotTrack: 'true',
|
||||
});
|
||||
const [script] = umamiScripts();
|
||||
expect(script.defer).toBe(true);
|
||||
expect(script.dataset).toMatchObject({
|
||||
websiteId,
|
||||
domains: hostname,
|
||||
doNotTrack: 'true',
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('voegt geen script toe op de host van de andere omgeving', () => {
|
||||
render(<UmamiAnalytics hostname="test.andreaslop.nl" />);
|
||||
expect(umamiScripts()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('voegt het script maar één keer toe', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect } from 'react';
|
||||
import { monitoringFor, umamiOrigin } from '@/monitoring/config';
|
||||
import { monitoringFor } from '@/monitoring/config';
|
||||
|
||||
const SCRIPT_ELEMENT_ID = 'umami-analytics-script';
|
||||
|
||||
@@ -16,7 +16,7 @@ export default function UmamiAnalytics({ hostname }: { hostname?: string }) {
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.id = SCRIPT_ELEMENT_ID;
|
||||
script.src = `${umamiOrigin}/script.js`;
|
||||
script.src = monitoring.umamiScriptUrl;
|
||||
script.defer = true;
|
||||
script.dataset.websiteId = monitoring.umamiWebsiteId;
|
||||
script.dataset.domains = host;
|
||||
|
||||
@@ -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)]);
|
||||
@@ -135,6 +135,24 @@ describe('Hero', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('laat de eerste foto inzoomen zolang hij de actieve is', async () => {
|
||||
const { container } = await renderWithProviders(
|
||||
<Hero content={heroContent} socials={siteContent.socials} />,
|
||||
);
|
||||
const picture = container.querySelector('.cms-hero-picture')!;
|
||||
expect(picture).toHaveAttribute('data-zoom');
|
||||
expect(picture).not.toHaveAttribute('aria-hidden');
|
||||
await userEvent.click(
|
||||
screen.getByRole('button', { name: 'Volgende foto' }),
|
||||
);
|
||||
expect(picture).not.toHaveAttribute('data-zoom');
|
||||
expect(picture).toHaveAttribute('aria-hidden', 'true');
|
||||
await userEvent.click(
|
||||
screen.getByRole('button', { name: 'Vorige foto' }),
|
||||
);
|
||||
expect(picture).toHaveAttribute('data-zoom');
|
||||
});
|
||||
|
||||
it('heeft pijlen met een toegankelijke naam', async () => {
|
||||
await renderWithProviders(
|
||||
<Hero content={heroContent} socials={siteContent.socials} />,
|
||||
|
||||
+216
-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,60 @@ 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, and it zooms (data-zoom, see .cms-hero-image) while it is the
|
||||
// active one
|
||||
useEffect(() => {
|
||||
const picture = section.current?.querySelector('.cms-hero-picture');
|
||||
if (active === 0) {
|
||||
picture?.removeAttribute('aria-hidden');
|
||||
picture?.setAttribute('data-zoom', '');
|
||||
} else {
|
||||
picture?.setAttribute('aria-hidden', 'true');
|
||||
picture?.removeAttribute('data-zoom');
|
||||
}
|
||||
}, [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 +196,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,
|
||||
};
|
||||
}
|
||||
@@ -45,7 +45,7 @@ describe('useHeroSlider', () => {
|
||||
expect(result.current.active).toBe(0);
|
||||
});
|
||||
|
||||
it('afspelen via de knop heft ook de pauze door hover op', () => {
|
||||
it('pauzeert niet bij hover met de muis, wel via de knop', () => {
|
||||
let slider!: ReturnType<typeof useHeroSlider>;
|
||||
function Probe() {
|
||||
slider = useHeroSlider(8);
|
||||
@@ -53,11 +53,11 @@ describe('useHeroSlider', () => {
|
||||
}
|
||||
const { getByTestId } = render(<Probe />);
|
||||
fireEvent.pointerEnter(getByTestId('hero'), { pointerType: 'mouse' });
|
||||
expect(slider.paused).toBe(true);
|
||||
fireEvent.mouseEnter(getByTestId('hero'));
|
||||
expect(slider.paused).toBe(false);
|
||||
|
||||
act(() => slider.toggleStopped());
|
||||
act(() => slider.toggleStopped());
|
||||
expect(slider.paused).toBe(false);
|
||||
expect(slider.paused).toBe(true);
|
||||
});
|
||||
|
||||
it('afspelen via de knop heft ook de pauze door toetsenbordfocus op', () => {
|
||||
|
||||
@@ -22,7 +22,6 @@ export default function useHeroSlider(count: number) {
|
||||
const [announcement, setAnnouncement] = useState<HeroAnnouncement>(null);
|
||||
// Pauzeknop: blijft gelden tot de bezoeker opnieuw klikt (WCAG 2.2.2)
|
||||
const [stopped, setStopped] = useState(false);
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const [focused, setFocused] = useState(false);
|
||||
// Server and hydrating render say "visible", like the HTML
|
||||
const hidden = useSyncExternalStore(
|
||||
@@ -49,16 +48,13 @@ export default function useHeroSlider(count: number) {
|
||||
announcement,
|
||||
reducedMotion,
|
||||
autoplay: count > 1 && !reducedMotion,
|
||||
paused: stopped || hovered || focused || hidden,
|
||||
paused: stopped || focused || hidden,
|
||||
stopped,
|
||||
// Afspelen via de knop geldt ook terwijl de muis of de
|
||||
// toetsenbordfocus nog in de hero staat (de klik zelf is een hover en
|
||||
// vaak een focus); zonder dit gebeurt er na "afspelen" niets zichtbaars.
|
||||
// Afspelen via de knop geldt ook terwijl de toetsenbordfocus nog in de
|
||||
// hero staat (de klik zelf is vaak een focus); zonder dit gebeurt er na
|
||||
// "afspelen" niets zichtbaars.
|
||||
toggleStopped: () => {
|
||||
if (stopped) {
|
||||
setHovered(false);
|
||||
setFocused(false);
|
||||
}
|
||||
if (stopped) setFocused(false);
|
||||
setStopped(!stopped);
|
||||
setAnnouncement(stopped ? 'playing' : 'paused');
|
||||
},
|
||||
@@ -66,12 +62,10 @@ export default function useHeroSlider(count: number) {
|
||||
prev,
|
||||
advance: () => go(active + 1, false),
|
||||
handlers: {
|
||||
// Alleen een echte muis pauzeert; een tik op mobiel niet.
|
||||
onPointerEnter: (event: React.PointerEvent<HTMLElement>) => {
|
||||
if (event.pointerType === 'mouse') setHovered(true);
|
||||
},
|
||||
onPointerLeave: () => setHovered(false),
|
||||
// Alleen toetsenbordfocus pauzeert, niet een klik op een pijl.
|
||||
// Hover pauzeert bewust niet (Bryan, 2026-11-17): een beeldvullende hero
|
||||
// heeft bijna altijd de muis erboven. Toetsenbordfocus op de besturing
|
||||
// pauzeert wel, want dat is een bewuste handeling; een klik op een
|
||||
// pijl niet.
|
||||
onFocus: (event: React.FocusEvent<HTMLElement>) => {
|
||||
if (event.target.matches(':focus-visible')) setFocused(true);
|
||||
},
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,22 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
monitoredHostnames,
|
||||
monitoringConfig,
|
||||
monitoringFor,
|
||||
sentryIngestOrigin,
|
||||
monitoringOrigins,
|
||||
} from './config';
|
||||
|
||||
const dsn = 'https://key@o1.ingest.de.sentry.io/2';
|
||||
const script = 'https://analytics.example.nl/script.js';
|
||||
const raw = (extra: Record<string, unknown> = {}) => ({
|
||||
environment: 'production',
|
||||
sentryDsn: dsn,
|
||||
umamiScriptUrl: script,
|
||||
umamiWebsiteId: 'site-1',
|
||||
...extra,
|
||||
});
|
||||
|
||||
// Alles wat geen test- of productiehost is
|
||||
const otherHostname = fc
|
||||
.oneof(
|
||||
@@ -25,32 +36,89 @@ const otherHostname = fc
|
||||
)
|
||||
.filter((host) => !monitoredHostnames.includes(host));
|
||||
|
||||
describe('monitoringFor', () => {
|
||||
it('productiehost meet als production met de productiewebsite', () => {
|
||||
expect(monitoringFor('andreaslop.nl')).toEqual({
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
describe('monitoringConfig', () => {
|
||||
it('leest de waarden uit de omgeving van de build', () => {
|
||||
// De testomgeving (vite.config.ts) is de productiebuild
|
||||
expect(monitoringConfig()).toMatchObject({
|
||||
environment: 'production',
|
||||
umamiWebsiteId: '3edbb7d1-4388-4f2d-9cef-11ade88ace96',
|
||||
});
|
||||
vi.stubEnv('VITE_APP_ENV', 'test');
|
||||
vi.stubEnv('VITE_UMAMI_WEBSITE_ID', ' abc ');
|
||||
expect(monitoringConfig()).toMatchObject({
|
||||
environment: 'test',
|
||||
umamiWebsiteId: 'abc',
|
||||
});
|
||||
});
|
||||
|
||||
it('testhost meet als test met de testwebsite', () => {
|
||||
expect(monitoringFor('test.andreaslop.nl')).toEqual({
|
||||
environment: 'test',
|
||||
umamiWebsiteId: '7fb301ab-6ecc-4aea-beee-71bcb6009bfe',
|
||||
it('geeft null als er iets ontbreekt of ongeldig is', () => {
|
||||
expect(monitoringConfig(raw())).not.toBeNull();
|
||||
for (const bad of [
|
||||
{ environment: 'staging' },
|
||||
{ environment: undefined },
|
||||
{ sentryDsn: undefined },
|
||||
{ sentryDsn: 'http://key@host/1' },
|
||||
{ sentryDsn: 'geen url' },
|
||||
{ umamiScriptUrl: '' },
|
||||
{ umamiScriptUrl: 'http://analytics.example.nl/script.js' },
|
||||
{ umamiWebsiteId: ' ' },
|
||||
{ umamiWebsiteId: 5 },
|
||||
]) {
|
||||
expect(monitoringConfig(raw(bad))).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('monitoringFor', () => {
|
||||
it('productiebuild meet alleen op de productiehost', () => {
|
||||
const config = monitoringConfig(raw());
|
||||
expect(monitoringFor('andreaslop.nl', config)).toEqual({
|
||||
environment: 'production',
|
||||
sentryDsn: dsn,
|
||||
umamiScriptUrl: script,
|
||||
umamiWebsiteId: 'site-1',
|
||||
});
|
||||
expect(monitoringFor('test.andreaslop.nl', config)).toBeNull();
|
||||
});
|
||||
|
||||
it('testbuild meet alleen op de testhost', () => {
|
||||
const config = monitoringConfig(raw({ environment: 'test' }));
|
||||
expect(monitoringFor('test.andreaslop.nl', config)?.environment).toBe(
|
||||
'test',
|
||||
);
|
||||
expect(monitoringFor('andreaslop.nl', config)).toBeNull();
|
||||
});
|
||||
|
||||
it('meet niets zonder instellingen', () => {
|
||||
expect(monitoringFor('andreaslop.nl', null)).toBeNull();
|
||||
});
|
||||
|
||||
it('elke andere host meet niets (M1)', () => {
|
||||
fc.assert(
|
||||
fc.property(otherHostname, (host) => {
|
||||
expect(monitoringFor(host)).toBeNull();
|
||||
expect(
|
||||
monitoringFor(
|
||||
host,
|
||||
monitoringConfig(raw({ environment: 'test' })),
|
||||
),
|
||||
).toBeNull();
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('Sentry-ingest is de EU-host uit de DSN, zonder sleutel', () => {
|
||||
expect(sentryIngestOrigin).toBe(
|
||||
'https://o4511795618185216.ingest.de.sentry.io',
|
||||
);
|
||||
describe('monitoringOrigins', () => {
|
||||
it('zijn de herkomst van het Umami-script en van de Sentry-ingest, zonder sleutel', () => {
|
||||
expect(monitoringOrigins(monitoringConfig(raw()))).toEqual({
|
||||
umami: ['https://analytics.example.nl'],
|
||||
sentry: ['https://o1.ingest.de.sentry.io'],
|
||||
});
|
||||
});
|
||||
|
||||
it('zijn leeg zonder instellingen', () => {
|
||||
expect(monitoringOrigins(null)).toEqual({ umami: [], sentry: [] });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,43 +1,96 @@
|
||||
// Instellingen voor Sentry en Umami (monitoring-plan M1/M2). Deze waarden zijn
|
||||
// openbaar: ze staan hoe dan ook in de browser van elke bezoeker.
|
||||
// Instellingen voor Sentry en Umami (monitoring-plan M1/M2). De waarden zijn
|
||||
// openbaar (ze staan in de browser van elke bezoeker) maar komen niet meer uit
|
||||
// de code: de pipeline geeft ze per omgeving mee aan de build, uit de Gitea-
|
||||
// variabelen {TEST|PROD}_SENTRY_DSN, _UMAMI_SCRIPT_URL en _UMAMI_WEBSITE_ID,
|
||||
// als VITE_SENTRY_DSN, VITE_UMAMI_SCRIPT_URL, VITE_UMAMI_WEBSITE_ID en
|
||||
// VITE_APP_ENV ('test' of 'production'). Eén build hoort dus bij één omgeving.
|
||||
// Geen imports uit Vite: config/securityHeaders.ts leest dit bestand ook in Node.
|
||||
|
||||
export type MonitoringEnvironment = 'test' | 'production';
|
||||
|
||||
export interface Monitoring {
|
||||
export interface MonitoringConfig {
|
||||
environment: MonitoringEnvironment;
|
||||
sentryDsn: string;
|
||||
umamiScriptUrl: string;
|
||||
umamiWebsiteId: string;
|
||||
}
|
||||
|
||||
export const sentryDsn =
|
||||
'https://12ec77dcc3216a98b96d3fb3dac13f66@o4511795618185216.ingest.de.sentry.io/4512282287472720';
|
||||
export type Monitoring = MonitoringConfig;
|
||||
|
||||
// Waar de browser fouten naartoe stuurt; nodig voor connect-src in de CSP
|
||||
export const sentryIngestOrigin = new URL(sentryDsn).origin;
|
||||
// De host waarop de build van een omgeving meet
|
||||
const hostnameByEnvironment: Record<MonitoringEnvironment, string> = {
|
||||
production: 'andreaslop.nl',
|
||||
test: 'test.andreaslop.nl',
|
||||
};
|
||||
|
||||
export const umamiOrigin = 'https://analytics.slpsoftware.nl';
|
||||
// In de Vite-build staan de waarden in import.meta.env (statisch vervangen,
|
||||
// daarom elke naam los); de buildscripts onder Node lezen process.env.
|
||||
const fromProcess = (name: string): unknown =>
|
||||
typeof process === 'undefined' ? undefined : process.env[name];
|
||||
|
||||
// Eén build voor beide omgevingen: de hostname bepaalt de omgeving
|
||||
const monitoringByHostname = new Map<string, Monitoring>([
|
||||
[
|
||||
'andreaslop.nl',
|
||||
{
|
||||
environment: 'production',
|
||||
umamiWebsiteId: '3edbb7d1-4388-4f2d-9cef-11ade88ace96',
|
||||
},
|
||||
],
|
||||
[
|
||||
'test.andreaslop.nl',
|
||||
{
|
||||
environment: 'test',
|
||||
umamiWebsiteId: '7fb301ab-6ecc-4aea-beee-71bcb6009bfe',
|
||||
},
|
||||
],
|
||||
]);
|
||||
|
||||
// Onbekende host (localhost, Lighthouse CI, previews): niets meten (M1)
|
||||
export function monitoringFor(hostname: string): Monitoring | null {
|
||||
return monitoringByHostname.get(hostname) ?? null;
|
||||
function rawSettings(): Record<keyof MonitoringConfig, unknown> {
|
||||
const env = import.meta.env;
|
||||
return {
|
||||
environment: env?.VITE_APP_ENV ?? fromProcess('VITE_APP_ENV'),
|
||||
sentryDsn: env?.VITE_SENTRY_DSN ?? fromProcess('VITE_SENTRY_DSN'),
|
||||
umamiScriptUrl:
|
||||
env?.VITE_UMAMI_SCRIPT_URL ?? fromProcess('VITE_UMAMI_SCRIPT_URL'),
|
||||
umamiWebsiteId:
|
||||
env?.VITE_UMAMI_WEBSITE_ID ?? fromProcess('VITE_UMAMI_WEBSITE_ID'),
|
||||
};
|
||||
}
|
||||
|
||||
export const monitoredHostnames = [...monitoringByHostname.keys()];
|
||||
const isHttps = (value: string): boolean => {
|
||||
try {
|
||||
return new URL(value).protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// De instellingen van deze build, of null als er iets ontbreekt of ongeldig is
|
||||
// (dan meet de site niets: liever geen meting dan een kapotte)
|
||||
export function monitoringConfig(
|
||||
raw: Record<keyof MonitoringConfig, unknown> = rawSettings(),
|
||||
): MonitoringConfig | null {
|
||||
const { environment, sentryDsn, umamiScriptUrl, umamiWebsiteId } = raw;
|
||||
if (environment !== 'test' && environment !== 'production') return null;
|
||||
const text = (value: unknown) =>
|
||||
typeof value === 'string' ? value.trim() : '';
|
||||
const dsn = text(sentryDsn);
|
||||
const script = text(umamiScriptUrl);
|
||||
const website = text(umamiWebsiteId);
|
||||
if (!isHttps(dsn) || !isHttps(script) || website === '') return null;
|
||||
return {
|
||||
environment,
|
||||
sentryDsn: dsn,
|
||||
umamiScriptUrl: script,
|
||||
umamiWebsiteId: website,
|
||||
};
|
||||
}
|
||||
|
||||
// Onbekende host (localhost, Lighthouse CI, previews, de andere omgeving):
|
||||
// niets meten (M1)
|
||||
export function monitoringFor(
|
||||
hostname: string,
|
||||
config: MonitoringConfig | null = monitoringConfig(),
|
||||
): Monitoring | null {
|
||||
if (!config || hostname !== hostnameByEnvironment[config.environment]) {
|
||||
return null;
|
||||
}
|
||||
return { ...config };
|
||||
}
|
||||
|
||||
// De herkomsten voor de CSP: Umami voor script-src en connect-src, de Sentry-
|
||||
// ingest voor connect-src. Leeg zonder meting.
|
||||
export function monitoringOrigins(
|
||||
config: MonitoringConfig | null = monitoringConfig(),
|
||||
): { umami: string[]; sentry: string[] } {
|
||||
if (!config) return { umami: [], sentry: [] };
|
||||
return {
|
||||
umami: [new URL(config.umamiScriptUrl).origin],
|
||||
sentry: [new URL(config.sentryDsn).origin],
|
||||
};
|
||||
}
|
||||
|
||||
export const monitoredHostnames = Object.values(hostnameByEnvironment);
|
||||
|
||||
@@ -11,6 +11,7 @@ async function freshSentry() {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
init.mockReset();
|
||||
captureException.mockReset();
|
||||
});
|
||||
@@ -27,6 +28,7 @@ describe('Sentry', () => {
|
||||
});
|
||||
|
||||
it('start op test met omgeving test en zonder persoonsgegevens', async () => {
|
||||
vi.stubEnv('VITE_APP_ENV', 'test');
|
||||
const { startSentry } = await freshSentry();
|
||||
startSentry('test.andreaslop.nl');
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { monitoringFor, sentryDsn } from './config';
|
||||
import { monitoringFor } from './config';
|
||||
|
||||
// Sentry laadt pas na het load-event, buiten de hoofdbundel (M4). Fouten van
|
||||
// daarvoor wachten in een wachtrij en gaan mee zodra Sentry klaar is.
|
||||
@@ -33,7 +33,7 @@ export function startSentry(hostname = window.location.hostname): void {
|
||||
// Alleen fouten: geen tracing, geen replay, geen persoonsgegevens (M5).
|
||||
// Sinds SDK 11 verzamelt Sentry standaard alles; daarom alles expliciet uit.
|
||||
Sentry.init({
|
||||
dsn: sentryDsn,
|
||||
dsn: monitoring.sentryDsn,
|
||||
environment: monitoring.environment,
|
||||
release: import.meta.env.VITE_RELEASE,
|
||||
dataCollection: {
|
||||
|
||||
@@ -28,6 +28,91 @@ 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',
|
||||
// Same slow zoom as the other photos of the slider: the plain HTML
|
||||
// is painted at 1.06 and the slider (after hydration) sets
|
||||
// data-zoom on the picture, which zooms out to 1 over 9 s. The
|
||||
// photo itself is never replaced, so the LCP does not wait for
|
||||
// hydration; the first frame is the same before and after it.
|
||||
transform: 'scale(1.06)',
|
||||
transition: 'transform 9s linear',
|
||||
'@media (prefers-reduced-motion: reduce)': {
|
||||
transform: 'none',
|
||||
transition: 'none',
|
||||
},
|
||||
},
|
||||
'.cms-hero-picture[data-zoom] .cms-hero-image': {
|
||||
transform: 'scale(1)',
|
||||
},
|
||||
'.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),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { monitoringTestEnv } from './config/monitoringTestEnv.ts';
|
||||
import { configDefaults, defineConfig } from 'vitest/config';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { tanstackStart } from '@tanstack/react-start/plugin/vite';
|
||||
@@ -80,6 +81,7 @@ export default defineConfig(({ mode }) => ({
|
||||
preview: { headers: securityHeaders('production') },
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
env: monitoringTestEnv,
|
||||
// De CI-runner (Raspberry Pi, arm64) is ±5-8x trager dan een pc; de
|
||||
// eerste render met axe duurt daar tot 7 s. 5 s (standaard) is te krap.
|
||||
testTimeout: 20_000,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import { monitoringTestEnv } from './config/monitoringTestEnv.ts';
|
||||
|
||||
// Browsertests (BR-TST-05, BR-TST-06) tegen de gebouwde site in dist/client.
|
||||
// Los van vite.config.ts: de Start-plugin en de jsdom-opzet van de
|
||||
@@ -8,6 +9,7 @@ export default defineConfig({
|
||||
resolve: { tsconfigPaths: true },
|
||||
test: {
|
||||
environment: 'node',
|
||||
env: monitoringTestEnv,
|
||||
include: ['e2e/**/*.e2e.ts'],
|
||||
// De CI-runner (Raspberry Pi) is veel trager dan een pc: Chrome starten
|
||||
// en een pagina hydrateren kost daar vele seconden. Tests die alle 11
|
||||
|
||||
Reference in New Issue
Block a user