From 026e6cb6c678a1fe64d12cbe70af66a9392e6b56 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 11:53:39 +0100 Subject: [PATCH 01/47] Hero-module: feature gestart (Workspace Detection, Requirements-vragen voor Bryan) Co-Authored-By: Claude Sonnet 5.5 --- aidlc-docs/active-features.md | 1 + .../features/hero-module/aidlc-state.md | 54 ++++++ aidlc-docs/features/hero-module/audit.md | 25 +++ .../requirement-verification-questions.md | 159 ++++++++++++++++++ 4 files changed, 239 insertions(+) create mode 100644 aidlc-docs/features/hero-module/aidlc-state.md create mode 100644 aidlc-docs/features/hero-module/audit.md create mode 100644 aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md diff --git a/aidlc-docs/active-features.md b/aidlc-docs/active-features.md index 36736b6..8f628d1 100644 --- a/aidlc-docs/active-features.md +++ b/aidlc-docs/active-features.md @@ -24,3 +24,4 @@ | Feature | [ASF: host injecteert in voorgerenderde pagina's (asf-host-injection)](features/asf-host-injection/plan.md) | ✅ Gebouwd en op test (afgesloten 2026-11-16; ASF-productie op IIS is een apart, later plan) | feature/contact-forms-module | Core (Hosting/Website), Modules.Offerings, docs | 2026-11-15 | | Feature | [Vertaalbestanden backend (translation-files)](../docs/translation-files.md) | ✅ Afgesloten 2026-11-16 (stappen 1-8, docs; buiten AI-DLC gebouwd; goedgekeurd door Bryan via SLS-Main; productie via de checklist) | feature/contact-forms-module | Core (Texts, Email, Identity, Hosting), Modules.Availability, Modules.Offerings | 2026-11-15 | | Bug | [theme-toggle-first-click](bugs/theme-toggle-first-click/bug-fix.md) | ✅ Complete (niet gecommit/gemerged; buiten AI-DLC gebouwd; oorzaak niet in een echte browser nagebootst) | feature/contact-forms-module | Frontend (useTheme, index.html) | 2026-11-15 | +| Feature | [Hero module (hero-module)](features/hero-module/aidlc-state.md) | 🔵 Inception (Requirements: vragen aan Bryan) | feature/hero-module | Modules (new Hero), Core (Hosting/Website, host injection), CI (release/-regel voor SLS-productie), Frontend (admin) | 2026-11-16 | diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md new file mode 100644 index 0000000..02e9dc7 --- /dev/null +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -0,0 +1,54 @@ +# AI-DLC State Tracking + +## Project Information +- **Feature Name**: Hero module (manageable hero for SLP Software and Andrea Slop Fotografie) +- **Feature Slug**: hero-module +- **Project Type**: Brownfield +- **Start Date**: 2026-11-16 +- **Current Stage**: INCEPTION - Requirements Analysis (clarifying questions sent, waiting for answers) +- **Branch**: feature/hero-module (worktree K:\Development\Projects\SlpModularCms-contact-forms, from master b2cacfe) + +## Workspace State +- **Existing Code**: Yes +- **Reverse Engineering Needed**: No full rerun (artifacts exist in `_shared/reverse-engineering/`; targeted review of Offerings banners, host injection and website hosting instead) +- **Workspace Root**: K:\Development\Projects\SlpModularCms + +## Code Location Rules +- **Application Code**: Workspace root `src/` and `frontend/` (NEVER in aidlc-docs/) +- **Feature Documentation**: aidlc-docs/features/hero-module/ only +- **Shared Artifacts**: aidlc-docs/_shared/ + +## Language Configuration +- **Documentation Language**: English +- **Conversation Language**: User Language (Dutch) +- **Note**: Inherited from the other features in this workspace. + +## Source Of Truth / Coordination +- Requested by Bryan via the session "SLP Software - SLS - Main" (2026-11-16). Starting points of Bryan: hero texts/image manageable in the CMS, immediately visible (NFR-10), but the hero LCP (image/text) must be in the first HTML (prerender / host injection), otherwise LCP regresses. Both sites (SLS and ASF) use it. +- NFR-10 (SLS requirements): CMS content is live; baked or host-injected HTML for crawlers plus a client refresh; on failure the baked version stays. +- Included in this feature (agreed 2026-11-16): align the SLS CI pipeline with ASF: production deploy only from a `release/*` branch (`startsWith(github.ref, 'refs/heads/release/')` on `publish-sls-production` and `deploy-sls-production`). The SLS site side is done by the SLS session. +- No merge, production deploy or production variables without Bryan's explicit go. + +## Extension Configuration +| Extension | Enabled | Decided At | +|---|---|---| +| Security Baseline | Pending | Requirements Analysis (question in the questions file) | +| Property-Based Testing | Pending | Requirements Analysis (question in the questions file) | + +## Operations Configuration +- **Include Operations Phase**: Undecided +- **Decided At**: Pending - asked at Requirements Analysis + +## Stage Progress +### 🔵 INCEPTION PHASE +- [x] Workspace Detection (classification: Feature) +- [x] Reverse Engineering (skipped: targeted review) +- [ ] Requirements Analysis (questions asked, waiting for answers) +- [ ] User Stories +- [ ] Workflow Planning +- [ ] Application Design +- [ ] Units Generation +### 🟢 CONSTRUCTION PHASE +- [ ] Not started +### 🟡 OPERATIONS PHASE +- [ ] Undecided diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md new file mode 100644 index 0000000..3848989 --- /dev/null +++ b/aidlc-docs/features/hero-module/audit.md @@ -0,0 +1,25 @@ +# Audit Log - hero-module + +## Workspace Detection (initial request) + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Daarna: start een nieuwe aidlc-feature voor de Hero als beheerbare CMS-module (naam bv. hero-module). Uitgangspunten van Bryan: Hero-teksten/-afbeelding beheerbaar vanuit het CMS, direct zichtbaar (NFR-10), maar de Hero-LCP (afbeelding/tekst) moet in de eerste HTML staan (prerender / host-injectie), anders gaat de LCP achteruit. Beide sites (SLS en ASF) gebruiken het. Begin met Workspace Detection/Requirements en stel de vragen aan mij; de statische teksten die nog niet door Bryan zijn bekeken nemen we daar mee. Ook als apart idee voor later (nog niet starten): feature voor een IIS-publish-pipeline voor ASF productie (self-contained win-x64, FTP, web.config, CMS-host als enige entry)." (cross-session message from "SLP Software - SLS - Main", relaying Bryan) + +**AI Response**: Classified as Feature (new capability). Brownfield; no full reverse engineering rerun. Created feature folder, state and questions file. + +**Context**: Workspace Detection complete; Requirements Analysis started. + +--- + +## Pipeline alignment agreed + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Extra voor die feature (Bryan): trek de SLS-pipeline gelijk aan die van ASF (bv. productie alleen vanaf een release/-branch); dat voeren we in de Hero-feature door, geen aparte feature." and "Akkoord: ASF gebruikt `startsWith(github.ref, 'refs/heads/release/')`, dus branchnaam `release/*` (bv. `release/2026-11-20` of `release/1.0`, de naam na release/ is vrij). Neem die conditie op bij publish-sls-production en deploy-sls-production in de Hero-feature." (relayed by SLP Software - SLS - Main) + +**AI Response**: Added to the feature scope (CMS repo side only: the two production jobs get the release-branch condition). + +**Context**: Scope decision, recorded in aidlc-state.md. + +--- diff --git a/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md b/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md new file mode 100644 index 0000000..dc54e5d --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md @@ -0,0 +1,159 @@ +# Vragen over de Hero-module + +Vul per vraag de letter in na `[Answer]:`. Past geen enkele optie, kies de laatste (Other) en beschrijf het. Opmerking per vraag mag ook achter de letter. + +**Wat er nu is:** de Hero van SLP Software is vaste tekst in de website-code (`Hero.tsx` en `content.ts`: kleine kop, grote kop in drie regels, lead, twee knoppen, een "code-regel"). Er is geen afbeelding. De Hero van ASF is nog niet bekeken voor deze vragen; als die een afbeelding heeft, komt dat in vraag 4 terug. De host kan al stukken van de pagina's invullen vanuit het CMS (pakketten, banners) via markers in de HTML, en dat is de route die we voor de Hero ook gebruiken. + +## Vraag 1 — Hoeveel heroes per site? + +- A) Eén hero per site (een vaste plek die je bewerkt) +- B) Meerdere heroes per site, waarvan er één tegelijk actief is (bijvoorbeeld seizoensgebonden), met aan/uit +- C) Meerdere heroes die op een rooster wisselen (carrousel) +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 2 — Welke teksten en knoppen moeten beheerbaar zijn? + +- A) Kop, subkop/lead en maximaal twee knoppen (label + link) +- B) Zoals A, plus een kleine kop erboven (eyebrow) en de grote kop in meerdere regels (zoals "Websites," / "apps" / "& meer.") +- C) Zoals B, plus de "code-regel" van SLP Software als vrij tekstveld +- D) Alleen kop en subkop; knoppen blijven in de website-code +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 3 — Hoe worden de teksten per site en per taal bewaard? + +- A) Eén taal per site (Nederlands); de site-eigenaar vult het in +- B) Nederlands en Engels per hero, beide in het CMS in te voeren +- C) Eén taal nu, maar het datamodel moet later talen kunnen toevoegen zonder migratie van bestaande data +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 4 — Heeft de hero een afbeelding? + +- A) Nee, alleen tekst (SLP Software zoals nu) +- B) Optioneel: een hero kan een afbeelding hebben, met verplichte alt-tekst (of expliciet "decoratief") +- C) Verplicht per hero, met alt-tekst +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 5 — Hoe komt de afbeelding in het CMS? (alleen als vraag 4 niet A is) + +- A) Upload in het CMS; de host bewaart het bestand en maakt automatisch varianten (verschillende breedtes, WebP/AVIF) voor snelle mobiele weergave +- B) Upload in het CMS; de host bewaart alleen het origineel (geen varianten); de website schaalt met CSS +- C) Geen upload: het CMS bewaart alleen een adres naar een afbeelding die in de website-build zit +- D) Niet van toepassing (vraag 4 = A) +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 6 — Hoe moet de LCP in de eerste HTML komen? + +De host schrijft de hero (tekst, afbeelding, knoppen) in de HTML voordat die naar de browser gaat: voor tekst als gewone elementen, voor een afbeelding met een `` in de kop, `width`/`height`, `fetchpriority="high"` en een `srcset`. Na het laden verfrist de website de hero uit de API (NFR-10); als dat mislukt blijft de ingebakken versie staan. + +- A) Ja, zo (host-injectie voor beide sites; de ingebakken tekst blijft als terugval als het CMS niet bereikbaar is) +- B) Zoals A, maar de hero in de ingebakken HTML hoeft alleen bij de volgende bouw van de website bijgewerkt te worden (geen injectie in de eerste HTML) +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 7 — Hoe snel moet een wijziging zichtbaar zijn? + +- A) Zoals banners en pakketten nu: binnen ongeveer een minuut (60 seconden cache, direct vernieuwd bij elke wijziging in het CMS) +- B) Direct, zonder cache, bij elke bezoeker +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 8 — Concept en publiceren + +- A) Opslaan is publiceren (zoals bij pakketten en banners) +- B) Er is een concept: eerst opslaan als concept, een voorbeeld bekijken, dan publiceren +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 9 — Planning (van/tot) + +- A) Geen planning: een hero is aan of uit +- B) Wel planning (van/tot), zoals bij pakketten en banners; buiten de periode valt de site terug op de standaard-hero +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 10 — Wie mag de hero wijzigen? + +- A) Administrator en hoger (zoals pakketten en banners) +- B) Alleen de eigenaar (Owner) +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 11 — Waar komt de code? + +- A) Een eigen module `SlpModularCms.Modules.Hero` (met tests), aan of uit per site, zoals Offerings en Contact +- B) Binnen de bestaande Offerings-module (hero naast pakketten en banners) +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 12 — Wat doen we met de statische teksten die jij nog niet hebt bekeken? + +Er zijn vaste teksten in de websites (hero, secties van de landingspagina) die nog niet door jou zijn gelezen. Jij vroeg ze in deze feature mee te nemen. + +- A) Alleen de hero-teksten: jij leest die en geeft de definitieve tekst; die komt als startinhoud (seed) in het CMS +- B) Hero én de andere secties van de landingspagina lezen/herschrijven in deze feature, maar alleen de hero gaat naar het CMS; de rest blijft vaste tekst +- C) Hero én de andere secties lezen, en later een algemene "blokken"-module voor al die teksten (apart plan; in deze feature alleen de hero) +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 13 — Start-inhoud (seed) + +- A) Een script zoals `Seed-Offerings.ps1` zet de huidige teksten van SLP Software en ASF als eerste hero in het CMS van de testomgeving; productie vullen we pas bij de release +- B) De eigenaar vult de hero zelf in via de admin na uitrol +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 14 — Als het CMS leeg of onbereikbaar is + +- A) De ingebakken hero uit de website-build blijft staan (geen lege hero), zoals in NFR-10 +- B) Het CMS is leidend: zonder hero in het CMS wordt de hero-sectie weggelaten +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 15 — Beveiligingsregels (extensie) + +Moeten de beveiligingsregels als harde vereisten worden afgedwongen voor deze feature? (Het gaat om een afbeelding-upload, invoer van beheerders en HTML die de host schrijft.) + +- A) Ja — dwing alle BEVEILIGINGSREGELS af als blokkerende vereisten (aanbevolen voor productietoepassingen) +- B) Nee — sla alle BEVEILIGINGSREGELS over (geschikt voor PoC's, prototypes en experimentele projecten) +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: + +## Vraag 16 — Property-based testing (extensie) + +- A) Ja — dwing alle PBT-regels af als blokkerende vereisten +- B) Gedeeltelijk — alleen voor pure functies en serialisatie round-trips (bijvoorbeeld HTML-codering van hero-teksten) +- C) Nee — sla alle PBT-regels over +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: + +## Vraag 17 — Operations-fase + +Moet deze feature na Construction door de Operations-fase (uitrol en monitoring inrichten)? De gezamenlijke productie-checklist (`docs/release-checklist-productie.md`) bestaat al en wordt in dat geval aangevuld. + +- A) Ja — Operations-fase draaien +- B) Nee — stoppen na Build and Test; de hero-punten komen in de gezamenlijke productie-checklist +- C) Nog niet zeker — vraag het opnieuw na Construction +- X) Other (please describe after [Answer]: tag below) + +[Answer]: -- 2.39.5 From e80e5108c05e6b1aa77cec25d3d6828ae90e93ba Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 11:54:24 +0100 Subject: [PATCH 02/47] Hero-module: vragen aangepast aan de ASF-slider (0..n slides per hero) Co-Authored-By: Claude Sonnet 5.5 --- .../requirement-verification-questions.md | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md b/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md index dc54e5d..6f61f24 100644 --- a/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md +++ b/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md @@ -2,13 +2,13 @@ Vul per vraag de letter in na `[Answer]:`. Past geen enkele optie, kies de laatste (Other) en beschrijf het. Opmerking per vraag mag ook achter de letter. -**Wat er nu is:** de Hero van SLP Software is vaste tekst in de website-code (`Hero.tsx` en `content.ts`: kleine kop, grote kop in drie regels, lead, twee knoppen, een "code-regel"). Er is geen afbeelding. De Hero van ASF is nog niet bekeken voor deze vragen; als die een afbeelding heeft, komt dat in vraag 4 terug. De host kan al stukken van de pagina's invullen vanuit het CMS (pakketten, banners) via markers in de HTML, en dat is de route die we voor de Hero ook gebruiken. +**Wat er nu is:** de Hero van SLP Software is vaste tekst in de website-code (`Hero.tsx` en `content.ts`: kleine kop, grote kop in drie regels, lead, twee knoppen, een "code-regel"). Er is geen afbeelding. De Hero van ASF (`web/src/components/Hero/Hero.tsx`, inhoud in `heroContent.ts`) is een diavoorstelling: titel, tagline, een knop en een lijst slides (afbeelding met alt/label per slide; 6 seconden per slide, pauzeknop, pijlen, reduced-motion). De eerste slide laadt eerst, de rest na de eerste weergave. Bij SLP Software is de LCP de tekst, bij ASF de eerste afbeelding. De host kan al stukken van de pagina's invullen vanuit het CMS (pakketten, banners) via markers in de HTML, en dat is de route die we voor de Hero ook gebruiken. ## Vraag 1 — Hoeveel heroes per site? -- A) Eén hero per site (een vaste plek die je bewerkt) +- A) Eén hero per site (een vaste plek die je bewerkt); de slides van ASF zitten daarbinnen (zie vraag 4) - B) Meerdere heroes per site, waarvan er één tegelijk actief is (bijvoorbeeld seizoensgebonden), met aan/uit -- C) Meerdere heroes die op een rooster wisselen (carrousel) +- C) Meerdere heroes die op een rooster wisselen (carrousel van hele heroes) - X) Other (please describe after [Answer]: tag below) [Answer]: @@ -32,28 +32,29 @@ Vul per vraag de letter in na `[Answer]:`. Past geen enkele optie, kies de laats [Answer]: -## Vraag 4 — Heeft de hero een afbeelding? +## Vraag 4 — Afbeeldingen en slides in de hero -- A) Nee, alleen tekst (SLP Software zoals nu) -- B) Optioneel: een hero kan een afbeelding hebben, met verplichte alt-tekst (of expliciet "decoratief") -- C) Verplicht per hero, met alt-tekst +Het datamodel krijgt ruimte voor 0 tot n slides per hero; een slide heeft een afbeelding, alt-tekst en eventueel eigen tekst. SLP Software gebruikt er nul, ASF meerdere. + +- A) Zo: 0 tot n slides per hero, elk met afbeelding, verplichte alt-tekst (of expliciet "decoratief"), optionele eigen tekst en volgorde; de website bepaalt de weergave (slider of niet) +- B) Zoals A, maar de wisselsnelheid, pauzeknop en pijlen zijn ook instelbaar in het CMS +- C) Eén afbeelding per hero (geen slides); de slider van ASF blijft vaste inhoud in de website-code - X) Other (please describe after [Answer]: tag below) [Answer]: -## Vraag 5 — Hoe komt de afbeelding in het CMS? (alleen als vraag 4 niet A is) +## Vraag 5 — Hoe komen de afbeeldingen in het CMS? -- A) Upload in het CMS; de host bewaart het bestand en maakt automatisch varianten (verschillende breedtes, WebP/AVIF) voor snelle mobiele weergave +- A) Upload in het CMS; de host bewaart het bestand en maakt automatisch varianten (verschillende breedtes, WebP/AVIF) met een adres met inhouds-hash, zodat ze lang gecachet kunnen worden - B) Upload in het CMS; de host bewaart alleen het origineel (geen varianten); de website schaalt met CSS -- C) Geen upload: het CMS bewaart alleen een adres naar een afbeelding die in de website-build zit -- D) Niet van toepassing (vraag 4 = A) +- C) Geen upload: het CMS bewaart alleen een adres naar een afbeelding die in de website-build zit (ASF zet de afbeeldingen zelf in zijn build) - X) Other (please describe after [Answer]: tag below) [Answer]: ## Vraag 6 — Hoe moet de LCP in de eerste HTML komen? -De host schrijft de hero (tekst, afbeelding, knoppen) in de HTML voordat die naar de browser gaat: voor tekst als gewone elementen, voor een afbeelding met een `` in de kop, `width`/`height`, `fetchpriority="high"` en een `srcset`. Na het laden verfrist de website de hero uit de API (NFR-10); als dat mislukt blijft de ingebakken versie staan. +De host schrijft de hero (tekst, afbeelding, knoppen) in de HTML voordat die naar de browser gaat: voor tekst als gewone elementen, voor een afbeelding met een `` in de kop, `width`/`height`, `fetchpriority="high"` en een `srcset`. Bij een slider is dat de eerste slide; de andere slides laden na de eerste weergave. Na het laden verfrist de website de hero uit de API (NFR-10); als dat mislukt blijft de ingebakken versie staan. - A) Ja, zo (host-injectie voor beide sites; de ingebakken tekst blijft als terugval als het CMS niet bereikbaar is) - B) Zoals A, maar de hero in de ingebakken HTML hoeft alleen bij de volgende bouw van de website bijgewerkt te worden (geen injectie in de eerste HTML) -- 2.39.5 From 75b883c576c582014fb1afde7489defaa4279dc8 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 13:05:53 +0100 Subject: [PATCH 03/47] Hero-module: vergelijking SLS-hero vs ASF-hero; vragenbestand herzien op Bryans besluiten Co-Authored-By: Claude Sonnet 5.5 --- aidlc-docs/features/hero-module/audit.md | 12 ++ .../inception/requirements/hero-comparison.md | 44 +++++ .../requirement-verification-questions.md | 156 +++++++++++------- 3 files changed, 149 insertions(+), 63 deletions(-) create mode 100644 aidlc-docs/features/hero-module/inception/requirements/hero-comparison.md diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index 3848989..25fe5d1 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -23,3 +23,15 @@ **Context**: Scope decision, recorded in aidlc-state.md. --- + +## Bryan's decisions and the comparison + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Bryan heeft besloten voor de Hero-feature (leg dit vast in de requirements): 1. Aanpak gelijk aan pakketten en formulieren: het CMS levert alleen INHOUD, elke site houdt zijn eigen layout/presentatie ... 2. De inhoud van de Hero komt volledig uit het CMS: teksten (titel, tagline/subtitel), knoppen (label, link) en afbeeldingen (0..n slides met afbeelding, alt-tekst, eventueel tekst per slide). Optioneel een veld "weergave" ... 3. EERSTE STAP in Requirements, vóór de vragen aan Bryan definitief worden: maak een vergelijking SLS-hero vs ASF-hero ... pas daarna het vragenbestand aan op wat overblijft. Bryan beantwoordt dan beide in één keer. 4. De ASF-sessie levert haar helft van de vergelijking ..." (relayed by SLP Software - SLS - Main; ASF half delivered by Andrea Slop Fotografie - ASF - Main) + +**AI Response**: Wrote `inception/requirements/hero-comparison.md` (table SLS vs ASF, decisions of Bryan, facts for the design) and rewrote the questions file: decided points listed at the top, 19 questions remain. + +**Context**: Requirements Analysis, waiting for Bryan's answers. + +--- diff --git a/aidlc-docs/features/hero-module/inception/requirements/hero-comparison.md b/aidlc-docs/features/hero-module/inception/requirements/hero-comparison.md new file mode 100644 index 0000000..fd18b3f --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/requirements/hero-comparison.md @@ -0,0 +1,44 @@ +# Hero comparison: SLP Software (SLS) vs Andrea Slop Fotografie (ASF) + +Input for the requirements of `hero-module`. Sources: SLS = `src/features/landing/components/Hero.tsx`, `src/features/landing/data/content.ts` (`heroContent`), `src/prerender/StaticLanding.tsx`, `src/variants/e/Era2026.tsx` (read from the code by the CMS session, 2026-11-16); ASF = `web/src/components/Hero/*`, `web/src/content/heroContent.ts`, `types.ts` (delivered by the ASF session, 2026-11-16). Nothing here is a design decision yet; the decisions of Bryan are at the end. + +## Comparison + +| Aspect | SLS (Tailwind) | ASF (Chakra) | Same / different | Consequence for the CMS content | +|---|---|---|---|---| +| Small label above the title | `eyebrow` ("Web & .NET development"), shown in the code strip below | `tagline` ("Lifestyle fotograaf · Huizen"), a small uppercase label above the title, in the same `h1` | Same idea (short label), different place | One short text field ("tagline"); the site decides where it goes | +| Title | `heading` ("SLP software: websites, apps & meer", screen-reader only) and `displayHeading` (3 lines: "Websites," / "apps" / "& meer."); the era variant joins the lines with a space | `title` ("Andrea Slop"), one string, in the `h1` with the tagline | Different: SLS has a visual line split | One title text; line breaks as a separate optional representation (decision needed) | +| Lead / subtitle | `lead` (long paragraph, about 250 characters) | none | SLS only | Optional "subtitle/lead" text field | +| Code line | `codeLine` ("var website = slp.Bouw(uwIdee);") with blinking caret | none | SLS only, a style element | Not CMS content unless Bryan wants it editable (decision needed) | +| Buttons | Two: "Bekijk pakketten" (anchor `#pakketten`), "Plan een gesprek" (anchor `#contact`). Labels hardcoded in `Hero.tsx`; the era variant takes them from `nl.json` (`era.e2026.ctaPackages/ctaContact`) | One: `cta` `{label "Lees meer", to "/over-mij"}`, an internal route | Same idea (label + target), different count and target kind (page anchor vs site route) | 0..2 buttons, each label + target; the target is free text that the site interprets (anchor, route or address) | +| Images | None | `slides[]`, 8 images of 220 to 440 KB, JPG, one file per slide, no srcset or variants, object-fit cover, 100svh | Different | 0..n slides: the SLS hero has zero | +| Per slide | n/a | `id` (stable), `src`, `alt` (also read by the screen reader as "Photo n of N: alt"). No per-slide label, link or caption | ASF only | Slide: image, alt text, order; stable id | +| Display | Static, no slider | Slider: 6 s per slide, crossfade, slow zoom, pause on mouse hover / keyboard focus / hidden tab / pause button (WCAG 2.2.2), arrows and swipe, wrap-around; one slide = no arrows and no autoplay | Different | Optional "display" value (single / slideshow) that every site renders as it supports; the site keeps the timing and animation | +| Reduced motion | Not relevant (no motion beyond the caret) | `prefers-reduced-motion`: no autoplay, no progress bar, no pause button, no zoom | ASF only | Stays in the site | +| Noscript | The prerendered landing contains the hero text | Slide 1 stays as a static ``; progress bar hidden; arrows and pause need JS | Both readable without JS | The first HTML must contain the hero (LCP) without JS | +| LCP | The text (heading) | The first slide image | **Different** | Host injection per kind: text for SLS; for ASF the first slide `` with `fetchpriority="high"`, `width`/`height`, `srcset` and a matching `` | +| Loading | Everything in one page, text only | Active slide first; next and previous after `onLoad` plus 2 frames; the rest while advancing | ASF only | The host writes only slide 1 into the HTML; the site loads the rest from the data block | +| Prerender | `StaticLanding` renders the `Hero` into `#root` at build time (no hydration; `createRoot` replaces it) | Prerendered with the first slide and a preload link; slides 2 to 8 are empty wrappers | Same pattern (baked HTML, replaced by the app) | Host injection fills the baked hero and puts the full hero in the data block | +| Variants | Five era variants (Era1989 to Era2026) in `variants/e/`; only `Era2026` shows the hero content, it joins `displayHeading` | One layout | SLS only | Same content for every variant; the site renders it. The CMS has no layout choice | +| Where the text is now | `content.ts` (`heroContent`), button labels in `Hero.tsx` and `nl.json` (era) | `heroContent.ts`; aria texts ("Uitgelicht werk", "n van N", "Foto n van N") in the components | Both in code | Title, tagline, lead, buttons and alt texts move to the CMS; the aria texts go to the site's own language file, not the CMS | +| Socials | none in the hero | `HeroSocials` bottom left, from `siteContent.socials` | ASF only | Outside the hero module (site-wide) | +| CMS data today | Packages and banner via markers in `index.html`; the hero is not part of it | Packages and banners via markers and `#cms-data` (`{siteUrl, offerings, banners}`); the hero is not part of it | Same host contract | The data block gets a `hero` key; the baked hero stays the fallback (fail-open) | +| Image address | n/a | Vite import with hashed name in `/assets/` | n/a | CMS media URLs: the preload URL must equal the `img` src exactly; CSP `img-src` must allow the media host (same origin avoids a change) | + +## What is the same (core of the CMS content) + +Title (text), a short tagline, optional lead text, 0..2 buttons (label + target), and a list of 0..n slides (image, alt text, order). The sites differ in presentation, count and kind of buttons, and in whether slides exist. + +## Decisions of Bryan (relayed by SLP Software - SLS - Main, 2026-11-16) + +1. Same approach as packages and forms: the CMS delivers **content only**; every site keeps its own layout and presentation (ASF Chakra, SLS Tailwind). No layouts or sketch choice in the CMS or in the react package. A sketch choice may come later, with a third site. +2. The hero content comes **entirely from the CMS**: texts (title, tagline/subtitle), buttons (label, link) and images (0..n slides with image, alt text and optionally text per slide). Optionally a "display" field (for example single / slideshow) that every site renders according to its own support. +3. The comparison (this file) comes first; the question file is adjusted to what remains. Bryan answers both in one go. +4. The hero LCP (image or text) must be in the first HTML (prerender / host injection), and content is live (NFR-10). + +## Facts from the sites that the design must respect + +- ASF: the order of the slides decides the LCP; the first CMS slide must be in the first HTML with a preload whose URL is exactly the `img` src. +- ASF proposes the data shape `hero {title, tagline, cta{label,url}, slides[{id, imageUrl, width, height, alt, srcset?}]}` and delivers golden files after Bryan approves the requirements. +- ASF aria texts and the 6-second timing stay in the site; they move to the site's language file. +- SLS has no images; its hero has a lead and two buttons. diff --git a/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md b/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md index 6f61f24..c7cdb38 100644 --- a/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md +++ b/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md @@ -2,67 +2,105 @@ Vul per vraag de letter in na `[Answer]:`. Past geen enkele optie, kies de laatste (Other) en beschrijf het. Opmerking per vraag mag ook achter de letter. -**Wat er nu is:** de Hero van SLP Software is vaste tekst in de website-code (`Hero.tsx` en `content.ts`: kleine kop, grote kop in drie regels, lead, twee knoppen, een "code-regel"). Er is geen afbeelding. De Hero van ASF (`web/src/components/Hero/Hero.tsx`, inhoud in `heroContent.ts`) is een diavoorstelling: titel, tagline, een knop en een lijst slides (afbeelding met alt/label per slide; 6 seconden per slide, pauzeknop, pijlen, reduced-motion). De eerste slide laadt eerst, de rest na de eerste weergave. Bij SLP Software is de LCP de tekst, bij ASF de eerste afbeelding. De host kan al stukken van de pagina's invullen vanuit het CMS (pakketten, banners) via markers in de HTML, en dat is de route die we voor de Hero ook gebruiken. +**Eerst lezen:** [hero-comparison.md](hero-comparison.md) zet de hero van SLP Software en die van Andrea Slop Fotografie naast elkaar (velden, afbeeldingen, knoppen, LCP, slider, varianten, wat nu in code staat). + +**Al besloten (hoef je niet meer te beantwoorden):** + +1. Het CMS levert alleen **inhoud**; elke site houdt zijn eigen layout en presentatie (ASF Chakra, SLS Tailwind). Geen layouts of schetsenkeuze in het CMS of in het react-pakket. +2. De inhoud komt volledig uit het CMS: teksten (titel, tagline/subtitel), knoppen (label, link) en afbeeldingen (0 tot n slides met afbeelding, alt-tekst en eventueel tekst per slide). Optioneel een veld "weergave" dat elke site naar eigen ondersteuning toont. +3. De hero-LCP (bij SLP de tekst, bij ASF de eerste slide) staat in de eerste HTML (host-injectie); de ingebakken hero blijft de terugval als het CMS niets levert; wijzigingen zijn direct zichtbaar (NFR-10). +4. De teksten voor schermlezers en bediening (zoals "Foto 2 van 8", "Diavoorstelling gepauzeerd") en de timing en animatie van de slider blijven in de site (eigen taalbestand), niet in het CMS. Socials blijven buiten de hero-module. +5. De productie-conditie `release/*` voor de SLP-pipeline gaat mee in deze feature. ## Vraag 1 — Hoeveel heroes per site? -- A) Eén hero per site (een vaste plek die je bewerkt); de slides van ASF zitten daarbinnen (zie vraag 4) +- A) Eén hero per site (een vaste plek die je bewerkt) - B) Meerdere heroes per site, waarvan er één tegelijk actief is (bijvoorbeeld seizoensgebonden), met aan/uit -- C) Meerdere heroes die op een rooster wisselen (carrousel van hele heroes) - X) Other (please describe after [Answer]: tag below) [Answer]: -## Vraag 2 — Welke teksten en knoppen moeten beheerbaar zijn? +## Vraag 2 — Hoe wordt de titel opgeslagen? -- A) Kop, subkop/lead en maximaal twee knoppen (label + link) -- B) Zoals A, plus een kleine kop erboven (eyebrow) en de grote kop in meerdere regels (zoals "Websites," / "apps" / "& meer.") -- C) Zoals B, plus de "code-regel" van SLP Software als vrij tekstveld -- D) Alleen kop en subkop; knoppen blijven in de website-code +SLP Software toont de titel in drie regels ("Websites," / "apps" / "& meer.") met een aparte tekst voor schermlezers en zoekmachines; ASF heeft één titel. + +- A) Eén titeltekst; regelafbrekingen schrijf je er zelf in (een nieuwe regel in het veld); de site bepaalt hoe die getoond wordt +- B) Eén titeltekst zonder regelafbrekingen; de site splitst zelf +- C) Een titel plus een aparte optionele lijst "weergaveregels" (zoals nu bij SLP Software) - X) Other (please describe after [Answer]: tag below) [Answer]: -## Vraag 3 — Hoe worden de teksten per site en per taal bewaard? +## Vraag 3 — Welke overige tekstvelden? + +- A) Tagline (kort label), subtitel/lead (lange tekst, optioneel) +- B) Zoals A, plus de "code-regel" van SLP Software als vrij tekstveld +- C) Alleen tagline; de lead en de code-regel blijven vaste tekst in de SLP-website +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 4 — Knoppen + +SLP Software heeft twee knoppen naar plekken op dezelfde pagina (`#pakketten`, `#contact`); ASF heeft één knop naar een andere pagina (`/over-mij`). + +- A) 0 tot 2 knoppen, elk met label en doel; het doel is vrije tekst (een anker, een pad of een adres) die de site zelf interpreteert +- B) 0 tot 2 knoppen, elk met label en doel, waarbij het CMS het doel controleert (alleen `#anker`, `/pad` of `https://…`) +- C) 0 tot 3 knoppen (ruimte voor later), verder zoals B +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 5 — Veld "weergave" + +- A) Een keuzeveld met de waarden `enkel` en `diavoorstelling`; een site die er een niet ondersteunt, toont het zoals het kan +- B) Geen veld; de site beslist op basis van het aantal slides (één slide of meer) +- C) Een vrij tekstveld, door de site te interpreteren +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 6 — Wat heeft een slide? + +ASF heeft nu per slide alleen een stabiel id, de afbeelding en de alt-tekst. Kandidaten die ASF noemt: aan/uit per slide en een eigen duur per slide. + +- A) Afbeelding, verplichte alt-tekst (of expliciet "decoratief"), volgorde, aan/uit per slide +- B) Zoals A, plus een optionele eigen tekst per slide (bijschrift) en een optionele eigen duur +- C) Alleen afbeelding, alt-tekst en volgorde +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 7 — Hoe komen de afbeeldingen in het CMS? + +De host levert de afbeeldingen zelf onder het eigen adres van de site (dus geen wijziging van de CSP `img-src`), met een adres dat de inhoud bevat (hash), zodat ze lang gecachet kunnen worden. Voor een snelle LCP moet het adres in de preload gelijk zijn aan dat van de afbeelding. + +- A) Upload in het CMS; de host bewaart het origineel, leest de afmetingen uit en maakt varianten (verschillende breedtes, WebP/AVIF) voor `srcset` +- B) Upload in het CMS; de host bewaart het origineel en de afmetingen, zonder varianten (ASF levert nu ook één JPG per slide) +- C) Geen upload: het CMS bewaart een adres naar een afbeelding die in de website-build zit +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 8 — Grenzen aan een upload (alleen bij A of B hierboven) + +- A) JPEG, PNG en WebP tot 10 MB; de host controleert het echte bestandstype (niet de naam) en haalt metadata (zoals GPS) uit het bestand +- B) Zoals A, maar tot 5 MB +- C) Niet van toepassing (vraag 7 = C) +- X) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Vraag 9 — Talen - A) Eén taal per site (Nederlands); de site-eigenaar vult het in - B) Nederlands en Engels per hero, beide in het CMS in te voeren -- C) Eén taal nu, maar het datamodel moet later talen kunnen toevoegen zonder migratie van bestaande data +- C) Eén taal nu, maar het datamodel laat later talen toe zonder migratie van bestaande data - X) Other (please describe after [Answer]: tag below) [Answer]: -## Vraag 4 — Afbeeldingen en slides in de hero - -Het datamodel krijgt ruimte voor 0 tot n slides per hero; een slide heeft een afbeelding, alt-tekst en eventueel eigen tekst. SLP Software gebruikt er nul, ASF meerdere. - -- A) Zo: 0 tot n slides per hero, elk met afbeelding, verplichte alt-tekst (of expliciet "decoratief"), optionele eigen tekst en volgorde; de website bepaalt de weergave (slider of niet) -- B) Zoals A, maar de wisselsnelheid, pauzeknop en pijlen zijn ook instelbaar in het CMS -- C) Eén afbeelding per hero (geen slides); de slider van ASF blijft vaste inhoud in de website-code -- X) Other (please describe after [Answer]: tag below) - -[Answer]: - -## Vraag 5 — Hoe komen de afbeeldingen in het CMS? - -- A) Upload in het CMS; de host bewaart het bestand en maakt automatisch varianten (verschillende breedtes, WebP/AVIF) met een adres met inhouds-hash, zodat ze lang gecachet kunnen worden -- B) Upload in het CMS; de host bewaart alleen het origineel (geen varianten); de website schaalt met CSS -- C) Geen upload: het CMS bewaart alleen een adres naar een afbeelding die in de website-build zit (ASF zet de afbeeldingen zelf in zijn build) -- X) Other (please describe after [Answer]: tag below) - -[Answer]: - -## Vraag 6 — Hoe moet de LCP in de eerste HTML komen? - -De host schrijft de hero (tekst, afbeelding, knoppen) in de HTML voordat die naar de browser gaat: voor tekst als gewone elementen, voor een afbeelding met een `` in de kop, `width`/`height`, `fetchpriority="high"` en een `srcset`. Bij een slider is dat de eerste slide; de andere slides laden na de eerste weergave. Na het laden verfrist de website de hero uit de API (NFR-10); als dat mislukt blijft de ingebakken versie staan. - -- A) Ja, zo (host-injectie voor beide sites; de ingebakken tekst blijft als terugval als het CMS niet bereikbaar is) -- B) Zoals A, maar de hero in de ingebakken HTML hoeft alleen bij de volgende bouw van de website bijgewerkt te worden (geen injectie in de eerste HTML) -- X) Other (please describe after [Answer]: tag below) - -[Answer]: - -## Vraag 7 — Hoe snel moet een wijziging zichtbaar zijn? +## Vraag 10 — Hoe snel moet een wijziging zichtbaar zijn? - A) Zoals banners en pakketten nu: binnen ongeveer een minuut (60 seconden cache, direct vernieuwd bij elke wijziging in het CMS) - B) Direct, zonder cache, bij elke bezoeker @@ -70,7 +108,7 @@ De host schrijft de hero (tekst, afbeelding, knoppen) in de HTML voordat die naa [Answer]: -## Vraag 8 — Concept en publiceren +## Vraag 11 — Concept en publiceren - A) Opslaan is publiceren (zoals bij pakketten en banners) - B) Er is een concept: eerst opslaan als concept, een voorbeeld bekijken, dan publiceren @@ -78,15 +116,15 @@ De host schrijft de hero (tekst, afbeelding, knoppen) in de HTML voordat die naa [Answer]: -## Vraag 9 — Planning (van/tot) +## Vraag 12 — Planning (van/tot) - A) Geen planning: een hero is aan of uit -- B) Wel planning (van/tot), zoals bij pakketten en banners; buiten de periode valt de site terug op de standaard-hero +- B) Wel planning (van/tot), zoals bij pakketten en banners; buiten de periode valt de site terug op de ingebakken hero - X) Other (please describe after [Answer]: tag below) [Answer]: -## Vraag 10 — Wie mag de hero wijzigen? +## Vraag 13 — Wie mag de hero wijzigen? - A) Administrator en hoger (zoals pakketten en banners) - B) Alleen de eigenaar (Owner) @@ -94,7 +132,7 @@ De host schrijft de hero (tekst, afbeelding, knoppen) in de HTML voordat die naa [Answer]: -## Vraag 11 — Waar komt de code? +## Vraag 14 — Waar komt de code? - A) Een eigen module `SlpModularCms.Modules.Hero` (met tests), aan of uit per site, zoals Offerings en Contact - B) Binnen de bestaande Offerings-module (hero naast pakketten en banners) @@ -102,34 +140,26 @@ De host schrijft de hero (tekst, afbeelding, knoppen) in de HTML voordat die naa [Answer]: -## Vraag 12 — Wat doen we met de statische teksten die jij nog niet hebt bekeken? +## Vraag 15 — Wat doen we met de statische teksten die jij nog niet hebt bekeken? -Er zijn vaste teksten in de websites (hero, secties van de landingspagina) die nog niet door jou zijn gelezen. Jij vroeg ze in deze feature mee te nemen. +Er zijn vaste teksten in de websites (de hero en de secties van de landingspagina) die nog niet door jou zijn gelezen. Jij vroeg ze in deze feature mee te nemen. -- A) Alleen de hero-teksten: jij leest die en geeft de definitieve tekst; die komt als startinhoud (seed) in het CMS +- A) Alleen de hero-teksten: jij leest die en geeft de definitieve tekst; die komt als startinhoud in het CMS - B) Hero én de andere secties van de landingspagina lezen/herschrijven in deze feature, maar alleen de hero gaat naar het CMS; de rest blijft vaste tekst - C) Hero én de andere secties lezen, en later een algemene "blokken"-module voor al die teksten (apart plan; in deze feature alleen de hero) - X) Other (please describe after [Answer]: tag below) [Answer]: -## Vraag 13 — Start-inhoud (seed) +## Vraag 16 — Startinhoud (seed) -- A) Een script zoals `Seed-Offerings.ps1` zet de huidige teksten van SLP Software en ASF als eerste hero in het CMS van de testomgeving; productie vullen we pas bij de release +- A) Een script zoals `Seed-Offerings.ps1` zet de huidige hero van SLP Software en ASF (inclusief de 8 foto's) als eerste hero in het CMS van de testomgeving; productie vullen we pas bij de release - B) De eigenaar vult de hero zelf in via de admin na uitrol - X) Other (please describe after [Answer]: tag below) [Answer]: -## Vraag 14 — Als het CMS leeg of onbereikbaar is - -- A) De ingebakken hero uit de website-build blijft staan (geen lege hero), zoals in NFR-10 -- B) Het CMS is leidend: zonder hero in het CMS wordt de hero-sectie weggelaten -- X) Other (please describe after [Answer]: tag below) - -[Answer]: - -## Vraag 15 — Beveiligingsregels (extensie) +## Vraag 17 — Beveiligingsregels (extensie) Moeten de beveiligingsregels als harde vereisten worden afgedwongen voor deze feature? (Het gaat om een afbeelding-upload, invoer van beheerders en HTML die de host schrijft.) @@ -139,7 +169,7 @@ Moeten de beveiligingsregels als harde vereisten worden afgedwongen voor deze fe [Answer]: -## Vraag 16 — Property-based testing (extensie) +## Vraag 18 — Property-based testing (extensie) - A) Ja — dwing alle PBT-regels af als blokkerende vereisten - B) Gedeeltelijk — alleen voor pure functies en serialisatie round-trips (bijvoorbeeld HTML-codering van hero-teksten) @@ -148,9 +178,9 @@ Moeten de beveiligingsregels als harde vereisten worden afgedwongen voor deze fe [Answer]: -## Vraag 17 — Operations-fase +## Vraag 19 — Operations-fase -Moet deze feature na Construction door de Operations-fase (uitrol en monitoring inrichten)? De gezamenlijke productie-checklist (`docs/release-checklist-productie.md`) bestaat al en wordt in dat geval aangevuld. +Moet deze feature na Construction door de Operations-fase? De gezamenlijke productie-checklist (`docs/release-checklist-productie.md`) bestaat al en wordt in dat geval aangevuld. - A) Ja — Operations-fase draaien - B) Nee — stoppen na Build and Test; de hero-punten komen in de gezamenlijke productie-checklist -- 2.39.5 From 9806175aedae08507da31d74a30346a8e5cb7006 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:18:17 +0100 Subject: [PATCH 04/47] Hero-module: requirements.md (antwoorden van Bryan verwerkt), SDA-hergebruik gecontroleerd Co-Authored-By: Claude Sonnet 5.5 --- .../features/hero-module/aidlc-state.md | 12 +- aidlc-docs/features/hero-module/audit.md | 12 ++ .../inception/requirements/requirements.md | 152 ++++++++++++++++++ 3 files changed, 170 insertions(+), 6 deletions(-) create mode 100644 aidlc-docs/features/hero-module/inception/requirements/requirements.md diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index 02e9dc7..3198a56 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: hero-module - **Project Type**: Brownfield - **Start Date**: 2026-11-16 -- **Current Stage**: INCEPTION - Requirements Analysis (clarifying questions sent, waiting for answers) +- **Current Stage**: INCEPTION - Requirements Analysis (requirements.md written, waiting for approval) - **Branch**: feature/hero-module (worktree K:\Development\Projects\SlpModularCms-contact-forms, from master b2cacfe) ## Workspace State @@ -32,18 +32,18 @@ ## Extension Configuration | Extension | Enabled | Decided At | |---|---|---| -| Security Baseline | Pending | Requirements Analysis (question in the questions file) | -| Property-Based Testing | Pending | Requirements Analysis (question in the questions file) | +| Security Baseline | Yes (blocking) | Requirements Analysis (Q17 = A) | +| Property-Based Testing | Partial (pure functions and round-trips) | Requirements Analysis (Q18 = B) | ## Operations Configuration -- **Include Operations Phase**: Undecided -- **Decided At**: Pending - asked at Requirements Analysis +- **Include Operations Phase**: No +- **Decided At**: Requirements Analysis (Q19 = B; hero points go into docs/release-checklist-productie.md) ## Stage Progress ### 🔵 INCEPTION PHASE - [x] Workspace Detection (classification: Feature) - [x] Reverse Engineering (skipped: targeted review) -- [ ] Requirements Analysis (questions asked, waiting for answers) +- [x] Requirements Analysis (requirements.md written, awaiting approval) - [ ] User Stories - [ ] Workflow Planning - [ ] Application Design diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index 25fe5d1..b71dc5a 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -35,3 +35,15 @@ **Context**: Requirements Analysis, waiting for Bryan's answers. --- + +## Answers of Bryan processed + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Bryans antwoorden op de 19 Hero-vragen (beantwoord interactief, 2026-11-16). 1 = A ... 7 = A MET EXTRA EISEN: de beheerder moet de afbeelding kunnen croppen, zoomen en/of verplaatsen (focuspunt/uitsnede) ... 8 = A ... MET EXTRA: het CMS verkleint, comprimeert en optimaliseert de foto voor de bedoelde grootte. Bryan wijst op de sessie Decks/Simple Deck App ... 15 = B ... 17 = A ... 18 = B ... 19 = B: geen Operations-fase." (full text relayed by SLP Software - SLS - Main; summarized in requirements.md section 3) + +**AI Response**: Wrote requirements.md (functional, non-functional, security, PBT, out of scope, open items). Asked the SDA session about image processing: nothing reusable (avatar upload only, client-side resize, no server-side validation of content, no crop). Extensions recorded: Security Yes, PBT partial; Operations No. + +**Context**: Requirements Analysis complete, waiting for Bryan's approval (via the SLS session). + +--- diff --git a/aidlc-docs/features/hero-module/inception/requirements/requirements.md b/aidlc-docs/features/hero-module/inception/requirements/requirements.md new file mode 100644 index 0000000..7a262f9 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/requirements/requirements.md @@ -0,0 +1,152 @@ +# Requirements: Hero module (hero-module) + +- **Feature slug**: hero-module +- **Status**: Draft for approval by Bryan (via SLP Software - SLS - Main); answers of 2026-11-16 processed; SDA reuse question answered (nothing to reuse) +- **Depth**: Standard (comprehensive for the image upload, which is security relevant) +- **Documentation Language**: English; **Conversation Language**: Dutch +- **Inputs**: `hero-comparison.md` (SLS vs ASF), `requirement-verification-questions.md` (19 questions, answered by Bryan 2026-11-16), decisions relayed by SLP Software - SLS - Main, facts from Andrea Slop Fotografie - ASF - Main, NFR-10 of the SLS requirements + +## 1. Intent analysis + +| Item | Value | +|---|---| +| User request | Make the hero of both websites (SLP Software and Andrea Slop Fotografie) manageable from the CMS (texts, buttons, images), immediately visible (NFR-10), with the LCP in the first HTML | +| Request type | New feature (a new module) plus a small CI change | +| Scope | Multiple components: new module `SlpModularCms.Modules.Hero`, Core (host injection, media serving), admin frontend, CI workflow, scripts, docs; the websites change on their side | +| Complexity | Moderate to complex (image processing and upload security, host injection contract with two sites) | +| Reverse engineering | Targeted review only (Offerings banners/packages, `HtmlMarkerEditor`/`HtmlMarkerInjector`, `CmsHost` website modes) | + +## 2. Principles decided by Bryan + +1. **Content only.** Like packages and forms: the CMS delivers content; every site keeps its own layout and presentation (ASF Chakra, SLS Tailwind). No layouts or sketch choice in the CMS or in the react package. A sketch choice may come with a third site. +2. **All hero content from the CMS**: title, tagline, lead, buttons, slides (0..n), plus a "display" field each site renders as it supports. +3. **LCP in the first HTML**: the host injects the hero into the HTML (SLS: text; ASF: first slide `` plus preload); the baked hero stays the fallback when the CMS delivers nothing (fail-open, NFR-10). +4. **Stays in the sites**: screen-reader and control texts ("Photo n of N", "Slideshow paused"), the slider timing and animation, reduced-motion behaviour, socials, the SLS code line. + +## 3. Answers (traceability) + +| Q | Answer | Decision | +|---|---|---| +| 1 | A | One hero per site | +| 2 | One title text with line breaks | Title is one text; a new line in the field is a visual line break. The SLS site derives the screen-reader/SEO text from the lines | +| 3 | Tagline and lead; no code line | The code line stays fixed text in the SLS website | +| 4 | A, with validated target | 0 to 2 buttons: label and target; target is `#anchor`, `/path` or `https://…`, validated by the CMS | +| 5 | A | Field `display`: `single` or `slideshow` | +| 6 | A | Slide: image, required alt text (or explicitly decorative), order, on/off | +| 7 | A + extra | Upload; host keeps the original, reads the size, makes variants for `srcset` (WebP/AVIF); **the administrator can set a focus point and/or crop per image and per use/ratio, with a preview in the admin** | +| 8 | A + extra | JPEG, PNG, WebP up to 10 MB; real file type check; strip metadata (GPS); **the CMS resizes, compresses and optimises for the intended size**; reuse what the Decks/SDA session already has (library, settings) without duplicating code | +| 9 | C | One language now; the data model allows more languages later without migrating existing data | +| 10 | A | As banners and packages: 60 s cache, invalidated directly on every CMS change | +| 11 | A | Saving is publishing (no draft) | +| 12 | B | Schedule (from/to); outside the period the site falls back on the baked hero | +| 13 | A | Administrator and higher | +| 14 | A | Own module `SlpModularCms.Modules.Hero` with tests, on/off per site | +| 15 | B | Bryan reviews/rewrites the hero **and** the other sections of the landing page in this feature; only the hero goes to the CMS, the rest stays fixed text in `nl.json` (the SLS session delivers the list of texts per section) | +| 16 | A | A seed script puts the current hero of SLP and ASF (including the 8 photos) in the CMS of the test environment; production only at the release with Bryan's go | +| 17 | A | Security rules enforced (blocking) | +| 18 | B | Property-based testing partial: pure functions and round-trips | +| 19 | B | No Operations phase; hero points go into the joint production checklist | + +## 4. Functional requirements + +### 4.1 Content model (sketch; refined in Application Design) + +| ID | Requirement | +|---|---| +| FR-01 | One hero per site (a single record). If none exists, or none is active, the public endpoint answers 204 and the site uses its baked hero. | +| FR-02 | Fields: `title` (required, one text, new lines allowed, max 200 chars), `tagline` (optional, max 120), `lead` (optional, max 600), `display` (`single` or `slideshow`, default `single`). Plain text only; the host and the sites encode it. | +| FR-03 | 0 to 2 buttons, each with `label` (max 50) and `target` (max 500). Both required per button. Target must match exactly one of: `#anchor` (letters, digits, `-`, `_`), a site path starting with a single `/` (no `//`, no scheme, no backslash, no control characters), or an absolute `https://` address with a host and no credentials. Anything else is rejected with a clear message. | +| FR-04 | 0 to n slides, each with: stable `id`, one image, `alt` text (required, max 300, or an explicit `decorative` flag instead), `order`, `isActive`. Inactive slides are not published. A reasonable maximum (for example 12) protects the page weight. | +| FR-05 | Schedule: optional `startsAt` / `endsAt` for the hero as a whole (as banners). Outside the period the hero counts as not available (204). | +| FR-06 | Text fields and slide data are stored so that a language can be added later without migrating existing rows (for example a language key or a translations structure with the current language as the default); only one language is exposed and edited now. | +| FR-07 | Management needs role Administrator or higher (policy `AdminOnly`); the public read endpoint is anonymous and reachable through the availability gate (like the banner). | + +### 4.2 Images + +| ID | Requirement | +|---|---| +| FR-10 | Upload in the admin of JPEG, PNG and WebP, max 10 MB. The type is decided from the file content (signature and a successful decode), never from the file name or the `Content-Type`. Other types, including SVG, are rejected. | +| FR-11 | All metadata (EXIF including GPS, ICC beyond what is needed for colour, XMP) is removed from every stored and published file. | +| FR-12 | The host keeps the original (after validation) and reads its pixel size. It generates optimised variants: several widths and WebP and AVIF (the format set is settled in Application Design with the image library; if AVIF is not feasible on every platform, WebP plus the original format is the minimum). Variants are resized, compressed and sized for the intended use, not the full upload. | +| FR-13 | **Focus point and crop.** Per image the administrator can set a focus point (the subject that must not be cut off) and/or a crop rectangle (move and zoom), per use or aspect ratio (for example wide desktop hero and tall mobile hero), with a live preview of the result in the admin. The default focus is the centre. The public data contains the focus point (and the ratio variants) so that a site can use it (for example as `object-position`) and the generated variants respect it. | +| FR-14 | Images are served by the host from the site's own address (same origin, no change in CSP `img-src`), at an address that contains the content hash, so they can be cached for a long time (`Cache-Control: public, max-age=31536000, immutable`). Uploading a new image gives a new address. | +| FR-15 | The preload address for the LCP image is exactly the address used in the `img` (or the same `srcset`/`sizes` pair in the preload), so the browser does not download it twice. | +| FR-16 | Deleting a slide or replacing its image removes files that nothing references any more (no orphans). | +| FR-17 | Reuse check done (Decks/SDA session, 2026-11-16): SimpleDeckApp has **no** reusable server-side image processing (only an avatar upload: browser `createImageBitmap` and canvas at 640 px JPEG 0.85, server checks only the `Content-Type` header, no magic bytes, no EXIF stripping, no crop or focus point, no srcset or AVIF). Nothing to reuse or duplicate; the hero module chooses and owns its library. The client-side idea (decode through the browser, re-encode to drop EXIF) is not enough here: the server must validate and strip itself (FR-10, FR-11). | + +### 4.3 Public contract and host injection + +| ID | Requirement | +|---|---| +| FR-20 | `GET /api/v1/hero` (anonymous, `public, max-age=60`, rate limited like the other public Offerings endpoints) returns `{ display, title, tagline, lead, buttons[], slides[{ id, alt, decorative, image{ width, height, focus{x,y}, src, srcset, variants[…] } }] }`, `204` when there is no active hero. The exact shape is agreed with the ASF and SLS sessions (ASF proposes `hero {title, tagline, cta{label,url}, slides[{id, imageUrl, width, height, alt, srcset?}]}`, delivered as golden files after approval). | +| FR-21 | Host injection into the first HTML for both modes (`SpaFallback` for SLS, `PrerenderedPages` for ASF), following the existing marker contract: a region marker for the hero HTML (SLS: title lines, tagline, lead, buttons; ASF: title, tagline, button, first slide `img`), a marker in the head for the preload link, and a `hero` key in the `#cms-data` block with the complete data for the client. Everything is HTML-encoded; script content is escaped like the existing data block. | +| FR-22 | Only the first active slide is injected into the HTML (LCP); the other slides come from the data block and load later in the site. | +| FR-23 | Fail-open: no marker, no hero, an invalid hero or a failing provider leaves the baked page unchanged. The hero follows the same 60 s cache, direct invalidation, ETag/304 and 256-entry cap as the other injected parts. | +| FR-24 | The scheduled hero (FR-05) and inactive slides take effect without a rebuild: outside the period the injected region falls back on the baked content. | +| FR-25 | The admin shows the hero form (texts, display, buttons with validation messages, schedule), the slide list (order, on/off, alt text), the image upload with focus/crop and preview, and a clear indication when the hero is not live. | + +### 4.4 Seed, texts and pipeline + +| ID | Requirement | +|---|---| +| FR-30 | A seed script (like `scripts/Seed-Offerings.ps1`) puts the current SLP hero and the ASF hero with its 8 photos into the CMS of the **test** environment; it needs the owner's credentials as the offerings seed does. Production is seeded only at the release with Bryan's explicit go. | +| FR-31 | Static texts: Bryan reviews and may rewrite the hero **and** the other sections of the landing page. Only the hero goes into the CMS; the other sections stay fixed text (`nl.json` on the SLS site). The SLS session delivers the list of texts per section; the rewritten hero text becomes the seed content. | +| FR-32 | CI: `publish-sls-production` and `deploy-sls-production` only run for a `workflow_dispatch` on a `release/*` branch (`startsWith(github.ref, 'refs/heads/release/')`), like ASF. A dispatch from another branch does nothing. A push never deploys production. Documented in `docs/deploy-en-testomgevingen.md` and `docs/release-checklist-productie.md`. | +| FR-33 | The backend texts of the module (validation messages, injection texts) go in the module's language files (`Texts/nl.json`, `en.json`) per `docs/translation-files.md`. | + +## 5. Non-functional requirements + +| ID | Requirement | +|---|---| +| NFR-01 (LCP) | The LCP element (SLS: heading text; ASF: first slide image) is in the first HTML response, with `fetchpriority="high"` and `width`/`height` for the image and no layout shift; the LCP must not regress against the baked version. Measured on test-ASF and test-SLP with Lighthouse or equivalent before and after. | +| NFR-02 (live) | A change in the CMS is visible within about a minute at most (NFR-10), and directly for the host cache. | +| NFR-03 (page weight) | The first slide delivered to a phone is a small variant (target: well below the 220 to 440 KB JPG of today at the same visual quality); the exact budgets are set in NFR Requirements. | +| NFR-04 (upload safety) | The decode is bounded: maximum pixel count and maximum memory per upload (decompression-bomb protection), a timeout, at most a few uploads processed in parallel, an upload rate limit per user, a body size limit of 10 MB at the framework level. A corrupt or oversized image never takes the host down. | +| NFR-05 (platforms) | The chosen library works on win-x64 self-contained (IIS production) and linux-arm64 (the Pi test hosts) and in the CI (linux x64), with a licence that suits a commercial site. This is verified, not assumed. | +| NFR-06 (storage) | The stored images survive a deploy (releases are replaced), are part of the backup, and work on the Pi and on IIS; whether bytes live in the database or in a shared directory is decided in Application Design. | +| NFR-07 (accessibility) | The CMS requires alt text or an explicit decorative flag; the sites keep their slider accessibility (pause, reduced motion, screen-reader texts). | +| NFR-08 (compatibility) | The public shapes of packages, banners and the injection markers do not change; existing golden files stay green. | +| NFR-09 (resilience) | A failing CMS never produces an empty or broken hero: the baked hero stays. | + +## 6. Security (extension: Security Baseline, enabled, blocking) + +Applicable rules and where the design must show compliance. Final compliance is checked at each stage. + +| Rule | Application to this feature | +|---|---| +| SECURITY-03 | Upload, processing failures and publish events logged with request id, no file contents, no personal data. | +| SECURITY-04 | The media endpoint and the injected HTML keep the existing security headers; `X-Content-Type-Options: nosniff` on media. | +| SECURITY-05 | Every field has type, length and format validation (FR-02, FR-03, FR-04); button targets are allow-listed; images validated by content (FR-10); no string concatenation into SQL; user text is HTML-encoded on injection. | +| SECURITY-08 | Management endpoints require `AdminOnly` server-side; object-level checks on slide and image ids; the public endpoints expose no ids beyond the stable slide id and no management data. | +| SECURITY-09 | Generic error messages; no stack traces; no directory listing for the media path. | +| SECURITY-10 | The new image library is a vetted, pinned dependency, covered by the vulnerability scan; unused packages are not added. | +| SECURITY-11 | Rate limiting on the public hero and media endpoints and on uploads; abuse cases (decompression bomb, polyglot files, path tricks in names, repeated uploads filling storage) are covered in the design. | +| SECURITY-13 | Critical changes (who changed the hero or an image, when) are traceable; no unsafe deserialization of untrusted data; the CMS never stores or uses the client's file name for a path. | +| SECURITY-15 | External calls and image processing have explicit error handling; fail closed on a bad upload, fail open on a bad injection (page served unchanged) — documented as deliberate; the global handler stays. | +| SECURITY-01, 02, 06, 07, 12, 14 | N/A for this feature (no new infrastructure or authentication; existing mechanisms apply). Re-checked in Infrastructure/Operations only if Operations is added. | + +## 7. Property-based testing (extension: partial) + +Properties for pure functions and round-trips only: focus/crop rectangle arithmetic (always inside the image, the focus point stays inside the crop where possible), choice and ordering of variants (monotonic widths, the preload address equals the image address), button target validation (anything accepted is one of the three forms and round-trips through encoding), HTML/JSON encoding of hero text in the injection (decoding returns the original text), slide ordering and the first-active-slide selection. Other behaviour uses example-based tests. + +## 8. Out of scope + +Layouts or sketch choice; the code line of SLS; socials; the timing, animation, aria texts and reduced-motion handling of a site; several languages in the UI; draft/preview workflow; several heroes or a carousel of whole heroes; a general "blocks" module for the other landing-page texts; the IIS publish pipeline for ASF production (separate later idea); production deploys and production variables. + +## 9. Assumptions and open items (to settle in design) + +| # | Item | Owner | +|---|---|---| +| A1 | Image library and AVIF feasibility on win-x64 and linux-arm64; licence. The SDA session has nothing to reuse (see FR-17). Candidates to compare in design: ImageSharp, SkiaSharp, NetVips, Magick.NET | CMS session | +| A2 | Storage of originals and variants (database vs shared directory) | Application Design | +| A3 | Exact crop/focus model: focus point only, crop per ratio, or both; which ratios (for example 16:9 and 3:4); who applies the crop (host-generated variants vs site `object-position`) | Application Design with ASF and SLS sessions | +| A4 | Public JSON shape and marker names: agree with ASF (their proposal and golden files) and SLS | CMS, ASF and SLS sessions | +| A5 | SLS renders the title lines and derives the screen-reader text from them; Bryan wants to see the result on SLP Software | SLS session | +| A6 | Limits: maximum slides, maximum pixels, maximum stored bytes per site | NFR Requirements | +| A7 | Performance budgets and the measuring method for NFR-01 and NFR-03 | NFR Requirements | +| A8 | Seed of the 8 ASF photos needs the files from the ASF repository and an owner login | ASF session, Bryan | +| A9 | `release/*` naming: free after `release/` (for example `release/2026-11-20`) | Agreed | + +## 10. Operations + +Not run as separate stages (Bryan, Q19 = B). Hero points go into [docs/release-checklist-productie.md](../../../../../docs/release-checklist-productie.md): seed on production at the release, Website variables unchanged, media path reachable, a check of the LCP after the release, the `release/*` rule for the SLP production deploy. -- 2.39.5 From 79d88469d3003504468e064d0ad870031ac2b653 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:21:44 +0100 Subject: [PATCH 05/47] Hero-module: execution plan (Workflow Planning) Co-Authored-By: Claude Sonnet 5.5 --- .../features/hero-module/aidlc-state.md | 21 ++- aidlc-docs/features/hero-module/audit.md | 12 ++ .../inception/plans/execution-plan.md | 168 ++++++++++++++++++ 3 files changed, 193 insertions(+), 8 deletions(-) create mode 100644 aidlc-docs/features/hero-module/inception/plans/execution-plan.md diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index 3198a56..7c659fe 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: hero-module - **Project Type**: Brownfield - **Start Date**: 2026-11-16 -- **Current Stage**: INCEPTION - Requirements Analysis (requirements.md written, waiting for approval) +- **Current Stage**: INCEPTION - Workflow Planning (execution plan written, waiting for approval) - **Branch**: feature/hero-module (worktree K:\Development\Projects\SlpModularCms-contact-forms, from master b2cacfe) ## Workspace State @@ -43,12 +43,17 @@ ### 🔵 INCEPTION PHASE - [x] Workspace Detection (classification: Feature) - [x] Reverse Engineering (skipped: targeted review) -- [x] Requirements Analysis (requirements.md written, awaiting approval) -- [ ] User Stories -- [ ] Workflow Planning -- [ ] Application Design -- [ ] Units Generation +- [x] Requirements Analysis (approved by Bryan 2026-11-16) +- [x] User Stories (SKIP: one persona, acceptance criteria in the requirements) +- [x] Workflow Planning (execution-plan.md, awaiting approval) +- [ ] Application Design - EXECUTE +- [ ] Units Generation - EXECUTE ### 🟢 CONSTRUCTION PHASE -- [ ] Not started +- [ ] Functional Design - EXECUTE +- [ ] NFR Requirements - EXECUTE +- [ ] NFR Design - EXECUTE +- [ ] Infrastructure Design - CONDITIONAL (only if storage is a shared directory) +- [ ] Code Generation - EXECUTE (per unit H0 to H6) +- [ ] Build and Test - EXECUTE ### 🟡 OPERATIONS PHASE -- [ ] Undecided +- [ ] SKIP (Q19 = B; points go into the joint production checklist) diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index b71dc5a..7154c67 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -47,3 +47,15 @@ **Context**: Requirements Analysis complete, waiting for Bryan's approval (via the SLS session). --- + +## Requirements approved; Workflow Planning + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Bryan heeft het Hero-requirements-document goedgekeurd (2026-11-16). Ga verder met Workflow Planning en Application Design. ... (1) De tekstenlijst per sectie voor Bryans review (vraag 15) is niet nodig: Bryan heeft het volledige src/i18n/nl.json van SLS al ... (2) SLS-titel in 3 regels met schermlezertekst afgeleid uit de regels: dat werk ik uit voor de SLS-kant ... Houd het datamodel (title met regelafbrekingen) daarop aan. (3) Stem JSON-vorm, markernamen, golden files en het crop/focus-model af met de ASF-sessie; leg de keuze (focuspunt voor object-position of door de host uitgesneden varianten) met een korte aanbeveling aan Bryan voor." (relayed by SLP Software - SLS - Main) + +**AI Response**: Wrote execution-plan.md (Application Design, Units Generation and the design stages execute; User Stories and Reverse Engineering skipped; no Operations phase; units H0 to H6). Asked for approval of the plan before starting Application Design. + +**Context**: Workflow Planning; waiting for approval. + +--- diff --git a/aidlc-docs/features/hero-module/inception/plans/execution-plan.md b/aidlc-docs/features/hero-module/inception/plans/execution-plan.md new file mode 100644 index 0000000..2d7a72d --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/plans/execution-plan.md @@ -0,0 +1,168 @@ +# Execution Plan: hero-module + +## Detailed Analysis Summary + +### Transformation Scope (Brownfield) +- **Transformation Type**: Single new module plus extensions in Core (media serving, host injection) and the admin frontend; a small CI change. +- **Primary Changes**: New `SlpModularCms.Modules.Hero` (+ Tests); image pipeline (validation, metadata stripping, variants, focus/crop); media serving with content-hash addresses; hero injection markers in the host (`HtmlMarkerEditor` / `HtmlMarkerInjector`, preload in the head, `hero` key in `#cms-data`); admin screens; seed script; release-branch condition on the SLP production jobs. +- **Related Components**: `SlpModularCms.Core` (Hosting/Website, rate limiting, texts), `SlpModularCms.Api` (master composition), `Api.SlpSoftware`, `Api.AndreaSlopFotografie` (module reference and committed defaults, `SiteContractTests`), `frontend/` (admin), `.gitea/workflows/continuous_integration.yaml`, `scripts/`, `openapi/slpsoftware.v1.json`, docs. The websites (SLS, ASF) change on their side. + +### Change Impact Assessment +- **User-facing changes**: Yes. The hero of both websites is rendered from CMS content; the admin gets a Hero screen; the public pages change when the sites adopt the markers. +- **Structural changes**: Yes. A new module, a new media-serving path and new injection parts. +- **Data model changes**: Yes. New tables (hero, slides, images/variants) and an EF migration. +- **API changes**: Yes. New public `GET /api/v1/hero`, new management endpoints, new media route; no change to existing contracts (NFR-08). +- **NFR impact**: Yes. LCP, upload safety (decompression bombs, memory), platform support (win-x64, linux-arm64), storage that survives deploys. + +### Component Relationships +```mermaid +flowchart LR + Admin["Admin frontend
(Hero screen)"] + Hero["Modules.Hero
(new)"] + Core["Core
(media serving, injection, texts)"] + Api["Api (master) and site projects"] + SLS["SLP Software website"] + ASF["ASF website"] + CI["CI workflow"] + Admin --> Hero + Hero --> Core + Api --> Hero + Core --> SLS + Core --> ASF + CI -.-> Api + classDef new fill:#FFA726,stroke:#E65100,stroke-width:2px,color:#000; + classDef exist fill:#BBDEFB,stroke:#1565C0,stroke-width:1px,color:#000; + classDef ext fill:#C8E6C9,stroke:#2E7D32,stroke-width:1px,color:#000; + class Hero new; + class Admin,Core,Api,CI exist; + class SLS,ASF ext; +``` +Text alternative: the admin talks to the new Hero module; the module uses Core for media and injection; the master and site projects reference it; Core serves both websites. + +- **Primary Component**: `SlpModularCms.Modules.Hero` (Major, new). +- **Shared Components**: `SlpModularCms.Core` (Minor: new injection parts and media route), `frontend/` (Minor: new feature folder). +- **Dependent Components**: the two websites (golden files and markers agreed with the ASF and SLS sessions); `Api.*` projects (Configuration-only: module reference). +- **Supporting Components**: CI workflow (Minor: release-branch condition), docs and checklist. + +### Risk Assessment +- **Risk Level**: Medium to High (image processing of untrusted uploads; a native library on several platforms; contract with two sites). +- **Rollback Complexity**: Moderate (the module can be switched off per site; the baked hero stays; one migration). +- **Testing Complexity**: Complex (image fixtures, platform matrix, golden files for injection, LCP measurement on test hosts). + +## Workflow Visualization + +```mermaid +flowchart TD + Start(["User Request"]) + + subgraph INCEPTION["🔵 INCEPTION PHASE"] + WD["Workspace Detection
COMPLETED"] + RE["Reverse Engineering
SKIP"] + RA["Requirements Analysis
COMPLETED"] + US["User Stories
SKIP"] + WP["Workflow Planning
IN PROGRESS"] + AD["Application Design
EXECUTE"] + UG["Units Generation
EXECUTE"] + end + + subgraph CONSTRUCTION["🟢 CONSTRUCTION PHASE"] + FD["Functional Design
EXECUTE"] + NFRA["NFR Requirements
EXECUTE"] + NFRD["NFR Design
EXECUTE"] + ID["Infrastructure Design
CONDITIONAL"] + CG["Code Generation
(Planning + Generation)
EXECUTE"] + BT["Build and Test
EXECUTE"] + end + + Start --> WD + WD --> RA + RA --> WP + WP --> AD + AD --> UG + UG --> FD + FD --> NFRA + NFRA --> NFRD + NFRD --> ID + ID --> CG + CG --> BT + BT --> End(["Complete"]) + + style WD fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style RA fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style WP fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style CG fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style BT fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style AD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style UG fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style FD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style NFRA fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style NFRD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style ID fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style RE fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 + style US fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 + style Start fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000 + style End fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000 + style INCEPTION fill:#BBDEFB,stroke:#1565C0,color:#000 + style CONSTRUCTION fill:#C8E6C9,stroke:#2E7D32,color:#000 + linkStyle default stroke:#333,stroke-width:2px +``` +Text alternative: Inception (detection, requirements done; planning in progress; application design and units to execute; reverse engineering and user stories skipped) leads to construction (design stages per unit, code generation, build and test) and ends without an Operations phase. + +## Phases to Execute + +### 🔵 INCEPTION PHASE +- [x] Workspace Detection (COMPLETED) +- [x] Reverse Engineering (SKIPPED: targeted review; `_shared/` artifacts exist) +- [x] Requirements Analysis (COMPLETED, approved by Bryan 2026-11-16) +- [x] User Stories (SKIPPED) + - **Rationale**: One persona (the site administrator) plus the two websites as consumers; the requirements already carry the acceptance criteria and the contract is agreed with the two site sessions. +- [x] Execution Plan (IN PROGRESS) +- [ ] Application Design - EXECUTE + - **Rationale**: New module and new Core components (image pipeline, media store, injection parts); public JSON shape, marker names and crop/focus model (A3, A4) and the storage decision (A2) are decided here, with the ASF and SLS sessions. +- [ ] Units Generation - EXECUTE + - **Rationale**: Several independent pieces (CI condition, image pipeline, module backend, media serving, injection, admin UI, seed and docs) with a dependency order. + +### 🟢 CONSTRUCTION PHASE +- [ ] Functional Design - EXECUTE (per unit where needed: hero and slide rules, focus/crop model, injection output) + - **Rationale**: New data model and business rules (validation of targets, scheduling, slide selection, variant choice). +- [ ] NFR Requirements - EXECUTE (image pipeline and injection units) + - **Rationale**: Library choice (AVIF, licence, win-x64 and linux-arm64), upload limits, LCP and weight budgets (A1, A6, A7). +- [ ] NFR Design - EXECUTE (image pipeline unit) + - **Rationale**: Decompression-bomb protection, bounded parallelism, timeouts, failure behaviour (SECURITY-05, 11, 15). +- [ ] Infrastructure Design - CONDITIONAL + - **Rationale**: Only if storage is a shared directory (A2); with storage in the database it is skipped. Decided in Application Design. +- [ ] Code Generation - EXECUTE (ALWAYS), per unit, build and tests after every unit +- [ ] Build and Test - EXECUTE (ALWAYS) + - **Rationale**: Full suite, OpenAPI snapshot, golden files with ASF, smoke test extended, LCP measured on both test hosts. + +### 🟡 OPERATIONS PHASE +- SKIP (decided at Requirements Analysis, Q19 = B). The hero points go into `docs/release-checklist-productie.md`. + +## Proposed Units (to be confirmed in Units Generation) + +| Unit | Content | Depends on | +|---|---|---| +| H0 | CI: `release/*` condition on `publish-sls-production` and `deploy-sls-production`, docs | none (can be merged early) | +| H1 | Image pipeline: validation by content, metadata stripping, resize/compress, variants, focus/crop arithmetic (pure, property-tested) | library decision | +| H2 | Hero module backend: entities, migration, admin CRUD, public `GET /hero`, validation, schedule, texts, OpenAPI | H1 for upload | +| H3 | Media storage and serving (hash addresses, immutable cache, nosniff, rate limits) | H1 | +| H4 | Host injection (region marker, head preload, `hero` key in `#cms-data`, cache invalidation, golden files with ASF) | H2, H3 | +| H5 | Admin frontend: hero form, slide list, upload with focus/crop and preview | H2, H3 | +| H6 | Seed script (test), docs, release checklist, smoke test extension | H2 to H5 | + +## Package Change Sequence +1. H0 (independent; can go to master first). +2. H1, then H2 and H3 (parallel after H1). +3. H4 and H5 (parallel after H2 and H3). +4. H6, then Build and Test on the test hosts with the websites' markers. + +## Estimated Timeline +- **Total Stages**: 11 to execute (Application Design, Units Generation, Functional Design, NFR Requirements, NFR Design, Infrastructure Design if needed, Code Generation per unit, Build and Test), 3 skipped or not applicable. +- **Estimated Duration**: roughly 6 to 9 working days of build time across the units, excluding the websites' own work and Bryan's review time. + +## Success Criteria +- **Primary Goal**: The hero of both sites comes from the CMS, is live within about a minute, and the LCP element is in the first HTML without a regression. +- **Key Deliverables**: `SlpModularCms.Modules.Hero`, media serving, host injection with golden files, admin Hero screen, seed script, `release/*` condition, docs and checklist update. +- **Quality Gates**: Security rules compliant (blocking); property tests for the pure functions; full suite green; OpenAPI snapshot updated; smoke tests on both test hosts; LCP measured; no merge or production deploy without Bryan's go. +- **Integration Testing**: Both websites with the markers on the test hosts. +- **Operational Readiness**: Covered by the joint production checklist (no Operations phase). -- 2.39.5 From f441ad9366358565a01eb99e6ba71f0b8b45c353 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:23:03 +0100 Subject: [PATCH 06/47] Hero-module: afspraken met ASF over het sitecontract (input voor Application Design) Co-Authored-By: Claude Sonnet 5.5 --- .../site-contract-agreed-with-asf.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md diff --git a/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md b/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md new file mode 100644 index 0000000..d7945d2 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md @@ -0,0 +1,59 @@ +# Hero contract with the websites: points agreed with the ASF session (2026-11-16) + +Input for Application Design. Source: message of "Andrea Slop Fotografie - ASF - Main" (technical answer; the crop/focus model stays Bryan's choice). The SLS side is delivered by the SLS session (three title lines with screen-reader text derived from the lines). + +## Agreed + +| Topic | Agreement | +|---|---| +| Buttons | `buttons[]` of `{label, target}`, 0 to 2. ASF shows one (the first, style "light"); a second would be "outline"; 0 buttons = no button. | +| Title | One text; a new line is a line break (ASF title is one line today). `tagline` stays the label above the title in the same `h1`. | +| Lead | ASF does not render it; if present the site ignores it. | +| Decorative | `decorative: true` renders `alt=""` and is not read aloud. | +| Display | `single`: no arrows, pause button or progress bar (ASF already does that for one slide). | +| 204 / schedule / error | The baked hero stays (fail-open). ASF shows the baked hero on 204, not nothing. If the host ever means "no hero at all", that must be said explicitly (not planned). | +| Image addresses | Same origin `/media/hero//…`, immutable; the CSP `img-src` does not change. | +| Markers | `…` (title, tagline, button(s), the FIRST slide as ``), `` in the head, key `hero` in `#cms-data` with all slides. Fail-open: no marker, 204 or an error leaves the baked page. | +| Hydration | The region holds neutral HTML (fixed classes, no Chakra classes); React takes over with the same source after hydration; slides 2..n load afterwards. The first slide of the data block must equal the first slide the host wrote into the HTML (same source, same cache rule). | +| Golden files | ASF delivers input JSON, expected HTML region and expected preload, with a README and the commit, in `web/contract/host-injection/hero/` on a new ASF branch `feature/hero-module`. They start once Bryan chose the crop model. An A/B-neutral subset (title, tagline, button, first slide `` without ``) can be delivered earlier. | + +## Crop/focus model: input for Bryan's choice + +- **A**: a focus point only; the site uses `object-position`; one ratio per width. +- **B (recommended by both sessions)**: the host cuts variants per named ratio around the focus point (or an administrator-set crop), the focus point stays in the data. ASF can use `` per ratio. + +ASF proposal if B is chosen: + +| Ratio | Name | Widths | Notes | +|---|---|---|---| +| 3:2 | `wide` | 960, 1600, 2560 (the host may choose its own steps, but never upscale) | the `img` itself | +| 4:5 | `tall` | 640, 960, 1280 | `` | + +- `sizes="100vw"`. Selection is by orientation, not by width, because the hero height comes from the screen (100svh with object-fit cover). The focus point stays as `object-position` for in-between shapes (tablet, narrow window). +- Two preload links: `tall` with `media="(orientation: portrait)"` and `wide` with `media="(orientation: landscape)"`, each with `imagesrcset`, `imagesizes="100vw"`, `fetchpriority="high"`. `srcset`, `sizes` and `media` in the preload must be byte-for-byte equal to those in ``/`` in HERO-HTML (the golden files check this). + +## Source images for the seed + +The 8 ASF photos are already resized exports, not camera originals: all landscape 3:2, 1600x1067 (five), 2048x1362 (two) and 2560x1702 (one). The host must never upscale: for the five 1600-wide photos a variant wider than 1600 does not exist. Bryan may supply better originals (needed for good AVIF variants and a true portrait crop); the focus point per photo is Bryan's choice, set in the CMS after the seed. + +Order, with the current alt texts (path `K:\Development\SlpSoftware\Projects\AndreaSlopFotografie\web\src\assets\hero-N.jpg`): + +| # | File | Size | Alt | +|---|---|---|---| +| 1 | hero-8 | 1600x1067 | Zwangerschapsfoto in de duinen | +| 2 | hero-7 | 1600x1067 | Knusse newbornfoto met de familie | +| 3 | hero-1 | 2560x1702 | Lifestyle fotografie | +| 4 | hero-2 | 1600x1067 | Zwangerschapsshoot in de buitenlucht | +| 5 | hero-3 | 1600x1067 | Newbornshoot van een pasgeboren baby | +| 6 | hero-4 | 2048x1362 | Spontaan portret buiten | +| 7 | hero-5 | 1600x1067 | Natuurlijke lifestylefoto | +| 8 | hero-6 | 2048x1362 | Portret in de natuur | + +Seed values: title "Andrea Slop", tagline "Lifestyle fotograaf · Huizen", button "Lees meer" to `/over-mij`, display `slideshow`. + +## Consequences for the design + +- A `` region needs a stable, deterministic rendering of `srcset`/`sizes`/`media` shared by the HERO-HTML and the preload (one generator, golden-tested). +- Variants are limited by the source size (no upscaling); the public data lists only variants that exist. +- Two preload links (portrait, landscape) are needed when a `tall` ratio exists. +- The first-slide data in `#cms-data` and in the HTML must come from the same computation. -- 2.39.5 From cdd0cf8947b0f4c13c7cbaa78bc29884c4a947ab Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:27:40 +0100 Subject: [PATCH 07/47] Hero-module: sitecontract definitief (crop-model B, plan goedgekeurd) Co-Authored-By: Claude Sonnet 5.5 --- aidlc-docs/features/hero-module/audit.md | 12 ++++++++++++ .../requirements/site-contract-agreed-with-asf.md | 11 ++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index 7154c67..c04c90e 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -59,3 +59,15 @@ **Context**: Workflow Planning; waiting for approval. --- + +## Plan approved; crop model B chosen + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Bryans besluiten (2026-11-16): (1) Uitvoeringsplan Hero-module (H0-H6, geen Operations, plan 79d8846) is GOEDGEKEURD: ga door met Application Design; H0 (release/*-conditie) als eerste los mergen naar master (PR + groene checks; alleen test-deploy, geen productie). (2) Crop/focus-model: B. De host snijdt varianten per benoemde verhouding (wide 3:2, tall 4:5, breedtes zoals voorgesteld) rond het focuspunt en levert het focuspunt ook mee; sites gebruiken . (3) Bronfoto's ASF: begin met de huidige 8 exports, geen grotere originelen aanleveren; later uploaden via de admin kan altijd. (4) Focuspunten van de 8 ASF-foto's: de ASF-sessie zet een voorstel ... Maak het contract-document definitief en laat de ASF-sessie de golden files voor + preload leveren." (relayed by SLP Software - SLS - Main) + +**AI Response**: Made the contract document final. H0 built on its own branch from master (458229f). Application Design starts next. + +**Context**: Workflow Planning approved; Application Design. + +--- diff --git a/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md b/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md index d7945d2..8b88eaa 100644 --- a/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md +++ b/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md @@ -1,4 +1,6 @@ -# Hero contract with the websites: points agreed with the ASF session (2026-11-16) +# Hero contract with the websites (FINAL, 2026-11-16) + +**Status**: final. Bryan chose crop/focus model **B** on 2026-11-16 (relayed by SLP Software - SLS - Main). The 8 current ASF exports are the seed sources (no larger originals now; a later upload through the admin is always possible). The ASF session proposes a first-guess focus point per photo (recorded in the seed data); Bryan adjusts them in the admin. The ASF session delivers the golden files for `` and the preload. Input for Application Design. Source: message of "Andrea Slop Fotografie - ASF - Main" (technical answer; the crop/focus model stays Bryan's choice). The SLS side is delivered by the SLS session (three title lines with screen-reader text derived from the lines). @@ -17,12 +19,11 @@ Input for Application Design. Source: message of "Andrea Slop Fotografie - ASF - | Hydration | The region holds neutral HTML (fixed classes, no Chakra classes); React takes over with the same source after hydration; slides 2..n load afterwards. The first slide of the data block must equal the first slide the host wrote into the HTML (same source, same cache rule). | | Golden files | ASF delivers input JSON, expected HTML region and expected preload, with a README and the commit, in `web/contract/host-injection/hero/` on a new ASF branch `feature/hero-module`. They start once Bryan chose the crop model. An A/B-neutral subset (title, tagline, button, first slide `` without ``) can be delivered earlier. | -## Crop/focus model: input for Bryan's choice +## Crop/focus model: B (decided) -- **A**: a focus point only; the site uses `object-position`; one ratio per width. -- **B (recommended by both sessions)**: the host cuts variants per named ratio around the focus point (or an administrator-set crop), the focus point stays in the data. ASF can use `` per ratio. +The host cuts variants per named ratio around the focus point (or an administrator-set crop) and also delivers the focus point; sites use `` per ratio and may use the focus point as `object-position` for in-between shapes. (Option A, a focus point only, was not chosen.) -ASF proposal if B is chosen: +Ratios and widths (ASF proposal, accepted): | Ratio | Name | Widths | Notes | |---|---|---|---| -- 2.39.5 From a1e740c5585aebe7d95745367a0032f27cb31419 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:28:35 +0100 Subject: [PATCH 08/47] Hero-module: application design plan met zes ontwerpvragen Co-Authored-By: Claude Sonnet 5.5 --- aidlc-docs/features/hero-module/audit.md | 12 +++ .../plans/application-design-plan.md | 91 +++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 aidlc-docs/features/hero-module/inception/plans/application-design-plan.md diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index c04c90e..178458d 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -71,3 +71,15 @@ **Context**: Workflow Planning approved; Application Design. --- + +## Application Design plan + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: (no new input; continuing after plan approval) + +**AI Response**: Wrote application-design-plan.md with six design questions (storage, image formats, data block composition, media service location, admin crop UI, focus model), each with a recommendation. The data block `#cms-data` is currently written only by OfferingsHtmlTransform, so the hero key needs a shared composition point. + +**Context**: Application Design, waiting for answers. + +--- diff --git a/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md b/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md new file mode 100644 index 0000000..3bce734 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md @@ -0,0 +1,91 @@ +# Application Design Plan: hero-module + +Vul per vraag de letter in na `[Answer]:`. Bij elke vraag staat mijn aanbeveling; "alle aanbevelingen" mag ook, dan vul ik die in. Het zijn technische keuzes waar ik een besluit van Bryan nodig heb omdat ze kosten, risico of werk voor de websites raken. + +## Wat al vaststaat (uit requirements en contract) + +- Eén module `SlpModularCms.Modules.Hero`; het CMS levert alleen inhoud; crop-model B (host snijdt `wide` 3:2 en `tall` 4:5 rond het focuspunt, focuspunt ook in de data); markers `CMS:HERO-HTML`, `CMS:HERO-PRELOAD` en sleutel `hero` in `#cms-data`; afbeeldingen op `/media/hero//…`, immutable; fail-open. +- Het bestaande blok `#cms-data` wordt nu volledig door `OfferingsHtmlTransform` geschreven (pakketten en banners). Het hero-deel moet in hetzelfde blok komen (afgesproken met ASF). + +## Plan (stappen) + +- [x] 1. Context geanalyseerd (requirements, contract, bestaande `HtmlMarkerInjector`/`IHtmlPageTransform`/`OfferingsHtmlTransform`) +- [ ] 2. Vragen hieronder beantwoord door Bryan +- [ ] 3. Antwoorden geanalyseerd op tegenstrijdigheden en vaagheid +- [ ] 4. `components.md` (componenten en verantwoordelijkheden) +- [ ] 5. `component-methods.md` (signaturen; bedrijfsregels volgen in Functional Design) +- [ ] 6. `services.md` (services en orkestratie) +- [ ] 7. `component-dependency.md` (afhankelijkheden, datastromen) +- [ ] 8. `application-design.md` (samenvatting) en consistentiecontrole +- [ ] 9. Goedkeuring van Bryan + +## Vragen + +### Vraag 1 — Waar bewaart de host de afbeeldingen? + +De bestanden moeten een deploy overleven (releases worden vervangen), in de back-up zitten en werken op de Pi én op IIS. + +- A) In de database (MariaDB, blobs; één plek voor back-up en herstel; geen schrijfrechten op een map nodig, handig op gedeelde hosting). Let op: de limiet `max_allowed_packet` van de database moet voor een upload van 10 MB hoog genoeg staan; dat controleer ik op beide testhosts. +- B) In een map buiten de release (bijvoorbeeld naast de app of in een gedeelde map), met alleen de metadata in de database. Vraagt Infrastructure Design en een aparte back-up van die map. +- C) Originelen in de database, varianten als cache in een map die opnieuw gemaakt kan worden. +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. + +[Answer]: + +### Vraag 2 — Welke afbeeldingsformaten leveren we? + +AVIF is vaak het punt waarop een bibliotheek of platform tegenvalt (win-x64 voor IIS, linux-arm64 op de Pi). De bibliotheek kiezen we in NFR Requirements met een korte proef; het ontwerp zet de verwerking achter een eigen koppeling, zodat de bibliotheek te wisselen is. + +- A) WebP en AVIF zijn beide verplicht; zonder AVIF-ondersteuning op een platform is de bibliotheek ongeschikt +- B) WebP is verplicht (met het originele formaat als terugval); AVIF komt erbij als de gekozen bibliotheek het op alle platformen kan, anders later +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: B. + +[Answer]: + +### Vraag 3 — Hoe komt het hero-deel in het blok `#cms-data`? + +Nu schrijft alleen de Offerings-module dit blok. Er moet één blok blijven (afspraak met ASF). + +- A) Core krijgt een koppeling waarmee elke module een sleutel aan het datablok toevoegt; de Offerings-module gebruikt die ook (uitvoer byte-identiek, de bestaande golden files blijven groen) en de Hero-module voegt `hero` toe +- B) De Hero-module leest het blok dat Offerings schreef en voegt `hero` toe (hangt van de volgorde af; kwetsbaar) +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. + +[Answer]: + +### Vraag 4 — Waar komt de beeldverwerking en het serveren van media? + +Er is al een plan voor een galerij (later), die dezelfde verwerking nodig heeft. + +- A) Alles in de Hero-module +- B) Een algemene, kleine mediadienst in Core (verwerking, opslag, serveren op `/media/…`), die de Hero-module gebruikt en een latere galerij ook kan gebruiken +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: B. + +[Answer]: + +### Vraag 5 — Hoe stelt de beheerder uitsnede en focus in? + +- A) Eigen lichte component in de admin: klik of sleep het focuspunt op de afbeelding, een zoomregelaar, en een live voorbeeld van `wide` en `tall`; geen extra pakket +- B) Een bestaand croppakket (bijvoorbeeld react-easy-crop) als dependency +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. + +[Answer]: + +### Vraag 6 — Wat legt de beheerder per afbeelding vast? + +- A) Eén focuspunt (x,y) en één zoomfactor, gedeeld door beide verhoudingen (`wide` en `tall`); de host berekent elke uitsnede rond dat punt +- B) Per verhouding een eigen focuspunt en zoom (meer vrijheid, meer werk voor de beheerder) +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. Per-verhouding-instellingen kunnen later zonder wijziging van het publieke contract, want de data bevat al per variant de verhouding. + +[Answer]: -- 2.39.5 From 47fcaeb0a1a46b07c32ab680ccee11fd0ddbc3c4 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:44:37 +0100 Subject: [PATCH 09/47] Hero-module: Application Design (componenten, methoden, services, afhankelijkheden); antwoorden van Bryan verwerkt Co-Authored-By: Claude Sonnet 5.5 --- .../features/hero-module/aidlc-state.md | 8 +- aidlc-docs/features/hero-module/audit.md | 12 ++ .../application-design/application-design.md | 55 ++++++++ .../component-dependency.md | 70 ++++++++++ .../application-design/component-methods.md | 125 ++++++++++++++++++ .../application-design/components.md | 76 +++++++++++ .../inception/application-design/services.md | 98 ++++++++++++++ .../plans/application-design-plan.md | 26 ++-- .../inception/requirements/requirements.md | 10 +- 9 files changed, 458 insertions(+), 22 deletions(-) create mode 100644 aidlc-docs/features/hero-module/inception/application-design/application-design.md create mode 100644 aidlc-docs/features/hero-module/inception/application-design/component-dependency.md create mode 100644 aidlc-docs/features/hero-module/inception/application-design/component-methods.md create mode 100644 aidlc-docs/features/hero-module/inception/application-design/components.md create mode 100644 aidlc-docs/features/hero-module/inception/application-design/services.md diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index 7c659fe..7fc5543 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: hero-module - **Project Type**: Brownfield - **Start Date**: 2026-11-16 -- **Current Stage**: INCEPTION - Workflow Planning (execution plan written, waiting for approval) +- **Current Stage**: INCEPTION - Application Design (artifacts written, waiting for approval) - **Branch**: feature/hero-module (worktree K:\Development\Projects\SlpModularCms-contact-forms, from master b2cacfe) ## Workspace State @@ -45,14 +45,14 @@ - [x] Reverse Engineering (skipped: targeted review) - [x] Requirements Analysis (approved by Bryan 2026-11-16) - [x] User Stories (SKIP: one persona, acceptance criteria in the requirements) -- [x] Workflow Planning (execution-plan.md, awaiting approval) -- [ ] Application Design - EXECUTE +- [x] Workflow Planning (approved by Bryan 2026-11-16) +- [x] Application Design (artifacts in inception/application-design/, awaiting approval) - [ ] Units Generation - EXECUTE ### 🟢 CONSTRUCTION PHASE - [ ] Functional Design - EXECUTE - [ ] NFR Requirements - EXECUTE - [ ] NFR Design - EXECUTE -- [ ] Infrastructure Design - CONDITIONAL (only if storage is a shared directory) +- [ ] Infrastructure Design - EXECUTE for the media unit (storage is a directory outside the release) - [ ] Code Generation - EXECUTE (per unit H0 to H6) - [ ] Build and Test - EXECUTE ### 🟡 OPERATIONS PHASE diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index 178458d..1700e7f 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -83,3 +83,15 @@ **Context**: Application Design, waiting for answers. --- + +## Answers to the design questions; Application Design artifacts + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Bryans antwoorden op de 6 ontwerpvragen (2026-11-16). 1. Opslag: een MAP buiten de release (niet de database) ... Zet opslag achter een eigen koppeling zodat database-opslag later kan ... 2. Formaten: Bryan wil dat de uploader zoveel mogelijk invoerformaten ondersteunt ... Welke uitvoerformaten ... mag het systeem zelf bepalen ... 3. Datablok ... Optie 1: Core-koppeling ... 4. Mediadienst: algemeen in Core. 5. Crop-UI: eigen lichte component. 6. Focus: standaard het MIDDEN voor alle verhoudingen; maar er moet per verhouding (mobiel/tall) een apart focuspunt ingesteld kunnen worden (optioneel, valt anders terug op het algemene punt/midden). Werk het ontwerp daarop bij en ga door." (relayed by SLP Software - SLS - Main). Also: "H0 is gemerged: PR #16, merge-commit 0824bfa op master." + +**AI Response**: Recorded the answers in the plan, widened the requirements (input formats, focus per ratio, storage), wrote components.md, component-methods.md, services.md, component-dependency.md and application-design.md. Infrastructure Design now executes for the media unit. + +**Context**: Application Design complete; waiting for approval. + +--- diff --git a/aidlc-docs/features/hero-module/inception/application-design/application-design.md b/aidlc-docs/features/hero-module/inception/application-design/application-design.md new file mode 100644 index 0000000..1cf5696 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/application-design.md @@ -0,0 +1,55 @@ +# Application Design: hero-module (consolidated) + +Details: [components.md](components.md), [component-methods.md](component-methods.md), [services.md](services.md), [component-dependency.md](component-dependency.md). Inputs: `requirements.md`, `site-contract-agreed-with-asf.md`, answers to `application-design-plan.md` (2026-11-16). + +## Decisions + +| # | Decision | Source | +|---|---|---| +| D1 | One module `SlpModularCms.Modules.Hero` (own DbContext, migrations, texts); on or off per site | Q14 (requirements) | +| D2 | A general media service in `Core.Media`: storage interface, image processor interface, upload guard, pure `FocusMath` and `VariantPlanner`, address scheme, media endpoint. Usable later for a gallery | Design Q4 = B | +| D3 | Images are stored in a **directory outside the release** behind `IMediaStore`; a database store can follow if the hosting requires it. Risk R1 recorded; Bryan tests write access on the ASF hosting and is asked again if it fails | Design Q1 = B | +| D4 | Input formats: as many as the library can decode (jpg/jpeg, png, webp always; gif, bmp, tiff, heic/avif where possible), real-signature check, metadata stripped, animation reduced to the first frame; output chosen by the system per platform (WebP required, AVIF when possible) | Design Q2 | +| D5 | `#cms-data` is composed by a Core `CmsDataBlockTransform` from `ICmsDataBlockContributor`s; Offerings becomes a contributor with byte-identical output; the Hero adds `hero` | Design Q3 = A | +| D6 | Crop model B: the host cuts `wide` (3:2) and `tall` (4:5) variants around the focus point and zoom. The focus defaults to the centre for all ratios; a separate focus (and zoom) per ratio is optional and falls back on the general one | Design Q6, contract | +| D7 | The admin focus editor is an own light component (draggable point, zoom, live `wide` and `tall` previews using a TypeScript twin of `FocusMath` with shared test vectors) | Design Q5 = A | +| D8 | Public contract: `GET /api/v1/hero` (204 = none), the same shape under `hero` in `#cms-data`; markers `CMS:HERO-HTML` (region with the first slide as ``) and `CMS:HERO-PRELOAD` (one or two preload links with `media`, byte-equal to the ``/`` attributes); addresses `/media/hero//-.`, immutable | Contract with ASF | +| D9 | One renderer (`HeroPictureRenderer`) produces both the region attributes and the preload attributes; one read model (`PublicHeroService`) feeds the API, the region, the preload and the data block | LCP requirement | +| D10 | Fail-open for page injection, fail-closed for uploads | Requirements, SECURITY-15 | +| D11 | Language: the hero row carries a `Language` (default `nl`, unique), so adding a language needs no migration of existing rows; only one is exposed and edited now | Q9 | + +## Architecture overview + +```mermaid +flowchart LR + Admin["Admin (Hero screen)"] --> Hero["Modules.Hero"] + Hero --> Media["Core.Media
(store, processor, guard, endpoint)"] + Hero --> Inj["Core.Hosting.Website
(transforms, data block, cache)"] + Off["Modules.Offerings"] --> Inj + Inj --> Pages["Website pages (SLS, ASF)"] + Media --> Pages + Dir[("Media directory
outside the release")] --- Media + Db[("MariaDB")] --- Hero + classDef new fill:#FFA726,stroke:#E65100,color:#000; + classDef chg fill:#BBDEFB,stroke:#1565C0,color:#000; + classDef ext fill:#C8E6C9,stroke:#2E7D32,color:#000; + class Hero,Media new; + class Inj,Off,Admin chg; + class Pages,Dir,Db ext; +``` + +Text alternative: the new Hero module and Core.Media (orange) work with the changed injection layer and Offerings (blue); media files live in a directory outside the release and metadata in the database; pages get the hero injected. + +## Open items carried to the next stages + +| Item | Stage | +|---|---| +| Choice and proof of the image library (win-x64, linux-arm64, formats, AVIF, licence), limits (pixels, memory, parallelism, timeouts), budgets for LCP and weight, maximum slides, grace period for old sets | NFR Requirements and NFR Design | +| Whether deleting an image used by a slide refuses or detaches; exact validation messages; byte-exact HTML of the region | Functional Design | +| Write permission of the directory on MijnHostingPartner (IIS) and the backup of the directory | Bryan with ASF; Infrastructure Design (storage is a directory, so this stage now executes for the media unit) | +| Golden files for `` and the preload; focus estimates for the 8 photos | ASF session | +| SLS rendering of the three-line title and its screen-reader text | SLS session | + +## Units (confirmed from the execution plan, adjusted) + +H0 (done, PR #16 merged, 0824bfa) · H1 image pipeline (`Core.Media` processor, guard, `FocusMath`, `VariantPlanner`) · H2 Hero module backend · H3 media store, endpoint, address scheme · H4 injection (data block contributor and Offerings change, region, preload, golden files) · H5 admin frontend · H6 seed, docs, smoke test. Infrastructure Design is now needed for H3 (directory storage). diff --git a/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md b/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md new file mode 100644 index 0000000..7dfd2fe --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md @@ -0,0 +1,70 @@ +# Component dependencies: hero-module + +## Dependency matrix + +Rows depend on columns (X = direct use). + +| | Core.Media | Core.Hosting.Website | Core.Texts | Modules.Hero | Modules.Offerings | Frontend admin | +|---|---|---|---|---|---|---| +| **Modules.Hero** | X (store, processor, guard, paths, math) | X (`IHtmlPageTransform`, `IIndexHtmlMarkerProvider`, `ICmsDataBlockContributor`, `IIndexHtmlCache`) | X | n/a | none | none | +| **Modules.Offerings** | none | X (adds `OfferingsDataContributor`; loses the data block write) | X | none | n/a | none | +| **Core.Media** | n/a | none (endpoint is mapped by the host) | none | none (knows no module) | none | none | +| **Core.Hosting.Website** | none | n/a | none | none | none | none | +| **Frontend admin** | none | none | none | HTTP only (OpenAPI) | HTTP only | n/a | +| **Api / site projects** | X (host registers the media endpoint and options) | X | X | X (project reference) | X | n/a | + +Rules: Core never references a module; the Hero module never references the Offerings module (the data block is composed through the Core contributor interface, so no module knows another). + +## Data flow + +```mermaid +flowchart TD + Admin["Admin browser
(HeroPage, FocusEditor)"] -->|"multipart upload, JSON"| HeroCtl["Hero controllers"] + HeroCtl --> HeroSvc["HeroService / HeroImageService"] + HeroSvc --> Guard["MediaUploadGuard"] + HeroSvc --> Proc["ImageProcessor (library)"] + HeroSvc --> Store["MediaStore (directory)"] + HeroSvc --> Db[("Hero tables
MariaDB")] + HeroSvc --> Cache["IIndexHtmlCache"] + Db --> PubSvc["PublicHeroService"] + PubSvc --> PubApi["GET /api/v1/hero"] + PubSvc --> Tr["Hero transform, preload, data contributor"] + Tr --> Inj["HtmlMarkerInjector"] + Inj --> Page["Website page
(first HTML)"] + Store --> MediaEp["GET /media/..."] + Page -->|"img, picture, preload"| MediaEp + Site["Website (SLS, ASF)"] -->|"refresh after load"| PubApi + Page --> Site + classDef user fill:#f6e05e,stroke:#c05621,color:#000; + classDef host fill:#63b3ed,stroke:#2b6cb0,color:#000; + classDef data fill:#9ae6b4,stroke:#2f855a,color:#000; + classDef ext fill:#CE93D8,stroke:#6A1B9A,color:#000; + class Admin user; + class HeroCtl,HeroSvc,Guard,Proc,PubSvc,PubApi,Tr,Inj,MediaEp,Cache host; + class Store,Db data; + class Page,Site ext; +``` + +Text alternative: the admin uploads through the Hero services into the media directory and the database; the public read model feeds the public endpoint and the page injection; the browser loads images from the media endpoint and the site refreshes from the public endpoint. + +## Communication patterns + +| From to | Pattern | +|---|---| +| Admin to host | REST over HTTPS, cookie/JWT as the other admin screens; multipart for the image | +| Host internal | Dependency injection; services scoped, `IMediaStore` and `IImageProcessor` singletons (stateless, thread-safe) | +| Page build | The injector (singleton with scoped providers) asks transforms in registration order; the data block contributor order fixes the key order | +| Site to host | Anonymous GET of `/api/v1/hero` and `/media/...`; ETag and 304 for pages and media | +| Change notification | Direct call `IIndexHtmlCache.Invalidate()` after commit | + +## Risks and consequences of the design choices + +| # | Risk or consequence | Mitigation | +|---|---|---| +| R1 | **Storage in a directory** (Bryan's choice): the directory must survive a deploy, be in the backup and be writable. Pi: place it in the `shared` directory next to `releases/current` and set `Media__Directory`; IIS (MijnHostingPartner, ASF production): write permission is unknown | The store sits behind `IMediaStore`, so a database store can be added without touching the Hero module. Bryan tests directory write access with ASF; if it fails Bryan is asked again. Startup check: the host logs an error and the hero admin upload is refused (public reads unaffected) when the directory is not writable. Backup: add the directory to the host's back-up script and to the release checklist | +| R2 | Image library: AVIF encoder and native binaries on win-x64 and linux-arm64, licence | Proof in NFR Requirements; processing behind `IImageProcessor`; WebP is the required output, AVIF optional | +| R3 | Wide input list (gif, bmp, tiff, heic/avif) enlarges the attack surface and the library requirements | Allow-list by real signature; decode only through the library inside the guard (pixel, memory and time limits); formats the platform cannot decode are reported as unsupported in the admin; animated input is reduced to the first frame | +| R4 | Two writers of `#cms-data` would conflict | Solved by the Core contributor; the Offerings output stays byte-identical (golden files prove it) | +| R5 | Variant addresses change when the focus changes; an old page cached by a site may point to removed files | Old set kept for a grace period after a change; sites refresh from the API after load | +| R6 | LCP regression if preload and `` differ | One renderer for both, golden-tested with the ASF files | +| R7 | Two preload links (portrait, landscape) double the first request when a browser ignores `media` on preload | Verified in the LCP measurement on both test hosts | diff --git a/aidlc-docs/features/hero-module/inception/application-design/component-methods.md b/aidlc-docs/features/hero-module/inception/application-design/component-methods.md new file mode 100644 index 0000000..c83c9e7 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/component-methods.md @@ -0,0 +1,125 @@ +# Component methods: hero-module + +Signatures and purposes only; business rules are detailed in Functional Design per unit. Types are C# sketches. + +## Core.Media + +```csharp +public interface IMediaStore +{ + Task PutAsync(string key, Stream content, string contentType, CancellationToken ct); + Task OpenReadAsync(string key, CancellationToken ct); // null = not found; MediaFile has Stream, ContentType, Length, LastWriteTime + Task ExistsAsync(string key, CancellationToken ct); + Task DeleteAsync(string key, CancellationToken ct); + Task DeletePrefixAsync(string prefix, CancellationToken ct); // removes every file below an area/hash directory +} + +public interface IImageProcessor +{ + // Real format, pixel size and frame count; throws ImageRejectedException (reason code) for anything unsafe or unsupported. + Task InspectAsync(Stream source, CancellationToken ct); + + // Decode (orientation applied), crop around the focus for a ratio, resize without upscaling, strip metadata, encode. + Task RenderAsync(Stream source, RenderRequest request, CancellationToken ct); + + IReadOnlySet SupportedInput { get; } + IReadOnlySet SupportedOutput { get; } // WebP always; AVIF when the platform can +} + +public sealed record RenderRequest(Ratio Ratio, int Width, ImageFormat Format, int Quality, FocusSetting Focus); +public sealed record FocusSetting(double X, double Y, double Zoom); // 0..1, 0..1, >= 1; default (0.5, 0.5, 1) +public sealed record Ratio(string Name, int Numerator, int Denominator); // wide 3:2, tall 4:5 + +public interface IMediaUploadGuard +{ + // Size, real format, pixel/memory bounds, timeout and parallel gate; returns ImageInfo or throws ImageRejectedException. + Task AdmitAsync(Stream upload, long declaredLength, CancellationToken ct); +} + +public static class FocusMath // pure, property-tested +{ + public static CropRect CropFor(int imageWidth, int imageHeight, Ratio ratio, FocusSetting focus); + public static FocusSetting Normalize(FocusSetting focus); // clamps to valid ranges +} + +public static class VariantPlanner // pure, property-tested +{ + public static IReadOnlyList Plan(int sourceWidth, int sourceHeight, IReadOnlyList ratios, IReadOnlySet outputs); +} + +public static class MediaPaths // pure +{ + public static string SetHash(string originalSha256, IEnumerable<(string Ratio, FocusSetting Focus)> crops); + public static string Url(string area, string setHash, string name); // "/media/hero//wide-1600.webp" + public static bool TryParse(string path, out MediaAddress address); // strict allow-list of characters +} +``` + +`MediaEndpoint` is a minimal-API/endpoint mapping `GET|HEAD /media/{**path}`: parse, open from the store, answer with the immutable headers and `304` on a matching `If-None-Match`; any failure is a plain 404. + +## Core.Hosting.Website + +```csharp +public interface ICmsDataBlockContributor +{ + string Key { get; } // "offerings", "banners", "hero" + int Order { get; } // 100 Offerings, 200 Hero: fixes the key order in the block + Task GetAsync(HtmlTransformContext context, CancellationToken ct); // null is written as JSON null +} + +public sealed class CmsDataBlockTransform(IEnumerable contributors) : IHtmlPageTransform +{ + public bool Wants(string html); // page contains + public Task ApplyAsync(string html, HtmlTransformContext context, CancellationToken ct); +} +``` + +## Modules.Hero + +```csharp +public interface IHeroService +{ + Task GetAsync(string language, CancellationToken ct); // management read incl. inactive + Task SaveAsync(HeroSaveRequest request, string actor, CancellationToken ct); +} + +public interface IHeroImageService +{ + Task UploadAsync(Stream upload, long length, string actor, CancellationToken ct); + Task SetFocusAsync(Guid imageId, HeroFocusRequest request, string actor, CancellationToken ct); // general + optional per ratio + Task DeleteAsync(Guid imageId, string actor, CancellationToken ct); // refuses while a slide uses it, or detaches (decided in Functional Design) + Task RemoveOrphansAsync(CancellationToken ct); +} + +public interface IPublicHeroService +{ + Task GetActiveAsync(string language, DateTimeOffset now, CancellationToken ct); // null = 204 +} + +public static class ButtonTargetValidator +{ + public static ButtonTargetResult Validate(string? target); // Anchor | Path | Https | Invalid(reason) +} + +public static class HeroPictureRenderer +{ + public static string RegionHtml(PublicHeroDto hero, ITextCatalog texts); // title, tagline, buttons, first slide + public static string PreloadHtml(PublicHeroDto hero); // one or two elements +} +``` + +DTO shape (public, `GET /api/v1/hero` and `hero` in `#cms-data`): + +```json +{ "display": "slideshow", "title": "…", "tagline": "…", "lead": null, + "buttons": [ { "label": "…", "target": "/over-mij" } ], + "slides": [ { "id": "guid", "alt": "…", "decorative": false, + "image": { "width": 1600, "height": 1067, "focus": { "x": 0.5, "y": 0.5, "zoom": 1 }, + "src": "/media/hero//wide-1600.webp", + "variants": [ { "ratio": "wide", "width": 1600, "type": "image/webp", "url": "…" }, + { "ratio": "tall", "width": 960, "type": "image/webp", "url": "…" } ] } } ] } +``` + +## Frontend + +`heroApi.getHero()`, `saveHero()`, `uploadImage(file, onProgress)`, `setFocus(imageId, …)`, `deleteImage(imageId)`; `focusMath.cropFor(...)` (TypeScript twin of `FocusMath`, same test vectors). diff --git a/aidlc-docs/features/hero-module/inception/application-design/components.md b/aidlc-docs/features/hero-module/inception/application-design/components.md new file mode 100644 index 0000000..38fc060 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/components.md @@ -0,0 +1,76 @@ +# Components: hero-module + +Namespaces follow the existing modules (`SlpModularCms.Core.*`, `SlpModularCms.Modules.Hero`). "New" = created in this feature, "Changed" = existing code that is adapted. + +## C1. `SlpModularCms.Modules.Hero` (New, the module) + +| Component | Purpose and responsibilities | +|---|---| +| `HeroModule` (`IModule`) | Registers services, DbContext, texts (`AddCmsTextsFrom`), the HTML transform, the preload marker provider and the data contributor; runs the module's migrations. Name `Hero`, switched on or off per site by the project references and committed defaults (like Offerings). | +| `HeroDbContext` + entities | Tables `Heroes`, `HeroSlides`, `HeroImages` (see data model below). Own migrations, same style as the Offerings migrations (hand-written, MySQL). | +| `IHeroRepository`, `IHeroImageRepository` | Persistence of the hero with its slides, and of the images with their variant lists. | +| `IHeroService` | Management use cases: read and save the hero (texts, buttons, display, schedule, slide list and order), validation, change notification. | +| `IHeroImageService` | Upload, replace and remove of an image: validates and processes through the media service, stores the files, writes the metadata, changes focus/zoom per ratio (regenerates the variants), removes orphans. | +| `IPublicHeroService` | The read model for sites: the active hero (schedule and active slides applied) as `PublicHeroDto`, or null. Used by `GET /hero`, the HTML transform and the data contributor, so all three show exactly the same thing. | +| `HeroController` | Public read `GET /api/v1/hero` (anonymous, `[PublicSiteEndpoint]`, `public, max-age=60`, rate-limit policy `hero-public`, 204 when there is no active hero); management `GET /api/v1/hero/all` (the full hero including inactive slides and the schedule) and `PUT /api/v1/hero` (policy `AdminOnly`). Same convention as `offerings` and `offerings/all`. | +| `HeroImagesController` (admin) | `POST /api/v1/hero/images` (multipart upload, size limit), `PUT /api/v1/hero/images/{id}/focus`, `DELETE /api/v1/hero/images/{id}`. | +| `ButtonTargetValidator` | Pure function: accepts `#anchor`, `/path`, `https://host/...`, rejects everything else. | +| `HeroHtmlTransform` (`IHtmlPageTransform`) | Fills `` regions: title lines, tagline, buttons and the first active slide as ``. Fail-open. | +| `HeroPreloadMarkerProvider` (`IIndexHtmlMarkerProvider`) | Writes the one or two `` elements at ``; shares the `srcset`/`sizes`/`media` generator with the transform so they are byte-for-byte equal. | +| `HeroPictureRenderer` | Pure: one place that produces the ``/`` attributes and the preload attributes from a `PublicHeroDto`; golden-tested. | +| `HeroDataContributor` (`ICmsDataBlockContributor`) | Adds the key `hero` (the `PublicHeroDto`, or null) to the data block. | +| `HeroTexts` + `Texts/nl.json`, `en.json` | Backend texts (validation messages) per `docs/translation-files.md`. | + +### Data model (sketch, detailed in Functional Design) + +| Entity | Fields | +|---|---| +| `Hero` | `Id`, `Language` (default `nl`; unique per language so a language can be added later without migrating rows), `Title` (text with line breaks), `Tagline`, `Lead`, `Display` (`single`/`slideshow`), `Button1Label/Target`, `Button2Label/Target`, `StartsAt`, `EndsAt`, `IsActive`, `UpdatedAt`, `UpdatedBy` | +| `HeroSlide` | `Id` (GUID, stable), `HeroId`, `ImageId`, `Alt`, `Decorative`, `SortOrder`, `IsActive` | +| `HeroImage` | `Id`, `OriginalKey` (store key), `Sha256`, `SourceFormat`, `Width`, `Height`, `Bytes`, `Focus` (general, default centre: `X`, `Y`, `Zoom`), optional `WideFocus` and `TallFocus` (`X`, `Y`, `Zoom`, nullable), `VariantSetHash`, `VariantsJson` (list of `{ratio, width, type, key, bytes}`), `CreatedAt` | + +## C2. `SlpModularCms.Core.Media` (New, general media service in Core) + +| Component | Purpose and responsibilities | +|---|---| +| `IMediaStore` | The storage interface: `PutAsync(key, stream, contentType)`, `OpenReadAsync(key)`, `DeleteAsync(key)`, `DeletePrefixAsync(prefix)`, `ExistsAsync`. Keys are relative paths made by the code, never by a client file name. Behind this interface the store can move from a directory to the database if the hosting demands it (risk R1). | +| `FileSystemMediaStore` | Implementation on a directory (`Media:Directory`) outside the release; atomic writes (temp file then move), path containment check (no `..`, no absolute paths, only a safe character set), no directory listing. | +| `IImageProcessor` | The image library behind an interface: `InspectAsync(stream)` (real format, size, frame count, or a rejection), `RenderAsync(source, RenderRequest)` (decode, apply orientation, crop around focus/zoom to a ratio, resize without upscaling, strip metadata, encode to a format and quality). Implementation chosen in NFR Requirements after a proof on win-x64 and linux-arm64 (candidates ImageSharp, NetVips, Magick.NET, SkiaSharp). | +| `ImageProcessingLimits` / `MediaOptions` | `Media:Directory`, maximum upload bytes (10 MB), maximum pixels, maximum parallel jobs, timeout, accepted input formats, output formats and quality per format. | +| `FocusMath`, `VariantPlanner` | Pure, property-tested: the crop rectangle for a ratio from focus and zoom (always inside the image, as close to the focus as the image allows), and the widths per ratio from the source size (no upscaling, monotonic steps). | +| `MediaPaths` | The address scheme `/media///`; builds and parses addresses, computes the set hash from the content hash and the crop parameters, so a change of focus gives a new address. | +| `MediaEndpoint` | `GET /media/{**path}`: anonymous, same origin; `Cache-Control: public, max-age=31536000, immutable`, `ETag`, `304`, `X-Content-Type-Options: nosniff`, content type from the stored file, `Content-Disposition` not set, rate-limit policy `media-public`; unknown or malformed path = 404 with no detail. Also `HEAD`. | +| `IMediaUploadGuard` | The upload checks in one place (size, real format, pixel and memory bounds, decode timeout, parallelism gate), used by every module that accepts images. | + +## C3. `SlpModularCms.Core.Hosting.Website` (Changed) + +| Component | Change | +|---|---| +| `ICmsDataBlockContributor` (New) | `Key`, `Order`, `GetAsync(context, ct)` returning the value (object) for that key or "no value". | +| `CmsDataBlockTransform` (New, `IHtmlPageTransform`) | Owns the `` marker: asks all contributors (ordered by `Order`) and writes `{"siteUrl": …, : , …}` into the data block. Wants = page contains the marker. Fail-open as every transform. If a contributor throws, the whole block is left as baked: a half-filled block would mislead the site (fail-open for the block as a whole). | +| `OfferingsHtmlTransform` (Changed, module Offerings) | No longer writes the data block; its regions, JSON-LD and prices stay. A new `OfferingsDataContributor` (`Order` 100) supplies `offerings` and `banners`. The output of the block stays byte-identical (key order `siteUrl`, `offerings`, `banners`, then `hero`), so all existing golden files stay green. | +| `HtmlMarkerEditor` | Unchanged API; the preload marker is written through the existing `IIndexHtmlMarkerProvider` (whole-comment replacement). | + +## C4. Frontend admin (New feature folder `frontend/src/features/hero`) + +| Component | Purpose | +|---|---| +| `HeroPage` | The Hero screen in the admin navigation (visible when the Hero module is on, via `/System/capabilities`), shows whether the hero is live (schedule, active slides). | +| `HeroForm` | Title (multi-line), tagline, lead, display, up to two buttons with target validation messages, schedule. | +| `SlideList` | Order (up/down), on/off, alt text or "decorative", remove, add. | +| `ImageUploader` | Upload with progress, shows the accepted formats and the size limit, rejection messages. | +| `FocusEditor` | Own light component: the image with a draggable focus point, a zoom control, live previews of `wide` (3:2) and `tall` (4:5) cut as the host will cut them (same pure maths, shared as a small TypeScript twin of `FocusMath` with the same test vectors), and optional per-ratio overrides with "use the general point" reset. | +| `heroApi`, translations | React Query hooks and `nl/en` texts. | + +## C5. Scripts, docs, CI + +| Component | Purpose | +|---|---| +| `scripts/Seed-Hero.ps1` (+ data) | Seeds the SLP hero and the ASF hero with its 8 photos and the focus estimates of the ASF session, on test only; needs the owner's login like `Seed-Offerings.ps1`. | +| `scripts/smoke-site.sh` (Changed) | Checks the public hero endpoint (200 or 204), a media address answers with the immutable header, and, for a site with markers, no unprocessed hero markers. | +| `docs/hero-module.md` (New) | Contract, addresses, storage and the hosting risk, operation. | +| CI H0 | Done (merged, 0824bfa). | + +## Sites (outside this repository) + +The SLP and ASF websites place the markers and render ``; contract in `site-contract-agreed-with-asf.md`. diff --git a/aidlc-docs/features/hero-module/inception/application-design/services.md b/aidlc-docs/features/hero-module/inception/application-design/services.md new file mode 100644 index 0000000..9806610 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/services.md @@ -0,0 +1,98 @@ +# Services and orchestration: hero-module + +## Services + +| Service | Responsibility | Collaborators | +|---|---|---| +| `HeroService` (management) | Reads and saves the hero: validates fields (lengths, button targets via `ButtonTargetValidator`, schedule order, slide count and order), writes the hero and slides in one transaction, calls the cache invalidation. | `IHeroRepository`, `ITextCatalog`, `IIndexHtmlCache` | +| `HeroImageService` | The upload pipeline and focus changes (below). Owns the rule that every stored file belongs to exactly one image set. | `IMediaUploadGuard`, `IImageProcessor`, `IMediaStore`, `IHeroImageRepository`, `IIndexHtmlCache` | +| `PublicHeroService` | Builds the public read model from the stored hero: schedule and `IsActive` applied, inactive slides removed, variants that exist listed, the first-slide choice made once here. | `IHeroRepository`, `TimeProvider` | +| Core `MediaEndpoint` | Serves stored variants; no knowledge of the Hero module. | `IMediaStore` | +| Core `CmsDataBlockTransform` | Composes the `#cms-data` block from all contributors. | `ICmsDataBlockContributor` implementations | +| `HeroHtmlTransform`, `HeroPreloadMarkerProvider` | Write the region and the preload from the same `PublicHeroDto` through `HeroPictureRenderer`. | `IPublicHeroService` | + +## Orchestration + +### Upload of an image + +```mermaid +sequenceDiagram + box rgba(246,224,94,0.4) Admin + participant A as Admin browser + end + box rgba(99,179,237,0.4) Host + participant C as HeroImagesController + participant S as HeroImageService + participant G as MediaUploadGuard + participant P as ImageProcessor + participant M as MediaStore + participant R as Repository + end + A->>C: POST image (multipart) + C->>S: UploadAsync(stream, length, actor) + S->>G: AdmitAsync (size, real format, bounds, timeout, gate) + G-->>S: ImageInfo or rejection + S->>M: Put original (set directory) + S->>P: Render variants per ratio and width + P-->>S: encoded files, metadata stripped + S->>M: Put variants + S->>R: Save HeroImage (hash, size, variants) + S-->>C: HeroImageDto + C-->>A: 201 with the image and its variants +``` + +Text alternative: the admin uploads; the service admits the file, stores the original, renders and stores the variants, saves the metadata, and returns the image with its variant addresses. + +Rules of the pipeline: +1. Reject early (size, real format, pixel count, frame count, timeout); a rejection is a clear 400 and nothing is stored. +2. Write to a temporary location first; only a completely processed set is made visible (one move per set). A failure removes the partial files. +3. The set hash is computed from the original's SHA-256 and the crop parameters; the variant addresses contain it. +4. At most a few uploads are processed in parallel (gate); the rest wait or get 429. + +### Change of focus + +`SetFocusAsync` validates the numbers (ranges), recomputes the set hash, renders the affected ratios again into the new set directory, saves the new addresses, then removes the old set directory (after the commit). A site that still holds the old data block keeps working until its cache expires (the old files go after a grace period, decided in Functional Design). + +### Publishing and live updates + +```mermaid +flowchart LR + Save["PUT /hero or image change"] --> Repo["Repository (commit)"] + Repo --> Inval["IIndexHtmlCache.Invalidate()"] + Inval --> Cache["HtmlMarkerInjector cache dropped"] + Req["Next page request"] --> Inj["HtmlMarkerInjector"] + Inj --> T1["CmsDataBlockTransform
(offerings, banners, hero)"] + Inj --> T2["HeroHtmlTransform
(region + first slide)"] + Inj --> T3["HeroPreloadMarkerProvider
(head)"] + T1 --> Pub["PublicHeroService"] + T2 --> Pub + T3 --> Pub + Api["GET /api/v1/hero"] --> Pub + classDef act fill:#FFA726,stroke:#E65100,color:#000; + classDef core fill:#BBDEFB,stroke:#1565C0,color:#000; + classDef mod fill:#9ae6b4,stroke:#2f855a,color:#000; + class Save,Req,Api act; + class Inval,Cache,Inj,T1 core; + class Repo,T2,T3,Pub mod; +``` + +Text alternative: a save commits and invalidates the page cache; the next page request rebuilds the page through the data block, region and preload, all reading the one public read model, which the public endpoint also uses. + +### Failure behaviour + +| Where | Behaviour | +|---|---| +| Upload or processing fails | Fail closed: 4xx with a generic message, partial files removed, nothing published. | +| `PublicHeroService` fails or finds no active hero | Region, preload and `hero` key are left as baked (data block: `hero` is `null`; the site keeps the baked hero). The page is served. | +| A contributor fails | The data block is left as baked entirely. | +| Media file missing or unreadable | 404 for that address; the data block lists only variants that were stored. | +| Storage unwritable | Upload fails with a generic 503-style message and an error log; public reads are unaffected. | + +## Cross-cutting + +- **Texts**: validation and rejection messages go through `ITextCatalog` with `HeroTexts` keys (`hero.validation.*`, `hero.image.*`); the technical rejection reason codes stay English constants. +- **Authorization**: management routes `AdminOnly`; public routes anonymous and marked `[PublicSiteEndpoint]` so they pass the availability gate. +- **Rate limiting**: new policies `hero-public` (120 per 60 s like offerings), `media-public` (high, per client address, allows the page's images), `hero-upload` (low, per user). +- **Logging**: structured, with the request id, actor and image id; never file contents or file names from the client. +- **Auditing**: `UpdatedBy`/`UpdatedAt` on the hero and `CreatedAt` plus actor on images, plus a log line per change (who, what, when) for SECURITY-13. +- **Cache keys**: the injector's per-file cache already keys by page; hero changes call `Invalidate()` like offerings and banners do. diff --git a/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md b/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md index 3bce734..72f9ebd 100644 --- a/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md +++ b/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md @@ -10,13 +10,13 @@ Vul per vraag de letter in na `[Answer]:`. Bij elke vraag staat mijn aanbeveling ## Plan (stappen) - [x] 1. Context geanalyseerd (requirements, contract, bestaande `HtmlMarkerInjector`/`IHtmlPageTransform`/`OfferingsHtmlTransform`) -- [ ] 2. Vragen hieronder beantwoord door Bryan -- [ ] 3. Antwoorden geanalyseerd op tegenstrijdigheden en vaagheid -- [ ] 4. `components.md` (componenten en verantwoordelijkheden) -- [ ] 5. `component-methods.md` (signaturen; bedrijfsregels volgen in Functional Design) -- [ ] 6. `services.md` (services en orkestratie) -- [ ] 7. `component-dependency.md` (afhankelijkheden, datastromen) -- [ ] 8. `application-design.md` (samenvatting) en consistentiecontrole +- [x] 2. Vragen hieronder beantwoord door Bryan (2026-11-16, via SLS-Main) +- [x] 3. Antwoorden geanalyseerd: geen tegenstrijdigheid; Q2 en Q6 verbreden de requirements (zie requirements.md, aangepast) +- [x] 4. `components.md` (componenten en verantwoordelijkheden) +- [x] 5. `component-methods.md` (signaturen; bedrijfsregels volgen in Functional Design) +- [x] 6. `services.md` (services en orkestratie) +- [x] 7. `component-dependency.md` (afhankelijkheden, datastromen) +- [x] 8. `application-design.md` (samenvatting) en consistentiecontrole - [ ] 9. Goedkeuring van Bryan ## Vragen @@ -32,7 +32,7 @@ De bestanden moeten een deploy overleven (releases worden vervangen), in de back Aanbeveling: A. -[Answer]: +[Answer]: B. Een MAP buiten de release (niet de database). Opslag komt achter een eigen koppeling zodat database-opslag later kan; risico's en gevolgen in het ontwerp; Bryan wordt opnieuw gevraagd als de proef op de hosting (MijnHostingPartner, IIS) tegenvalt. ### Vraag 2 — Welke afbeeldingsformaten leveren we? @@ -44,7 +44,7 @@ AVIF is vaak het punt waarop een bibliotheek of platform tegenvalt (win-x64 voor Aanbeveling: B. -[Answer]: +[Answer]: Invoer: zoveel mogelijk formaten (jpg/jpeg, png, webp en waar de bibliotheek het kan gif, bmp, tiff, heic/avif), met echte typecontrole en metadata strippen. Uitvoer: het systeem kiest per platform (WebP verplicht, AVIF als het kan). ### Vraag 3 — Hoe komt het hero-deel in het blok `#cms-data`? @@ -56,7 +56,7 @@ Nu schrijft alleen de Offerings-module dit blok. Er moet één blok blijven (afs Aanbeveling: A. -[Answer]: +[Answer]: A. Core-koppeling waarmee elke module een sleutel aan het datablok toevoegt; Offerings gebruikt die ook (byte-identieke uitvoer, groene golden files). ### Vraag 4 — Waar komt de beeldverwerking en het serveren van media? @@ -68,7 +68,7 @@ Er is al een plan voor een galerij (later), die dezelfde verwerking nodig heeft. Aanbeveling: B. -[Answer]: +[Answer]: B. Algemene mediadienst in Core. ### Vraag 5 — Hoe stelt de beheerder uitsnede en focus in? @@ -78,7 +78,7 @@ Aanbeveling: B. Aanbeveling: A. -[Answer]: +[Answer]: A. Eigen lichte component. ### Vraag 6 — Wat legt de beheerder per afbeelding vast? @@ -88,4 +88,4 @@ Aanbeveling: A. Aanbeveling: A. Per-verhouding-instellingen kunnen later zonder wijziging van het publieke contract, want de data bevat al per variant de verhouding. -[Answer]: +[Answer]: Standaard het midden voor alle verhoudingen; per verhouding (tall/mobiel, ook wide) kan optioneel een apart focuspunt worden ingesteld, anders terugval op het algemene punt (midden). diff --git a/aidlc-docs/features/hero-module/inception/requirements/requirements.md b/aidlc-docs/features/hero-module/inception/requirements/requirements.md index 7a262f9..20149da 100644 --- a/aidlc-docs/features/hero-module/inception/requirements/requirements.md +++ b/aidlc-docs/features/hero-module/inception/requirements/requirements.md @@ -34,7 +34,7 @@ | 5 | A | Field `display`: `single` or `slideshow` | | 6 | A | Slide: image, required alt text (or explicitly decorative), order, on/off | | 7 | A + extra | Upload; host keeps the original, reads the size, makes variants for `srcset` (WebP/AVIF); **the administrator can set a focus point and/or crop per image and per use/ratio, with a preview in the admin** | -| 8 | A + extra | JPEG, PNG, WebP up to 10 MB; real file type check; strip metadata (GPS); **the CMS resizes, compresses and optimises for the intended size**; reuse what the Decks/SDA session already has (library, settings) without duplicating code | +| 8 | A + extra, widened by Bryan (design answer Q2) | Input: as many formats as possible, mainly the common ones (jpg/jpeg, png, webp and, where the library can, gif, bmp, tiff, heic/avif), up to 10 MB, with a real file type check and metadata stripping (GPS). Output: the system chooses what is best per platform (WebP required, AVIF when it can). **The CMS resizes, compresses and optimises for the intended size**; the Decks/SDA session has nothing to reuse | | 9 | C | One language now; the data model allows more languages later without migrating existing data | | 10 | A | As banners and packages: 60 s cache, invalidated directly on every CMS change | | 11 | A | Saving is publishing (no draft) | @@ -65,10 +65,10 @@ | ID | Requirement | |---|---| -| FR-10 | Upload in the admin of JPEG, PNG and WebP, max 10 MB. The type is decided from the file content (signature and a successful decode), never from the file name or the `Content-Type`. Other types, including SVG, are rejected. | +| FR-10 | Upload in the admin, max 10 MB, of the common image formats: JPEG, PNG and WebP always, and where the chosen library supports them GIF, BMP, TIFF, HEIC and AVIF (the supported list is fixed in NFR Requirements and shown in the admin). The type is decided from the file content (signature and a successful decode), never from the file name or the `Content-Type`. Anything else, including SVG, is rejected. An animated input (GIF, WebP) is reduced to its first frame. | | FR-11 | All metadata (EXIF including GPS, ICC beyond what is needed for colour, XMP) is removed from every stored and published file. | | FR-12 | The host keeps the original (after validation) and reads its pixel size. It generates optimised variants: several widths and WebP and AVIF (the format set is settled in Application Design with the image library; if AVIF is not feasible on every platform, WebP plus the original format is the minimum). Variants are resized, compressed and sized for the intended use, not the full upload. | -| FR-13 | **Focus point and crop.** Per image the administrator can set a focus point (the subject that must not be cut off) and/or a crop rectangle (move and zoom), per use or aspect ratio (for example wide desktop hero and tall mobile hero), with a live preview of the result in the admin. The default focus is the centre. The public data contains the focus point (and the ratio variants) so that a site can use it (for example as `object-position`) and the generated variants respect it. | +| FR-13 | **Focus point and crop.** Per image the administrator can set a focus point (the subject that must not be cut off) and/or a crop rectangle (move and zoom), per use or aspect ratio (for example wide desktop hero and tall mobile hero), with a live preview of the result in the admin. The default focus is the centre for every ratio; per ratio (`tall`, `wide`) a separate focus point (and zoom) can optionally be set, otherwise the general point (the centre) applies (Bryan, design answer Q6). The public data contains the general focus point and the ratio variants so that a site can use it (for example as `object-position`) and the generated variants respect the per-ratio settings. | | FR-14 | Images are served by the host from the site's own address (same origin, no change in CSP `img-src`), at an address that contains the content hash, so they can be cached for a long time (`Cache-Control: public, max-age=31536000, immutable`). Uploading a new image gives a new address. | | FR-15 | The preload address for the LCP image is exactly the address used in the `img` (or the same `srcset`/`sizes` pair in the preload), so the browser does not download it twice. | | FR-16 | Deleting a slide or replacing its image removes files that nothing references any more (no orphans). | @@ -103,7 +103,7 @@ | NFR-03 (page weight) | The first slide delivered to a phone is a small variant (target: well below the 220 to 440 KB JPG of today at the same visual quality); the exact budgets are set in NFR Requirements. | | NFR-04 (upload safety) | The decode is bounded: maximum pixel count and maximum memory per upload (decompression-bomb protection), a timeout, at most a few uploads processed in parallel, an upload rate limit per user, a body size limit of 10 MB at the framework level. A corrupt or oversized image never takes the host down. | | NFR-05 (platforms) | The chosen library works on win-x64 self-contained (IIS production) and linux-arm64 (the Pi test hosts) and in the CI (linux x64), with a licence that suits a commercial site. This is verified, not assumed. | -| NFR-06 (storage) | The stored images survive a deploy (releases are replaced), are part of the backup, and work on the Pi and on IIS; whether bytes live in the database or in a shared directory is decided in Application Design. | +| NFR-06 (storage) | Decided (design answer Q1): the images live in a **directory outside the release**, behind an own storage interface so that database storage can follow if the hosting demands it. The directory survives a deploy (Pi: `releases/current/shared`; IIS: a data directory), is part of the backup, and the host account has write permission there. Write permission on the ASF production hosting (MijnHostingPartner, IIS) is not known and is tested by Bryan with ASF; Bryan is asked again if that test fails. | | NFR-07 (accessibility) | The CMS requires alt text or an explicit decorative flag; the sites keep their slider accessibility (pause, reduced motion, screen-reader texts). | | NFR-08 (compatibility) | The public shapes of packages, banners and the injection markers do not change; existing golden files stay green. | | NFR-09 (resilience) | A failing CMS never produces an empty or broken hero: the baked hero stays. | @@ -138,7 +138,7 @@ Layouts or sketch choice; the code line of SLS; socials; the timing, animation, | # | Item | Owner | |---|---|---| | A1 | Image library and AVIF feasibility on win-x64 and linux-arm64; licence. The SDA session has nothing to reuse (see FR-17). Candidates to compare in design: ImageSharp, SkiaSharp, NetVips, Magick.NET | CMS session | -| A2 | Storage of originals and variants (database vs shared directory) | Application Design | +| A2 | ~~Storage~~ Decided: directory outside the release behind an interface (see NFR-06); the hosting test is open | Bryan with ASF | | A3 | Exact crop/focus model: focus point only, crop per ratio, or both; which ratios (for example 16:9 and 3:4); who applies the crop (host-generated variants vs site `object-position`) | Application Design with ASF and SLS sessions | | A4 | Public JSON shape and marker names: agree with ASF (their proposal and golden files) and SLS | CMS, ASF and SLS sessions | | A5 | SLS renders the title lines and derives the screen-reader text from them; Bryan wants to see the result on SLP Software | SLS session | -- 2.39.5 From 850f02d5ecffe5d86f802dab98e4081edfc8e59e Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:45:28 +0100 Subject: [PATCH 10/47] Hero-module: ASF golden files verwerkt in het ontwerp (preload als regio-paar, alleen WebP in LCP) Co-Authored-By: Claude Sonnet 5.5 --- .../application-design/application-design.md | 2 +- .../application-design/component-dependency.md | 2 +- .../inception/application-design/components.md | 3 +-- .../inception/application-design/services.md | 4 ++-- .../requirements/site-contract-agreed-with-asf.md | 14 ++++++++++++++ 5 files changed, 19 insertions(+), 6 deletions(-) diff --git a/aidlc-docs/features/hero-module/inception/application-design/application-design.md b/aidlc-docs/features/hero-module/inception/application-design/application-design.md index 1cf5696..d68c183 100644 --- a/aidlc-docs/features/hero-module/inception/application-design/application-design.md +++ b/aidlc-docs/features/hero-module/inception/application-design/application-design.md @@ -13,7 +13,7 @@ Details: [components.md](components.md), [component-methods.md](component-method | D5 | `#cms-data` is composed by a Core `CmsDataBlockTransform` from `ICmsDataBlockContributor`s; Offerings becomes a contributor with byte-identical output; the Hero adds `hero` | Design Q3 = A | | D6 | Crop model B: the host cuts `wide` (3:2) and `tall` (4:5) variants around the focus point and zoom. The focus defaults to the centre for all ratios; a separate focus (and zoom) per ratio is optional and falls back on the general one | Design Q6, contract | | D7 | The admin focus editor is an own light component (draggable point, zoom, live `wide` and `tall` previews using a TypeScript twin of `FocusMath` with shared test vectors) | Design Q5 = A | -| D8 | Public contract: `GET /api/v1/hero` (204 = none), the same shape under `hero` in `#cms-data`; markers `CMS:HERO-HTML` (region with the first slide as ``) and `CMS:HERO-PRELOAD` (one or two preload links with `media`, byte-equal to the ``/`` attributes); addresses `/media/hero//-.`, immutable | Contract with ASF | +| D8 | Public contract: `GET /api/v1/hero` (204 = none), the same shape under `hero` in `#cms-data`; region pairs `…` (first slide as ``) and `…` in the head (one or two preload links with `media`, byte-equal to the ``/`` attributes); only WebP in the LCP picture and the preload; addresses `/media/hero//-.`, immutable | Contract with ASF | | D9 | One renderer (`HeroPictureRenderer`) produces both the region attributes and the preload attributes; one read model (`PublicHeroService`) feeds the API, the region, the preload and the data block | LCP requirement | | D10 | Fail-open for page injection, fail-closed for uploads | Requirements, SECURITY-15 | | D11 | Language: the hero row carries a `Language` (default `nl`, unique), so adding a language needs no migration of existing rows; only one is exposed and edited now | Q9 | diff --git a/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md b/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md index 7dfd2fe..1548291 100644 --- a/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md +++ b/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md @@ -6,7 +6,7 @@ Rows depend on columns (X = direct use). | | Core.Media | Core.Hosting.Website | Core.Texts | Modules.Hero | Modules.Offerings | Frontend admin | |---|---|---|---|---|---|---| -| **Modules.Hero** | X (store, processor, guard, paths, math) | X (`IHtmlPageTransform`, `IIndexHtmlMarkerProvider`, `ICmsDataBlockContributor`, `IIndexHtmlCache`) | X | n/a | none | none | +| **Modules.Hero** | X (store, processor, guard, paths, math) | X (`IHtmlPageTransform`, `ICmsDataBlockContributor`, `IIndexHtmlCache`) | X | n/a | none | none | | **Modules.Offerings** | none | X (adds `OfferingsDataContributor`; loses the data block write) | X | none | n/a | none | | **Core.Media** | n/a | none (endpoint is mapped by the host) | none | none (knows no module) | none | none | | **Core.Hosting.Website** | none | n/a | none | none | none | none | diff --git a/aidlc-docs/features/hero-module/inception/application-design/components.md b/aidlc-docs/features/hero-module/inception/application-design/components.md index 38fc060..9f1452e 100644 --- a/aidlc-docs/features/hero-module/inception/application-design/components.md +++ b/aidlc-docs/features/hero-module/inception/application-design/components.md @@ -15,8 +15,7 @@ Namespaces follow the existing modules (`SlpModularCms.Core.*`, `SlpModularCms.M | `HeroController` | Public read `GET /api/v1/hero` (anonymous, `[PublicSiteEndpoint]`, `public, max-age=60`, rate-limit policy `hero-public`, 204 when there is no active hero); management `GET /api/v1/hero/all` (the full hero including inactive slides and the schedule) and `PUT /api/v1/hero` (policy `AdminOnly`). Same convention as `offerings` and `offerings/all`. | | `HeroImagesController` (admin) | `POST /api/v1/hero/images` (multipart upload, size limit), `PUT /api/v1/hero/images/{id}/focus`, `DELETE /api/v1/hero/images/{id}`. | | `ButtonTargetValidator` | Pure function: accepts `#anchor`, `/path`, `https://host/...`, rejects everything else. | -| `HeroHtmlTransform` (`IHtmlPageTransform`) | Fills `` regions: title lines, tagline, buttons and the first active slide as ``. Fail-open. | -| `HeroPreloadMarkerProvider` (`IIndexHtmlMarkerProvider`) | Writes the one or two `` elements at ``; shares the `srcset`/`sizes`/`media` generator with the transform so they are byte-for-byte equal. | +| `HeroHtmlTransform` (`IHtmlPageTransform`) | Fills the two regions `…` (title, tagline, buttons and the first active slide as ``) and `…` in the head (one or two ``), both from the same renderer so `srcset`/`sizes`/`media` are byte-for-byte equal. Fail-open. (Changed after the ASF golden files: the preload is a region pair, not a single marker, so no separate marker provider is needed.) | | `HeroPictureRenderer` | Pure: one place that produces the ``/`` attributes and the preload attributes from a `PublicHeroDto`; golden-tested. | | `HeroDataContributor` (`ICmsDataBlockContributor`) | Adds the key `hero` (the `PublicHeroDto`, or null) to the data block. | | `HeroTexts` + `Texts/nl.json`, `en.json` | Backend texts (validation messages) per `docs/translation-files.md`. | diff --git a/aidlc-docs/features/hero-module/inception/application-design/services.md b/aidlc-docs/features/hero-module/inception/application-design/services.md index 9806610..bc2e6b8 100644 --- a/aidlc-docs/features/hero-module/inception/application-design/services.md +++ b/aidlc-docs/features/hero-module/inception/application-design/services.md @@ -9,7 +9,7 @@ | `PublicHeroService` | Builds the public read model from the stored hero: schedule and `IsActive` applied, inactive slides removed, variants that exist listed, the first-slide choice made once here. | `IHeroRepository`, `TimeProvider` | | Core `MediaEndpoint` | Serves stored variants; no knowledge of the Hero module. | `IMediaStore` | | Core `CmsDataBlockTransform` | Composes the `#cms-data` block from all contributors. | `ICmsDataBlockContributor` implementations | -| `HeroHtmlTransform`, `HeroPreloadMarkerProvider` | Write the region and the preload from the same `PublicHeroDto` through `HeroPictureRenderer`. | `IPublicHeroService` | +| `HeroHtmlTransform` | Writes the hero region and the preload region from the same `PublicHeroDto` through `HeroPictureRenderer`. | `IPublicHeroService` | ## Orchestration @@ -63,7 +63,7 @@ flowchart LR Req["Next page request"] --> Inj["HtmlMarkerInjector"] Inj --> T1["CmsDataBlockTransform
(offerings, banners, hero)"] Inj --> T2["HeroHtmlTransform
(region + first slide)"] - Inj --> T3["HeroPreloadMarkerProvider
(head)"] + Inj --> T3["HeroHtmlTransform
(preload region, head)"] T1 --> Pub["PublicHeroService"] T2 --> Pub T3 --> Pub diff --git a/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md b/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md index 8b88eaa..7dd9c3d 100644 --- a/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md +++ b/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md @@ -58,3 +58,17 @@ Seed values: title "Andrea Slop", tagline "Lifestyle fotograaf · Huizen", butto - Variants are limited by the source size (no upscaling); the public data lists only variants that exist. - Two preload links (portrait, landscape) are needed when a `tall` ratio exists. - The first-slide data in `#cms-data` and in the HTML must come from the same computation. + +## Golden files delivered (ASF commit 13f78c4, branch feature/hero-module of the ASF repository) + +Folder `web/contract/host-injection/hero/` (README with all rules, `seed.json`, six inputs: standard, minimal, two-lines, hostile, no-alt, none; per input `NAME.expected.html` and `NAME.expected-preload.html`). The CMS host template must produce exactly these files (Build and Test unit H4). Choices accepted by the CMS session: + +1. Only WebP in the LCP picture and the preload (a preload cannot say "AVIF if supported"); AVIF variants may exist for slides 2..n on the client. +2. Selection by orientation: `` for `tall` plus the `img` for `wide` inside ``; two preloads with `media` portrait and landscape; without `tall` one preload without `media`; without `wide` an `img src` and a preload `href`. +3. Focus as `style="object-position:X% Y%"` on the `img` (no trailing zeros, at most two decimals; no style without a valid focus). `width` and `height` on the `img` are the original image size from the data. +4. The preload is a region pair `…` in the head, like `CMS:HERO-HTML` (this replaces the earlier single-marker idea). +5. A slide without alt (and not decorative), with a foreign or unsafe path or without a size is skipped; no usable slide or no title gives empty regions (the baked hero stays). At most 2 buttons; targets are `#anchor`, `/path` or `https://`. New lines in the title become `
` after escaping. +6. Variant names `/media/hero//wide-1600.webp` and `tall-960.avif`. +7. Seed (first focus estimates by looking at the photos, (x,y) from the top left): hero-8 (0.50,0.55), hero-7 (0.45,0.50), hero-1 (0.55,0.60), hero-2 (0.45,0.45), hero-3 (0.45,0.40), hero-4 (0.45,0.35), hero-5 (0.50,0.55), hero-6 (0.50,0.35). Bryan adjusts them in the admin. + +Not yet built on the ASF side (after this design): hydration and slider from the data block, marker injection in the build, e2e against a stand-in host, the baked fallback from the CMS-driven format. -- 2.39.5 From d00d9c91206fc61e2d710ca6f30e6e03ed03325b Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:46:37 +0100 Subject: [PATCH 11/47] Hero-module: unit-of-work plan met vier vragen Co-Authored-By: Claude Sonnet 5.5 --- aidlc-docs/features/hero-module/audit.md | 12 ++++ .../inception/plans/unit-of-work-plan.md | 71 +++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index 1700e7f..1dd5712 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -95,3 +95,15 @@ **Context**: Application Design complete; waiting for approval. --- + +## Application Design approved; Units Generation plan + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Bryan heeft het Application Design van de Hero-module goedgekeurd (2026-11-16, 47fcaeb). Ga door met Units Generation, Functional Design, NFR Requirements (incl. de beeldbibliotheek-proef op win-x64 en linux-arm64, AVIF/licentie) en NFR Design. Stel vragen aan Bryan via mij." (relayed by SLP Software - SLS - Main) + +**AI Response**: Wrote unit-of-work-plan.md with four questions (delivery, first test deploy, library proof approach, project references), each with a recommendation. + +**Context**: Units Generation planning; waiting for answers. + +--- diff --git a/aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md b/aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md new file mode 100644 index 0000000..51f7f70 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md @@ -0,0 +1,71 @@ +# Unit of Work Plan: hero-module + +Vul per vraag de letter in na `[Answer]:` (of "alle aanbevelingen"). Dit is een enkele service (de CMS-host) met één nieuwe module en een uitbreiding van Core; "units" zijn dus bouwonderdelen, geen aparte services. De units H0 tot en met H6 komen uit het uitvoeringsplan en het ontwerp; hieronder staan de keuzes over volgorde en oplevering. + +## Voorstel (uit het ontwerp) + +| Unit | Inhoud | Hangt af van | +|---|---|---| +| H0 | CI: `release/*` voor SLP-productie. **Klaar** (PR #16, 0824bfa) | - | +| H1 | Beeldpijplijn in `Core.Media`: proef met bibliotheken, `IImageProcessor`, uploadwacht, `FocusMath`, `VariantPlanner`, `MediaPaths` | - | +| H3 | Mediaopslag en -serving: `IMediaStore`, `FileSystemMediaStore`, `/media/…`-endpoint, opties, snelheidsbegrenzing | H1 (adressen) | +| H2 | Hero-module backend: tabellen en migratie, beheer-API, publieke `GET /hero`, validatie, planning, teksten, OpenAPI | H1, H3 | +| H4 | Host-injectie: `CmsDataBlockTransform` + `ICmsDataBlockContributor`, Offerings omzetten (byte-identiek), `HeroHtmlTransform` (regio + preload), golden files van ASF | H2 | +| H5 | Admin-frontend: hero-formulier, slides, upload, focus-editor met voorbeeld | H2, H3 | +| H6 | Seed-script, `docs/hero-module.md`, rooktest, productie-checklist, LCP-meting op beide testhosts | H2 tot H5 | + +## Plan (stappen) + +- [x] 1. Eenheden afgeleid uit uitvoeringsplan en ontwerp +- [ ] 2. Vragen hieronder beantwoord +- [ ] 3. Antwoorden geanalyseerd +- [ ] 4. `unit-of-work.md` (definities en verantwoordelijkheden, codeorganisatie) +- [ ] 5. `unit-of-work-dependency.md` (afhankelijkheden, bouwvolgorde) +- [ ] 6. `unit-of-work-story-map.md` (user stories zijn overgeslagen: de requirements-ID's FR/NFR worden aan units gekoppeld) +- [ ] 7. Grenzen en afhankelijkheden gecontroleerd; alle FR/NFR hebben een unit + +## Vragen + +### Vraag 1 — Hoe leveren we op naar master? + +H0 is al los gemerged. + +- A) Eén pull request voor H1 tot en met H6, pas gemerged na Bryans acceptatie op de testhosts; tussendoor deployen we de featurebranch niet automatisch (de leader dispatcht test-deploys) +- B) In stappen: eerst H1+H3 (media), dan H2+H4 (module en injectie), dan H5+H6, elk met een eigen pull request en groene checks +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. De sites hebben markers, module en admin samen nodig om iets te zien; stapsgewijs mergen levert niets zichtbaars op en vergroot het aantal reviews. + +[Answer]: + +### Vraag 2 — Wanneer de eerste test-deploy? + +- A) Na H1 tot en met H4 (API, media en injectie werken; de seed vult de hero via de beheer-API of het script), zodat de ASF- en SLS-sessies al kunnen integreren; H5 (de admin) volgt daarna +- B) Pas als alles incl. H5 klaar is +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. Dat ontsluit het werk van de sites één stap eerder en laat de LCP en het contract vroeg meten. + +[Answer]: + +### Vraag 3 — Hoe pakken we de bibliotheekproef aan (onderdeel van H1 en NFR Requirements)? + +De proef vergelijkt ImageSharp, NetVips, Magick.NET en SkiaSharp op: invoerformaten (incl. heic, avif, tiff), WebP- en AVIF-uitvoer, geheugen en snelheid met een 10 MB-foto, licentie, en werking op win-x64, linux-x64 (CI) en linux-arm64 (Pi). + +- A) Lokaal op win-x64 en in een linux-arm64-container (emulatie) op deze machine; de echte Pi bevestigt het pas bij de eerste test-deploy. Als de bibliotheek daar faalt, schakel ik terug naar de volgende kandidaat (de koppeling `IImageProcessor` maakt dat klein) +- B) Eerst een aparte testrun op de Pi, voordat we de bibliotheek vastleggen (kost extra tijd en een handmatige stap van Pi-Main) +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. + +[Answer]: + +### Vraag 4 — Welke projecten verwijzen naar de Hero-module? + +- A) De master-`Api` en beide sites (`Api.SlpSoftware` en `Api.AndreaSlopFotografie`) vanaf H2; `Api.Slave` niet. Het werkt pas zichtbaar als een site de markers gebruikt, dus mergen naar test heeft geen effect op pagina's zonder markers +- B) Alleen de master-`Api` en `Api.AndreaSlopFotografie` nu; SLP volgt pas als SLS de markers heeft +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A (zelfde regel als Offerings; `SiteContractTests` leggen de samenstelling vast). + +[Answer]: -- 2.39.5 From a29dc2262075dff89069d56448aabc0fed876b7e Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:48:24 +0100 Subject: [PATCH 12/47] Hero-module: Units Generation (unit-of-work, dependency, requirement-map) Co-Authored-By: Claude Sonnet 5.5 --- .../features/hero-module/aidlc-state.md | 2 +- .../unit-of-work-dependency.md | 43 +++++++++++++++++++ .../unit-of-work-story-map.md | 42 ++++++++++++++++++ .../application-design/unit-of-work.md | 33 ++++++++++++++ .../inception/plans/unit-of-work-plan.md | 20 ++++----- 5 files changed, 129 insertions(+), 11 deletions(-) create mode 100644 aidlc-docs/features/hero-module/inception/application-design/unit-of-work-dependency.md create mode 100644 aidlc-docs/features/hero-module/inception/application-design/unit-of-work-story-map.md create mode 100644 aidlc-docs/features/hero-module/inception/application-design/unit-of-work.md diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index 7fc5543..fedac0f 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -47,7 +47,7 @@ - [x] User Stories (SKIP: one persona, acceptance criteria in the requirements) - [x] Workflow Planning (approved by Bryan 2026-11-16) - [x] Application Design (artifacts in inception/application-design/, awaiting approval) -- [ ] Units Generation - EXECUTE +- [x] Units Generation (unit-of-work.md, -dependency.md, -story-map.md; plan answered 2026-11-16) ### 🟢 CONSTRUCTION PHASE - [ ] Functional Design - EXECUTE - [ ] NFR Requirements - EXECUTE diff --git a/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-dependency.md b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-dependency.md new file mode 100644 index 0000000..faaadee --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-dependency.md @@ -0,0 +1,43 @@ +# Unit dependencies: hero-module + +Rows depend on columns (X = needs it built first; (c) = only a contract, no code dependency). + +| | H1 | H3 | H2 | H4 | H5 | H6 | ASF golden files | SLS input | +|---|---|---|---|---|---|---|---|---| +| **H1** Image pipeline | n/a | | | | | | | | +| **H3** Media store and serving | X (addresses, options) | n/a | | | | | | | +| **H2** Hero module backend | X | X | n/a | | | | (c) JSON shape | | +| **H4** Injection | | | X | n/a | | | X (tests) | (c) title lines | +| **H5** Admin | | | X (API) | | n/a | | | | +| **H6** Delivery | | | X | X | X | n/a | | | + +```mermaid +flowchart LR + H1["H1 Image pipeline"] --> H3["H3 Media store
and serving"] + H1 --> H2["H2 Hero backend"] + H3 --> H2 + H2 --> H4["H4 Injection"] + H2 --> H5["H5 Admin"] + H3 --> H5 + H4 --> T1(["First test deploy"]) + T1 --> H5 + H4 --> H6["H6 Delivery"] + H5 --> H6 + classDef u fill:#FFA726,stroke:#E65100,color:#000; + classDef m fill:#CE93D8,stroke:#6A1B9A,color:#000; + class H1,H2,H3,H4,H5,H6 u; + class T1 m; +``` + +Text alternative: H1 feeds H3 and H2; H3 feeds H2; H2 feeds H4 and H5; the first test deploy follows H4; H5 and H4 feed H6. + +## Shared resources and contracts + +- The Core data block contract (H4) changes how Offerings writes `#cms-data`: its golden files must stay green. +- The public JSON shape (H2) is a contract with the ASF and SLS sessions; the golden files from ASF (13f78c4) drive H4. +- The media address scheme (H1) is used by H2 (data), H3 (endpoint) and H4 (HTML). +- One migration (H2); no change to existing tables. + +## Parallelism + +H2 and H3 can be built in parallel after H1 by different sessions, but the work is done by one session in the order above; the ASF and SLS sessions work on their sides in parallel from the first test deploy. diff --git a/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-story-map.md b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-story-map.md new file mode 100644 index 0000000..12eb273 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-story-map.md @@ -0,0 +1,42 @@ +# Requirement to unit map: hero-module + +User stories were skipped for this feature (one persona, acceptance criteria in the requirements), so the requirement IDs of `requirements.md` are mapped to units instead. + +| Requirement | H1 | H3 | H2 | H4 | H5 | H6 | +|---|---|---|---|---|---|---| +| FR-01 one hero per site | | | X | | | | +| FR-02 text fields | | | X | | X | | +| FR-03 buttons and target validation | | | X | | X | | +| FR-04 slides | | | X | | X | | +| FR-05 schedule | | | X | | X | | +| FR-06 language-ready model | | | X | | | | +| FR-07 roles and public access | | | X | | | | +| FR-10 upload, real type, formats | X | | X | | X | | +| FR-11 metadata stripped | X | | | | | | +| FR-12 variants, resize and compress | X | | X | | | | +| FR-13 focus and crop per ratio, preview | X | | X | | X | | +| FR-14 own address, hash, immutable | X | X | | | | | +| FR-15 preload equals img | | | | X | | | +| FR-16 no orphans | | X | X | | | | +| FR-17 reuse check | done (SDA: nothing to reuse) | | | | | | +| FR-20 public contract | | | X | | | | +| FR-21 injection into the first HTML | | | | X | | | +| FR-22 only the first slide injected | | | | X | | | +| FR-23 fail-open, cache, ETag | | | | X | | | +| FR-24 schedule and inactive without rebuild | | | X | X | | | +| FR-25 admin screens | | | | | X | | +| FR-30 seed script | | | | | | X | +| FR-31 static texts reviewed | | | | | | X (SLS and ASF sessions) | +| FR-32 `release/*` CI | H0 (done) | | | | | | +| FR-33 backend texts | | | X | | | | +| NFR-01 LCP | | | | X | | X (measure) | +| NFR-02 live | | | X | X | | | +| NFR-03 page weight | X | | | | | X | +| NFR-04 upload safety | X | X | | | | | +| NFR-05 platforms and licence | X | | | | | X | +| NFR-06 storage | | X | | | | X (checklist) | +| NFR-07 accessibility | | | X | X | X | | +| NFR-08 compatibility | | | | X | | X | +| NFR-09 resilience | | | | X | | | + +Every FR and NFR has at least one unit. diff --git a/aidlc-docs/features/hero-module/inception/application-design/unit-of-work.md b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work.md new file mode 100644 index 0000000..dce9f7b --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work.md @@ -0,0 +1,33 @@ +# Units of work: hero-module + +One deployable service (the CMS host); the units are build parts with their own tests. Delivery: **one pull request for H1 to H6**, merged only after Bryan accepts the result on the test hosts (decision 2026-11-16). The first test deploy comes after H1 to H4; H5 follows. + +## Code organisation (brownfield, existing layout) + +| Area | Location | +|---|---| +| Media service | `src/SlpModularCms.Core/Media/` (+ tests in `SlpModularCms.Core.Tests/Media/`) | +| Data block and injection | `src/SlpModularCms.Core/Hosting/Website/` (+ tests in `SlpModularCms.Core.Tests/Hosting/`) | +| Hero module | `src/SlpModularCms.Modules.Hero/` and `src/SlpModularCms.Modules.Hero.Tests/` (new projects, in the solution folders Application/Modules and Tests/Modules, added to `SlpModularCms.Ci.slnf`) | +| Offerings change | `src/SlpModularCms.Modules.Offerings/Services/` | +| Master and sites | `src/SlpModularCms.Api`, `Api.SlpSoftware`, `Api.AndreaSlopFotografie` (module reference, committed defaults, `SiteContractTests`); not `Api.Slave` | +| Admin | `frontend/src/features/hero/` | +| Scripts, docs | `scripts/Seed-Hero.ps1`, `docs/hero-module.md`, `docs/release-checklist-productie.md`, `scripts/smoke-site.sh`, `openapi/slpsoftware.v1.json` | + +## Units + +| Unit | Responsibility | Main artifacts | Per-unit stages | +|---|---|---|---| +| **H0** (done) | `release/*` rule for SLP production | workflow, docs (PR #16, 0824bfa) | none | +| **H1** Image pipeline | Library proof and choice; `IImageProcessor`, `IMediaUploadGuard`, `ImageRejectedException`, pure `FocusMath`, `VariantPlanner`, `MediaPaths`; limits and options | `Core/Media/*`, tests incl. property tests, image fixtures | Functional Design, NFR Requirements (proof), NFR Design, Code Generation | +| **H3** Media store and serving | `IMediaStore`, `FileSystemMediaStore`, `/media/...` endpoint, rate-limit policy, startup check of the directory, options | `Core/Media/*`, host registration | Functional Design, Infrastructure Design (directory outside the release, backup, permissions), Code Generation | +| **H2** Hero module backend | Entities, migration, repositories, `HeroService`, `HeroImageService`, `PublicHeroService`, controllers, `ButtonTargetValidator`, texts, OpenAPI | `Modules.Hero`, tests | Functional Design, Code Generation | +| **H4** Injection | `ICmsDataBlockContributor`, `CmsDataBlockTransform`, Offerings contributor (byte-identical), `HeroHtmlTransform`, `HeroPictureRenderer`, ASF golden files (13f78c4) | `Core/Hosting/Website`, `Modules.Hero`, `Modules.Offerings`, golden files | Functional Design, Code Generation | +| **H5** Admin | Hero screen, slide list, upload, focus editor with previews, TypeScript `focusMath` twin | `frontend/src/features/hero` | Functional Design, Code Generation | +| **H6** Delivery | Seed script (test), docs, smoke test, checklist, LCP measurement, OpenAPI snapshot | scripts, docs | Code Generation, Build and Test | + +NFR Requirements and NFR Design run for H1 and H3 (library, limits, upload safety, storage) and, for the LCP budgets, for H4. Security Baseline and property-based (partial) rules apply as recorded in the requirements. + +## Build order + +1. H1 (library proof first), 2. H3 (needs H1 for addresses), 3. H2, 4. H4, then **first test deploy** and integration with the ASF and SLS sessions, 5. H5, 6. H6. diff --git a/aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md b/aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md index 51f7f70..1310294 100644 --- a/aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md +++ b/aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md @@ -17,12 +17,12 @@ Vul per vraag de letter in na `[Answer]:` (of "alle aanbevelingen"). Dit is een ## Plan (stappen) - [x] 1. Eenheden afgeleid uit uitvoeringsplan en ontwerp -- [ ] 2. Vragen hieronder beantwoord -- [ ] 3. Antwoorden geanalyseerd -- [ ] 4. `unit-of-work.md` (definities en verantwoordelijkheden, codeorganisatie) -- [ ] 5. `unit-of-work-dependency.md` (afhankelijkheden, bouwvolgorde) -- [ ] 6. `unit-of-work-story-map.md` (user stories zijn overgeslagen: de requirements-ID's FR/NFR worden aan units gekoppeld) -- [ ] 7. Grenzen en afhankelijkheden gecontroleerd; alle FR/NFR hebben een unit +- [x] 2. Vragen hieronder beantwoord (2026-11-16, alle aanbevelingen) +- [x] 3. Antwoorden geanalyseerd: geen vaagheid of tegenstrijdigheid +- [x] 4. `unit-of-work.md` (definities en verantwoordelijkheden, codeorganisatie) +- [x] 5. `unit-of-work-dependency.md` (afhankelijkheden, bouwvolgorde) +- [x] 6. `unit-of-work-story-map.md` (user stories zijn overgeslagen: de requirements-ID's FR/NFR worden aan units gekoppeld) +- [x] 7. Grenzen en afhankelijkheden gecontroleerd; alle FR/NFR hebben een unit ## Vragen @@ -36,7 +36,7 @@ H0 is al los gemerged. Aanbeveling: A. De sites hebben markers, module en admin samen nodig om iets te zien; stapsgewijs mergen levert niets zichtbaars op en vergroot het aantal reviews. -[Answer]: +[Answer]: A. Eén PR voor H1 t/m H6, pas gemerged na Bryans acceptatie op de testhosts. ### Vraag 2 — Wanneer de eerste test-deploy? @@ -46,7 +46,7 @@ Aanbeveling: A. De sites hebben markers, module en admin samen nodig om iets te Aanbeveling: A. Dat ontsluit het werk van de sites één stap eerder en laat de LCP en het contract vroeg meten. -[Answer]: +[Answer]: A. Eerste test-deploy na H1 t/m H4; H5 volgt. ### Vraag 3 — Hoe pakken we de bibliotheekproef aan (onderdeel van H1 en NFR Requirements)? @@ -58,7 +58,7 @@ De proef vergelijkt ImageSharp, NetVips, Magick.NET en SkiaSharp op: invoerforma Aanbeveling: A. -[Answer]: +[Answer]: A. Lokaal op win-x64 en in een linux-arm64-container; de echte Pi bevestigt het bij de eerste test-deploy. ### Vraag 4 — Welke projecten verwijzen naar de Hero-module? @@ -68,4 +68,4 @@ Aanbeveling: A. Aanbeveling: A (zelfde regel als Offerings; `SiteContractTests` leggen de samenstelling vast). -[Answer]: +[Answer]: A. Master-Api en beide sites verwijzen vanaf H2; de Slave niet. -- 2.39.5 From caa7dad6c7589c48ddee159c8cf1cb9c2cd8f198 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:52:28 +0100 Subject: [PATCH 13/47] Hero-module: bibliotheekproef voor de beeldverwerking (Magick.NET aanbevolen) Co-Authored-By: Claude Sonnet 5.5 --- aidlc-docs/features/hero-module/audit.md | 12 ++++++++ .../nfr-requirements/library-proof.md | 28 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 aidlc-docs/features/hero-module/construction/h1-image-pipeline/nfr-requirements/library-proof.md diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index 1dd5712..e1b93b4 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -107,3 +107,15 @@ **Context**: Units Generation planning; waiting for answers. --- + +## Units answered; image library proof + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Bryans antwoorden op de 4 Units-vragen (2026-11-16): alle vier de aanbevelingen. (1) Eén PR voor H1 t/m H6, pas gemerged na Bryans acceptatie op de testhosts. (2) Eerste test-deploy na H1 t/m H4, zodat ASF en SLS kunnen integreren terwijl H5 nog volgt. (3) Bibliotheekproef lokaal op win-x64 en in een linux-arm64-container, de echte Pi bevestigt het bij de eerste test-deploy. (4) Master-Api en beide sites verwijzen vanaf H2 naar de Hero-module, de Slave niet. Maak de unit-documenten en ga door met Functional Design en NFR Requirements; begin met de bibliotheekproef." (relayed by SLP Software - SLS - Main) + +**AI Response**: Wrote the three unit documents. Ran the library proof on win-x64 and linux-x64 (container); the arm64 emulation could not be set up (privileged binfmt container refused by the tooling, nothing changed), so arm64 stays to be confirmed on the Pi. Result: Magick.NET-Q8 recommended, NetVips fallback, ImageSharp (paid licence key required to build) and SkiaSharp excluded. Documented in construction/h1-image-pipeline/nfr-requirements/library-proof.md. + +**Context**: Construction, NFR Requirements input for H1. + +--- diff --git a/aidlc-docs/features/hero-module/construction/h1-image-pipeline/nfr-requirements/library-proof.md b/aidlc-docs/features/hero-module/construction/h1-image-pipeline/nfr-requirements/library-proof.md new file mode 100644 index 0000000..8b12469 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h1-image-pipeline/nfr-requirements/library-proof.md @@ -0,0 +1,28 @@ +# Image library proof (H1), 2026-11-16 + +Question: which library behind `IImageProcessor` decodes the widest set of input formats, writes WebP (required) and AVIF (when possible), keeps memory bounded for a 10 MB upload, has a licence that suits a commercial site, and works on win-x64 (IIS production), linux-x64 (CI) and linux-arm64 (Pi test hosts)? + +Method: a throw-away console project (not in the repository; sources in the session scratchpad) with the candidates; input is the ASF photo `hero-1.jpg` (2560x1702), converted by Magick to PNG, WebP, GIF, BMP, TIFF and AVIF as decode samples; per library: decode of every sample, crop for `wide` 3:2 and `tall` 4:5 around a focus point, resize to 960/1600 and 640/960 wide, WebP quality 80, metadata stripped, AVIF encode at 960 wide. A 24 MP stress image (6000x4000, 30 MB, noisy) measured peak memory. + +## Candidates and findings + +| Library | Licence | Result | +|---|---|---| +| **SixLabors.ImageSharp 4.1.3** | Six Labors Split License | **Excluded.** The package fails the build without a paid licence key (`No Six Labors license found ... obtain a licence from sixlabors.com/pricing`). A commercial closed-source site needs the paid licence, and CI would need the key as a secret. No AVIF or HEIC types in the assembly either. | +| **SkiaSharp 4.156.1** | MIT | **Excluded.** Cannot decode TIFF or AVIF (decode returns null), no HEIC, WebP only; on slim Linux images the native library failed to initialise without extra system libraries. | +| **NetVips 3.2.0** (libvips 8.18.7) | wrapper MIT; native `NetVips.Native` LGPL-3.0-or-later | Works on win-x64 and linux-x64. Decodes PNG, WebP, GIF, TIFF, AVIF, JPEG; **no BMP** (needs ImageMagick loader). Writes WebP and AVIF (`heifsave`). Fast (about 330 to 490 ms for four WebP variants). Peak memory 303 MB for the 24 MP stress image. Native libraries for linux-arm64 are in the package (`libvips.so.42`, 18 MB) but could not be executed here. HEIC is unverified (no sample). | +| **Magick.NET-Q8-AnyCPU 15.1.0** (ImageMagick) | wrapper Apache-2.0 | Works on win-x64 and linux-x64. Reports readable and writable: AVIF, BMP, GIF, JXL, TIFF, WebP; **HEIC and HEIF readable**. Decodes every sample (PNG, WebP, GIF, BMP, TIFF, AVIF, JPEG). Writes WebP and AVIF. Slower (about 0.7 to 1.3 s for four WebP variants, 1.5 to 2 times NetVips), but peak memory only 128 MB for the 24 MP stress image. A native arm64 build is in the package (`Magick.Native-Q8-arm64.dll.so`, 35 MB), not executed here. Has resource limits (`ResourceLimits`: width, height, area, memory, time) that fit decompression-bomb protection. | + +Output equality: WebP at quality 80 gave the same sizes in NetVips and Magick.NET (wide 960 about 38 KB, wide 1600 about 74 KB, tall 640 about 37 KB, tall 960 about 64 KB), against 220 to 440 KB for the ASF JPEGs today. AVIF at 960 wide: about 22 to 23 KB. + +## What could not be verified + +1. **linux-arm64 (Pi) was not executed.** Running an arm64 container on this machine needs an emulator registration (a privileged binfmt container) that the tooling refused; no change was made. The packages do contain native arm64 libraries for both candidates. The real Pi confirms at the first test deploy (agreed). To make that quick the host will run an image-library self-test at start-up (decode and encode a tiny embedded image in every supported format; log the capabilities; refuse uploads when it fails; public reads unaffected). +2. **HEIC** was verified only as a declared capability of Magick.NET (`Heic:r`), not with a real HEIC file. +3. The `AnyCPU` Magick package carries natives for several platforms; a self-contained win-x64 publish keeps only the matching one (to be checked in the H1 publish test). + +## Recommendation + +**Magick.NET-Q8 (Apache-2.0) behind `IImageProcessor`**: the widest input list (incl. BMP, TIFF, HEIC read, AVIF read and write), WebP and AVIF output, bounded memory with built-in resource limits, a licence without keys or LGPL obligations, native builds for all three platforms. NetVips stays the documented fallback (faster, lower licence friction on the wrapper, but no BMP and LGPL natives) and the interface makes switching small. ImageSharp and SkiaSharp are out. + +Residual risks: ImageMagick has a history of CVEs, so the package is kept current and covered by the CI vulnerability scan (SECURITY-10); only the allow-listed formats are decoded (our own signature check first, then the library with an explicit format); the process gets pixel, memory and time limits. -- 2.39.5 From 5f6d2b4bd2ee40e7a24e5243e20b93b03dbf34c4 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:52:56 +0100 Subject: [PATCH 14/47] Hero-module: functional design plan (H1 t/m H5) met zes vragen Co-Authored-By: Claude Sonnet 5.5 --- aidlc-docs/features/hero-module/audit.md | 12 +++ .../plans/functional-design-plan.md | 92 +++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 aidlc-docs/features/hero-module/construction/plans/functional-design-plan.md diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index e1b93b4..649cdf5 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -119,3 +119,15 @@ **Context**: Construction, NFR Requirements input for H1. --- + +## Functional Design plan + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Master-run #121 (0824bfa, H0) is groen en deployde alleen naar test: publish-/deploy-sls-test, publish-/deploy-asf-test en beide rooktests success; publish-sls-production en deploy-sls-production skipped. De release/*-regel werkt. Verder met Functional Design / NFR Requirements." (relayed by SLP Software - SLS - Main) + +**AI Response**: H0 verified by the leader. Wrote functional-design-plan.md (bundled for H1 to H5) with six questions and the defaults I set without asking. + +**Context**: Functional Design planning; waiting for answers. + +--- diff --git a/aidlc-docs/features/hero-module/construction/plans/functional-design-plan.md b/aidlc-docs/features/hero-module/construction/plans/functional-design-plan.md new file mode 100644 index 0000000..40a0a05 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/plans/functional-design-plan.md @@ -0,0 +1,92 @@ +# Functional Design Plan: hero-module (units H1 tot en met H5) + +Gebundeld voor alle units, zodat Bryan één keer antwoordt. De uitkomst wordt per unit uitgewerkt in `construction//functional-design/` (bedrijfslogica, regels, entiteiten). Vul de letter in na `[Answer]:`, of "alle aanbevelingen". + +H0 is klaar (master-run #121 groen, alleen test). De bibliotheek is gekozen (Magick.NET, zie `h1-image-pipeline/nfr-requirements/library-proof.md`). + +## Plan + +- [x] 1. Context geladen (requirements, ontwerp, units, contract met ASF, golden files 13f78c4, bibliotheekproef) +- [ ] 2. Vragen hieronder beantwoord +- [ ] 3. Antwoorden geanalyseerd +- [ ] 4. H1 Beeldpijplijn: `business-logic-model.md`, `business-rules.md`, `domain-entities.md` +- [ ] 5. H3 Mediaopslag en -serving: idem +- [ ] 6. H2 Hero-backend: idem +- [ ] 7. H4 Injectie: idem, inclusief de byte-exacte HTML volgens de ASF-golden files +- [ ] 8. H5 Admin: `frontend-components.md`, schermen en validatie +- [ ] 9. Controle: elk FR/NFR gedekt; regels consistent over de units + +## Wat ik zonder vraag vastleg (zeg het als het anders moet) + +- Kwaliteit: WebP 80, AVIF 50, JPEG als terugval 82; bredere uitvoer dan de bron wordt niet gemaakt. +- Breedtes: `wide` 640, 960, 1280, 1600, 2560 en `tall` 480, 640, 960, 1280, alleen tot de breedte van de bron die na de uitsnede overblijft; er is altijd minstens één variant per verhouding (de grootste mogelijke). +- Een upload telt als één beeldset; een foto wordt nooit twee keer opgeslagen (dezelfde inhoud + focus geeft dezelfde set). +- Tekst is platte tekst; de host codeert bij het schrijven (HTML en JSON). Lengtes: titel 200 (max 5 regels), tagline 120, lead 600, knoplabel 50, doel 500, alt 300. +- Het publieke antwoord is er alleen als er een actieve hero met minstens één bruikbare slide of een titel is; anders 204. +- Beheer slaat de hele hero in één keer op (volledig vervangen, met de slidelijst en volgorde); afbeeldingen worden apart geüpload. + +## Vragen + +### Vraag 1 — Wat gebeurt er met een afbeelding die een slide nog gebruikt, bij verwijderen? + +- A) Het CMS weigert (409) met een duidelijke melding; eerst de slide verwijderen of een andere afbeelding kiezen +- B) Het CMS haalt de afbeelding van de slide af en laat de slide zonder afbeelding staan (die dan niet gepubliceerd wordt) +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. Dat voorkomt dat per ongeluk een slide uit de hero verdwijnt. + +[Answer]: + +### Vraag 2 — Hoe lang blijven oude afbeeldingsbestanden bestaan na een nieuwe focus of een vervangen foto? + +Een website die de oude data nog in de cache heeft, verwijst nog naar de oude adressen. + +- A) 7 dagen, daarna worden ze door een opschoontaak verwijderd +- B) Direct verwijderen +- C) 24 uur +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. Een paar dagen dekt browsercaches en gecachete prerender-pagina's; de opslag is klein. + +[Answer]: + +### Vraag 3 — Hoeveel slides mag een hero hebben? + +- A) Maximaal 12 +- B) Maximaal 8 (de huidige ASF-hero heeft er 8) +- C) Geen vaste grens, alleen de totale opslaglimiet +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. Ruimte boven de huidige 8 zonder dat de pagina te zwaar wordt. + +[Answer]: + +### Vraag 4 — Hoe gaan we om met HTML of speciale tekens in de teksten? + +- A) Toegestaan als platte tekst en altijd gecodeerd bij het schrijven (een `<` blijft zichtbaar als `<`; er komt nooit opmaak of script uit een tekstveld) +- B) Het CMS weigert tekens als `<` en `>` in de velden +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. + +[Answer]: + +### Vraag 5 — Wat toont de admin als de hero (nog) niet live is? + +- A) Een duidelijke melding bovenaan met de reden (buiten de planning, uitgezet, geen bruikbare slide, geen titel) en wat de sites dan tonen (de ingebakken hero) +- B) Alleen een kleine status-badge +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. + +[Answer]: + +### Vraag 6 — Wie mag een afbeelding uploaden? + +- A) Dezelfde rol als de hero wijzigen (Administrator en hoger); uploads zijn beperkt per gebruiker (bijvoorbeeld 20 per uur) +- B) Alleen de eigenaar +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. + +[Answer]: -- 2.39.5 From 259d48bd9cdcb42c7cf7f717ddd559f7b8e60763 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 15:09:40 +0100 Subject: [PATCH 15/47] Hero-module: Functional Design, NFR Requirements, NFR Design en Infrastructure Design (H1-H5) Co-Authored-By: Claude Sonnet 5.5 --- .../features/hero-module/aidlc-state.md | 10 +-- aidlc-docs/features/hero-module/audit.md | 12 +++ .../functional-design/business-logic-model.md | 72 ++++++++++++++++++ .../functional-design/business-rules.md | 70 +++++++++++++++++ .../functional-design/domain-entities.md | 75 +++++++++++++++++++ .../functional-design/frontend-components.md | 44 +++++++++++ .../infrastructure-design.md | 40 ++++++++++ .../nfr-design/nfr-design-patterns.md | 50 +++++++++++++ .../nfr-requirements/nfr-requirements.md | 68 +++++++++++++++++ .../nfr-requirements/tech-stack-decisions.md | 19 +++++ 10 files changed, 455 insertions(+), 5 deletions(-) create mode 100644 aidlc-docs/features/hero-module/construction/functional-design/business-logic-model.md create mode 100644 aidlc-docs/features/hero-module/construction/functional-design/business-rules.md create mode 100644 aidlc-docs/features/hero-module/construction/functional-design/domain-entities.md create mode 100644 aidlc-docs/features/hero-module/construction/functional-design/frontend-components.md create mode 100644 aidlc-docs/features/hero-module/construction/infrastructure-design/infrastructure-design.md create mode 100644 aidlc-docs/features/hero-module/construction/nfr-design/nfr-design-patterns.md create mode 100644 aidlc-docs/features/hero-module/construction/nfr-requirements/nfr-requirements.md create mode 100644 aidlc-docs/features/hero-module/construction/nfr-requirements/tech-stack-decisions.md diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index fedac0f..eeaf340 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: hero-module - **Project Type**: Brownfield - **Start Date**: 2026-11-16 -- **Current Stage**: INCEPTION - Application Design (artifacts written, waiting for approval) +- **Current Stage**: CONSTRUCTION - Code Generation (H1 first) - **Branch**: feature/hero-module (worktree K:\Development\Projects\SlpModularCms-contact-forms, from master b2cacfe) ## Workspace State @@ -49,10 +49,10 @@ - [x] Application Design (artifacts in inception/application-design/, awaiting approval) - [x] Units Generation (unit-of-work.md, -dependency.md, -story-map.md; plan answered 2026-11-16) ### 🟢 CONSTRUCTION PHASE -- [ ] Functional Design - EXECUTE -- [ ] NFR Requirements - EXECUTE -- [ ] NFR Design - EXECUTE -- [ ] Infrastructure Design - EXECUTE for the media unit (storage is a directory outside the release) +- [x] Functional Design (bundled H1-H5, construction/functional-design/; answered 2026-11-16) +- [x] NFR Requirements (construction/nfr-requirements/) +- [x] NFR Design (construction/nfr-design/) +- [x] Infrastructure Design (media directory; construction/infrastructure-design/) - [ ] Code Generation - EXECUTE (per unit H0 to H6) - [ ] Build and Test - EXECUTE ### 🟡 OPERATIONS PHASE diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index 649cdf5..c296aa3 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -131,3 +131,15 @@ **Context**: Functional Design planning; waiting for answers. --- + +## Functional Design answered; design stages written + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Bryans besluiten (2026-11-16): BIBLIOTHEEK: Magick.NET-Q8 goedgekeurd, achter IImageProcessor. arm64 niet vooraf testen; de Pi bevestigt het bij de eerste test-deploy, met de opstart-zelftest ... Noteer HEIC als alleen-capability ... FUNCTIONAL DESIGN (6 vragen): 1. weigeren met melding. 2. 7 dagen bewaren. 3. Maximaal aantal slides: ONBEGRENSD ... Leg wel een technische bovengrens vast die geen beheerdersgrens is maar een veiligheidsgrens ... en meld Bryan als je die nodig vindt ... 4. platte tekst, altijd gecodeerd. 5. Admin als de hero niet live is: ALLEEN EEN BADGE. 6. Administrator en hoger met limiet per gebruiker. De defaults onderaan het plan ... zijn akkoord. Ga door met NFR Requirements, NFR Design, Infrastructure Design (mediamap) en Code Generation." (relayed by SLP Software - SLS - Main) + +**AI Response**: Wrote the bundled Functional Design (business logic model, business rules, domain entities, admin screens), NFR Requirements and tech stack decisions, NFR Design patterns, and Infrastructure Design for the media directory. A technical ceiling of 50 published slides (`Hero:MaxPublishedSlides`) is set and reported for Bryan. + +**Context**: Construction; moving to Code Generation (H1). + +--- diff --git a/aidlc-docs/features/hero-module/construction/functional-design/business-logic-model.md b/aidlc-docs/features/hero-module/construction/functional-design/business-logic-model.md new file mode 100644 index 0000000..13656aa --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/functional-design/business-logic-model.md @@ -0,0 +1,72 @@ +# Functional Design: business logic model (units H1 to H5) + +Bundled for all units; answers of Bryan (2026-11-16) are applied. Names refer to `application-design/`. HTML for the region and preload is defined by the ASF golden files (`web/contract/host-injection/hero/`, commit 13f78c4), which are authoritative. + +## H1. Image pipeline + +### Upload admission (`IMediaUploadGuard.AdmitAsync`) + +1. Reject at once when the declared length is above the maximum (10 MB) or the stream turns out longer (read through a counting stream, stop at the limit). +2. Read the first bytes and decide the format from the **signature**, never from a name or `Content-Type`: JPEG, PNG, GIF, BMP, TIFF (both byte orders), WebP (`RIFF....WEBP`), and the ISO-BMFF family for AVIF and HEIC/HEIF (`ftyp` with brand `avif`, `avis`, `heic`, `heix`, `hevc`, `mif1`, `msf1`). Anything else (SVG, PDF, executables, text) is rejected as `unsupported_format`. +3. Inspect through the library with an explicit format and resource limits: pixel size, frame count. Reject `too_many_pixels` (above the pixel ceiling), `corrupt` (decode error), `timeout`. +4. Animated input (GIF, WebP, AVIF sequences) is reduced to the first frame. +5. Wait for a free processing slot (at most `MaxParallelJobs`); when none frees within a few seconds answer `busy` (HTTP 429). + +### Render planning (pure) + +For an image of `W x H` pixels, a ratio `r = n:d`, a focus setting `(fx, fy, z)` (centre `0.5, 0.5` and `z = 1` by default; a ratio may have its own setting, otherwise the general one applies): + +- The **largest crop** of ratio `r` inside the image: `cw0 x ch0` (if `W/H > n/d` then `ch0 = H`, `cw0 = ch0 * n / d`, else `cw0 = W`, `ch0 = cw0 * d / n`). +- With zoom `z >= 1` the crop is `cw = cw0 / z` by `ch = ch0 / z`. +- The crop is centred on the point `(fx * W, fy * H)` and then moved the smallest amount needed to lie inside the image. So the subject stays as close to the centre of the crop as the image allows, and a crop never leaves the image. +- Widths: from the configured steps for the ratio (`wide`: 640, 960, 1280, 1600, 2560; `tall`: 480, 640, 960, 1280) keep those `<= cw` (never upscale). If none is `<= cw`, one variant at `cw` is made. The height is `round(width * d / n)`. +- Formats per width: WebP always; AVIF when the processor reports AVIF output; the page-critical HTML uses WebP only (contract). +- Quality: WebP 80, AVIF 50. Metadata is removed from every output; EXIF orientation is applied before cropping. + +### Set hash and addresses + +`setHash` = first 16 hex characters of SHA-256 over the canonical string `sha256-of-original | wide:fx,fy,z | tall:fx,fy,z` (numbers rounded to 4 decimals, invariant culture). A change of focus therefore gives a new set and new addresses; an identical upload of the same photo with the same focus gives the same set (no second copy is stored). Variant file name: `-.` (`wide-1600.webp`, `tall-960.avif`); address `/media/hero//`. + +### Self-test at start-up + +The processor decodes and encodes a tiny embedded image in every supported format and logs the capability list (input and output formats, library version). A failure marks the processor unavailable: uploads answer 503 with a generic message; reading and publishing are unaffected. + +## H3. Media store and serving + +- **Keys**: variants `hero//-.`; originals `originals/.` (never served). Only keys made by the code exist; a client file name is never used in a path. +- **Write**: a set is written to a temporary directory next to the target and moved into place with one rename; a half-written set is never visible. +- **Serve** `GET|HEAD /media/{**path}`: the path must match `^hero/[0-9a-f]{16}/(wide|tall)-[0-9]{2,5}\.(webp|avif|jpg)$` (area pattern from a registered allow-list, so other areas can register their own); otherwise 404. Headers: `Content-Type` from the extension, `Cache-Control: public, max-age=31536000, immutable`, strong `ETag` (from the set hash and name), `X-Content-Type-Options: nosniff`, `Vary: Accept-Encoding` not needed (images are not recompressed). `If-None-Match` equal gives 304. Rate limit policy `media-public`. +- **Clean-up** (hosted service, daily): removes sets and originals that no image row references and that are older than 7 days (a retired set is stamped when it stops being referenced; the files go 7 days later). Never removes a referenced file. +- **Free space and size**: before writing, check free space (at least the expected output plus a margin) and the total size of the media directory against the safety limit `Media:MaxTotalBytes`; refuse with a generic message when exceeded. + +## H2. Hero backend + +### Save (`PUT /api/v1/hero`, whole hero replaced) + +Input: hero fields, buttons, display, schedule, slide list in order (`id` optional for a new slide, `imageId`, `alt`, `decorative`, `isActive`). In one transaction: validate everything, update the hero, upsert slides, remove slides no longer listed, renumber the order, record actor and time. Afterwards `IIndexHtmlCache.Invalidate()`. + +### Public read model (`PublicHeroService.GetActiveAsync`) + +Returns null (204) when: no hero row for the language, `IsActive` false, `now` before `StartsAt` or at or after `EndsAt`, or the hero has no title. Otherwise: only active slides that have a stored image; a slide without alt that is not decorative is **not** published (the admin does not allow saving it anyway); order as saved. Each slide carries the general focus, plus the per-ratio overrides, and all stored variants (WebP and AVIF) with their ratio, width, type and address. The result is also what the HTML transform and the data block use, so the three always agree. + +### Image operations + +- **Upload** (`POST /api/v1/hero/images`): guard, store original, render the planned sets for the default focus, save the row, return the image with its variants. +- **Set focus** (`PUT /api/v1/hero/images/{id}/focus`): validate ranges (`0..1`, zoom `1..4`), compute the new set hash, render the sets into new addresses, update the row, stamp the old set as retired; the slides keep pointing at the same image id. +- **Delete** (`DELETE /api/v1/hero/images/{id}`): refused with 409 and a clear message while any slide uses the image (Bryan, Q1); otherwise the row goes and its set and original are stamped retired. + +## H4. Injection + +Order of work for a page that mentions hero markers: get `PublicHeroDto?` once per request cycle; if null, leave regions and preload as baked (and the data block carries `"hero": null`); otherwise: + +1. `HERO-HTML` region: exactly the ASF golden rules (title lines with `
`, tagline span, buttons, first kept slide as ``; slides skipped when they have no alt and are not decorative, a path outside our host, or no size; WebP only; `object-position` from the focus of the ratio that the `img` shows, i.e. the general focus). +2. `HERO-PRELOAD` region in the head: one preload for `tall` with `media="(orientation: portrait)"` and one for `wide` with `media="(orientation: landscape)"` when both exist; one without `media` when only one ratio exists; `srcset`, `sizes`, `media` byte-equal to the picture. +3. Data block: key `hero` with the whole `PublicHeroDto` (all slides) in the shared block. + +Fail-open: any exception, an unreadable hero or a missing marker leaves that part as baked; a failing data-block contributor leaves the whole block as baked. + +**Safety ceiling for unlimited slides** (Bryan: no administrator limit, a technical ceiling only): the hero endpoint, the HTML transform and the data block never emit more than `Hero:MaxPublishedSlides` slides (default 50, configurable) so the first HTML and the data block cannot grow without bound; when a hero has more active slides the first 50 in order are published and the admin shows a notice. The ceiling is reported to Bryan; LCP and page weight stay leading (the first HTML contains only the first slide). + +## H5. Admin + +Screens and states are in `frontend-components.md`; the admin only shows a **live badge** (Bryan, Q5): "Live" or "Niet live" with the schedule dates, no long reason text. Uploads are limited per user (20 per hour). Every validation message comes from the server (`ProblemDetails`-style error with a field) and is shown at the field. diff --git a/aidlc-docs/features/hero-module/construction/functional-design/business-rules.md b/aidlc-docs/features/hero-module/construction/functional-design/business-rules.md new file mode 100644 index 0000000..2802a9b --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/functional-design/business-rules.md @@ -0,0 +1,70 @@ +# Functional Design: business rules (units H1 to H5) + +IDs are used in the code, tests and the build and test summary. + +## Hero content (H2) + +| ID | Rule | +|---|---| +| BR-H01 | One hero per language; the language defaults to `nl`. `Language` is unique. Only `nl` is exposed and edited now. | +| BR-H02 | `title` required (after trimming), at most 200 characters and at most 5 lines; line breaks are `\n` (`\r\n` is normalised). Plain text. | +| BR-H03 | `tagline` optional, at most 120 characters, single line (line breaks are replaced by a space). `lead` optional, at most 600 characters, line breaks kept. | +| BR-H04 | `display` is `single` or `slideshow`; default `single`; any other value is rejected. | +| BR-H05 | 0 to 2 buttons. Both `label` (1 to 50 characters) and `target` (at most 500) are required for a button; a half-filled button is rejected. | +| BR-H06 | A target is exactly one of: **anchor** `#` followed by a letter and then letters, digits, `-` or `_` (at most 100 characters); **path** starting with a single `/` (not `//`), no `\`, no control characters, no whitespace, no `:` before the first `/`; **https address** with the scheme `https`, a host, no user info, parsed as an absolute URI. Anything else is rejected with the message "Kies een #anker, een /pad of een https://-adres." | +| BR-H07 | Schedule: `startsAt` and `endsAt` optional; when both exist `endsAt` must be after `startsAt`. Stored in UTC; displayed in the admin in local time. | +| BR-H08 | Text in every field is plain text. The server stores it as typed (control characters other than the line break are removed) and encodes it when writing HTML (`& < > " '`) and JSON in a script element (`< > &` and U+2028/2029 as `\uXXXX`). No field can produce markup or script. | +| BR-H09 | Slides: no administrator limit on the number. Each slide has an existing image, `alt` (at most 300 characters) or `decorative = true`, an order, and `isActive`. A slide that is not decorative needs a non-empty alt to be saved. `decorative` and a non-empty alt together are accepted; the alt is then ignored when published. | +| BR-H10 | Technical safety ceiling: at most `Hero:MaxPublishedSlides` (default 50) slides are published; the rest stay saved. Reported to Bryan (see the logic model). | +| BR-H11 | Saving replaces the whole hero (one transaction). A slide id the caller sends must belong to this hero; unknown ids are rejected. Slides not listed are removed. | +| BR-H12 | Actor and time of every change are stored (`UpdatedBy`, `UpdatedAt`) and logged. | + +## Public availability (H2, H4) + +| ID | Rule | +|---|---| +| BR-P01 | The public hero exists only when the hero `isActive`, now is within the schedule (start inclusive, end exclusive), the title is non-empty. Otherwise 204 and the baked hero stays. | +| BR-P02 | Only active slides with a stored image are published, in saved order. | +| BR-P03 | `GET /api/v1/hero` answers with `Cache-Control: public, max-age=60`, rate-limited (policy `hero-public`, 120 per 60 s), anonymous, through the availability gate. | +| BR-P04 | The HTML region, the preload and the data block are derived from the same read model per request cycle. | + +## Images (H1, H2) + +| ID | Rule | +|---|---| +| BR-I01 | Upload only for Administrator and higher; at most 20 uploads per user per hour; body at most 10 MB. | +| BR-I02 | The format is decided from the signature (see the logic model); not on the allow-list = `unsupported_format`. SVG is never accepted. | +| BR-I03 | Pixel ceiling `Media:MaxPixels` (default 64 million) and a side ceiling of 16 384 pixels; decode timeout `Media:DecodeTimeoutSeconds` (default 20). | +| BR-I04 | Metadata (EXIF including GPS, XMP, IPTC, embedded thumbnails) is never written to an output file; the original is also stored without GPS (the stored original is re-encoded without metadata only when it contains GPS or other metadata; the pixel data are not altered otherwise). | +| BR-I05 | Output never exceeds the source size (no upscaling); every ratio gets at least one variant. | +| BR-I06 | Focus values: `x` and `y` between 0 and 1, `zoom` between 1 and 4; an invalid value is rejected. The default is the centre (0.5, 0.5) and zoom 1 for every ratio. A ratio override is optional; without it the general setting applies. | +| BR-I07 | An image used by a slide cannot be deleted (409, "Deze afbeelding wordt nog gebruikt door een slide."). | +| BR-I08 | Retired files (old sets, deleted images) are removed after 7 days by the clean-up; referenced files are never removed. | +| BR-I09 | Rejection reasons are stable codes (`too_large`, `unsupported_format`, `corrupt`, `too_many_pixels`, `timeout`, `busy`, `unavailable`); the messages shown come from the texts files, with no file names or internals. | + +## Media serving (H3) + +| ID | Rule | +|---|---| +| BR-M01 | Only addresses that match the registered area pattern are served; everything else is a 404 without detail. | +| BR-M02 | Served files carry the immutable cache header, a strong ETag and `nosniff`; `HEAD` and 304 are supported. | +| BR-M03 | Writes are atomic per set; a failed write leaves nothing visible. | +| BR-M04 | A start-up check proves the media directory exists and is writable; if not, uploads are refused (503) and an error is logged; public reads of existing files and the public hero keep working. | + +## Injection (H4) + +| ID | Rule | +|---|---| +| BR-J01 | The output must equal the ASF golden files byte for byte (six cases: standard, minimal, two-lines, hostile, no-alt, none). | +| BR-J02 | Only WebP in the picture and the preload; the `img` has the original `width` and `height`; `fetchpriority="high"`; the `object-position` from the general focus, formatted without trailing zeros and at most two decimals; no `style` without a valid focus. | +| BR-J03 | Fail-open per part; a failing contributor leaves the whole data block as baked. | +| BR-J05 | Before writing the hero into a page the transform checks that the first kept slide's variant files exist in the store; when they do not, regions and preload stay as baked. | +| BR-J04 | The Offerings output stays byte-identical after the change to the shared data block (existing golden files stay green). | + +## Admin (H5) + +| ID | Rule | +|---|---| +| BR-A01 | The Hero screen shows a badge "Live" or "Niet live" (with the schedule dates) and nothing more about the reason. | +| BR-A02 | The focus editor shows `wide` and `tall` previews cut with the same maths as the host (a TypeScript twin tested with the same vectors). A ratio can be reset to "use the general point". | +| BR-A03 | Upload errors show the server message at the upload control; validation errors at the field. | diff --git a/aidlc-docs/features/hero-module/construction/functional-design/domain-entities.md b/aidlc-docs/features/hero-module/construction/functional-design/domain-entities.md new file mode 100644 index 0000000..0a9bf5c --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/functional-design/domain-entities.md @@ -0,0 +1,75 @@ +# Functional Design: domain entities (units H1 to H5) + +Database: one new migration in the Hero module's own DbContext (MariaDB, hand-written like the Offerings migrations). Tables use the prefix `Hero`. + +## Tables + +### `Heroes` + +| Column | Type | Notes | +|---|---|---| +| `Id` | `char(36)` | primary key | +| `Language` | `varchar(10)` | default `nl`, unique | +| `Title` | `varchar(1000)` | max 200 chars by validation; room for 5 lines | +| `Tagline` | `varchar(200)` | max 120 | +| `Lead` | `varchar(1000)` | max 600 | +| `Display` | `varchar(20)` | `single` or `slideshow` | +| `Button1Label`, `Button1Target`, `Button2Label`, `Button2Target` | `varchar(100)` / `varchar(500)` | nullable pairs | +| `StartsAt`, `EndsAt` | `datetime(6)` | nullable, UTC | +| `IsActive` | `bit` | default true | +| `UpdatedAt` | `datetime(6)` | UTC | +| `UpdatedBy` | `varchar(256)` | actor id or name | + +### `HeroImages` + +| Column | Type | Notes | +|---|---|---| +| `Id` | `char(36)` | primary key | +| `OriginalSha256` | `char(64)` | content hash of the stored original | +| `OriginalKey` | `varchar(200)` | `originals/.` | +| `SourceFormat` | `varchar(10)` | `jpeg`, `png`, ... | +| `Width`, `Height` | `int` | original pixel size | +| `Bytes` | `bigint` | size of the stored original | +| `FocusX`, `FocusY`, `Zoom` | `double` | general setting; default 0.5, 0.5, 1 | +| `WideFocusX`, `WideFocusY`, `WideZoom` | `double?` | optional override | +| `TallFocusX`, `TallFocusY`, `TallZoom` | `double?` | optional override | +| `SetHash` | `char(16)` | current set | +| `VariantsJson` | `json`/`longtext` | list of `{ratio, width, height, type, key, bytes}` of the current set | +| `RetiredSetsJson` | `longtext` | previous sets with their retire time (for the 7-day clean-up) | +| `CreatedAt`, `CreatedBy` | `datetime(6)`, `varchar(256)` | | + +### `HeroSlides` + +| Column | Type | Notes | +|---|---|---| +| `Id` | `char(36)` | primary key, stable id used by the sites | +| `HeroId` | `char(36)` | foreign key, cascade delete | +| `ImageId` | `char(36)` | foreign key, restrict (deleting an image in use is refused) | +| `Alt` | `varchar(600)` | max 300 chars by validation | +| `Decorative` | `bit` | | +| `SortOrder` | `int` | unique per hero | +| `IsActive` | `bit` | | + +Indexes: `Heroes(Language)` unique; `HeroSlides(HeroId, SortOrder)` unique; `HeroSlides(ImageId)`. + +## Public DTOs (shape fixed in `component-methods.md`) + +`PublicHeroDto { display, title, tagline, lead, buttons[], slides[] }`, `PublicSlideDto { id, alt, decorative, image }`, `PublicImageDto { width, height, focus{x,y,zoom}, focusByRatio?, src, srcset?, variants[] }`, `PublicVariantDto { ratio, width, height, type, url }`. `focusByRatio` is present only when an override exists. Fields that are null are written as JSON null (like the offerings data); the shapes match the ASF golden inputs (`web/contract/host-injection/hero/*.input.json`). + +## Pure value types (H1, Core.Media) + +`ImageFormat` (enum), `ImageInfo { Format, Width, Height, FrameCount }`, `Ratio`, `FocusSetting`, `CropRect { X, Y, Width, Height }`, `VariantSpec { Ratio, Width, Height, Format, Quality }`, `RenderedImage { Bytes, Width, Height, Format }`, `MediaAddress { Area, SetHash, Name }`. + +## Configuration + +| Key | Default | Meaning | +|---|---|---| +| `Media:Directory` | none (required for uploads) | the media directory outside the release | +| `Media:MaxUploadBytes` | 10 485 760 | upload limit | +| `Media:MaxPixels` | 64 000 000 | pixel ceiling | +| `Media:MaxParallelJobs` | 2 | processing slots | +| `Media:DecodeTimeoutSeconds` | 20 | per image | +| `Media:MaxTotalBytes` | 2 147 483 648 | safety limit of the directory | +| `Media:RetentionDays` | 7 | retired files | +| `Hero:MaxPublishedSlides` | 50 | technical ceiling on published slides | +| `RateLimiting:HeroPublic`, `MediaPublic`, `HeroUpload` | 120/60 s, 600/60 s, 20/hour per user | policies | diff --git a/aidlc-docs/features/hero-module/construction/functional-design/frontend-components.md b/aidlc-docs/features/hero-module/construction/functional-design/frontend-components.md new file mode 100644 index 0000000..43cd6bf --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/functional-design/frontend-components.md @@ -0,0 +1,44 @@ +# Functional Design: admin screens (unit H5) + +New navigation item "Hero" (visible when `/api/v1/System/capabilities` lists the Hero module; for the Administrator role and higher). Follows the existing admin conventions (React Query, `nl` and `en` translation files, the Offerings feature as the pattern). Admin texts live in the frontend translation files. + +## Screen: Hero + +``` +[Hero] [Live | Niet live van .. tot ..] +------------------------------------------------------------------------------- +Tekst Titel (meerdere regels) Tagline Lead +Weergave ( ) Enkel ( ) Diavoorstelling +Knoppen Knop 1: label + doel Knop 2: label + doel (0 tot 2) +Planning Aan/uit Van ... Tot ... +------------------------------------------------------------------------------- +Slides [+ Afbeelding toevoegen] + #1 [thumb] alt-tekst / decoratief aan/uit omhoog omlaag [Focus] [Verwijder] + #2 ... +------------------------------------------------------------------------------- + [Opslaan] +``` + +- **Badge** (Bryan, Q5): "Live" or "Niet live" with the schedule dates; no reason text. It reflects the public rules (active, within the schedule, a title, at least one usable slide) as computed by the server (`GET /hero/all` returns `isLive`). +- **Form** validates on the server; messages come back per field and are shown at the field. A button target hint shows the three accepted forms. A slide without alt text and not marked decorative blocks saving, with the message at that slide. +- **Slides** are listed in order; reorder with up and down buttons (keyboard accessible); on/off per slide; the number is not limited in the screen (a notice appears above the safety ceiling). +- **Upload**: a file picker and a drop area; shows the accepted formats (from the server's capability list) and the 10 MB limit; progress; the server message on rejection (`unsupported_format`, `too_large`, `corrupt`, `too_many_pixels`, `busy`, `unavailable`). +- **Delete** of an image or slide: a confirmation; the server refuses an image still in use (409) and the screen shows the message. + +## Dialog: Focus + +- The image with a draggable focus point (keyboard: arrow keys move by 1%, with shift by 5%), a zoom slider (1 to 4), the numeric values, and two live previews: `wide` (3:2) and `tall` (4:5), each cut exactly as the host will cut (shared maths, TypeScript twin of `FocusMath` with the same test vectors). +- Tabs or toggles: "Algemeen punt" (default centre) and optional "Alleen wide" / "Alleen tall" overrides; a "Gebruik algemeen punt" reset per ratio. +- Save sends `PUT /api/v1/hero/images/{id}/focus`; the previews update from the response variants. + +## States + +Loading, empty (no hero yet: an empty form with the button "Opslaan"), saving, error (server messages), saved. Unsaved-changes warning when leaving the screen. + +## API used + +`GET /api/v1/hero/all`, `PUT /api/v1/hero`, `POST /api/v1/hero/images` (multipart), `PUT /api/v1/hero/images/{id}/focus`, `DELETE /api/v1/hero/images/{id}`, `GET /api/v1/System/capabilities`. + +## Accessibility and tests + +Labels and descriptions on all fields, focus management in the dialog, keyboard operation of reorder and focus point, `aria-live` for save and upload results. Tests: component tests (form validation display, slide reorder, upload errors, badge), the `focusMath` vectors shared with the C# tests, and an interaction test for the focus dialog. diff --git a/aidlc-docs/features/hero-module/construction/infrastructure-design/infrastructure-design.md b/aidlc-docs/features/hero-module/construction/infrastructure-design/infrastructure-design.md new file mode 100644 index 0000000..7ee44c6 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/infrastructure-design/infrastructure-design.md @@ -0,0 +1,40 @@ +# Infrastructure Design: media directory (unit H3) + +Bryan's decision: images live in a **directory outside the release**. This stage records how the directory is provided on each host and what is still unknown. + +## Requirements on the directory + +1. Outside the release and outside the web root (not served by IIS or nginx as static content; only the host's `/media/...` endpoint serves from it). +2. Survives deploys (the release directory is replaced on every deploy). +3. Writable by the account the host runs as; nothing else writes to it. +4. Included in the backup of the site. +5. Large enough: default safety limit `Media:MaxTotalBytes` 2 GB; expected use well below 100 MB. + +## Per host + +| Host | Directory | Setting | Backup | Status | +|---|---|---|---|---| +| **Pi test, SLP** (`~/apps/slpsoftware/test`) | `~/apps/slpsoftware/test/shared/media` (next to `shared/env`, `shared/wwwroot-web`) | `Media__Directory=%h/apps/slpsoftware/test/shared/media` in `shared/env` | Add the directory to the host backup routine for test (a test site may also be re-seeded) | To do by Pi-Main with the first test deploy: `mkdir -p`, mode 700, owner the service account | +| **Pi test, ASF** | `~/apps//shared/media` (same pattern, its own env file) | `Media__Directory=…` | as above | same | +| **SLP production** (Pi, later) | `~/apps/slpsoftware/production/shared/media` | `shared/env` | The production backup script (`backup-slpsoftware-db.sh` covers the database only): the directory must be added | Open until the release; listed in the production checklist | +| **ASF production** (MijnHostingPartner, IIS, self-contained win-x64) | A data directory beside the site, outside the web root (for example `..\data\media`), writable by the application pool identity | environment variable or `appsettings.Production.json` | The hosting provider's file backup, or an FTP copy; to confirm | **Unknown: write permission and backup on this hosting are not known.** Bryan tests with ASF (hosting package, application pool identity). If the test fails, Bryan is asked again and the database store (behind `IMediaStore`) is built. | + +## Deployment behaviour + +- `deploy-scp.yaml` builds `releases//` and switches `current`; `shared/` is not touched, so `shared/media` survives. No workflow change is needed for the Pi. +- The directory is created by Pi-Main once (documented in `docs/hero-module.md` and in the checklist); the host also creates it at start-up when it is missing and the account may. +- Release artifact size: Magick.NET adds about 35 MB native per platform; the upload limit of the deploy path (`deployment-instructions.md` 1.7.3, the nginx `client_max_body_size` for artifact upload) must allow the artifact; to be measured at the first deploy (the current artifact size is the reference). + +## Backup and restore + +- Files are immutable and content-addressed; a restore of the directory plus the database brings the site back; a restore needs both. A restored database without the directory leaves slides without files. Two safeguards: the start-up check logs a warning with the count of sets that the database refers to but the directory lacks, and the page injection (H4) checks that the first slide's files exist (through `IMediaStore.ExistsAsync`, cached with the page for 60 seconds) and leaves the baked hero in place when they do not, so a missing directory never produces a broken first image. +- Test hosts: the seed script can rebuild the hero and images from the ASF sources, so a test restore is optional. + +## Risks + +| Risk | Handling | +|---|---| +| Write permission or backup unavailable on the ASF production hosting | Bryan tests with ASF before the release; `IMediaStore` allows a database implementation; Bryan is asked again when the test fails | +| Disk fills | `Media:MaxTotalBytes`, free-space check before writing, clean-up of retired files, an error log line when 80% is reached | +| Directory missing after a server move | Start-up check disables uploads and logs; the injection sees the missing first-slide files and leaves the baked hero (no broken image); documented in the checklist | +| Deploy artifact too large for the proxy limit | Measured at the first deploy; the limit is raised on the proxy when needed | diff --git a/aidlc-docs/features/hero-module/construction/nfr-design/nfr-design-patterns.md b/aidlc-docs/features/hero-module/construction/nfr-design/nfr-design-patterns.md new file mode 100644 index 0000000..4161b8e --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/nfr-design/nfr-design-patterns.md @@ -0,0 +1,50 @@ +# NFR Design: patterns for the hero-module (H1, H3, H4) + +Each NFR of `nfr-requirements.md` is mapped to a pattern and the component that carries it. + +## Patterns + +| Pattern | Applies to | Where it lives | Notes | +|---|---|---|---| +| **Defence in depth for uploads**: size gate, signature allow-list, library decode with resource limits, parallelism gate, per-user rate limit, timeout, rejection codes | SEC-01, SEC-07, R-02 | `IMediaUploadGuard` (Core.Media), `HeroImagesController` (size limit attribute and `hero-upload` policy) | Each layer rejects alone; no single check is the only protection. A counting stream enforces the byte limit even when the declared length lies. | +| **Resource limits in the library**: `ResourceLimits.Width/Height/Area/Memory/Time` set once at start-up from `Media:*` options | SEC-01, P-03 | `MagickImageProcessor` initialisation | Process-wide limits, not per call; documented because Magick's limits are global. Format policy: decode only the allow-listed formats by passing the explicit `MagickFormat` after the signature check. | +| **Bulkhead**: a semaphore with `MaxParallelJobs` slots and a short wait; when full the answer is `busy` (429) | SEC-01, S-01 | `MediaProcessingGate` | Protects the host's CPU and memory on the Pi. | +| **Atomic publish of a set**: write to a temp directory, then one rename into place; clean the temp on failure (`try/finally`) | R-02, BR-M03 | `FileSystemMediaStore.PutSetAsync` | Nothing half-written is ever addressable. | +| **Content-addressed, immutable addresses** | P-05, FR-14 | `MediaPaths` | The set hash contains the original's SHA-256 and the crop parameters; a change gives a new address; long immutable caching is safe. | +| **Retire, then delete** (grace of 7 days) | R-04, BR-I08 | `HeroMediaCleanupService` (hosted, daily) | Sets are stamped when they stop being referenced; deleted later; idempotent; never deletes a referenced key (checked against the database right before deleting). | +| **Single read model** | NFR-09, BR-P04 | `PublicHeroService` | The endpoint, the region, the preload and the data block cannot disagree. | +| **One renderer for picture and preload** | P-01, BR-J01 | `HeroPictureRenderer` | Same inputs and the same formatting functions produce `srcset`, `sizes`, `media`; golden-tested. | +| **Fail-open injection, fail-closed upload** | R-01, R-02 | transforms catch and log; upload throws typed rejections | Documented deliberate asymmetry (SECURITY-15). | +| **Composable data block** | C-01 | `CmsDataBlockTransform` + contributors | Output of Offerings unchanged; contributors ordered by `Order`; a throwing contributor leaves the block baked. | +| **Self-test and capability reporting** | R-03, C-02 | `ImageProcessorSelfTest` hosted service; `GET /api/v1/System/capabilities` lists the accepted input formats | A failed self-test disables uploads only. | +| **Start-up directory check** | R-03, BR-M04 | `MediaDirectoryCheck` hosted service | Creates the directory when missing (when permitted), writes and deletes a probe file; logs the result; a failed check disables uploads. | +| **Output encoding at the edge** | SEC-03, BR-H08 | `HeroPictureRenderer` and the data contributor | Text stored as typed, encoded when written; the JSON for the script element uses the existing `HtmlMarkerEditor.EscapeForScript`. | +| **Allow-listed addresses** | SEC-03, BR-M01 | `MediaPaths.TryParse` and the endpoint's area registry | Anything else is a 404. | +| **Audit trail** | SEC-05 | `HeroService`, `HeroImageService` | Log line per change with actor, entity and id (no content), plus `UpdatedBy`/`CreatedBy` columns. | +| **Rate-limit policies** | SEC-07 | `ServiceCollectionExtensions` of the module and Core | `hero-public` 120/60 s per client address, `media-public` 600/60 s, `hero-upload` 20 per hour per user. | + +## Logical components added by this stage + +| Component | Role | +|---|---| +| `MagickImageProcessor` | The `IImageProcessor` implementation (sets limits, decodes, crops, resizes, strips, encodes) | +| `MediaProcessingGate` | The bulkhead | +| `ImageProcessorSelfTest` | Hosted self-test and capability list | +| `MediaDirectoryCheck` | Hosted start-up check of the directory | +| `HeroMediaCleanupService` | Daily clean-up of retired files | +| `MediaAreaRegistry` | The allow-list of media areas and their path patterns (`hero`) | + +## Security compliance summary (this stage) + +| Rule | Status | Evidence | +|---|---|---| +| SECURITY-03 | Compliant (design) | structured logs with request id and actor, no contents or client names | +| SECURITY-04 | Compliant | `nosniff` on media; existing headers on pages | +| SECURITY-05 | Compliant | validation of every field, signature allow-list, target allow-list, encoding | +| SECURITY-08 | Compliant | `AdminOnly`, object checks, public endpoints expose published data only | +| SECURITY-09 | Compliant | generic errors, no listing, media outside the web root | +| SECURITY-10 | Compliant | pinned package, vulnerability scan covers it | +| SECURITY-11 | Compliant | rate limits, gate, abuse cases listed in the tests | +| SECURITY-13 | Compliant | audit logs and columns; no unsafe deserialization (typed JSON only) | +| SECURITY-15 | Compliant | explicit error handling, global handler, deliberate fail-open and fail-closed split | +| SECURITY-01, 02, 06, 07, 12, 14 | N/A | no new infrastructure or authentication | diff --git a/aidlc-docs/features/hero-module/construction/nfr-requirements/nfr-requirements.md b/aidlc-docs/features/hero-module/construction/nfr-requirements/nfr-requirements.md new file mode 100644 index 0000000..79d0410 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/nfr-requirements/nfr-requirements.md @@ -0,0 +1,68 @@ +# NFR Requirements: hero-module (units H1, H3, H4; applies to H2 and H5 where noted) + +Derived from `requirements.md` section 5, the security extension (blocking), the functional design and the library proof. Bryan approved the library, the defaults and the safety approach on 2026-11-16. + +## Performance + +| ID | Requirement | Measure | +|---|---|---| +| P-01 | **LCP**: the LCP element is in the first HTML and does not regress against the baked version: ASF the first slide `` with `fetchpriority="high"`, `width`/`height`, and the matching preload; SLS the title text. | Lighthouse (lab) on the test hosts before and after, mobile profile: LCP not worse than the baked page; no layout shift from the hero (CLS contribution 0). | +| P-02 | **Weight**: the first slide image sent to a phone is the `tall` variant; target at most 80 KB WebP at 960 wide for a photo like the ASF ones (measured 37 to 64 KB), at most 250 KB for the largest desktop variant. | Recorded in the build and test summary. | +| P-03 | **Processing time**: an upload of a 10 MB photo is processed (all sets) within 10 seconds on the Pi and 5 seconds on a workstation; the request does not time out. | Timed in the integration test and on the test host. | +| P-04 | **Page build**: the hero adds at most 5 ms (cached) to building an injected page; the 60-second cache and ETag/304 behaviour stay as for the other parts. | Unit and integration tests. | +| P-05 | **Media serving**: a media file answers from disk with a strong ETag and 304; no processing on the request path. | Integration test. | + +## Scalability and capacity + +| ID | Requirement | +|---|---| +| S-01 | Expected size: one hero per site, tens of slides at most, a few uploads per day; the design must stay correct under concurrent uploads (processing gate) but is not built for throughput. | +| S-02 | Disk: the media directory is limited by `Media:MaxTotalBytes` (2 GB default); uploads refused with a generic message above it; free space checked before writing. | +| S-03 | The data block and the hero JSON are bounded by `Hero:MaxPublishedSlides` (50): the first HTML does not grow without bound. | + +## Reliability and availability + +| ID | Requirement | +|---|---| +| R-01 | Page injection is fail-open per part; a failing media directory, library or database read never takes a page down. | +| R-02 | Uploads fail closed with a stable code and a generic message; nothing partial is visible (atomic set writes); a crash during processing leaves no referenced half-set. | +| R-03 | Start-up self-test of the image library and a writability check of the media directory; when they fail, uploads answer 503 and a clear error is logged; public reads continue. | +| R-04 | Orphan clean-up never deletes referenced files and tolerates being interrupted (idempotent, daily). | +| R-05 | A restart or deploy keeps all images (directory outside the release) and the metadata (database). | + +## Security (blocking, extension enabled) + +| ID | Requirement | Rule | +|---|---|---| +| SEC-01 | Upload hardening: size limit at framework level, signature allow-list, library decode with explicit format and resource limits (pixels, side length, memory, time), parallelism gate, per-user rate limit, no client file names in paths, no SVG. | SECURITY-05, 11 | +| SEC-02 | Management endpoints require `AdminOnly` server side; object ids are verified against the hero; the public endpoints expose only published data. | SECURITY-08 | +| SEC-03 | Output encoding: all text encoded for HTML and for JSON in script; the button target allow-list prevents `javascript:` and other schemes; the media endpoint only serves registered path patterns; `X-Content-Type-Options: nosniff`. | SECURITY-04, 05 | +| SEC-04 | Generic error responses; no stack traces or paths; the global handler stays. | SECURITY-09, 15 | +| SEC-05 | Logging with request id and actor, no file contents and no client file names; changes auditable (who, what, when). | SECURITY-03, 13 | +| SEC-06 | Dependencies pinned and scanned: `Magick.NET-Q8-AnyCPU` 15.1.0 (Apache-2.0) is added to the vulnerability scan; the package is kept current; no unused packages. | SECURITY-10 | +| SEC-07 | Rate limiting on `hero-public`, `media-public` and `hero-upload`; abuse cases covered by tests (oversized, decompression bomb, polyglot, path tricks, repeated uploads). | SECURITY-11 | +| SEC-08 | Media directory permissions: only the host's service account writes; no directory listing; files are never executed (no handler mapping in IIS for the media directory when it lives under a web root; it lives outside the web root). | SECURITY-09 | + +## Maintainability and testability + +| ID | Requirement | +|---|---| +| M-01 | The image library only behind `IImageProcessor`; the store only behind `IMediaStore`; both replaceable. | +| M-02 | Pure functions (`FocusMath`, `VariantPlanner`, `MediaPaths`, `ButtonTargetValidator`, `HeroPictureRenderer`) property-tested (extension partial): crop inside the image; widths monotonic and never above the source; the set hash changes iff the crop parameters change; targets accepted are of the three forms; encoded text round-trips; the first slide and the preload attributes equal the picture attributes. | +| M-03 | Golden files for the region and the preload (ASF), for the data block and for the Offerings output stay byte-exact. | +| M-04 | Image fixtures for each input format, including corrupt, truncated, oversized and polyglot files; a real HEIC photo is added when one can be obtained (HEIC is a declared capability only until then, per Bryan). | +| M-05 | Texts per `docs/translation-files.md`; OpenAPI snapshot regenerated. | + +## Usability and accessibility + +| ID | Requirement | +|---|---| +| U-01 | Admin: keyboard operation of reorder and focus point, labels, live regions, a clear badge; the server messages in Dutch. | +| U-02 | Sites: alt text required (or decorative), slider accessibility kept in the site (contract). | + +## Compatibility + +| ID | Requirement | +|---|---| +| C-01 | The existing public contracts and markers do not change; the Offerings data block output is byte-identical. | +| C-02 | Platforms: win-x64 self-contained (IIS), linux-x64 (CI), linux-arm64 (Pi); proven on the first two, confirmed on the Pi at the first test deploy by the start-up self-test. | diff --git a/aidlc-docs/features/hero-module/construction/nfr-requirements/tech-stack-decisions.md b/aidlc-docs/features/hero-module/construction/nfr-requirements/tech-stack-decisions.md new file mode 100644 index 0000000..b4e5f58 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/nfr-requirements/tech-stack-decisions.md @@ -0,0 +1,19 @@ +# Tech stack decisions: hero-module + +| # | Decision | Rationale | Alternatives and why not | +|---|---|---|---| +| T1 | **Magick.NET-Q8-AnyCPU 15.1.0** (Apache-2.0) behind `IImageProcessor` | Widest formats (JPEG, PNG, GIF, BMP, TIFF, WebP, AVIF read and write; HEIC/HEIF read as a declared capability), WebP and AVIF output, 128 MB peak for 24 MP, resource limits; proven on win-x64 and linux-x64 (library-proof.md) | NetVips (reserve; no BMP, LGPL natives); ImageSharp 4 (paid licence key needed to build); SkiaSharp (no TIFF or AVIF) | +| T2 | Q8 build (8 bit per channel) | Enough for web output, half the memory of Q16 | Q16 | +| T3 | `IMediaStore` with a **file-system store** in a directory outside the release (`Media:Directory`) | Bryan's decision; database store possible later behind the interface | Database blobs (rejected by Bryan; `max_allowed_packet` risk) | +| T4 | New module project `SlpModularCms.Modules.Hero` + test project; `Core.Media` in the existing Core project | Follows the existing module layout and the decision for a general media service | A separate Media assembly (not needed yet) | +| T5 | EF Core with the existing MySQL provider and hand-written migration, `NonLockingMySQLHistoryRepository` | Same as Offerings | n/a | +| T6 | Frontend: existing React, React Query, i18n; focus editor an own component; `focusMath` TypeScript twin | Bryan's choice (no cropping package) | react-easy-crop | +| T7 | Property-based tests: **FsCheck** (xUnit integration) for the pure functions in C#; **fast-check** if already present in the frontend, otherwise example vectors shared between C# and TypeScript | Extension partial; check the existing test dependencies in H1 and add only what is missing | Hand-written random loops | +| T8 | Start-up self-test as a hosted service; clean-up as a hosted `BackgroundService` (daily) | Same pattern as `ContactRetentionService` | A cron outside the host | +| T9 | Rate limiting through the existing ASP.NET Core rate limiter policies (`hero-public`, `media-public`, `hero-upload`) | Existing mechanism | n/a | + +## Package and publish notes + +- `Magick.NET-Q8-AnyCPU` carries natives for several platforms; the self-contained win-x64 publish must keep only the matching native (to be verified in a publish test in H1) and the Linux publish must include `Magick.Native-Q8-x64.dll.so` or `-arm64`. +- The CI vulnerability scan covers the new package automatically (transitive and direct). +- The package size (about 35 MB per platform native) is acceptable for the release artifacts; checked against the SCP upload limit (see `deployment-instructions.md` 1.7.3) in Infrastructure Design. -- 2.39.5 From 3a50c9750e1f1e8b1cdd5152329924e37d88018c Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 15:18:02 +0100 Subject: [PATCH 16/47] H1: beeldpijplijn in Core.Media (Magick.NET achter IImageProcessor), pure functies met property-tests, uploadwacht Co-Authored-By: Claude Sonnet 5.5 --- SlpModularCms.Ci.slnf | 1 + SlpModularCms.sln | 15 + .../features/hero-module/aidlc-state.md | 2 +- .../h1-image-pipeline/code/summary.md | 26 ++ .../MagickImageProcessor.cs | 312 ++++++++++++++++++ .../MagickServiceCollectionExtensions.cs | 15 + .../SlpModularCms.Core.Media.Magick.csproj | 20 ++ .../Media/MagickImageProcessorTests.cs | 235 +++++++++++++ .../Media/MediaPureFunctionTests.cs | 290 ++++++++++++++++ .../Media/MediaUploadGuardTests.cs | 157 +++++++++ .../SlpModularCms.Core.Tests.csproj | 1 + src/SlpModularCms.Core/Media/FocusMath.cs | 55 +++ .../Media/ImageProcessing.cs | 148 +++++++++ .../Media/ImageSignature.cs | 89 +++++ src/SlpModularCms.Core/Media/MediaPaths.cs | 78 +++++ .../Media/MediaServiceCollectionExtensions.cs | 61 ++++ src/SlpModularCms.Core/Media/MediaTypes.cs | 118 +++++++ .../Media/MediaUploadGuard.cs | 95 ++++++ .../Media/VariantPlanner.cs | 67 ++++ 19 files changed, 1784 insertions(+), 1 deletion(-) create mode 100644 aidlc-docs/features/hero-module/construction/h1-image-pipeline/code/summary.md create mode 100644 src/SlpModularCms.Core.Media.Magick/MagickImageProcessor.cs create mode 100644 src/SlpModularCms.Core.Media.Magick/MagickServiceCollectionExtensions.cs create mode 100644 src/SlpModularCms.Core.Media.Magick/SlpModularCms.Core.Media.Magick.csproj create mode 100644 src/SlpModularCms.Core.Tests/Media/MagickImageProcessorTests.cs create mode 100644 src/SlpModularCms.Core.Tests/Media/MediaPureFunctionTests.cs create mode 100644 src/SlpModularCms.Core.Tests/Media/MediaUploadGuardTests.cs create mode 100644 src/SlpModularCms.Core/Media/FocusMath.cs create mode 100644 src/SlpModularCms.Core/Media/ImageProcessing.cs create mode 100644 src/SlpModularCms.Core/Media/ImageSignature.cs create mode 100644 src/SlpModularCms.Core/Media/MediaPaths.cs create mode 100644 src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs create mode 100644 src/SlpModularCms.Core/Media/MediaTypes.cs create mode 100644 src/SlpModularCms.Core/Media/MediaUploadGuard.cs create mode 100644 src/SlpModularCms.Core/Media/VariantPlanner.cs diff --git a/SlpModularCms.Ci.slnf b/SlpModularCms.Ci.slnf index a5045cf..0761549 100644 --- a/SlpModularCms.Ci.slnf +++ b/SlpModularCms.Ci.slnf @@ -4,6 +4,7 @@ "projects": [ "src\\SlpModularCms.Api\\SlpModularCms.Api.csproj", "src\\SlpModularCms.Core\\SlpModularCms.Core.csproj", + "src\\SlpModularCms.Core.Media.Magick\\SlpModularCms.Core.Media.Magick.csproj", "src\\SlpModularCms.Core.Tests\\SlpModularCms.Core.Tests.csproj", "src\\SlpModularCms.Modules.Availability\\SlpModularCms.Modules.Availability.csproj", "src\\SlpModularCms.Modules.Availability.Tests\\SlpModularCms.Modules.Availability.Tests.csproj", diff --git a/SlpModularCms.sln b/SlpModularCms.sln index 6576ff6..5923717 100644 --- a/SlpModularCms.sln +++ b/SlpModularCms.sln @@ -44,6 +44,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Conta EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact.Tests", "src\SlpModularCms.Modules.Contact.Tests\SlpModularCms.Modules.Contact.Tests.csproj", "{06C25AF5-D63F-4007-8796-C4BA27940EBA}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Core.Media.Magick", "src\SlpModularCms.Core.Media.Magick\SlpModularCms.Core.Media.Magick.csproj", "{9EAC8A27-8DB0-4E3B-B144-280882828DE8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -258,6 +260,18 @@ Global {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x64.Build.0 = Release|Any CPU {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x86.ActiveCfg = Release|Any CPU {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x86.Build.0 = Release|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Debug|x64.ActiveCfg = Debug|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Debug|x64.Build.0 = Debug|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Debug|x86.ActiveCfg = Debug|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Debug|x86.Build.0 = Debug|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Release|Any CPU.Build.0 = Release|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Release|x64.ActiveCfg = Release|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Release|x64.Build.0 = Release|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Release|x86.ActiveCfg = Release|Any CPU + {9EAC8A27-8DB0-4E3B-B144-280882828DE8}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -282,5 +296,6 @@ Global {759EE53D-EECA-4054-A17F-4172B0EC2015} = {D72703E6-B021-4360-B1EE-0E99999B5899} {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} {06C25AF5-D63F-4007-8796-C4BA27940EBA} = {77DF6642-7863-4D67-BAEE-217EC2D99894} + {9EAC8A27-8DB0-4E3B-B144-280882828DE8} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} EndGlobalSection EndGlobal diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index eeaf340..6155f8b 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -53,7 +53,7 @@ - [x] NFR Requirements (construction/nfr-requirements/) - [x] NFR Design (construction/nfr-design/) - [x] Infrastructure Design (media directory; construction/infrastructure-design/) -- [ ] Code Generation - EXECUTE (per unit H0 to H6) +- [ ] Code Generation - per unit: H0 done, H1 done (image pipeline), H2 to H6 open - [ ] Build and Test - EXECUTE ### 🟡 OPERATIONS PHASE - [ ] SKIP (Q19 = B; points go into the joint production checklist) diff --git a/aidlc-docs/features/hero-module/construction/h1-image-pipeline/code/summary.md b/aidlc-docs/features/hero-module/construction/h1-image-pipeline/code/summary.md new file mode 100644 index 0000000..2208b0a --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h1-image-pipeline/code/summary.md @@ -0,0 +1,26 @@ +# H1 Image pipeline: code summary + +Built 2026-11-16 on `feature/hero-module`. Build and tests of the unit run green (Core tests 876 of 876, of which 79 are new; the CI solution filter builds). + +## What was built + +| Area | Files | +|---|---| +| Types, options, rejection | `Core/Media/MediaTypes.cs` (`ImageFormat`, `ImageInfo`, `Ratio` wide 3:2 and tall 4:5, `FocusSetting`, `CropRect`, `VariantSpec`, `RatioPlan`, `RenderedImage`, `MediaAddress`), `Core/Media/ImageProcessing.cs` (`ImageRejection`, `ImageRejectedException` with stable codes, `MediaOptions`, `IImageProcessor`, `MediaStatus`, `MediaProcessingGate`) | +| Pure functions | `ImageSignature` (format from the first bytes; SVG, PDF, executables never recognised), `FocusMath` (crop around the focus, round-half-up so the TypeScript twin matches), `VariantPlanner` (widths never above the crop, WebP always, AVIF when possible, JPEG when WebP is missing), `MediaPaths` (set hash, address, strict allow-listed parser) | +| Guard | `MediaUploadGuard` (availability, counted byte limit, signature, library inspection with pixel and side limits, processing slot), `GuardedUpload` | +| Registration and self-test | `MediaServiceCollectionExtensions.AddCmsMedia`, `ImageProcessorSelfTest` (hosted; a failed self-test only turns uploads off) | +| Library | new project `SlpModularCms.Core.Media.Magick` (`MagickImageProcessor`, `AddMagickImageProcessor`), Magick.NET-Q8-AnyCPU 15.1.0. Deviation from the design text: the library lives in its own project so that hosts that never process images (the slave) do not carry the 35 MB native library; the abstractions stay in Core | +| Tests | `Core.Tests/Media/`: pure functions with FsCheck properties (crop inside the image, focus inside the crop, ratio kept, zoom monotonic, planner never upscales, ladder ascending, signature never throws on random input), known vectors shared with the future TypeScript twin, address tests (including path tricks), signature tests, guard tests (limits, busy, unavailable), Magick processor tests on generated fixtures (formats, orientation, animated GIF, metadata stripped, crop keeps the chosen side, AVIF output, truncated and garbage files, mismatched format, strip of metadata) | +| Solution | project added to `SlpModularCms.sln` (folder Application) and `SlpModularCms.Ci.slnf` | + +## Decisions made while building + +- Truncated or damaged files are rejected as `corrupt`: the library returns a partly decoded picture with a warning for them, so decode warnings that mean damage (premature end, truncated, corrupt, ...) are turned into a rejection. +- The orientation is applied before cropping and `InspectAsync` reports the oriented size, so the plan and the crop always use the same numbers. +- HEIC stays a declared capability only; no real HEIC test photo yet (to add when one is available, per Bryan). +- The original is stored as received unless it carries metadata: `StripMetadataAsync` removes it (the pixels are re-encoded at quality 92 or the source quality, whichever is higher). + +## Not done in this unit (planned elsewhere) + +Media store, endpoint and directory check (H3); the `Hero:*` options and the rate-limit policies (H2/H3); the self-contained publish check of the native library (done with the first project that references it, H2). diff --git a/src/SlpModularCms.Core.Media.Magick/MagickImageProcessor.cs b/src/SlpModularCms.Core.Media.Magick/MagickImageProcessor.cs new file mode 100644 index 0000000..a4d9f17 --- /dev/null +++ b/src/SlpModularCms.Core.Media.Magick/MagickImageProcessor.cs @@ -0,0 +1,312 @@ +using ImageMagick; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Media; + +namespace SlpModularCms.Core.Media.Magick; + +/// +/// on Magick.NET (Q8). The format is always passed explicitly (it was decided from the +/// signature by the caller), only the first frame is read, the orientation is applied before cropping, and every output +/// is stripped of metadata after the colours are converted to sRGB. The resource limits of ImageMagick are process +/// wide and are set once from . +/// +public sealed class MagickImageProcessor : IImageProcessor +{ + private static readonly object LimitsLock = new(); + private static bool _limitsSet; + + private readonly MediaOptions _options; + private readonly ILogger _logger; + + public MagickImageProcessor(IOptions options, ILogger logger) + { + _options = options.Value; + _logger = logger; + SetLimits(_options); + SupportedInput = DetectInput(); + SupportedOutput = DetectOutput(); + } + + public IReadOnlySet SupportedInput { get; } + + public IReadOnlySet SupportedOutput { get; } + + public Task InspectAsync(ReadOnlyMemory data, ImageFormat declared, CancellationToken cancellationToken) + => RunAsync(() => Inspect(data, declared), cancellationToken); + + public Task RenderAsync(ReadOnlyMemory data, ImageFormat declared, VariantSpec variant, CancellationToken cancellationToken) + => RunAsync(() => Render(data, declared, variant), cancellationToken); + + public Task StripMetadataAsync(ReadOnlyMemory data, ImageFormat declared, CancellationToken cancellationToken) + => RunAsync(() => StripMetadata(data, declared), cancellationToken); + + public async Task SelfTestAsync(CancellationToken cancellationToken) + { + await RunAsync(() => + { + foreach (var format in SupportedOutput) + { + using var image = new MagickImage(MagickColors.CornflowerBlue, 32, 32); + using var stream = new MemoryStream(); + image.Quality = 80; + image.Write(stream, ToMagick(format)); + var bytes = stream.ToArray(); + var detected = ImageSignature.Detect(bytes); + if (detected != format && !(format == ImageFormat.Avif && detected == ImageFormat.Heic)) + { + throw new InvalidOperationException($"The self-test wrote {format} but the signature says {detected}."); + } + + using var back = new MagickImage(bytes, new MagickReadSettings { Format = ToMagick(format) }); + if (back.Width != 32 || back.Height != 32) + { + throw new InvalidOperationException($"The self-test could not read back {format}."); + } + } + + return true; + }, cancellationToken); + _logger.LogInformation( + "Image library Magick.NET self-test passed. Input: {Input}. Output: {Output}.", + string.Join(",", SupportedInput.Order()), + string.Join(",", SupportedOutput.Order())); + } + + // ----- work done on a pool thread with a time limit (the native limit below stops a runaway decode) ------------ + + private async Task RunAsync(Func work, CancellationToken cancellationToken) + { + try + { + return await Task.Run(work, cancellationToken) + .WaitAsync(TimeSpan.FromSeconds(Math.Max(1, _options.DecodeTimeoutSeconds)), cancellationToken); + } + catch (TimeoutException) + { + throw new ImageRejectedException(ImageRejection.Timeout, "Processing the image took too long."); + } + catch (ImageRejectedException) + { + throw; + } + catch (MagickResourceLimitErrorException exception) + { + _logger.LogWarning("Image refused by a resource limit: {Message}", Shorten(exception.Message)); + throw new ImageRejectedException(ImageRejection.TooManyPixels, "The image exceeds a processing limit."); + } + catch (MagickException exception) + { + _logger.LogInformation("Image could not be decoded: {Message}", Shorten(exception.Message)); + throw new ImageRejectedException(ImageRejection.Corrupt, "The image could not be decoded."); + } + } + + private static string Shorten(string message) => message.Length <= 160 ? message : message[..160]; + + private ImageInfo Inspect(ReadOnlyMemory data, ImageFormat declared) + { + var settings = new MagickReadSettings { Format = ToMagick(declared) }; + using var image = new MagickImage(); + image.Ping(data.Span, settings); + + var width = (int)image.Width; + var height = (int)image.Height; + if (image.Orientation is Orientation.LeftTop or Orientation.RightTop or Orientation.RightBottom or Orientation.LeftBottom) + { + (width, height) = (height, width); + } + + var frames = 1; + try + { + frames = Math.Min(MagickImageInfo.ReadCollection(data.ToArray(), settings).Count(), 10_000); + } + catch (MagickException) + { + // A single readable frame is enough; the count is informational. + } + + var hasMetadata = image.GetExifProfile() is not null || image.GetXmpProfile() is not null || image.GetIptcProfile() is not null; + return new ImageInfo(declared, width, height, Math.Max(1, frames), hasMetadata); + } + + private RenderedImage Render(ReadOnlyMemory data, ImageFormat declared, VariantSpec variant) + { + var settings = new MagickReadSettings { Format = ToMagick(declared), FrameIndex = 0, FrameCount = 1 }; + using var image = ReadStrict(data, settings); + + image.AutoOrient(); + var crop = variant.Crop; + if (crop.X < 0 || crop.Y < 0 || crop.Width < 1 || crop.Height < 1 + || crop.X + crop.Width > image.Width || crop.Y + crop.Height > image.Height) + { + throw new ImageRejectedException(ImageRejection.Corrupt, "The planned crop does not fit the decoded image."); + } + + image.Crop(new MagickGeometry(crop.X, crop.Y, (uint)crop.Width, (uint)crop.Height)); + image.ResetPage(); + image.Resize(new MagickGeometry((uint)variant.Width, (uint)variant.Height) { IgnoreAspectRatio = true }); + ToSrgb(image); + image.Strip(); + image.Quality = (uint)variant.Quality; + + var format = ToMagick(variant.Format); + if (variant.Format == ImageFormat.Avif) + { + image.Settings.SetDefine(MagickFormat.Avif, "speed", "6"); + } + + using var stream = new MemoryStream(); + image.Write(stream, format); + return new RenderedImage(stream.ToArray(), (int)image.Width, (int)image.Height, variant.Format); + } + + private static byte[]? StripMetadata(ReadOnlyMemory data, ImageFormat declared) + { + var settings = new MagickReadSettings { Format = ToMagick(declared), FrameIndex = 0, FrameCount = 1 }; + using var probe = new MagickImage(); + probe.Ping(data.Span, settings); + if (probe.GetExifProfile() is null && probe.GetXmpProfile() is null && probe.GetIptcProfile() is null) + { + return null; + } + + using var image = ReadStrict(data, settings); + var colour = image.GetColorProfile(); + var quality = image.Quality; + image.Strip(); + if (colour is not null) + { + image.SetProfile(colour); + } + + if (declared is ImageFormat.Jpeg or ImageFormat.WebP or ImageFormat.Avif or ImageFormat.Heic) + { + image.Quality = Math.Max(quality, 92u); + } + + using var stream = new MemoryStream(); + image.Write(stream, declared == ImageFormat.Heic ? MagickFormat.Jpeg : ToMagick(declared)); + return stream.ToArray(); + } + + // Warnings that mean "the file is damaged": the library would hand back a partly decoded picture, but a truncated + // upload must not become a published image. + private static readonly System.Text.RegularExpressions.Regex DamageWarning = new( + "premature end|truncat|unexpected end|insufficient image data|corrupt|not enough|bad (?:huffman|data)", + System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant); + + private static MagickImage ReadStrict(ReadOnlyMemory data, MagickReadSettings settings) + { + var image = new MagickImage(); + string? damage = null; + image.Warning += (_, e) => + { + if (damage is null && DamageWarning.IsMatch(e.Message)) + { + damage = e.Message; + } + }; + try + { + image.Read(data.Span, settings); + } + catch + { + image.Dispose(); + throw; + } + + if (damage is not null) + { + image.Dispose(); + throw new ImageRejectedException(ImageRejection.Corrupt, "The image is damaged or incomplete."); + } + + return image; + } + + private static void ToSrgb(MagickImage image) + { + try + { + if (image.ColorSpace == ColorSpace.CMYK || image.GetColorProfile() is not null) + { + image.TransformColorSpace(ColorProfiles.SRGB); + } + } + catch (MagickException) + { + // An unusual profile: keep the pixels, the metadata is stripped afterwards anyway. + } + } + + // ----- capabilities and limits --------------------------------------------------------------------------------- + + private static void SetLimits(MediaOptions options) + { + lock (LimitsLock) + { + if (_limitsSet) + { + return; + } + + ResourceLimits.Area = (ulong)Math.Max(1, options.MaxPixels); + ResourceLimits.Width = (ulong)Math.Max(1, options.MaxSide); + ResourceLimits.Height = (ulong)Math.Max(1, options.MaxSide); + ResourceLimits.Memory = 1UL * 1024 * 1024 * 1024; + ResourceLimits.Time = (ulong)Math.Max(1, options.DecodeTimeoutSeconds); + _limitsSet = true; + } + } + + private static HashSet DetectInput() + { + var wanted = new Dictionary + { + [MagickFormat.Jpeg] = ImageFormat.Jpeg, + [MagickFormat.Png] = ImageFormat.Png, + [MagickFormat.Gif] = ImageFormat.Gif, + [MagickFormat.Bmp] = ImageFormat.Bmp, + [MagickFormat.Tiff] = ImageFormat.Tiff, + [MagickFormat.WebP] = ImageFormat.WebP, + [MagickFormat.Avif] = ImageFormat.Avif, + [MagickFormat.Heic] = ImageFormat.Heic, + }; + var supported = MagickNET.SupportedFormats.Where(f => f.SupportsReading).Select(f => f.Format).ToHashSet(); + return wanted.Where(w => supported.Contains(w.Key) || (w.Key == MagickFormat.Jpeg && supported.Contains(MagickFormat.Jpg))) + .Select(w => w.Value).ToHashSet(); + } + + private static HashSet DetectOutput() + { + var writable = MagickNET.SupportedFormats.Where(f => f.SupportsWriting).Select(f => f.Format).ToHashSet(); + var result = new HashSet { ImageFormat.Jpeg }; + if (writable.Contains(MagickFormat.WebP)) + { + result.Add(ImageFormat.WebP); + } + + if (writable.Contains(MagickFormat.Avif)) + { + result.Add(ImageFormat.Avif); + } + + return result; + } + + private static MagickFormat ToMagick(ImageFormat format) => format switch + { + ImageFormat.Jpeg => MagickFormat.Jpeg, + ImageFormat.Png => MagickFormat.Png, + ImageFormat.Gif => MagickFormat.Gif, + ImageFormat.Bmp => MagickFormat.Bmp, + ImageFormat.Tiff => MagickFormat.Tiff, + ImageFormat.WebP => MagickFormat.WebP, + ImageFormat.Avif => MagickFormat.Avif, + ImageFormat.Heic => MagickFormat.Heic, + _ => throw new ArgumentOutOfRangeException(nameof(format), format, "Not an image format the processor knows."), + }; +} diff --git a/src/SlpModularCms.Core.Media.Magick/MagickServiceCollectionExtensions.cs b/src/SlpModularCms.Core.Media.Magick/MagickServiceCollectionExtensions.cs new file mode 100644 index 0000000..78e4dd7 --- /dev/null +++ b/src/SlpModularCms.Core.Media.Magick/MagickServiceCollectionExtensions.cs @@ -0,0 +1,15 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using SlpModularCms.Core.Media; + +namespace SlpModularCms.Core.Media.Magick; + +public static class MagickServiceCollectionExtensions +{ + /// Registers the Magick.NET implementation of (stateless, thread-safe). + public static IServiceCollection AddMagickImageProcessor(this IServiceCollection services) + { + services.TryAddSingleton(); + return services; + } +} diff --git a/src/SlpModularCms.Core.Media.Magick/SlpModularCms.Core.Media.Magick.csproj b/src/SlpModularCms.Core.Media.Magick/SlpModularCms.Core.Media.Magick.csproj new file mode 100644 index 0000000..bd00568 --- /dev/null +++ b/src/SlpModularCms.Core.Media.Magick/SlpModularCms.Core.Media.Magick.csproj @@ -0,0 +1,20 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + diff --git a/src/SlpModularCms.Core.Tests/Media/MagickImageProcessorTests.cs b/src/SlpModularCms.Core.Tests/Media/MagickImageProcessorTests.cs new file mode 100644 index 0000000..4c547ae --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Media/MagickImageProcessorTests.cs @@ -0,0 +1,235 @@ +using FluentAssertions; +using ImageMagick; +using ImageMagick.Formats; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Media; +using SlpModularCms.Core.Media.Magick; + +namespace SlpModularCms.Core.Tests.Media; + +/// The real image library on small generated fixtures (no files from disk, so they run the same everywhere). +public class MagickImageProcessorTests +{ + private static readonly MagickImageProcessor Processor = new(Options.Create(new MediaOptions()), NullLogger.Instance); + + private static byte[] Encode(MagickImage image, MagickFormat format) + { + using var stream = new MemoryStream(); + image.Write(stream, format); + return stream.ToArray(); + } + + /// Left half red, right half blue: lets a test see which part of the picture a crop kept. + private static MagickImage TwoColours(int width, int height) + { + var image = new MagickImage(MagickColors.Red, (uint)width, (uint)height); + using var blue = new MagickImage(MagickColors.Blue, (uint)(width / 2), (uint)height); + image.Composite(blue, width - width / 2, 0, CompositeOperator.Over); + return image; + } + + private static VariantSpec Spec(int w, int h, int x, int y, int cw, int ch, ImageFormat format = ImageFormat.WebP, Ratio? ratio = null) + => new(ratio ?? Ratio.Wide, w, h, format, 80, new CropRect(x, y, cw, ch)); + + [Fact] + public void TheCapabilities_CoverTheCommonFormats() + { + Processor.SupportedInput.Should().Contain([ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif, ImageFormat.Bmp, ImageFormat.Tiff, ImageFormat.WebP, ImageFormat.Avif]); + Processor.SupportedOutput.Should().Contain([ImageFormat.WebP, ImageFormat.Jpeg]); + } + + [Fact] + public async Task TheSelfTest_Passes() => await Processor.Invoking(p => p.SelfTestAsync(CancellationToken.None)).Should().NotThrowAsync(); + + [Theory] + [InlineData(MagickFormat.Jpeg, ImageFormat.Jpeg)] + [InlineData(MagickFormat.Png, ImageFormat.Png)] + [InlineData(MagickFormat.Gif, ImageFormat.Gif)] + [InlineData(MagickFormat.Bmp, ImageFormat.Bmp)] + [InlineData(MagickFormat.Tiff, ImageFormat.Tiff)] + [InlineData(MagickFormat.WebP, ImageFormat.WebP)] + [InlineData(MagickFormat.Avif, ImageFormat.Avif)] + public async Task EveryCommonFormat_IsRecognisedAndInspected(MagickFormat magick, ImageFormat expected) + { + using var image = TwoColours(120, 80); + var bytes = Encode(image, magick); + + var detected = ImageSignature.Detect(bytes); + detected.Should().Be(expected == ImageFormat.Avif ? ImageFormat.Avif : expected); + var info = await Processor.InspectAsync(bytes, detected, CancellationToken.None); + + info.Width.Should().Be(120); + info.Height.Should().Be(80); + info.FrameCount.Should().Be(1); + } + + [Fact] + public async Task ARotatedPhoto_IsReportedInItsOrientedSize() + { + using var image = new MagickImage(MagickColors.Green, 400, 200); + var exif = new ExifProfile(); + image.Orientation = Orientation.RightTop; // rotate 90 degrees clockwise on display + exif.SetValue(ExifTag.Orientation, (ushort)6); + image.SetProfile(exif); + var bytes = Encode(image, MagickFormat.Jpeg); + + var info = await Processor.InspectAsync(bytes, ImageFormat.Jpeg, CancellationToken.None); + + (info.Width, info.Height).Should().Be((200, 400)); + info.HasMetadata.Should().BeTrue(); + } + + [Fact] + public async Task AnAnimatedGif_ReportsItsFrames_AndRendersTheFirst() + { + using var frames = new MagickImageCollection(); + frames.Add(new MagickImage(MagickColors.Red, 60, 40) { AnimationDelay = 10 }); + frames.Add(new MagickImage(MagickColors.Blue, 60, 40) { AnimationDelay = 10 }); + using var stream = new MemoryStream(); + frames.Write(stream, MagickFormat.Gif); + var bytes = stream.ToArray(); + + var info = await Processor.InspectAsync(bytes, ImageFormat.Gif, CancellationToken.None); + var rendered = await Processor.RenderAsync(bytes, ImageFormat.Gif, Spec(60, 40, 0, 0, 60, 40, ImageFormat.Png), CancellationToken.None); + + info.FrameCount.Should().Be(2); + using var back = new MagickImage(rendered.Bytes); + back.GetPixels().GetPixel(5, 5).ToColor()!.ToString().Should().StartWith("#FF0000"); + } + + [Fact] + public async Task ARender_HasTheRequestedSize_AndNoMetadata() + { + using var image = TwoColours(1600, 1067); + var exif = new ExifProfile(); + exif.SetValue(ExifTag.Software, "camera firmware"); + exif.SetValue(ExifTag.GPSLatitudeRef, "N"); + image.SetProfile(exif); + var bytes = Encode(image, MagickFormat.Jpeg); + + var rendered = await Processor.RenderAsync(bytes, ImageFormat.Jpeg, Spec(960, 640, 0, 0, 1600, 1067), CancellationToken.None); + + rendered.Format.Should().Be(ImageFormat.WebP); + (rendered.Width, rendered.Height).Should().Be((960, 640)); + ImageSignature.Detect(rendered.Bytes).Should().Be(ImageFormat.WebP); + using var back = new MagickImage(); + back.Ping(rendered.Bytes); + back.GetExifProfile().Should().BeNull(); + back.GetXmpProfile().Should().BeNull(); + } + + [Fact] + public async Task TheCrop_KeepsTheChosenPartOfThePicture() + { + using var image = TwoColours(1000, 500); + var bytes = Encode(image, MagickFormat.Png); + var left = FocusMath.CropFor(1000, 500, Ratio.Tall, new FocusSetting(0.0, 0.5, 1)); + var right = FocusMath.CropFor(1000, 500, Ratio.Tall, new FocusSetting(1.0, 0.5, 1)); + + var leftImage = await Processor.RenderAsync(bytes, ImageFormat.Png, Spec(200, 250, left.X, left.Y, left.Width, left.Height, ImageFormat.Png, Ratio.Tall), CancellationToken.None); + var rightImage = await Processor.RenderAsync(bytes, ImageFormat.Png, Spec(200, 250, right.X, right.Y, right.Width, right.Height, ImageFormat.Png, Ratio.Tall), CancellationToken.None); + + using var l = new MagickImage(leftImage.Bytes); + using var r = new MagickImage(rightImage.Bytes); + l.GetPixels().GetPixel(100, 125).ToColor()!.ToString().Should().StartWith("#FF0000"); // red + r.GetPixels().GetPixel(100, 125).ToColor()!.ToString().Should().StartWith("#0000FF"); // blue + } + + [Fact] + public async Task ARotatedPhoto_IsCroppedInItsOrientedSize() + { + using var image = TwoColours(400, 200); + var exif = new ExifProfile(); + image.Orientation = Orientation.RightTop; + exif.SetValue(ExifTag.Orientation, (ushort)6); + image.SetProfile(exif); + var bytes = Encode(image, MagickFormat.Jpeg); + + var rendered = await Processor.RenderAsync(bytes, ImageFormat.Jpeg, Spec(100, 200, 0, 0, 200, 400, ImageFormat.Jpeg, Ratio.Tall), CancellationToken.None); + + (rendered.Width, rendered.Height).Should().Be((100, 200)); + } + + [Fact] + public async Task AvifOutput_IsWrittenWhenSupported() + { + Processor.SupportedOutput.Should().Contain(ImageFormat.Avif); + using var image = TwoColours(640, 427); + var bytes = Encode(image, MagickFormat.Png); + + var rendered = await Processor.RenderAsync(bytes, ImageFormat.Png, Spec(320, 213, 0, 0, 640, 427, ImageFormat.Avif), CancellationToken.None); + + ImageSignature.Detect(rendered.Bytes).Should().Be(ImageFormat.Avif); + } + + [Fact] + public async Task ATruncatedFile_IsRejectedAsCorrupt() + { + using var image = TwoColours(800, 600); + var bytes = Encode(image, MagickFormat.Jpeg); + var truncated = bytes.AsMemory(0, bytes.Length / 3); + + var act = async () => await Processor.RenderAsync(truncated, ImageFormat.Jpeg, Spec(100, 67, 0, 0, 800, 534), CancellationToken.None); + + (await act.Should().ThrowAsync()).Which.Reason.Should().Be(ImageRejection.Corrupt); + } + + [Fact] + public async Task AFileWithAJpegHeaderAndGarbage_IsRejectedAsCorrupt() + { + var garbage = new byte[2000]; + new Random(7).NextBytes(garbage); + garbage[0] = 0xFF; + garbage[1] = 0xD8; + garbage[2] = 0xFF; + + var act = async () => await Processor.InspectAsync(garbage, ImageFormat.Jpeg, CancellationToken.None); + + (await act.Should().ThrowAsync()).Which.Reason.Should().Be(ImageRejection.Corrupt); + } + + [Fact] + public async Task AFileThatClaimsAnotherFormat_IsRejected() + { + using var image = TwoColours(50, 50); + var png = Encode(image, MagickFormat.Png); + + var act = async () => await Processor.InspectAsync(png, ImageFormat.Tiff, CancellationToken.None); + + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task StrippingMetadata_RemovesTheProfiles_AndKeepsTheSize() + { + using var image = TwoColours(300, 200); + var exif = new ExifProfile(); + exif.SetValue(ExifTag.Software, "camera"); + image.SetProfile(exif); + var withExif = Encode(image, MagickFormat.Jpeg); + using var plain = TwoColours(300, 200); + var withoutExif = Encode(plain, MagickFormat.Jpeg); + + var stripped = await Processor.StripMetadataAsync(withExif, ImageFormat.Jpeg, CancellationToken.None); + var untouched = await Processor.StripMetadataAsync(withoutExif, ImageFormat.Jpeg, CancellationToken.None); + + untouched.Should().BeNull(); + stripped.Should().NotBeNull(); + using var back = new MagickImage(); + back.Ping(stripped!); + back.GetExifProfile().Should().BeNull(); + (back.Width, back.Height).Should().Be((300u, 200u)); + } + + [Fact] + public async Task APlannedCrop_ThatDoesNotFit_IsRefused() + { + using var image = TwoColours(100, 100); + var bytes = Encode(image, MagickFormat.Png); + + var act = async () => await Processor.RenderAsync(bytes, ImageFormat.Png, Spec(50, 33, 50, 50, 100, 100), CancellationToken.None); + + await act.Should().ThrowAsync(); + } +} diff --git a/src/SlpModularCms.Core.Tests/Media/MediaPureFunctionTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaPureFunctionTests.cs new file mode 100644 index 0000000..2a9a186 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Media/MediaPureFunctionTests.cs @@ -0,0 +1,290 @@ +using FluentAssertions; +using FsCheck; +using FsCheck.Fluent; +using SlpModularCms.Core.Media; + +namespace SlpModularCms.Core.Tests.Media; + +public class FocusMathTests +{ + private static Arbitrary<(int W, int H, FocusSetting Focus, Ratio Ratio)> Cases() => + (from w in Gen.Choose(1, 9000) + from h in Gen.Choose(1, 9000) + from fx in Gen.Choose(0, 1000) + from fy in Gen.Choose(0, 1000) + from zoom in Gen.Choose(1000, 4000) + from tall in Gen.Elements(true, false) + select (w, h, new FocusSetting(fx / 1000.0, fy / 1000.0, zoom / 1000.0), tall ? Ratio.Tall : Ratio.Wide)).ToArbitrary(); + + private static void ForAllCases(Action<(int W, int H, FocusSetting Focus, Ratio Ratio)> check) => + Prop.ForAll(Cases(), c => { check(c); return true; }).Check(Config.QuickThrowOnFailure.WithMaxTest(2000)); + + [Fact] + public void TheCrop_IsAlwaysInsideTheImage() => ForAllCases(c => + { + var crop = FocusMath.CropFor(c.W, c.H, c.Ratio, c.Focus); + crop.Width.Should().BeInRange(1, c.W); + crop.Height.Should().BeInRange(1, c.H); + crop.X.Should().BeGreaterThanOrEqualTo(0); + crop.Y.Should().BeGreaterThanOrEqualTo(0); + (crop.X + crop.Width).Should().BeLessThanOrEqualTo(c.W); + (crop.Y + crop.Height).Should().BeLessThanOrEqualTo(c.H); + }); + + [Fact] + public void TheFocusPoint_IsInsideTheCrop() => ForAllCases(c => + { + var crop = FocusMath.CropFor(c.W, c.H, c.Ratio, c.Focus); + var px = c.Focus.X * c.W; + var py = c.Focus.Y * c.H; + px.Should().BeInRange(crop.X - 1, crop.X + crop.Width + 1); + py.Should().BeInRange(crop.Y - 1, crop.Y + crop.Height + 1); + }); + + [Fact] + public void TheCrop_HasTheRatio_WithinOnePixel() => ForAllCases(c => + { + // Only meaningful when the crop is big enough for one pixel not to matter. + var crop = FocusMath.CropFor(c.W, c.H, c.Ratio, c.Focus); + if (crop.Width >= 50 && crop.Height >= 50) + { + var expectedHeight = crop.Width * (double)c.Ratio.Denominator / c.Ratio.Numerator; + Math.Abs(crop.Height - expectedHeight).Should().BeLessThanOrEqualTo(1.0); + } + }); + + [Fact] + public void MoreZoom_NeverGivesABiggerCrop() => ForAllCases(c => + { + var plain = FocusMath.CropFor(c.W, c.H, c.Ratio, c.Focus with { Zoom = 1 }); + var zoomed = FocusMath.CropFor(c.W, c.H, c.Ratio, c.Focus); + zoomed.Width.Should().BeLessThanOrEqualTo(plain.Width); + }); + + [Fact] + public void InvalidFocusValues_AreClamped_NotFatal() + { + var crop = FocusMath.CropFor(1600, 1067, Ratio.Tall, new FocusSetting(double.NaN, double.PositiveInfinity, double.NegativeInfinity)); + crop.X.Should().BeGreaterThanOrEqualTo(0); + (crop.X + crop.Width).Should().BeLessThanOrEqualTo(1600); + } + + // Shared vectors: the admin's TypeScript twin has the same cases (frontend/src/features/hero/focusMath.test.ts). + [Theory] + [InlineData(1600, 1067, "wide", 0.5, 0.5, 1.0, 0, 0, 1600, 1067)] + [InlineData(1600, 1067, "tall", 0.5, 0.5, 1.0, 374, 1, 853, 1066)] + [InlineData(1600, 1067, "tall", 0.0, 0.5, 1.0, 0, 1, 853, 1066)] + [InlineData(1600, 1067, "tall", 1.0, 0.5, 1.0, 747, 1, 853, 1066)] + [InlineData(1600, 1067, "wide", 0.45, 0.35, 2.0, 320, 107, 800, 533)] + [InlineData(2560, 1702, "tall", 0.55, 0.6, 1.0, 728, 1, 1361, 1701)] + [InlineData(1000, 2000, "wide", 0.5, 0.5, 1.0, 0, 667, 1000, 667)] + public void KnownVectors(int w, int h, string ratio, double fx, double fy, double zoom, int x, int y, int cw, int ch) + { + var crop = FocusMath.CropFor(w, h, ratio == "tall" ? Ratio.Tall : Ratio.Wide, new FocusSetting(fx, fy, zoom)); + crop.Should().Be(new CropRect(x, y, cw, ch)); + } +} + +public class VariantPlannerTests +{ + private static readonly IReadOnlySet WebPAndAvif = new HashSet { ImageFormat.WebP, ImageFormat.Avif }; + private static readonly IReadOnlySet WebPOnly = new HashSet { ImageFormat.WebP }; + + private static RatioPlan[] Plans() => + [ + new(Ratio.Wide, FocusSetting.Centre, VariantPlanner.DefaultWidths(Ratio.Wide)), + new(Ratio.Tall, FocusSetting.Centre, VariantPlanner.DefaultWidths(Ratio.Tall)), + ]; + + [Fact] + public void ASmallSource_IsNeverScaledUp() + { + var plan = VariantPlanner.Plan(1600, 1067, Plans(), WebPAndAvif); + + plan.Should().OnlyContain(v => v.Width <= v.Crop.Width); + plan.Where(v => v.Ratio.Name == "wide").Select(v => v.Width).Distinct().Should().Equal(640, 960, 1280, 1600); + plan.Where(v => v.Ratio.Name == "tall").Select(v => v.Width).Distinct().Should().Equal(480, 640); // the tall crop of a 1600x1067 image is 853 wide + } + + [Fact] + public void ALargeSource_GetsTheWholeLadder() + { + var plan = VariantPlanner.Plan(6000, 4000, Plans(), WebPAndAvif); + + plan.Where(v => v.Ratio.Name == "wide").Select(v => v.Width).Distinct().Should().Equal(640, 960, 1280, 1600, 2560); + plan.Where(v => v.Ratio.Name == "tall").Select(v => v.Width).Distinct().Should().Equal(480, 640, 960, 1280); + } + + [Fact] + public void ATinySource_StillGetsOneVariantPerRatio() + { + var plan = VariantPlanner.Plan(300, 200, Plans(), WebPOnly); + + plan.Where(v => v.Ratio.Name == "wide").Should().ContainSingle().Which.Width.Should().Be(300); + plan.Where(v => v.Ratio.Name == "tall").Should().ContainSingle().Which.Width.Should().Be(160); + } + + [Fact] + public void WebPIsAlwaysPlanned_AvifOnlyWhenTheProcessorCan() + { + VariantPlanner.Plan(2000, 1500, Plans(), WebPOnly).Select(v => v.Format).Distinct().Should().Equal(ImageFormat.WebP); + VariantPlanner.Plan(2000, 1500, Plans(), WebPAndAvif).Select(v => v.Format).Distinct().Should().BeEquivalentTo([ImageFormat.WebP, ImageFormat.Avif]); + } + + [Fact] + public void WithoutAWebPEncoder_TheFallbackIsJpeg() + { + var onlyAvif = new HashSet { ImageFormat.Avif }; + + VariantPlanner.Plan(2000, 1500, Plans(), onlyAvif).Select(v => v.Format).Distinct().Should().BeEquivalentTo([ImageFormat.Jpeg, ImageFormat.Avif]); + } + + [Fact] + public void Widths_AreAscendingPerRatio_AndHeightsKeepTheRatio() + { + Prop.ForAll(Gen.Choose(50, 9000).SelectMany(w => Gen.Choose(50, 9000).Select(h => (w, h))).ToArbitrary(), size => + { + var plan = VariantPlanner.Plan(size.w, size.h, Plans(), WebPAndAvif); + foreach (var group in plan.GroupBy(v => v.Ratio.Name)) + { + var widths = group.Where(v => v.Format == ImageFormat.WebP).Select(v => v.Width).ToList(); + widths.Should().BeInAscendingOrder().And.OnlyHaveUniqueItems(); + widths.Should().NotBeEmpty(); + foreach (var v in group) + { + Math.Abs(v.Height - v.Width * (double)v.Ratio.Denominator / v.Ratio.Numerator).Should().BeLessThanOrEqualTo(0.5); + } + } + + return true; + }).Check(Config.QuickThrowOnFailure.WithMaxTest(500)); + } +} + +public class MediaPathsTests +{ + private const string Sha = "0f8c6d3e2a1b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5"; + + [Fact] + public void TheSetHash_IsStable_AndChangesWhenTheFocusChanges() + { + var a = MediaPaths.SetHash(Sha, [("wide", FocusSetting.Centre), ("tall", FocusSetting.Centre)]); + var again = MediaPaths.SetHash(Sha, [("tall", FocusSetting.Centre), ("wide", FocusSetting.Centre)]); + var moved = MediaPaths.SetHash(Sha, [("wide", FocusSetting.Centre), ("tall", new FocusSetting(0.4, 0.5, 1))]); + var other = MediaPaths.SetHash(Sha.Replace('0', '1'), [("wide", FocusSetting.Centre), ("tall", FocusSetting.Centre)]); + + a.Should().MatchRegex("^[0-9a-f]{16}$"); + again.Should().Be(a); + moved.Should().NotBe(a); + other.Should().NotBe(a); + } + + [Fact] + public void SmallDifferences_BelowTheCanonicalPrecision_GiveTheSameSet() + => MediaPaths.SetHash(Sha, [("wide", new FocusSetting(0.50001, 0.5, 1))]) + .Should().Be(MediaPaths.SetHash(Sha, [("wide", new FocusSetting(0.5, 0.5, 1))])); + + [Fact] + public void AnAddress_RoundTrips() + { + var hash = MediaPaths.SetHash(Sha, [("wide", FocusSetting.Centre)]); + var name = MediaPaths.FileName("wide", 1600, ImageFormat.WebP); + var url = MediaPaths.Url("hero", hash, name); + + url.Should().Be($"/media/hero/{hash}/wide-1600.webp"); + MediaPaths.TryParse(url[MediaPaths.UrlPrefix.Length..], out var address).Should().BeTrue(); + address.Should().Be(new MediaAddress("hero", hash, "wide-1600.webp")); + MediaPaths.TryParseName(name, out var ratio, out var width, out var format).Should().BeTrue(); + (ratio, width, format).Should().Be(("wide", 1600, ImageFormat.WebP)); + } + + [Theory] + [InlineData("")] + [InlineData("hero/0123456789abcdef/wide-1600.png")] + [InlineData("hero/0123456789abcde/wide-1600.webp")] + [InlineData("hero/0123456789ABCDEF/wide-1600.webp")] + [InlineData("hero/0123456789abcdef/../wide-1600.webp")] + [InlineData("../hero/0123456789abcdef/wide-1600.webp")] + [InlineData("hero//0123456789abcdef/wide-1600.webp")] + [InlineData("hero/0123456789abcdef/wide-1600.webp/")] + [InlineData("hero\\0123456789abcdef\\wide-1600.webp")] + [InlineData("hero/0123456789abcdef/wide-16.webp ")] + [InlineData("hero/0123456789abcdef/WIDE-1600.webp")] + [InlineData("hero/0123456789abcdef/original.jpg")] + [InlineData("originals/0123456789abcdef/wide-1600.webp.exe")] + public void AnythingElse_IsNotAnAddress(string path) => MediaPaths.TryParse(path, out _).Should().BeFalse(); +} + +public class ImageSignatureTests +{ + private static byte[] Padded(params byte[] head) => head.Concat(new byte[32 - head.Length]).ToArray(); + + [Fact] + public void KnownSignatures_AreRecognised() + { + ImageSignature.Detect(Padded(0xFF, 0xD8, 0xFF, 0xE0)).Should().Be(ImageFormat.Jpeg); + ImageSignature.Detect(Padded(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)).Should().Be(ImageFormat.Png); + ImageSignature.Detect("GIF89a"u8.ToArray().Concat(new byte[26]).ToArray()).Should().Be(ImageFormat.Gif); + ImageSignature.Detect(Padded(0x49, 0x49, 0x2A, 0x00)).Should().Be(ImageFormat.Tiff); + ImageSignature.Detect(Padded(0x4D, 0x4D, 0x00, 0x2A)).Should().Be(ImageFormat.Tiff); + ImageSignature.Detect(Riff("WEBP")).Should().Be(ImageFormat.WebP); + ImageSignature.Detect(Ftyp("avif")).Should().Be(ImageFormat.Avif); + ImageSignature.Detect(Ftyp("heic")).Should().Be(ImageFormat.Heic); + ImageSignature.Detect(Bmp(40)).Should().Be(ImageFormat.Bmp); + } + + [Theory] + [InlineData("")] + [InlineData("")] + [InlineData("%PDF-1.7 and more text here to fill")] + [InlineData("MZ\u0090\u0000\u0003 an executable header")] + [InlineData("")] + [InlineData("PK\u0003\u0004 a zip archive of something")] + [InlineData("")] + public void NotAnImage_IsUnknown(string text) + => ImageSignature.Detect(System.Text.Encoding.Latin1.GetBytes(text)).Should().Be(ImageFormat.Unknown); + + [Fact] + public void ARiffThatIsNotWebP_IsUnknown() => ImageSignature.Detect(Riff("WAVE")).Should().Be(ImageFormat.Unknown); + + [Fact] + public void AnIsoFileWithAnotherBrand_IsUnknown() => ImageSignature.Detect(Ftyp("mp42")).Should().Be(ImageFormat.Unknown); + + [Fact] + public void ABmThatIsNoBitmap_IsUnknown() => ImageSignature.Detect(Bmp(7)).Should().Be(ImageFormat.Unknown); + + [Fact] + public void ARandomHead_NeverThrows() + => Prop.ForAll(Gen.Choose(0, 255).Select(i => (byte)i).ArrayOf().ToArbitrary(), bytes => + { + var act = () => ImageSignature.Detect(bytes); + act.Should().NotThrow(); + return true; + }).Check(Config.QuickThrowOnFailure.WithMaxTest(1000)); + + private static byte[] Riff(string kind) + { + var b = new byte[32]; + "RIFF"u8.CopyTo(b); + System.Text.Encoding.ASCII.GetBytes(kind).CopyTo(b, 8); + return b; + } + + private static byte[] Ftyp(string brand) + { + var b = new byte[32]; + b[3] = 0x1C; + "ftyp"u8.CopyTo(b.AsSpan(4)); + System.Text.Encoding.ASCII.GetBytes(brand).CopyTo(b, 8); + return b; + } + + private static byte[] Bmp(int headerSize) + { + var b = new byte[32]; + b[0] = (byte)'B'; + b[1] = (byte)'M'; + b[14] = (byte)headerSize; + return b; + } +} diff --git a/src/SlpModularCms.Core.Tests/Media/MediaUploadGuardTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaUploadGuardTests.cs new file mode 100644 index 0000000..268d922 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Media/MediaUploadGuardTests.cs @@ -0,0 +1,157 @@ +using FluentAssertions; +using Microsoft.Extensions.Options; +using NSubstitute; +using SlpModularCms.Core.Media; + +namespace SlpModularCms.Core.Tests.Media; + +public class MediaUploadGuardTests +{ + private static readonly byte[] Png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4, 5, 6, 7, 8]; + + private sealed class Rig + { + public MediaOptions Options { get; } = new() { MaxUploadBytes = 1000, MaxPixels = 1_000_000, MaxSide = 5000, MaxParallelJobs = 1, BusyWaitSeconds = 0 }; + + public IImageProcessor Processor { get; } = Substitute.For(); + + public MediaStatus Status { get; } = new(); + + public MediaProcessingGate Gate { get; } + + public MediaUploadGuard Guard { get; } + + public Rig(bool available = true) + { + Gate = new MediaProcessingGate(Microsoft.Extensions.Options.Options.Create(Options)); + Processor.SupportedInput.Returns(new HashSet { ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.WebP }); + Processor.InspectAsync(default, default, default).ReturnsForAnyArgs(new ImageInfo(ImageFormat.Png, 800, 600, 1, false)); + Status.SetProcessor(available, Processor.SupportedInput, new HashSet { ImageFormat.WebP }); + Status.SetDirectory(true); + Guard = new MediaUploadGuard(Processor, Gate, Status, Microsoft.Extensions.Options.Options.Create(Options)); + } + } + + private static MemoryStream Stream(byte[] bytes) => new(bytes); + + [Fact] + public async Task AValidImage_IsAdmitted_WithItsInfo() + { + var rig = new Rig(); + + using var upload = await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None); + + upload.Bytes.Should().Equal(Png); + upload.Info.Width.Should().Be(800); + } + + [Fact] + public async Task ADeclaredLength_AboveTheLimit_IsRefusedBeforeReading() + { + var rig = new Rig(); + + var act = async () => await rig.Guard.AdmitAsync(Stream(Png), 5000, CancellationToken.None); + + (await act.Should().ThrowAsync()).Which.Code.Should().Be("too_large"); + } + + [Fact] + public async Task AnUpload_LongerThanItsDeclaredLength_IsStillStopped() + { + var rig = new Rig(); + var big = new byte[2000]; + Png.CopyTo(big, 0); + + var act = async () => await rig.Guard.AdmitAsync(Stream(big), 10, CancellationToken.None); + + (await act.Should().ThrowAsync()).Which.Code.Should().Be("too_large"); + } + + [Theory] + [InlineData("")] + [InlineData("%PDF-1.4 not an image")] + [InlineData("GIF89a is not in the accepted list of this rig but the processor lacks it")] + public async Task NotAnAcceptedImage_IsRefused(string text) + { + var rig = new Rig(); + var bytes = System.Text.Encoding.ASCII.GetBytes(text); + + var act = async () => await rig.Guard.AdmitAsync(Stream(bytes), bytes.Length, CancellationToken.None); + + (await act.Should().ThrowAsync()).Which.Code.Should().Be("unsupported_format"); + } + + [Fact] + public async Task AnEmptyUpload_IsCorrupt() + { + var rig = new Rig(); + + var act = async () => await rig.Guard.AdmitAsync(Stream([]), 0, CancellationToken.None); + + (await act.Should().ThrowAsync()).Which.Code.Should().Be("corrupt"); + } + + [Theory] + [InlineData(2000, 2000)] // 4 MP, above the 1 MP ceiling + [InlineData(6000, 10)] // a side above the limit + public async Task ATooBigPicture_IsRefused(int width, int height) + { + var rig = new Rig(); + rig.Processor.InspectAsync(default, default, default).ReturnsForAnyArgs(new ImageInfo(ImageFormat.Png, width, height, 1, false)); + + var act = async () => await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None); + + (await act.Should().ThrowAsync()).Which.Code.Should().Be("too_many_pixels"); + } + + [Fact] + public async Task WhenTheLibraryIsNotAvailable_NothingIsAccepted() + { + var rig = new Rig(available: false); + + var act = async () => await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None); + + (await act.Should().ThrowAsync()).Which.Code.Should().Be("unavailable"); + } + + [Fact] + public async Task WhenTheDirectoryIsNotWritable_NothingIsAccepted() + { + var rig = new Rig(); + rig.Status.SetDirectory(false); + + var act = async () => await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None); + + (await act.Should().ThrowAsync()).Which.Code.Should().Be("unavailable"); + } + + [Fact] + public async Task WhenAllSlotsAreTaken_TheAnswerIsBusy_AndAFreedSlotWorksAgain() + { + var rig = new Rig(); + var first = await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None); + + var act = async () => await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None); + (await act.Should().ThrowAsync()).Which.Code.Should().Be("busy"); + + first.Dispose(); + using var second = await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None); + second.Info.Should().NotBeNull(); + } + + [Fact] + public async Task ARefusal_ReleasesTheSlot() + { + var rig = new Rig(); + var bad = System.Text.Encoding.ASCII.GetBytes("not an image at all"); + + for (var i = 0; i < 3; i++) + { + var act = async () => await rig.Guard.AdmitAsync(Stream(bad), bad.Length, CancellationToken.None); + await act.Should().ThrowAsync(); + } + + using var ok = await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None); + ok.Should().NotBeNull(); + } +} diff --git a/src/SlpModularCms.Core.Tests/SlpModularCms.Core.Tests.csproj b/src/SlpModularCms.Core.Tests/SlpModularCms.Core.Tests.csproj index 16b0e15..a505fb4 100644 --- a/src/SlpModularCms.Core.Tests/SlpModularCms.Core.Tests.csproj +++ b/src/SlpModularCms.Core.Tests/SlpModularCms.Core.Tests.csproj @@ -36,6 +36,7 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs new file mode 100644 index 0000000..220917f --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs @@ -0,0 +1,156 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Availability; +using SlpModularCms.Core.Media; +using SlpModularCms.Core.Texts; +using SlpModularCms.Modules.Hero.Models; +using SlpModularCms.Modules.Hero.Services; + +namespace SlpModularCms.Modules.Hero.Controllers; + +/// +/// The hero of the site. GET /hero is what websites read (200 with the hero, 204 when there is none to show); +/// management (GET /hero/all, PUT /hero) is for administrators. +/// +[ApiController] +[Route("hero")] +public class HeroController(IHeroService service, IPublicHeroService publicService) : ControllerBase +{ + [HttpGet] + [AllowAnonymous] + [PublicSiteEndpoint] + [EnableRateLimiting("hero-public")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task Get(CancellationToken cancellationToken) + { + Response.Headers.CacheControl = "public, max-age=60"; + var hero = await publicService.GetActiveAsync(cancellationToken); + return hero is null ? NoContent() : Ok(hero); + } + + [HttpGet("all")] + [Authorize(Policy = "AdminOnly")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task GetForAdmin(CancellationToken cancellationToken) + => Ok(await service.GetAsync(cancellationToken)); + + [HttpPut] + [Authorize(Policy = "AdminOnly")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Save([FromBody] HeroSaveRequest request, CancellationToken cancellationToken) + { + try + { + return Ok(await service.SaveAsync(request, HeroCaller.Id(User), cancellationToken)); + } + catch (HeroSaveRejectedException exception) + { + ModelState.AddModelError(exception.Field, exception.Message); + return ValidationProblem(ModelState); + } + } +} + +/// Images of the hero: upload, focus and delete. Administrators only. +[ApiController] +[Route("hero/images")] +[Authorize(Policy = "AdminOnly")] +public class HeroImagesController(IHeroImageService service, IOptions media) : ControllerBase +{ + /// The body limit leaves room for the multipart envelope around the file limit of . + private const long RequestLimit = 12 * 1024 * 1024; + + [HttpPost] + [RequestSizeLimit(RequestLimit)] + [EnableRateLimiting("hero-upload")] + [Consumes("multipart/form-data")] + [ProducesResponseType(StatusCodes.Status201Created)] + public async Task Upload(IFormFile file, CancellationToken cancellationToken) + { + try + { + await using var stream = file.OpenReadStream(); + var image = await service.UploadAsync(stream, file.Length, HeroCaller.Id(User), cancellationToken); + return Created($"/api/v1/hero/images/{image.Id}", image); + } + catch (ImageRejectedException rejection) + { + return Rejected(rejection); + } + catch (MediaStorageFullException) + { + return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "storage_full", message = Texts().Get(HeroTexts.Image.StorageFull) }); + } + } + + [HttpPut("{id:guid}/focus")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task SetFocus(Guid id, [FromBody] HeroFocusRequest request, CancellationToken cancellationToken) + { + try + { + return Ok(await service.SetFocusAsync(id, request, HeroCaller.Id(User), cancellationToken)); + } + catch (HeroImageNotFoundException) + { + return NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) }); + } + catch (ImageRejectedException rejection) + { + return Rejected(rejection); + } + } + + [HttpDelete("{id:guid}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + public async Task Delete(Guid id, CancellationToken cancellationToken) + { + try + { + await service.DeleteAsync(id, HeroCaller.Id(User), cancellationToken); + return NoContent(); + } + catch (HeroImageNotFoundException) + { + return NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) }); + } + catch (HeroImageInUseException) + { + return Conflict(new { error = "in_use", message = Texts().Get(HeroTexts.Image.InUse) }); + } + } + + private ITextCatalog Texts() => HttpTexts.From(HttpContext); + + private IActionResult Rejected(ImageRejectedException rejection) + { + var status = rejection.Reason switch + { + ImageRejection.TooLarge => StatusCodes.Status413PayloadTooLarge, + ImageRejection.Busy => StatusCodes.Status429TooManyRequests, + ImageRejection.Unavailable => StatusCodes.Status503ServiceUnavailable, + _ => StatusCodes.Status400BadRequest, + }; + var key = HeroTexts.Image.For(rejection.Reason); + var message = rejection.Reason == ImageRejection.TooLarge + ? Texts().Get(key, args: ("max", media.Value.MaxUploadBytes / (1024 * 1024))) + : Texts().Get(key); + return StatusCode(status, new { error = rejection.Code, message }); + } +} + +internal static class HeroCaller +{ + public static Guid Id(ClaimsPrincipal user) + { + var claim = user.FindFirstValue(ClaimTypes.NameIdentifier) ?? user.FindFirstValue("sub"); + return Guid.TryParse(claim, out var id) ? id : Guid.Empty; + } +} diff --git a/src/SlpModularCms.Modules.Hero/Data/Entities/HeroEntities.cs b/src/SlpModularCms.Modules.Hero/Data/Entities/HeroEntities.cs new file mode 100644 index 0000000..419a80b --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Data/Entities/HeroEntities.cs @@ -0,0 +1,106 @@ +using SlpModularCms.Core.Media; + +namespace SlpModularCms.Modules.Hero.Data.Entities; + +/// The hero of the site in one language: texts, up to two buttons, the display, the schedule and the slides. +public class HeroContent +{ + public Guid Id { get; set; } + + /// Unique; only is exposed and edited now, the column keeps the model ready for more. + public string Language { get; set; } = HeroLanguages.Default; + + public string Title { get; set; } = string.Empty; + public string? Tagline { get; set; } + public string? Lead { get; set; } + public string Display { get; set; } = HeroDisplays.Single; + public string? Button1Label { get; set; } + public string? Button1Target { get; set; } + public string? Button2Label { get; set; } + public string? Button2Target { get; set; } + public DateTimeOffset? StartsAt { get; set; } + public DateTimeOffset? EndsAt { get; set; } + public bool IsActive { get; set; } = true; + public DateTimeOffset UpdatedAt { get; set; } + public Guid LastModifiedByUserId { get; set; } + + public List Slides { get; set; } = []; +} + +public class HeroSlide +{ + public Guid Id { get; set; } + public Guid HeroId { get; set; } + public Guid ImageId { get; set; } + public HeroImage? Image { get; set; } + public string Alt { get; set; } = string.Empty; + public bool Decorative { get; set; } + public int SortOrder { get; set; } + public bool IsActive { get; set; } = true; +} + +/// A stored image: the original (never served), where the subject is, and the current set of variants. +public class HeroImage +{ + public Guid Id { get; set; } + + /// SHA-256 of the file as uploaded (hex); the same photo uploaded twice is one image. + public string OriginalSha256 { get; set; } = string.Empty; + public string OriginalKey { get; set; } = string.Empty; + public string SourceFormat { get; set; } = string.Empty; + public int Width { get; set; } + public int Height { get; set; } + public long Bytes { get; set; } + + public double FocusX { get; set; } = 0.5; + public double FocusY { get; set; } = 0.5; + public double Zoom { get; set; } = 1.0; + public double? WideFocusX { get; set; } + public double? WideFocusY { get; set; } + public double? WideZoom { get; set; } + public double? TallFocusX { get; set; } + public double? TallFocusY { get; set; } + public double? TallZoom { get; set; } + + public string SetHash { get; set; } = string.Empty; + public List Variants { get; set; } = []; + + public DateTimeOffset CreatedAt { get; set; } + public Guid CreatedByUserId { get; set; } + + public FocusSetting General => new FocusSetting(FocusX, FocusY, Zoom).Normalize(); + + public FocusSetting FocusFor(string ratio) => ratio switch + { + "wide" when WideFocusX is not null && WideFocusY is not null => new FocusSetting(WideFocusX.Value, WideFocusY.Value, WideZoom ?? Zoom).Normalize(), + "tall" when TallFocusX is not null && TallFocusY is not null => new FocusSetting(TallFocusX.Value, TallFocusY.Value, TallZoom ?? Zoom).Normalize(), + _ => General, + }; +} + +/// One file of the current set: the ratio, its pixel size, the type and the file name inside the set. +public record HeroVariant(string Ratio, int Width, int Height, string Type, string FileName, long Bytes); + +/// A set or an original that nothing uses any more; the clean-up deletes it once the retention time has passed. +public class HeroRetiredFile +{ + public Guid Id { get; set; } + + /// set (a set hash) or original (an original key). + public string Kind { get; set; } = string.Empty; + public string Key { get; set; } = string.Empty; + public DateTimeOffset RetiredAt { get; set; } +} + +public static class HeroLanguages +{ + public const string Default = "nl"; +} + +public static class HeroDisplays +{ + public const string Single = "single"; + public const string Slideshow = "slideshow"; + + public static bool IsValid(string? value) => value is Single or Slideshow; +} diff --git a/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs b/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs new file mode 100644 index 0000000..c56c929 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs @@ -0,0 +1,87 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using SlpModularCms.Modules.Hero.Data.Entities; + +namespace SlpModularCms.Modules.Hero.Data; + +public class HeroDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet Heroes => Set(); + public DbSet HeroSlides => Set(); + public DbSet HeroImages => Set(); + public DbSet HeroRetiredFiles => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(entity => + { + entity.ToTable("Heroes"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Language).IsRequired().HasMaxLength(10); + entity.HasIndex(e => e.Language).IsUnique(); + entity.Property(e => e.Title).IsRequired().HasMaxLength(1000); + entity.Property(e => e.Tagline).HasMaxLength(200); + entity.Property(e => e.Lead).HasMaxLength(1000); + entity.Property(e => e.Display).IsRequired().HasMaxLength(20); + entity.Property(e => e.Button1Label).HasMaxLength(100); + entity.Property(e => e.Button1Target).HasMaxLength(500); + entity.Property(e => e.Button2Label).HasMaxLength(100); + entity.Property(e => e.Button2Target).HasMaxLength(500); + entity.Property(e => e.IsActive).IsRequired(); + entity.Property(e => e.UpdatedAt).IsRequired(); + entity.Property(e => e.LastModifiedByUserId).IsRequired(); + entity.HasMany(e => e.Slides).WithOne().HasForeignKey(s => s.HeroId).OnDelete(DeleteBehavior.Cascade); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("HeroSlides"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Alt).IsRequired().HasMaxLength(600); + entity.Property(e => e.SortOrder).IsRequired(); + // Not unique: re-ordering updates several rows in one save and must not trip over itself. + entity.HasIndex(e => new { e.HeroId, e.SortOrder }); + entity.HasIndex(e => e.ImageId); + + // Restrict: an image that a slide still uses cannot be deleted (the service answers 409 first). + entity.HasOne(e => e.Image).WithMany().HasForeignKey(e => e.ImageId).OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("HeroImages"); + entity.HasKey(e => e.Id); + entity.Property(e => e.OriginalSha256).IsRequired().HasMaxLength(64); + entity.HasIndex(e => e.OriginalSha256).IsUnique(); + entity.Property(e => e.OriginalKey).IsRequired().HasMaxLength(200); + entity.Property(e => e.SourceFormat).IsRequired().HasMaxLength(10); + entity.Property(e => e.SetHash).IsRequired().HasMaxLength(16); + entity.Property(e => e.CreatedAt).IsRequired(); + entity.Property(e => e.CreatedByUserId).IsRequired(); + entity.Ignore(e => e.General); + + // The variants of the current set: a small list that is always replaced as a whole. + entity.Property(e => e.Variants) + .HasConversion( + variants => JsonSerializer.Serialize(variants, (JsonSerializerOptions?)null), + json => JsonSerializer.Deserialize>(json, (JsonSerializerOptions?)null) ?? new List()) + .HasColumnType("longtext") + .Metadata.SetValueComparer(new ValueComparer>( + (a, b) => (a ?? new List()).SequenceEqual(b ?? new List()), + v => v.Aggregate(0, (hash, item) => HashCode.Combine(hash, item.GetHashCode())), + v => v.ToList())); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("HeroRetiredFiles"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Kind).IsRequired().HasMaxLength(10); + entity.Property(e => e.Key).IsRequired().HasMaxLength(200); + entity.Property(e => e.RetiredAt).IsRequired(); + }); + } +} diff --git a/src/SlpModularCms.Modules.Hero/HeroModule.cs b/src/SlpModularCms.Modules.Hero/HeroModule.cs new file mode 100644 index 0000000..2a82eb6 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/HeroModule.cs @@ -0,0 +1,56 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Builder; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Media; +using SlpModularCms.Core.Media.Magick; +using SlpModularCms.Core.Modules; +using SlpModularCms.Core.Texts; +using SlpModularCms.Modules.Hero.Data; +using SlpModularCms.Modules.Hero.Repositories; +using SlpModularCms.Modules.Hero.Services; + +namespace SlpModularCms.Modules.Hero; + +/// The manageable hero of a website: texts, buttons, slides with images, schedule; images are processed and served by the host. +[ExcludeFromCodeCoverage] +public class HeroModule : IModule +{ + public string Name => "Hero"; + public string Version => "1.0.0"; + + public void RegisterServices(IServiceCollection services) + { + services.AddDbContext((serviceProvider, options) => + { + var config = serviceProvider.GetRequiredService(); + options.UseMySQL(config.GetConnectionString("DefaultConnection")!); + options.ReplaceService(); + }); + + services.AddCmsTextsFrom(typeof(HeroModule).Assembly); + services.AddOptions().Configure((options, configuration) => + configuration.GetSection(HeroOptions.SectionName).Bind(options)); + + // Image processing and the media area this module owns (served at /media/hero/...). + services.AddCmsMediaArea(HeroMapping.Area); + services.AddMagickImageProcessor(); + + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddHostedService(); + } + + public void UseModule(IApplicationBuilder app) + { + using var scope = app.ApplicationServices.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Database.Migrate(); + } +} diff --git a/src/SlpModularCms.Modules.Hero/HeroTexts.cs b/src/SlpModularCms.Modules.Hero/HeroTexts.cs new file mode 100644 index 0000000..4227bfa --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/HeroTexts.cs @@ -0,0 +1,76 @@ +using System.ComponentModel.DataAnnotations; +using SlpModularCms.Core.Media; +using SlpModularCms.Core.Texts; + +namespace SlpModularCms.Modules.Hero; + +/// The keys of the Hero module texts (Texts/nl.json, Texts/en.json, key path hero.*). +public static class HeroTexts +{ + public static class Validation + { + public static class Title + { + public static readonly TextKey Required = new("hero.validation.title.required"); + public static readonly TextKey TooLong = new("hero.validation.title.tooLong", "max"); + public static readonly TextKey TooManyLines = new("hero.validation.title.tooManyLines", "max"); + } + + public static readonly TextKey TaglineTooLong = new("hero.validation.tagline.tooLong", "max"); + public static readonly TextKey LeadTooLong = new("hero.validation.lead.tooLong", "max"); + public static readonly TextKey DisplayInvalid = new("hero.validation.display.invalid"); + + public static class Button + { + public static readonly TextKey Incomplete = new("hero.validation.button.incomplete"); + public static readonly TextKey LabelTooLong = new("hero.validation.button.labelTooLong", "max"); + public static readonly TextKey TargetTooLong = new("hero.validation.button.targetTooLong", "max"); + public static readonly TextKey TargetInvalid = new("hero.validation.button.targetInvalid"); + public static readonly TextKey TooMany = new("hero.validation.button.tooMany", "max"); + } + + public static readonly TextKey EndAfterStart = new("hero.validation.schedule.endAfterStart"); + + public static class Slide + { + public static readonly TextKey ImageRequired = new("hero.validation.slide.imageRequired"); + public static readonly TextKey ImageUnknown = new("hero.validation.slide.imageUnknown"); + public static readonly TextKey AltRequired = new("hero.validation.slide.altRequired"); + public static readonly TextKey AltTooLong = new("hero.validation.slide.altTooLong", "max"); + public static readonly TextKey IdUnknown = new("hero.validation.slide.idUnknown"); + } + + public static readonly TextKey FocusInvalid = new("hero.validation.focus.invalid", "maxZoom"); + } + + public static class Image + { + public static readonly TextKey InUse = new("hero.image.inUse"); + public static readonly TextKey NotFound = new("hero.image.notFound"); + public static readonly TextKey StorageFull = new("hero.image.storageFull"); + + public static readonly TextKey TooLarge = new("hero.image.rejected.tooLarge", "max"); + public static readonly TextKey UnsupportedFormat = new("hero.image.rejected.unsupportedFormat"); + public static readonly TextKey Corrupt = new("hero.image.rejected.corrupt"); + public static readonly TextKey TooManyPixels = new("hero.image.rejected.tooManyPixels"); + public static readonly TextKey Timeout = new("hero.image.rejected.timeout"); + public static readonly TextKey Busy = new("hero.image.rejected.busy"); + public static readonly TextKey Unavailable = new("hero.image.rejected.unavailable"); + + /// The text key for a rejection; the size limit is given in MB for the "too large" message. + public static TextKey For(ImageRejection reason) => reason switch + { + ImageRejection.TooLarge => TooLarge, + ImageRejection.UnsupportedFormat => UnsupportedFormat, + ImageRejection.Corrupt => Corrupt, + ImageRejection.TooManyPixels => TooManyPixels, + ImageRejection.Timeout => Timeout, + ImageRejection.Busy => Busy, + _ => Unavailable, + }; + } + + /// The catalogue of the request being validated, or the shared default one outside a request (unit tests). + public static ITextCatalog From(ValidationContext? context) + => context?.GetService(typeof(ITextCatalog)) as ITextCatalog ?? TextCatalog.Default; +} diff --git a/src/SlpModularCms.Modules.Hero/Migrations/20261116142730_InitialCreate.Designer.cs b/src/SlpModularCms.Modules.Hero/Migrations/20261116142730_InitialCreate.Designer.cs new file mode 100644 index 0000000..77269c2 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Migrations/20261116142730_InitialCreate.Designer.cs @@ -0,0 +1,256 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Hero.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Hero.Migrations +{ + [DbContext(typeof(HeroDbContext))] + [Migration("20261116142730_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Button1Label") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Button1Target") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("Button2Label") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Button2Target") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("Display") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("EndsAt") + .HasColumnType("datetime"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("Lead") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("StartsAt") + .HasColumnType("datetime"); + + b.Property("Tagline") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("Language") + .IsUnique(); + + b.ToTable("Heroes", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroImage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CreatedByUserId") + .HasColumnType("char(36)"); + + b.Property("FocusX") + .HasColumnType("double"); + + b.Property("FocusY") + .HasColumnType("double"); + + b.Property("Height") + .HasColumnType("int"); + + b.Property("OriginalKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("OriginalSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("SetHash") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("SourceFormat") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("TallFocusX") + .HasColumnType("double"); + + b.Property("TallFocusY") + .HasColumnType("double"); + + b.Property("TallZoom") + .HasColumnType("double"); + + b.Property("Variants") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("WideFocusX") + .HasColumnType("double"); + + b.Property("WideFocusY") + .HasColumnType("double"); + + b.Property("WideZoom") + .HasColumnType("double"); + + b.Property("Width") + .HasColumnType("int"); + + b.Property("Zoom") + .HasColumnType("double"); + + b.HasKey("Id"); + + b.HasIndex("OriginalSha256") + .IsUnique(); + + b.ToTable("HeroImages", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroRetiredFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("RetiredAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.ToTable("HeroRetiredFiles", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Alt") + .IsRequired() + .HasMaxLength(600) + .HasColumnType("varchar(600)"); + + b.Property("Decorative") + .HasColumnType("tinyint(1)"); + + b.Property("HeroId") + .HasColumnType("char(36)"); + + b.Property("ImageId") + .HasColumnType("char(36)"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ImageId"); + + b.HasIndex("HeroId", "SortOrder"); + + b.ToTable("HeroSlides", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b => + { + b.HasOne("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", null) + .WithMany("Slides") + .HasForeignKey("HeroId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SlpModularCms.Modules.Hero.Data.Entities.HeroImage", "Image") + .WithMany() + .HasForeignKey("ImageId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Image"); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", b => + { + b.Navigation("Slides"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Hero/Migrations/20261116142730_InitialCreate.cs b/src/SlpModularCms.Modules.Hero/Migrations/20261116142730_InitialCreate.cs new file mode 100644 index 0000000..32a1cae --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Migrations/20261116142730_InitialCreate.cs @@ -0,0 +1,158 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Hero.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterDatabase() + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "Heroes", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + Language = table.Column(type: "varchar(10)", maxLength: 10, nullable: false), + Title = table.Column(type: "varchar(1000)", maxLength: 1000, nullable: false), + Tagline = table.Column(type: "varchar(200)", maxLength: 200, nullable: true), + Lead = table.Column(type: "varchar(1000)", maxLength: 1000, nullable: true), + Display = table.Column(type: "varchar(20)", maxLength: 20, nullable: false), + Button1Label = table.Column(type: "varchar(100)", maxLength: 100, nullable: true), + Button1Target = table.Column(type: "varchar(500)", maxLength: 500, nullable: true), + Button2Label = table.Column(type: "varchar(100)", maxLength: 100, nullable: true), + Button2Target = table.Column(type: "varchar(500)", maxLength: 500, nullable: true), + StartsAt = table.Column(type: "datetime", nullable: true), + EndsAt = table.Column(type: "datetime", nullable: true), + IsActive = table.Column(type: "tinyint(1)", nullable: false), + UpdatedAt = table.Column(type: "datetime", nullable: false), + LastModifiedByUserId = table.Column(type: "char(36)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Heroes", x => x.Id); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "HeroImages", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + OriginalSha256 = table.Column(type: "varchar(64)", maxLength: 64, nullable: false), + OriginalKey = table.Column(type: "varchar(200)", maxLength: 200, nullable: false), + SourceFormat = table.Column(type: "varchar(10)", maxLength: 10, nullable: false), + Width = table.Column(type: "int", nullable: false), + Height = table.Column(type: "int", nullable: false), + Bytes = table.Column(type: "bigint", nullable: false), + FocusX = table.Column(type: "double", nullable: false), + FocusY = table.Column(type: "double", nullable: false), + Zoom = table.Column(type: "double", nullable: false), + WideFocusX = table.Column(type: "double", nullable: true), + WideFocusY = table.Column(type: "double", nullable: true), + WideZoom = table.Column(type: "double", nullable: true), + TallFocusX = table.Column(type: "double", nullable: true), + TallFocusY = table.Column(type: "double", nullable: true), + TallZoom = table.Column(type: "double", nullable: true), + SetHash = table.Column(type: "varchar(16)", maxLength: 16, nullable: false), + Variants = table.Column(type: "longtext", nullable: false), + CreatedAt = table.Column(type: "datetime", nullable: false), + CreatedByUserId = table.Column(type: "char(36)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_HeroImages", x => x.Id); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "HeroRetiredFiles", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + Kind = table.Column(type: "varchar(10)", maxLength: 10, nullable: false), + Key = table.Column(type: "varchar(200)", maxLength: 200, nullable: false), + RetiredAt = table.Column(type: "datetime", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_HeroRetiredFiles", x => x.Id); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "HeroSlides", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + HeroId = table.Column(type: "char(36)", nullable: false), + ImageId = table.Column(type: "char(36)", nullable: false), + Alt = table.Column(type: "varchar(600)", maxLength: 600, nullable: false), + Decorative = table.Column(type: "tinyint(1)", nullable: false), + SortOrder = table.Column(type: "int", nullable: false), + IsActive = table.Column(type: "tinyint(1)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_HeroSlides", x => x.Id); + table.ForeignKey( + name: "FK_HeroSlides_HeroImages_ImageId", + column: x => x.ImageId, + principalTable: "HeroImages", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_HeroSlides_Heroes_HeroId", + column: x => x.HeroId, + principalTable: "Heroes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_Heroes_Language", + table: "Heroes", + column: "Language", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_HeroImages_OriginalSha256", + table: "HeroImages", + column: "OriginalSha256", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_HeroSlides_HeroId_SortOrder", + table: "HeroSlides", + columns: new[] { "HeroId", "SortOrder" }); + + migrationBuilder.CreateIndex( + name: "IX_HeroSlides_ImageId", + table: "HeroSlides", + column: "ImageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "HeroRetiredFiles"); + + migrationBuilder.DropTable( + name: "HeroSlides"); + + migrationBuilder.DropTable( + name: "HeroImages"); + + migrationBuilder.DropTable( + name: "Heroes"); + } + } +} diff --git a/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs new file mode 100644 index 0000000..25a15de --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs @@ -0,0 +1,253 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Hero.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Hero.Migrations +{ + [DbContext(typeof(HeroDbContext))] + partial class HeroDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Button1Label") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Button1Target") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("Button2Label") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Button2Target") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("Display") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("EndsAt") + .HasColumnType("datetime"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("Lead") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("StartsAt") + .HasColumnType("datetime"); + + b.Property("Tagline") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("Language") + .IsUnique(); + + b.ToTable("Heroes", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroImage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CreatedByUserId") + .HasColumnType("char(36)"); + + b.Property("FocusX") + .HasColumnType("double"); + + b.Property("FocusY") + .HasColumnType("double"); + + b.Property("Height") + .HasColumnType("int"); + + b.Property("OriginalKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("OriginalSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("SetHash") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("SourceFormat") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("TallFocusX") + .HasColumnType("double"); + + b.Property("TallFocusY") + .HasColumnType("double"); + + b.Property("TallZoom") + .HasColumnType("double"); + + b.Property("Variants") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("WideFocusX") + .HasColumnType("double"); + + b.Property("WideFocusY") + .HasColumnType("double"); + + b.Property("WideZoom") + .HasColumnType("double"); + + b.Property("Width") + .HasColumnType("int"); + + b.Property("Zoom") + .HasColumnType("double"); + + b.HasKey("Id"); + + b.HasIndex("OriginalSha256") + .IsUnique(); + + b.ToTable("HeroImages", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroRetiredFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("RetiredAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.ToTable("HeroRetiredFiles", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Alt") + .IsRequired() + .HasMaxLength(600) + .HasColumnType("varchar(600)"); + + b.Property("Decorative") + .HasColumnType("tinyint(1)"); + + b.Property("HeroId") + .HasColumnType("char(36)"); + + b.Property("ImageId") + .HasColumnType("char(36)"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ImageId"); + + b.HasIndex("HeroId", "SortOrder"); + + b.ToTable("HeroSlides", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b => + { + b.HasOne("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", null) + .WithMany("Slides") + .HasForeignKey("HeroId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SlpModularCms.Modules.Hero.Data.Entities.HeroImage", "Image") + .WithMany() + .HasForeignKey("ImageId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Image"); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", b => + { + b.Navigation("Slides"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Hero/Models/ButtonTargetValidator.cs b/src/SlpModularCms.Modules.Hero/Models/ButtonTargetValidator.cs new file mode 100644 index 0000000..d21fd34 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Models/ButtonTargetValidator.cs @@ -0,0 +1,57 @@ +using System.Text.RegularExpressions; + +namespace SlpModularCms.Modules.Hero.Models; + +public enum ButtonTargetKind +{ + Invalid = 0, + Anchor, + Path, + Https, +} + +/// +/// The only kinds of button target the CMS accepts: a page anchor (#contact), a path of the site (/over-mij) +/// or an absolute https address. Nothing else, so a button can never carry javascript:, data:, a +/// protocol-relative address or a backslash trick. Pure. +/// +public static partial class ButtonTargetValidator +{ + [GeneratedRegex("^#[A-Za-z][A-Za-z0-9_-]{0,99}$", RegexOptions.CultureInvariant)] + private static partial Regex AnchorPattern(); + + public static ButtonTargetKind Validate(string? target) + { + if (string.IsNullOrEmpty(target) || target != target.Trim()) + { + return ButtonTargetKind.Invalid; + } + + if (target.Any(c => char.IsWhiteSpace(c) || char.IsControl(c) || c == '\\' || c == '"' || c == '<' || c == '>' || c == '`')) + { + return ButtonTargetKind.Invalid; + } + + if (target[0] == '#') + { + return AnchorPattern().IsMatch(target) ? ButtonTargetKind.Anchor : ButtonTargetKind.Invalid; + } + + if (target[0] == '/') + { + // One leading slash, not "//host"; no scheme in the first segment ("/a:b" is fine, "/:" is not a concern here). + return target.Length == 1 || target[1] != '/' ? ButtonTargetKind.Path : ButtonTargetKind.Invalid; + } + + if (Uri.TryCreate(target, UriKind.Absolute, out var uri) + && uri.Scheme == Uri.UriSchemeHttps + && !string.IsNullOrEmpty(uri.Host) + && string.IsNullOrEmpty(uri.UserInfo) + && target.StartsWith("https://", StringComparison.Ordinal)) + { + return ButtonTargetKind.Https; + } + + return ButtonTargetKind.Invalid; + } +} diff --git a/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs b/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs new file mode 100644 index 0000000..e46a893 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs @@ -0,0 +1,241 @@ +using System.ComponentModel.DataAnnotations; +using System.Text; +using System.Text.Json.Serialization; +using SlpModularCms.Core.Media; +using SlpModularCms.Modules.Hero.Data.Entities; + +namespace SlpModularCms.Modules.Hero.Models; + +public record FocusDto(double X, double Y, double Zoom) +{ + public FocusSetting ToSetting() => new(X, Y, Zoom); + + public static FocusDto From(FocusSetting focus) => new(focus.X, focus.Y, focus.Zoom); +} + +public record HeroVariantDto(string Ratio, int Width, int Height, string Type, string Url); + +public record HeroImageDto( + string Id, + int Width, + int Height, + FocusDto Focus, + FocusDto? WideFocus, + FocusDto? TallFocus, + string Src, + IReadOnlyList Variants); + +public record HeroButtonDto(string Label, string Target); + +public record HeroSlideAdminDto(string Id, string ImageId, string Alt, bool Decorative, bool IsActive, int SortOrder, HeroImageDto Image); + +/// What the admin edits. When no hero exists yet is null and the fields hold the defaults. +public record HeroAdminDto( + string? Id, + string Title, + string? Tagline, + string? Lead, + string Display, + IReadOnlyList Buttons, + bool IsActive, + DateTimeOffset? StartsAt, + DateTimeOffset? EndsAt, + IReadOnlyList Slides, + bool IsLive, + DateTimeOffset? UpdatedAt, + int MaxPublishedSlides); + +/// The image of a published slide. is the largest WebP of the wide ratio. +public record PublicImageDto( + int Width, + int Height, + FocusDto Focus, + string Src, + IReadOnlyList Variants, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyDictionary? FocusByRatio = null); + +public record PublicSlideDto(string Id, string Alt, bool Decorative, PublicImageDto Image); + +/// What visitors and websites get: only content, never the schedule or on/off switches. The same shape is written into #cms-data. +public record PublicHeroDto( + string Display, + string Title, + string? Tagline, + string? Lead, + IReadOnlyList Buttons, + IReadOnlyList Slides); + +// ----- requests ---------------------------------------------------------------------------------------------------- + +public record HeroButtonRequest(string? Label, string? Target); + +public record HeroSlideRequest(Guid? Id, Guid ImageId, string? Alt, bool Decorative = false, bool IsActive = true); + +public record HeroFocusRequest(FocusDto Focus, FocusDto? Wide = null, FocusDto? Tall = null) : IValidatableObject +{ + public IEnumerable Validate(ValidationContext validationContext) + { + var texts = HeroTexts.From(validationContext); + foreach (var (name, value) in new[] { (nameof(Focus), Focus), (nameof(Wide), Wide), (nameof(Tall), Tall) }) + { + if (value is not null && !value.ToSetting().IsValid) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.FocusInvalid, args: ("maxZoom", FocusSetting.MaxZoom)), [name]); + } + } + + if (Focus is null) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.FocusInvalid, args: ("maxZoom", FocusSetting.MaxZoom)), [nameof(Focus)]); + } + } +} + +/// The whole hero in one go (full replace). Nothing here is trusted: is the one place that checks it. +public record HeroSaveRequest( + string? Title, + string? Tagline, + string? Lead, + string? Display, + IReadOnlyList? Buttons, + bool IsActive, + DateTimeOffset? StartsAt, + DateTimeOffset? EndsAt, + IReadOnlyList? Slides) : IValidatableObject +{ + public const int TitleMax = 200; + public const int TitleMaxLines = 5; + public const int TaglineMax = 120; + public const int LeadMax = 600; + public const int ButtonLabelMax = 50; + public const int ButtonTargetMax = 500; + public const int ButtonsMax = 2; + public const int AltMax = 300; + + public IEnumerable Validate(ValidationContext validationContext) + { + var texts = HeroTexts.From(validationContext); + + var title = HeroText.Clean(Title, keepLineBreaks: true); + if (title.Length == 0) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Title.Required), [nameof(Title)]); + } + else + { + if (title.Length > TitleMax) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Title.TooLong, args: ("max", TitleMax)), [nameof(Title)]); + } + + if (title.Count(c => c == '\n') + 1 > TitleMaxLines) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Title.TooManyLines, args: ("max", TitleMaxLines)), [nameof(Title)]); + } + } + + if (HeroText.Clean(Tagline, keepLineBreaks: false).Length > TaglineMax) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.TaglineTooLong, args: ("max", TaglineMax)), [nameof(Tagline)]); + } + + if (HeroText.Clean(Lead, keepLineBreaks: true).Length > LeadMax) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.LeadTooLong, args: ("max", LeadMax)), [nameof(Lead)]); + } + + if (!HeroDisplays.IsValid(Display ?? HeroDisplays.Single)) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.DisplayInvalid), [nameof(Display)]); + } + + var buttons = Buttons ?? []; + if (buttons.Count > ButtonsMax) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.TooMany, args: ("max", ButtonsMax)), [nameof(Buttons)]); + } + + for (var i = 0; i < buttons.Count; i++) + { + var label = HeroText.Clean(buttons[i].Label, keepLineBreaks: false); + var target = (buttons[i].Target ?? string.Empty).Trim(); + if (label.Length == 0 && target.Length == 0) + { + continue; + } + + if (label.Length == 0 || target.Length == 0) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.Incomplete), [$"{nameof(Buttons)}[{i}]"]); + continue; + } + + if (label.Length > ButtonLabelMax) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.LabelTooLong, args: ("max", ButtonLabelMax)), [$"{nameof(Buttons)}[{i}].Label"]); + } + + if (target.Length > ButtonTargetMax) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.TargetTooLong, args: ("max", ButtonTargetMax)), [$"{nameof(Buttons)}[{i}].Target"]); + } + else if (ButtonTargetValidator.Validate(target) == ButtonTargetKind.Invalid) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.TargetInvalid), [$"{nameof(Buttons)}[{i}].Target"]); + } + } + + if (StartsAt is not null && EndsAt is not null && EndsAt <= StartsAt) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.EndAfterStart), [nameof(EndsAt)]); + } + + var slides = Slides ?? []; + for (var i = 0; i < slides.Count; i++) + { + var slide = slides[i]; + if (slide.ImageId == Guid.Empty) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Slide.ImageRequired), [$"{nameof(Slides)}[{i}].ImageId"]); + } + + var alt = HeroText.Clean(slide.Alt, keepLineBreaks: false); + if (!slide.Decorative && alt.Length == 0) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Slide.AltRequired), [$"{nameof(Slides)}[{i}].Alt"]); + } + else if (alt.Length > AltMax) + { + yield return new ValidationResult(texts.Get(HeroTexts.Validation.Slide.AltTooLong, args: ("max", AltMax)), [$"{nameof(Slides)}[{i}].Alt"]); + } + } + } +} + +/// Plain text handling: stored as typed, minus control characters; encoding happens where the text is written. +public static class HeroText +{ + public static string Clean(string? value, bool keepLineBreaks) + { + if (string.IsNullOrEmpty(value)) + { + return string.Empty; + } + + var text = value.Replace("\r\n", "\n").Replace('\r', '\n'); + var builder = new StringBuilder(text.Length); + foreach (var c in text) + { + if (c == '\n') + { + builder.Append(keepLineBreaks ? '\n' : ' '); + } + else if (!char.IsControl(c) && c != '\u2028' && c != '\u2029') + { + builder.Append(c); + } + } + + return builder.ToString().Trim(); + } +} diff --git a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs new file mode 100644 index 0000000..cb52681 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs @@ -0,0 +1,94 @@ +using Microsoft.EntityFrameworkCore; +using SlpModularCms.Modules.Hero.Data; +using SlpModularCms.Modules.Hero.Data.Entities; + +namespace SlpModularCms.Modules.Hero.Repositories; + +public interface IHeroRepository +{ + /// The hero of a language with its slides (and their images), tracked for update. + Task GetAsync(string language, CancellationToken cancellationToken); + + /// The same, not tracked (read paths). + Task GetReadOnlyAsync(string language, CancellationToken cancellationToken); + + void Add(HeroContent hero); + void AddSlide(HeroSlide slide); + void RemoveSlide(HeroSlide slide); + + Task GetImageAsync(Guid id, CancellationToken cancellationToken); + Task> GetImagesAsync(IReadOnlyCollection ids, CancellationToken cancellationToken); + Task GetImageBySha256Async(string sha256, CancellationToken cancellationToken); + void AddImage(HeroImage image); + void RemoveImage(HeroImage image); + Task ImageInUseAsync(Guid imageId, CancellationToken cancellationToken); + + Task> GetUnattachedImagesCreatedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken); + Task> GetReferencedSetHashesAsync(CancellationToken cancellationToken); + Task> GetReferencedOriginalKeysAsync(CancellationToken cancellationToken); + + void AddRetired(HeroRetiredFile file); + void RemoveRetired(HeroRetiredFile file); + Task> GetRetiredBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken); + Task> GetRetiredSetHashesAsync(CancellationToken cancellationToken); + + Task SaveChangesAsync(CancellationToken cancellationToken); +} + +public class HeroRepository(HeroDbContext context) : IHeroRepository +{ + public Task GetAsync(string language, CancellationToken cancellationToken) + => context.Heroes.Include(h => h.Slides).ThenInclude(s => s.Image) + .FirstOrDefaultAsync(h => h.Language == language, cancellationToken); + + public Task GetReadOnlyAsync(string language, CancellationToken cancellationToken) + => context.Heroes.AsNoTracking().Include(h => h.Slides).ThenInclude(s => s.Image) + .FirstOrDefaultAsync(h => h.Language == language, cancellationToken); + + public void Add(HeroContent hero) => context.Heroes.Add(hero); + + public void AddSlide(HeroSlide slide) => context.HeroSlides.Add(slide); + + public void RemoveSlide(HeroSlide slide) => context.HeroSlides.Remove(slide); + + public Task GetImageAsync(Guid id, CancellationToken cancellationToken) + => context.HeroImages.FirstOrDefaultAsync(i => i.Id == id, cancellationToken); + + public async Task> GetImagesAsync(IReadOnlyCollection ids, CancellationToken cancellationToken) + => await context.HeroImages.Where(i => ids.Contains(i.Id)).ToListAsync(cancellationToken); + + public Task GetImageBySha256Async(string sha256, CancellationToken cancellationToken) + => context.HeroImages.FirstOrDefaultAsync(i => i.OriginalSha256 == sha256, cancellationToken); + + public void AddImage(HeroImage image) => context.HeroImages.Add(image); + + public void RemoveImage(HeroImage image) => context.HeroImages.Remove(image); + + public Task ImageInUseAsync(Guid imageId, CancellationToken cancellationToken) + => context.HeroSlides.AnyAsync(s => s.ImageId == imageId, cancellationToken); + + public async Task> GetUnattachedImagesCreatedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken) + { + var used = context.HeroSlides.Select(s => s.ImageId); + var candidates = await context.HeroImages.Where(i => !used.Contains(i.Id)).ToListAsync(cancellationToken); + return candidates.Where(i => i.CreatedAt < cutoff).ToList(); + } + + public async Task> GetReferencedSetHashesAsync(CancellationToken cancellationToken) + => (await context.HeroImages.Select(i => i.SetHash).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal); + + public async Task> GetReferencedOriginalKeysAsync(CancellationToken cancellationToken) + => (await context.HeroImages.Select(i => i.OriginalKey).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal); + + public void AddRetired(HeroRetiredFile file) => context.HeroRetiredFiles.Add(file); + + public void RemoveRetired(HeroRetiredFile file) => context.HeroRetiredFiles.Remove(file); + + public async Task> GetRetiredBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken) + => (await context.HeroRetiredFiles.ToListAsync(cancellationToken)).Where(f => f.RetiredAt < cutoff).ToList(); + + public async Task> GetRetiredSetHashesAsync(CancellationToken cancellationToken) + => (await context.HeroRetiredFiles.Where(f => f.Kind == "set").Select(f => f.Key).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal); + + public Task SaveChangesAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken); +} diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs new file mode 100644 index 0000000..29c2265 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs @@ -0,0 +1,198 @@ +using System.Security.Cryptography; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Core.Media; +using SlpModularCms.Modules.Hero.Data.Entities; +using SlpModularCms.Modules.Hero.Models; +using SlpModularCms.Modules.Hero.Repositories; + +namespace SlpModularCms.Modules.Hero.Services; + +/// The image is still used by a slide (the administrator gets a 409 and a message). +public sealed class HeroImageInUseException() : Exception("The image is still used by a slide."); + +public sealed class HeroImageNotFoundException() : Exception("The image does not exist."); + +/// There is not enough room in the media directory for the image. +public sealed class MediaStorageFullException() : Exception("The media directory is full."); + +public interface IHeroImageService +{ + /// Admits, stores and processes an uploaded image (all variants of the default focus). The same photo twice is one image. + /// The upload is refused; see the code. + Task UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken); + + /// Changes where the subject is (general and optionally per ratio) and cuts the variants again around it. + Task SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken); + + /// Removes an image nothing uses; its files go after the retention time. + Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); +} + +public class HeroImageService( + IMediaUploadGuard guard, + IImageProcessor processor, + IMediaStore store, + MediaProcessingGate gate, + IHeroRepository repository, + IOptions mediaOptions, + ILogger logger, + TimeProvider? time = null, + IIndexHtmlCache? indexCache = null) : IHeroImageService +{ + private readonly TimeProvider _time = time ?? TimeProvider.System; + + public async Task UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken) + { + using var admitted = await guard.AdmitAsync(upload, declaredLength, cancellationToken); + var sha = Convert.ToHexStringLower(SHA256.HashData(admitted.Bytes)); + + var existing = await repository.GetImageBySha256Async(sha, cancellationToken); + if (existing is not null) + { + return HeroMapping.ToImageDto(existing); + } + + await EnsureRoomAsync(admitted.Bytes.Length, cancellationToken); + + // The original is kept without metadata (GPS and the like); formats that cannot be written back (HEIC) become JPEG. + var format = admitted.Info.Format; + var stripped = await processor.StripMetadataAsync(admitted.Bytes, format, cancellationToken); + var original = stripped ?? admitted.Bytes; + var storedFormat = stripped is not null && format == ImageFormat.Heic ? ImageFormat.Jpeg : format; + + var image = new HeroImage + { + Id = Guid.NewGuid(), + OriginalSha256 = sha, + OriginalKey = $"originals/{sha}.{storedFormat.Extension()}", + SourceFormat = storedFormat.Extension(), + Width = admitted.Info.Width, + Height = admitted.Info.Height, + Bytes = original.Length, + CreatedAt = _time.GetUtcNow(), + CreatedByUserId = callerId, + }; + + var files = await RenderSetAsync(image, original, storedFormat, cancellationToken); + + await store.PutAsync(image.OriginalKey, original, cancellationToken); + await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken); + repository.AddImage(image); + await repository.SaveChangesAsync(cancellationToken); + + logger.LogInformation("Hero image {ImageId} uploaded by user {UserId} ({Width}x{Height}, {Variants} variants)", image.Id, callerId, image.Width, image.Height, image.Variants.Count); + return HeroMapping.ToImageDto(image); + } + + public async Task SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken) + { + var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException(); + + var oldSet = image.SetHash; + var general = request.Focus.ToSetting().Normalize(); + image.FocusX = general.X; + image.FocusY = general.Y; + image.Zoom = general.Zoom; + Apply(request.Wide, v => (image.WideFocusX, image.WideFocusY, image.WideZoom) = v); + Apply(request.Tall, v => (image.TallFocusX, image.TallFocusY, image.TallZoom) = v); + + var newSet = SetHashOf(image); + if (newSet != oldSet) + { + using var slot = await gate.EnterAsync(cancellationToken); + + var file = await store.OpenReadAsync(image.OriginalKey, cancellationToken) + ?? throw new ImageRejectedException(ImageRejection.Unavailable, "The stored original is missing."); + using var memory = new MemoryStream(); + await using (file.Content) + { + await file.Content.CopyToAsync(memory, cancellationToken); + } + + var storedFormat = ImageFormatExtensions.FromExtension(Path.GetExtension(image.OriginalKey).TrimStart('.')); + + var files = await RenderSetAsync(image, memory.ToArray(), storedFormat, cancellationToken); + await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken); + repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() }); + } + + await repository.SaveChangesAsync(cancellationToken); + indexCache?.Invalidate(); + logger.LogInformation("Hero image {ImageId} focus changed by user {UserId}", imageId, callerId); + return HeroMapping.ToImageDto(image); + } + + public async Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken) + { + var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException(); + if (await repository.ImageInUseAsync(imageId, cancellationToken)) + { + throw new HeroImageInUseException(); + } + + var now = _time.GetUtcNow(); + repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = image.SetHash, RetiredAt = now }); + repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = now }); + repository.RemoveImage(image); + await repository.SaveChangesAsync(cancellationToken); + + logger.LogInformation("Hero image {ImageId} removed by user {UserId}", imageId, callerId); + } + + private static void Apply(FocusDto? value, Action<(double?, double?, double?)> assign) + { + if (value is null) + { + assign((null, null, null)); + return; + } + + var f = value.ToSetting().Normalize(); + assign((f.X, f.Y, f.Zoom)); + } + + private static string SetHashOf(HeroImage image) + => MediaPaths.SetHash(image.OriginalSha256, [("wide", image.FocusFor("wide")), ("tall", image.FocusFor("tall"))]); + + /// Cuts and encodes every planned variant of the image and fills its set hash and variant list. Returns the files by name. + private async Task> RenderSetAsync(HeroImage image, byte[] original, ImageFormat storedFormat, CancellationToken cancellationToken) + { + var ratios = new[] { Ratio.Wide, Ratio.Tall } + .Select(r => new RatioPlan(r, image.FocusFor(r.Name), VariantPlanner.DefaultWidths(r))) + .ToList(); + var specs = VariantPlanner.Plan(image.Width, image.Height, ratios, processor.SupportedOutput); + + var files = new Dictionary(); + var variants = new List(); + foreach (var spec in specs) + { + var rendered = await processor.RenderAsync(original, storedFormat, spec, cancellationToken); + var name = MediaPaths.FileName(spec.Ratio.Name, spec.Width, spec.Format); + files[name] = rendered.Bytes; + variants.Add(new HeroVariant(spec.Ratio.Name, rendered.Width, rendered.Height, spec.Format.MimeType(), name, rendered.Bytes.LongLength)); + } + + image.SetHash = SetHashOf(image); + image.Variants = variants; + return files; + } + + private async Task EnsureRoomAsync(long incomingBytes, CancellationToken cancellationToken) + { + var limits = mediaOptions.Value; + // A set is a few times the size of the original at most; keep a margin so the write cannot fill the disk. + var needed = incomingBytes * 4; + var total = await store.GetTotalBytesAsync(cancellationToken); + if (limits.MaxTotalBytes > 0 && total + needed > limits.MaxTotalBytes) + { + throw new MediaStorageFullException(); + } + + if (store.GetFreeBytes() is { } free && free < needed + 64L * 1024 * 1024) + { + throw new MediaStorageFullException(); + } + } +} diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs new file mode 100644 index 0000000..8bd04cd --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs @@ -0,0 +1,137 @@ +using SlpModularCms.Core.Media; +using SlpModularCms.Modules.Hero.Data.Entities; +using SlpModularCms.Modules.Hero.Models; + +namespace SlpModularCms.Modules.Hero.Services; + +public sealed class HeroOptions +{ + public const string SectionName = "Hero"; + + /// + /// A technical safety ceiling, not an administrator limit: the public hero, the injected page and the data block never + /// carry more slides than this, so the first HTML cannot grow without bound. Everything above stays saved. + /// + public int MaxPublishedSlides { get; set; } = 50; +} + +/// Turns stored entities into the shapes of the API and the data block. Pure. +public static class HeroMapping +{ + public const string Area = "hero"; + + public static HeroVariantDto ToDto(HeroImage image, HeroVariant variant) + => new(variant.Ratio, variant.Width, variant.Height, variant.Type, MediaPaths.Url(Area, image.SetHash, variant.FileName)); + + /// The address the plain img uses: the largest WebP of the wide ratio, else the largest WebP, else the first variant. + public static string SrcFor(HeroImage image) + { + var webp = image.Variants.Where(v => v.Type == ImageFormat.WebP.MimeType()).ToList(); + var pick = webp.Where(v => v.Ratio == "wide").OrderByDescending(v => v.Width).FirstOrDefault() + ?? webp.OrderByDescending(v => v.Width).FirstOrDefault() + ?? image.Variants.FirstOrDefault(); + return pick is null ? string.Empty : MediaPaths.Url(Area, image.SetHash, pick.FileName); + } + + public static HeroImageDto ToImageDto(HeroImage image) + => new( + image.Id.ToString(), + image.Width, + image.Height, + FocusDto.From(image.General), + image.WideFocusX is null ? null : FocusDto.From(image.FocusFor("wide")), + image.TallFocusX is null ? null : FocusDto.From(image.FocusFor("tall")), + SrcFor(image), + image.Variants.Select(v => ToDto(image, v)).ToList()); + + public static bool IsLive(HeroContent hero, DateTimeOffset now) + => hero.IsActive + && !string.IsNullOrWhiteSpace(hero.Title) + && (hero.StartsAt is null || hero.StartsAt <= now) + && (hero.EndsAt is null || now < hero.EndsAt); + + private static List Buttons(HeroContent hero) + { + var buttons = new List(); + if (!string.IsNullOrWhiteSpace(hero.Button1Label) && !string.IsNullOrWhiteSpace(hero.Button1Target)) + { + buttons.Add(new HeroButtonDto(hero.Button1Label, hero.Button1Target)); + } + + if (!string.IsNullOrWhiteSpace(hero.Button2Label) && !string.IsNullOrWhiteSpace(hero.Button2Target)) + { + buttons.Add(new HeroButtonDto(hero.Button2Label, hero.Button2Target)); + } + + return buttons; + } + + /// The published hero, or null when it is not live. Inactive slides and slides without a stored image are left out. + public static PublicHeroDto? ToPublic(HeroContent hero, DateTimeOffset now, int maxPublishedSlides) + { + if (!IsLive(hero, now)) + { + return null; + } + + var slides = hero.Slides + .Where(s => s.IsActive && s.Image is { Variants.Count: > 0 } && (s.Decorative || !string.IsNullOrWhiteSpace(s.Alt))) + .OrderBy(s => s.SortOrder) + .Take(Math.Max(1, maxPublishedSlides)) + .Select(s => new PublicSlideDto(s.Id.ToString(), s.Decorative ? string.Empty : s.Alt, s.Decorative, ToPublicImage(s.Image!))) + .ToList(); + + return new PublicHeroDto(hero.Display, hero.Title, hero.Tagline, hero.Lead, Buttons(hero), slides); + } + + private static PublicImageDto ToPublicImage(HeroImage image) + { + Dictionary? byRatio = null; + if (image.WideFocusX is not null) + { + (byRatio ??= new Dictionary())["wide"] = FocusDto.From(image.FocusFor("wide")); + } + + if (image.TallFocusX is not null) + { + (byRatio ??= new Dictionary())["tall"] = FocusDto.From(image.FocusFor("tall")); + } + + return new PublicImageDto( + image.Width, + image.Height, + FocusDto.From(image.General), + SrcFor(image), + image.Variants.Select(v => ToDto(image, v)).ToList(), + byRatio); + } + + public static HeroAdminDto ToAdmin(HeroContent? hero, DateTimeOffset now, int maxPublishedSlides) + { + if (hero is null) + { + return new HeroAdminDto(null, string.Empty, null, null, HeroDisplays.Single, [], true, null, null, [], false, null, maxPublishedSlides); + } + + var slides = hero.Slides + .Where(s => s.Image is not null) + .OrderBy(s => s.SortOrder) + .Select(s => new HeroSlideAdminDto(s.Id.ToString(), s.ImageId.ToString(), s.Alt, s.Decorative, s.IsActive, s.SortOrder, ToImageDto(s.Image!))) + .ToList(); + + return new HeroAdminDto( + hero.Id.ToString(), + hero.Title, + hero.Tagline, + hero.Lead, + hero.Display, + Buttons(hero), + hero.IsActive, + hero.StartsAt, + hero.EndsAt, + slides, + IsLive(hero, now), + hero.UpdatedAt, + maxPublishedSlides); + } +} diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs new file mode 100644 index 0000000..943c0f1 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs @@ -0,0 +1,111 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Media; +using SlpModularCms.Modules.Hero.Data.Entities; +using SlpModularCms.Modules.Hero.Repositories; + +namespace SlpModularCms.Modules.Hero.Services; + +/// +/// Removes files nothing uses any more, a retention time (7 days) after they stopped being used, so a site that still +/// holds older data keeps working for a while. Idempotent and safe to interrupt; a referenced file is never removed +/// (a retired set whose hash is used again, because the same photo and focus came back, is simply forgotten as retired). +/// +public class HeroMediaCleanup( + IHeroRepository repository, + IMediaStore store, + IOptions options, + ILogger logger, + TimeProvider? time = null) +{ + private readonly TimeProvider _time = time ?? TimeProvider.System; + + public async Task RunOnceAsync(CancellationToken cancellationToken) + { + var now = _time.GetUtcNow(); + var cutoff = now.AddDays(-Math.Max(0, options.Value.RetentionDays)); + var removed = 0; + + // 1. Images that were uploaded but never used by a slide: retire them (their files go on a later run). + foreach (var image in await repository.GetUnattachedImagesCreatedBeforeAsync(cutoff, cancellationToken)) + { + repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = image.SetHash, RetiredAt = cutoff.AddSeconds(-1) }); + repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = cutoff.AddSeconds(-1) }); + repository.RemoveImage(image); + } + + await repository.SaveChangesAsync(cancellationToken); + + // 2. Retired files whose retention has passed, unless an image uses them again. + var referencedSets = await repository.GetReferencedSetHashesAsync(cancellationToken); + var referencedOriginals = await repository.GetReferencedOriginalKeysAsync(cancellationToken); + foreach (var file in await repository.GetRetiredBeforeAsync(cutoff, cancellationToken)) + { + if (file.Kind == "set" && !referencedSets.Contains(file.Key)) + { + await store.DeleteSetAsync(HeroMapping.Area, file.Key, cancellationToken); + removed++; + } + else if (file.Kind == "original" && !referencedOriginals.Contains(file.Key)) + { + await store.DeleteAsync(file.Key, cancellationToken); + removed++; + } + + repository.RemoveRetired(file); + } + + await repository.SaveChangesAsync(cancellationToken); + + // 3. Sets in the store that no row knows (a crash between writing the files and saving the row). + var retiredSets = await repository.GetRetiredSetHashesAsync(cancellationToken); + referencedSets = await repository.GetReferencedSetHashesAsync(cancellationToken); + foreach (var set in await store.ListSetsAsync(HeroMapping.Area, cancellationToken)) + { + if (set.CreatedUtc < cutoff && !referencedSets.Contains(set.SetHash) && !retiredSets.Contains(set.SetHash)) + { + await store.DeleteSetAsync(HeroMapping.Area, set.SetHash, cancellationToken); + removed++; + } + } + + if (removed > 0) + { + logger.LogInformation("Hero media clean-up removed {Removed} unused sets or originals.", removed); + } + + return removed; + } +} + +/// Runs shortly after start-up and then once a day. +public sealed class HeroMediaCleanupService(IServiceScopeFactory scopes, ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + await Task.Delay(TimeSpan.FromMinutes(2), stoppingToken); + while (!stoppingToken.IsCancellationRequested) + { + try + { + using var scope = scopes.CreateScope(); + await scope.ServiceProvider.GetRequiredService().RunOnceAsync(stoppingToken); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError(exception, "The hero media clean-up failed; it is tried again tomorrow."); + } + + await Task.Delay(TimeSpan.FromHours(24), stoppingToken); + } + } + catch (OperationCanceledException) + { + // Shutting down. + } + } +} diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroService.cs new file mode 100644 index 0000000..2c7400c --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Services/HeroService.cs @@ -0,0 +1,158 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Core.Texts; +using SlpModularCms.Modules.Hero.Data.Entities; +using SlpModularCms.Modules.Hero.Models; +using SlpModularCms.Modules.Hero.Repositories; + +namespace SlpModularCms.Modules.Hero.Services; + +/// A save that refers to something that is not there (an image or a slide of another hero). The message is for the administrator. +public sealed class HeroSaveRejectedException(string field, string message) : Exception(message) +{ + public string Field { get; } = field; +} + +public interface IHeroService +{ + /// The hero for the admin (empty defaults when none exists yet), with whether it is live right now. + Task GetAsync(CancellationToken cancellationToken); + + /// Replaces the whole hero: texts, buttons, display, schedule and the ordered slide list. + Task SaveAsync(HeroSaveRequest request, Guid callerId, CancellationToken cancellationToken); +} + +public class HeroService( + IHeroRepository repository, + IOptions options, + ILogger logger, + TimeProvider? time = null, + IIndexHtmlCache? indexCache = null, + ITextCatalog? texts = null) : IHeroService +{ + private readonly TimeProvider _time = time ?? TimeProvider.System; + private readonly ITextCatalog _texts = texts ?? TextCatalog.Default; + + public async Task GetAsync(CancellationToken cancellationToken) + => HeroMapping.ToAdmin(await repository.GetReadOnlyAsync(HeroLanguages.Default, cancellationToken), _time.GetUtcNow(), options.Value.MaxPublishedSlides); + + public async Task SaveAsync(HeroSaveRequest request, Guid callerId, CancellationToken cancellationToken) + { + var now = _time.GetUtcNow(); + var slideRequests = request.Slides ?? []; + + var imageIds = slideRequests.Select(s => s.ImageId).Distinct().ToList(); + var images = (await repository.GetImagesAsync(imageIds, cancellationToken)).ToDictionary(i => i.Id); + for (var i = 0; i < slideRequests.Count; i++) + { + if (!images.ContainsKey(slideRequests[i].ImageId)) + { + throw new HeroSaveRejectedException($"Slides[{i}].ImageId", _texts.Get(HeroTexts.Validation.Slide.ImageUnknown)); + } + } + + var hero = await repository.GetAsync(HeroLanguages.Default, cancellationToken); + var created = hero is null; + if (hero is null) + { + hero = new HeroContent { Id = Guid.NewGuid(), Language = HeroLanguages.Default }; + repository.Add(hero); + } + + var existing = hero.Slides.ToDictionary(s => s.Id); + for (var i = 0; i < slideRequests.Count; i++) + { + if (slideRequests[i].Id is { } id && !existing.ContainsKey(id)) + { + throw new HeroSaveRejectedException($"Slides[{i}].Id", _texts.Get(HeroTexts.Validation.Slide.IdUnknown)); + } + } + + Apply(hero, request, now, callerId); + + var keep = new HashSet(); + for (var i = 0; i < slideRequests.Count; i++) + { + var r = slideRequests[i]; + HeroSlide slide; + if (r.Id is { } id) + { + slide = existing[id]; + } + else + { + slide = new HeroSlide { Id = Guid.NewGuid(), HeroId = hero.Id }; + hero.Slides.Add(slide); + repository.AddSlide(slide); + } + + keep.Add(slide.Id); + slide.ImageId = r.ImageId; + slide.Image = images[r.ImageId]; + slide.Decorative = r.Decorative; + slide.Alt = r.Decorative ? string.Empty : HeroText.Clean(r.Alt, keepLineBreaks: false); + slide.IsActive = r.IsActive; + slide.SortOrder = i; + } + + foreach (var removed in hero.Slides.Where(s => !keep.Contains(s.Id)).ToList()) + { + hero.Slides.Remove(removed); + if (!created) + { + repository.RemoveSlide(removed); + } + } + + await repository.SaveChangesAsync(cancellationToken); + + indexCache?.Invalidate(); + logger.LogInformation("Hero {HeroId} {Action} by user {LastModifiedByUserId} ({Slides} slides)", hero.Id, created ? "Created" : "Updated", callerId, keep.Count); + + return HeroMapping.ToAdmin(hero, now, options.Value.MaxPublishedSlides); + } + + private static void Apply(HeroContent hero, HeroSaveRequest r, DateTimeOffset now, Guid callerId) + { + hero.Title = HeroText.Clean(r.Title, keepLineBreaks: true); + hero.Tagline = NullIfEmpty(HeroText.Clean(r.Tagline, keepLineBreaks: false)); + hero.Lead = NullIfEmpty(HeroText.Clean(r.Lead, keepLineBreaks: true)); + hero.Display = r.Display ?? HeroDisplays.Single; + + var buttons = (r.Buttons ?? []) + .Select(b => (Label: HeroText.Clean(b.Label, keepLineBreaks: false), Target: (b.Target ?? string.Empty).Trim())) + .Where(b => b.Label.Length > 0 && b.Target.Length > 0) + .Take(HeroSaveRequest.ButtonsMax) + .ToList(); + hero.Button1Label = buttons.Count > 0 ? buttons[0].Label : null; + hero.Button1Target = buttons.Count > 0 ? buttons[0].Target : null; + hero.Button2Label = buttons.Count > 1 ? buttons[1].Label : null; + hero.Button2Target = buttons.Count > 1 ? buttons[1].Target : null; + + hero.IsActive = r.IsActive; + hero.StartsAt = r.StartsAt; + hero.EndsAt = r.EndsAt; + hero.UpdatedAt = now; + hero.LastModifiedByUserId = callerId; + } + + private static string? NullIfEmpty(string value) => value.Length == 0 ? null : value; +} + +public interface IPublicHeroService +{ + /// The hero as websites get it, or null (no hero, switched off, outside the schedule or without a title). + Task GetActiveAsync(CancellationToken cancellationToken); +} + +public class PublicHeroService(IHeroRepository repository, IOptions options, TimeProvider? time = null) : IPublicHeroService +{ + private readonly TimeProvider _time = time ?? TimeProvider.System; + + public async Task GetActiveAsync(CancellationToken cancellationToken) + { + var hero = await repository.GetReadOnlyAsync(HeroLanguages.Default, cancellationToken); + return hero is null ? null : HeroMapping.ToPublic(hero, _time.GetUtcNow(), options.Value.MaxPublishedSlides); + } +} diff --git a/src/SlpModularCms.Modules.Hero/SlpModularCms.Modules.Hero.csproj b/src/SlpModularCms.Modules.Hero/SlpModularCms.Modules.Hero.csproj new file mode 100644 index 0000000..756fb89 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/SlpModularCms.Modules.Hero.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + enable + enable + + + + + <_Parameter1>SlpModularCms.Modules.Hero.Tests + + + + + + + + + + + + + diff --git a/src/SlpModularCms.Modules.Hero/Texts/en.json b/src/SlpModularCms.Modules.Hero/Texts/en.json new file mode 100644 index 0000000..23bcea0 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Texts/en.json @@ -0,0 +1,54 @@ +{ + "hero": { + "validation": { + "title": { + "required": "A title is required.", + "tooLong": "The title can have at most {max} characters.", + "tooManyLines": "The title can have at most {max} lines." + }, + "tagline": { + "tooLong": "The tagline can have at most {max} characters." + }, + "lead": { + "tooLong": "The introduction can have at most {max} characters." + }, + "display": { + "invalid": "The display must be 'single' or 'slideshow'." + }, + "button": { + "incomplete": "A button needs both a label and a target.", + "labelTooLong": "The button label can have at most {max} characters.", + "targetTooLong": "The button target can have at most {max} characters.", + "targetInvalid": "Choose an #anchor, a /path or an https:// address.", + "tooMany": "At most {max} buttons are possible." + }, + "schedule": { + "endAfterStart": "The end must be after the start." + }, + "slide": { + "imageRequired": "Every slide needs an image.", + "imageUnknown": "An image of a slide does not exist (any more).", + "altRequired": "Give a description (alt text) or mark the image as decorative.", + "altTooLong": "The alt text can have at most {max} characters.", + "idUnknown": "A slide does not belong to this hero." + }, + "focus": { + "invalid": "The focus point must be between 0 and 1 and the zoom between 1 and {maxZoom}." + } + }, + "image": { + "inUse": "This image is still used by a slide.", + "notFound": "This image does not exist.", + "rejected": { + "tooLarge": "The image is too large (at most {max} MB).", + "unsupportedFormat": "This file type is not supported. Choose a JPEG, PNG, WebP or another common image file.", + "corrupt": "The image could not be read or is damaged.", + "tooManyPixels": "The image has too many pixels. Choose a smaller image.", + "timeout": "Processing the image took too long. Try a smaller image.", + "busy": "Other images are being processed. Try again in a moment.", + "unavailable": "Uploading images is not available at the moment." + }, + "storageFull": "There is not enough storage space for this image." + } + } +} diff --git a/src/SlpModularCms.Modules.Hero/Texts/nl.json b/src/SlpModularCms.Modules.Hero/Texts/nl.json new file mode 100644 index 0000000..ebea26c --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Texts/nl.json @@ -0,0 +1,54 @@ +{ + "hero": { + "validation": { + "title": { + "required": "Een titel is verplicht.", + "tooLong": "De titel mag maximaal {max} tekens bevatten.", + "tooManyLines": "De titel mag maximaal {max} regels hebben." + }, + "tagline": { + "tooLong": "De tagline mag maximaal {max} tekens bevatten." + }, + "lead": { + "tooLong": "De introductietekst mag maximaal {max} tekens bevatten." + }, + "display": { + "invalid": "De weergave moet 'enkel' of 'diavoorstelling' zijn." + }, + "button": { + "incomplete": "Een knop heeft zowel een tekst als een doel nodig.", + "labelTooLong": "De knoptekst mag maximaal {max} tekens bevatten.", + "targetTooLong": "Het doel van een knop mag maximaal {max} tekens bevatten.", + "targetInvalid": "Kies een #anker, een /pad of een https://-adres.", + "tooMany": "Er zijn maximaal {max} knoppen mogelijk." + }, + "schedule": { + "endAfterStart": "Het einde moet na het begin liggen." + }, + "slide": { + "imageRequired": "Elke slide heeft een afbeelding nodig.", + "imageUnknown": "Een afbeelding van een slide bestaat niet (meer).", + "altRequired": "Geef een beschrijving (alt-tekst) of markeer de afbeelding als decoratief.", + "altTooLong": "De alt-tekst mag maximaal {max} tekens bevatten.", + "idUnknown": "Een slide hoort niet bij deze hero." + }, + "focus": { + "invalid": "Het focuspunt moet tussen 0 en 1 liggen en de zoom tussen 1 en {maxZoom}." + } + }, + "image": { + "inUse": "Deze afbeelding wordt nog gebruikt door een slide.", + "notFound": "Deze afbeelding bestaat niet.", + "rejected": { + "tooLarge": "De afbeelding is te groot (maximaal {max} MB).", + "unsupportedFormat": "Dit bestandstype wordt niet ondersteund. Kies een JPEG-, PNG-, WebP- of ander gangbaar afbeeldingsbestand.", + "corrupt": "De afbeelding kon niet worden gelezen of is beschadigd.", + "tooManyPixels": "De afbeelding heeft te veel pixels. Kies een kleinere afbeelding.", + "timeout": "Het verwerken van de afbeelding duurde te lang. Probeer een kleinere afbeelding.", + "busy": "Er worden nu andere afbeeldingen verwerkt. Probeer het zo opnieuw.", + "unavailable": "Afbeeldingen uploaden is op dit moment niet beschikbaar." + }, + "storageFull": "Er is te weinig opslagruimte voor deze afbeelding." + } + } +} -- 2.39.5 From 4369c905cddc104eb37ea8d57eac823d1e584075 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 15:58:02 +0100 Subject: [PATCH 19/47] H4: hero in de eerste HTML (regio, preload), gedeeld datablok met contributors (Offerings byte-identiek), ASF golden files, volledige pijplijntest Co-Authored-By: Claude Sonnet 5.5 --- .../features/hero-module/aidlc-state.md | 2 +- .../construction/h4-injection/code/summary.md | 22 ++ .../HeroInjectionPipelineTests.cs | 202 ++++++++++++ .../HeroOnTheMasterHostTests.cs | 10 + .../Website/CmsDataBlockTransformTests.cs | 97 ++++++ .../Hosting/Website/CmsDataBlock.cs | 68 +++++ .../Website/PrerenderedSiteExtensions.cs | 4 + .../Hosting/Website/SpaSeoExtensions.cs | 4 + .../Golden/SOURCE.md | 8 + .../Golden/host-injection/hero/README.md | 33 ++ .../hero/hero-hostile.expected-preload.html | 1 + .../hero/hero-hostile.expected.html | 1 + .../hero/hero-hostile.input.json | 58 ++++ .../hero/hero-minimal.expected-preload.html | 1 + .../hero/hero-minimal.expected.html | 1 + .../hero/hero-minimal.input.json | 17 ++ .../hero/hero-no-alt.expected-preload.html | 1 + .../hero/hero-no-alt.expected.html | 1 + .../hero/hero-no-alt.input.json | 13 + .../hero/hero-none.expected-preload.html | 1 + .../hero/hero-none.expected.html | 1 + .../host-injection/hero/hero-none.input.json | 1 + .../hero/hero-standard.expected-preload.html | 1 + .../hero/hero-standard.expected.html | 1 + .../hero/hero-standard.input.json | 76 +++++ .../hero/hero-two-lines.expected-preload.html | 1 + .../hero/hero-two-lines.expected.html | 1 + .../hero/hero-two-lines.input.json | 23 ++ .../Golden/host-injection/hero/seed.json | 73 +++++ .../HeroInjectionTests.cs | 287 ++++++++++++++++++ .../HeroServiceTests.cs | 18 ++ .../SlpModularCms.Modules.Hero.Tests.csproj | 4 + src/SlpModularCms.Modules.Hero/HeroModule.cs | 4 + .../Repositories/HeroRepository.cs | 7 +- .../Services/HeroImageService.cs | 32 +- .../Services/HeroInjection.cs | 80 +++++ .../Services/HeroPictureRenderer.cs | 213 +++++++++++++ .../Services/OfferingsHtmlTransformTests.cs | 7 +- .../OfferingsModule.cs | 2 + .../Services/OfferingsDataContributors.cs | 30 ++ .../Services/OfferingsHtmlTransform.cs | 26 +- 41 files changed, 1402 insertions(+), 31 deletions(-) create mode 100644 aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md create mode 100644 src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs create mode 100644 src/SlpModularCms.Core.Tests/Hosting/Website/CmsDataBlockTransformTests.cs create mode 100644 src/SlpModularCms.Core/Hosting/Website/CmsDataBlock.cs create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/SOURCE.md create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/README.md create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-minimal.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-minimal.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-minimal.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-no-alt.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-no-alt.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-no-alt.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-none.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-none.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-none.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-standard.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-standard.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-standard.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-two-lines.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-two-lines.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-two-lines.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/seed.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/HeroInjectionTests.cs create mode 100644 src/SlpModularCms.Modules.Hero/Services/HeroInjection.cs create mode 100644 src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Services/OfferingsDataContributors.cs diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index 6155f8b..998ffcd 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -53,7 +53,7 @@ - [x] NFR Requirements (construction/nfr-requirements/) - [x] NFR Design (construction/nfr-design/) - [x] Infrastructure Design (media directory; construction/infrastructure-design/) -- [ ] Code Generation - per unit: H0 done, H1 done (image pipeline), H2 to H6 open +- [ ] Code Generation - per unit: H0, H1, H2, H3, H4 done; H5 (admin) and H6 (seed, docs, smoke) open - [ ] Build and Test - EXECUTE ### 🟡 OPERATIONS PHASE - [ ] SKIP (Q19 = B; points go into the joint production checklist) diff --git a/aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md b/aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md new file mode 100644 index 0000000..56aa2b0 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md @@ -0,0 +1,22 @@ +# H4 Host injection: code summary + +Built 2026-11-16 on `feature/hero-module`. The CI solution filter is green (Core 921, Hero 141, Offerings 212, Availability 171, Identity 145, Api 47, Contact 349, Master 61). The Api tests run the whole chain on the master host with a real MariaDB. + +| Area | What | +|---|---| +| Shared data block | `ICmsDataBlockContributor` and `CmsDataBlockTransform` in Core (`Hosting/Website/CmsDataBlock.cs`), registered next to the injector in both website modes. Keys follow the contributors order (100 offerings, 110 banners, 200 hero); a failing contributor fails the whole block, so the page keeps its baked block | +| Offerings | `OfferingsHtmlTransform` no longer writes the block; `OfferingsDataContributor` and `BannersDataContributor` supply `offerings` and `banners`. The block is byte-for-byte what it was (the existing assertions on shape, escaping and the ASF pipeline test pass unchanged apart from calling the new transform) | +| Hero regions | `HeroPictureRenderer` (pure) writes the `` region and the preload links exactly as the ASF golden files; `HeroHtmlTransform` fills `` and `` and leaves the page alone when the hero is unusable | +| Hero data | `HeroDataContributor` adds `hero` (the full public hero with all slides, or null) | +| Missing files | `HeroPageModel` checks that the files of the first slide exist in the media store; when they do not, region, preload and data are left baked (no broken first image) | +| Golden files | ASF commit 13f78c4 copied to `Hero.Tests/Golden/host-injection/hero` (6 cases, region and preload byte-exact) | +| Tests | golden files, renderer details (focus, no tall, no AVIF, first usable slide, encoding, property test that nothing breaks out of the HTML), transform behaviour, page model (files present or missing), data block order and escaping (Core), and a full pipeline test on the master host: no hero leaves the baked page and `hero: null`; a hero made through the services shows in the first HTML with the preload and the data block (same JSON as `GET /api/v1/hero`), every variant address is served immutable, 304 works, switching the hero off and losing the media directory both restore the baked page | + +## Found and fixed while building + +- The EF MySQL provider cannot translate `IN` on a Guid list parameter (found only by the real-database test; the in-memory tests hid it): the images of a save are now read and filtered in memory (a few dozen rows). +- Re-uploading a photo whose row exists but whose files were lost (a restored database without the media directory) now repairs the files instead of returning the broken image. + +## Not yet + +The admin screens (H5), the seed script, the smoke test and the docs (H6), the LCP measurement on the test hosts (needs the sites with the markers). diff --git a/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs b/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs new file mode 100644 index 0000000..d0a30df --- /dev/null +++ b/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs @@ -0,0 +1,202 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using ImageMagick; +using Microsoft.AspNetCore.Hosting; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using SlpModularCms.Modules.Hero.Data; +using SlpModularCms.Modules.Hero.Models; +using SlpModularCms.Modules.Hero.Services; + +namespace SlpModularCms.Api.Tests; + +/// The hero on the master host with Andrea Slop Fotografie's settings: a prerendered page with the hero markers, a media directory and a real database. +public sealed class HeroInjectionFactory : AsfVariantFactory, IDisposable +{ + public string WebRoot { get; } = Path.Combine(Path.GetTempPath(), "slp-hero-web-" + Guid.NewGuid().ToString("N")); + public string MediaDirectory { get; } = Path.Combine(Path.GetTempPath(), "slp-hero-media-" + Guid.NewGuid().ToString("N")); + + public HeroInjectionFactory() => Directory.CreateDirectory(Path.Combine(WebRoot, "web")); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + builder.UseWebRoot(WebRoot); + builder.ConfigureAppConfiguration((_, config) => + config.AddInMemoryCollection(new Dictionary { ["Media:Directory"] = MediaDirectory, ["Website:PublicBaseUrl"] = "https://test.andreaslop.nl" })); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (disposing) + { + foreach (var directory in new[] { WebRoot, MediaDirectory }) + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + } +} + +[Collection("HeroDatabase")] +public class HeroInjectionPipelineTests : IClassFixture +{ + private const string Page = + "baked preload" + + "" + + "baked hero"; + + private readonly HeroInjectionFactory _factory; + + public HeroInjectionPipelineTests(HeroInjectionFactory factory) + { + _factory = factory; + File.WriteAllText(Path.Combine(factory.WebRoot, "web", "hero.html"), Page); + } + + private async Task InScope(Func> action) + { + _ = _factory.CreateClient(); // starts the host, migrates and runs the start-up checks + await using var scope = _factory.Services.CreateAsyncScope(); + return await action(scope.ServiceProvider); + } + + private static byte[] Photo() + { + using var image = new MagickImage(MagickColors.Red, 1600, 1067); + using var blue = new MagickImage(MagickColors.Blue, 800, 1067); + image.Composite(blue, 800, 0, CompositeOperator.Over); + using var stream = new MemoryStream(); + image.Write(stream, MagickFormat.Jpeg); + return stream.ToArray(); + } + + private static string DataBlock(string body) + { + const string open = "", start, StringComparison.Ordinal)]; + } + + [Fact] + public async Task AHeroMadeThroughTheModule_ShowsInTheFirstHtml_AndItsImagesAreServed() + { + try + { + await RunAsync(); + } + finally + { + await ClearHeroes(); + } + } + + private async Task ClearHeroes() + => await InScope(async sp => + { + var db = sp.GetRequiredService(); + db.Heroes.RemoveRange(await db.Heroes.ToListAsync()); + await db.SaveChangesAsync(); + return 0; + }); + + private async Task RunAsync() + { + var client = _factory.CreateClient(); + var caller = Guid.NewGuid(); + + // Clean slate: the database is shared with other tests. + await InScope(async sp => + { + var db = sp.GetRequiredService(); + db.Heroes.RemoveRange(await db.Heroes.ToListAsync()); + await db.SaveChangesAsync(); + return 0; + }); + + // Without a hero the page stays as it was built, and the data block says so. + var before = await client.GetAsync("/hero"); + before.StatusCode.Should().Be(HttpStatusCode.OK); + var beforeBody = await before.Content.ReadAsStringAsync(); + beforeBody.Should().Contain("baked hero").And.Contain("baked preload"); + JsonDocument.Parse(DataBlock(beforeBody)).RootElement.GetProperty("hero").ValueKind.Should().Be(JsonValueKind.Null); + var etagBefore = before.Headers.ETag!.Tag; + + // Upload a photo and publish a hero through the module's services. + var image = await InScope(sp => sp.GetRequiredService().UploadAsync(new MemoryStream(Photo()), Photo().Length, caller, default)); + await InScope(async sp => await sp.GetRequiredService().SaveAsync( + new HeroSaveRequest("Andrea Slop", "Lifestyle fotograaf · Huizen", null, "slideshow", [new HeroButtonRequest("Lees meer", "/over-mij")], true, null, null, + [new HeroSlideRequest(null, Guid.Parse(image.Id), "Zwangerschapsfoto in de duinen")]), caller, default)); + + var live = await client.GetAsync("/hero"); + var body = await live.Content.ReadAsStringAsync(); + live.Headers.ETag!.Tag.Should().NotBe(etagBefore); + body.Should().NotContain("baked hero").And.NotContain("baked preload"); + body.Should().Contain("Andrea Slop"); + body.Should().Contain("Lees meer"); + body.Should().Contain(" p.Name).Should().Equal("siteUrl", "offerings", "banners", "hero"); + var api = JsonDocument.Parse(await client.GetStringAsync("/api/v1/hero")).RootElement; + System.Text.Json.Nodes.JsonNode.DeepEquals(System.Text.Json.Nodes.JsonNode.Parse(data.GetProperty("hero").GetRawText()), System.Text.Json.Nodes.JsonNode.Parse(api.GetRawText())) + .Should().BeTrue("the data block carries the same JSON as GET /api/v1/hero"); + + // Every address in the page is served by the host: immutable, same origin. + var src = api.GetProperty("slides")[0].GetProperty("image").GetProperty("src").GetString()!; + body.Should().Contain($"src=\"{src}\""); + foreach (var url in api.GetProperty("slides")[0].GetProperty("image").GetProperty("variants").EnumerateArray().Select(v => v.GetProperty("url").GetString()!)) + { + var media = await client.GetAsync(url); + media.StatusCode.Should().Be(HttpStatusCode.OK, url); + media.Headers.CacheControl!.ToString().Should().Be("public, max-age=31536000, immutable"); + (await media.Content.ReadAsByteArrayAsync()).Length.Should().BeGreaterThan(100); + } + + // A matching ETag is a 304. + var conditional = new HttpRequestMessage(HttpMethod.Get, "/hero"); + conditional.Headers.IfNoneMatch.Add(live.Headers.ETag); + (await client.SendAsync(conditional)).StatusCode.Should().Be(HttpStatusCode.NotModified); + + // Switching the hero off puts the baked page back at once. + await InScope(async sp => + { + var service = sp.GetRequiredService(); + var current = await service.GetAsync(default); + await service.SaveAsync(new HeroSaveRequest(current.Title, current.Tagline, current.Lead, current.Display, [], IsActive: false, null, null, + current.Slides.Select(s => new HeroSlideRequest(Guid.Parse(s.Id), Guid.Parse(s.ImageId), s.Alt)).ToList()), caller, default); + return 0; + }); + var off = await client.GetStringAsync("/hero"); + off.Should().Contain("baked hero").And.Contain("baked preload").And.NotContain("cms-hero-picture"); + + // And a media directory that lost its files leaves the baked hero too (no broken first image). + await InScope(async sp => + { + var service = sp.GetRequiredService(); + var current = await service.GetAsync(default); + await service.SaveAsync(new HeroSaveRequest(current.Title, current.Tagline, current.Lead, current.Display, [], IsActive: true, null, null, + current.Slides.Select(s => new HeroSlideRequest(Guid.Parse(s.Id), Guid.Parse(s.ImageId), s.Alt)).ToList()), caller, default); + return 0; + }); + (await client.GetStringAsync("/hero")).Should().Contain("cms-hero-picture"); + Directory.Delete(Path.Combine(_factory.MediaDirectory, "hero"), recursive: true); + await InScope(sp => { sp.GetRequiredService().Invalidate(); return Task.FromResult(0); }); + var missing = await client.GetStringAsync("/hero"); + missing.Should().Contain("baked hero").And.NotContain("cms-hero-picture"); + + // Clean up for the other tests. + await InScope(async sp => + { + var db = sp.GetRequiredService(); + db.Heroes.RemoveRange(await db.Heroes.ToListAsync()); + await db.SaveChangesAsync(); + return 0; + }); + } +} diff --git a/src/SlpModularCms.Api.Tests/HeroOnTheMasterHostTests.cs b/src/SlpModularCms.Api.Tests/HeroOnTheMasterHostTests.cs index 654e8a1..ba67b68 100644 --- a/src/SlpModularCms.Api.Tests/HeroOnTheMasterHostTests.cs +++ b/src/SlpModularCms.Api.Tests/HeroOnTheMasterHostTests.cs @@ -7,6 +7,7 @@ using SlpModularCms.Modules.Hero.Data; namespace SlpModularCms.Api.Tests; /// The Hero module on the real master host and the real, migrated database. +[Collection("HeroDatabase")] public class HeroOnTheMasterHostTests : IClassFixture { private readonly ApiWebApplicationFactory _factory; @@ -25,6 +26,15 @@ public class HeroOnTheMasterHostTests : IClassFixture [Fact] public async Task WithoutAHero_ThePublicEndpointAnswers204_WithTheShortCache() { + // The database is shared with other tests (and earlier runs): start without a hero. + _ = _factory.CreateClient(); + using (var scope = _factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Heroes.RemoveRange(await db.Heroes.ToListAsync()); + await db.SaveChangesAsync(); + } + var response = await _factory.CreateClient().GetAsync("/api/v1/hero"); response.StatusCode.Should().Be(HttpStatusCode.NoContent); diff --git a/src/SlpModularCms.Core.Tests/Hosting/Website/CmsDataBlockTransformTests.cs b/src/SlpModularCms.Core.Tests/Hosting/Website/CmsDataBlockTransformTests.cs new file mode 100644 index 0000000..989be86 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Hosting/Website/CmsDataBlockTransformTests.cs @@ -0,0 +1,97 @@ +using System.Text.Json; +using FluentAssertions; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Core.Hosting.Website; + +namespace SlpModularCms.Core.Tests.Hosting.Website; + +public class CmsDataBlockTransformTests +{ + private static readonly HtmlTransformContext Context = new("https://test.example.nl"); + private const string Open = "", start, StringComparison.Ordinal)]).RootElement; + } + + [Theory] + [InlineData("", true)] + [InlineData("

nothing

", false)] + [InlineData("", false)] + public void Wants_OnlyPagesWithTheDataMarker(string html, bool expected) + => new CmsDataBlockTransform([]).Wants(html).Should().Be(expected); + + [Fact] + public async Task TheKeys_FollowTheOrderOfTheContributors_AfterTheSiteUrl() + { + var transform = new CmsDataBlockTransform([Contributor("hero", 200, new { a = 1 }), Contributor("offerings", 100, new[] { 1, 2 }), Contributor("banners", 110, new { top = (string?)null })]); + + var html = await transform.ApplyAsync("", Context, default); + + html.Should().StartWith("" + Open).And.EndWith("").And.NotContain("baked"); + var data = Data(html); + data.EnumerateObject().Select(p => p.Name).Should().Equal("siteUrl", "offerings", "banners", "hero"); + data.GetProperty("siteUrl").GetString().Should().Be("https://test.example.nl"); + data.GetProperty("offerings").GetRawText().Should().Be("[1,2]"); + data.GetProperty("banners").GetProperty("top").ValueKind.Should().Be(JsonValueKind.Null); + } + + [Fact] + public async Task ANullValue_IsWrittenAsNull_SoTheWebsiteKeepsItsBakedVersion() + { + var html = await new CmsDataBlockTransform([Contributor("hero", 200, null)]).ApplyAsync("", Context, default); + + Data(html).GetProperty("hero").ValueKind.Should().Be(JsonValueKind.Null); + } + + [Fact] + public async Task TheValues_UseTheCamelCaseShapeOfThePublicApi() + { + var html = await new CmsDataBlockTransform([Contributor("x", 1, new { SomeName = "a", Nested = new { InnerValue = (int?)null } })]).ApplyAsync("", Context, default); + + html.Should().Contain("\"someName\":\"a\"").And.Contain("\"innerValue\":null"); + } + + [Fact] + public async Task TheBlock_CannotCloseTheScriptElement() + { + var html = await new CmsDataBlockTransform([Contributor("x", 1, new { text = " & \u2028" })]).ApplyAsync("", Context, default); + + var inner = html[Open.Length..^"".Length]; + inner.Should().NotContain("<").And.NotContain(">").And.NotContain("&").And.NotContain("\u2028"); + JsonDocument.Parse(inner).RootElement.GetProperty("x").GetProperty("text").GetString().Should().Be(" & \u2028"); + } + + [Fact] + public async Task AFailingContributor_FailsTheWholeBlock_SoThePageKeepsItsBakedBlock() + { + var failing = Substitute.For(); + failing.Key.Returns("hero"); + failing.Order.Returns(200); + failing.GetAsync(default!, default).ThrowsAsyncForAnyArgs(new InvalidOperationException("boom")); + + var act = async () => await new CmsDataBlockTransform([Contributor("offerings", 100, new[] { 1 }), failing]).ApplyAsync("", Context, default); + + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task WithoutContributors_TheBlockHoldsTheSiteUrlOnly() + { + var html = await new CmsDataBlockTransform([]).ApplyAsync("", Context, default); + + Data(html).EnumerateObject().Select(p => p.Name).Should().Equal("siteUrl"); + } +} diff --git a/src/SlpModularCms.Core/Hosting/Website/CmsDataBlock.cs b/src/SlpModularCms.Core/Hosting/Website/CmsDataBlock.cs new file mode 100644 index 0000000..3eb7e82 --- /dev/null +++ b/src/SlpModularCms.Core/Hosting/Website/CmsDataBlock.cs @@ -0,0 +1,68 @@ +using System.Buffers; +using System.Text; +using System.Text.Json; +using Microsoft.Extensions.Logging; + +namespace SlpModularCms.Core.Hosting.Website; + +/// +/// A module's key in the data block that the host writes into a website page (<script type="application/json" +/// id="cms-data"> after the <!--CMS:DATA--> marker). The website reads this block instead of +/// fetching, so the same data that the public API answers is in the first HTML. Contributors are scoped. +/// +public interface ICmsDataBlockContributor +{ + /// The property name in the block (offerings, banners, hero). + string Key { get; } + + /// Fixes the order of the keys in the block: lower first (100 offerings, 110 banners, 200 hero). + int Order { get; } + + /// The value to write for ; null is written as JSON null (the website then keeps what it was built with). + Task GetAsync(HtmlTransformContext context, CancellationToken cancellationToken); +} + +/// +/// Owns the <!--CMS:DATA--> marker: composes one block from siteUrl and every registered +/// , so modules never edit each other's output. If one contributor fails the whole +/// block stays as it was built: a half-filled block would mislead the website (fail-open for the block as a whole). +/// +public sealed class CmsDataBlockTransform(IEnumerable contributors) : IHtmlPageTransform +{ + public const string Marker = "CMS:DATA"; + public const string BlockId = "cms-data"; + + // The shape of the public API answers: camelCase, nulls written. + private static readonly JsonSerializerOptions ApiJson = new(JsonSerializerDefaults.Web); + + public bool Wants(string html) => html.Contains("", StringComparison.Ordinal); + + public async Task ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken) + { + var buffer = new ArrayBufferWriter(); + await using (var writer = new Utf8JsonWriter(buffer)) + { + writer.WriteStartObject(); + writer.WriteString("siteUrl", context.SiteUrl); + foreach (var contributor in contributors.OrderBy(c => c.Order).ThenBy(c => c.Key, StringComparer.Ordinal)) + { + var value = await contributor.GetAsync(context, cancellationToken); + writer.WritePropertyName(contributor.Key); + if (value is null) + { + writer.WriteNullValue(); + } + else + { + JsonSerializer.Serialize(writer, value, value.GetType(), ApiJson); + } + } + + writer.WriteEndObject(); + } + + var json = Encoding.UTF8.GetString(buffer.WrittenSpan); + var block = ""; + return HtmlMarkerEditor.ReplaceDataBlock(html, Marker, BlockId, block); + } +} diff --git a/src/SlpModularCms.Core/Hosting/Website/PrerenderedSiteExtensions.cs b/src/SlpModularCms.Core/Hosting/Website/PrerenderedSiteExtensions.cs index 94a6fbc..1ae1df3 100644 --- a/src/SlpModularCms.Core/Hosting/Website/PrerenderedSiteExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/Website/PrerenderedSiteExtensions.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.ResponseCompression; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; namespace SlpModularCms.Core.Hosting.Website; @@ -40,6 +41,9 @@ public static class PrerenderedSiteExtensions services.AddSingleton(); services.AddSingleton(provider => provider.GetRequiredService()); + // The shared CMS data block of the pages (siteUrl plus what each module contributes). + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + // Presence of the marker switches on the full security-header set for website responses. services.AddSingleton(); diff --git a/src/SlpModularCms.Core/Hosting/Website/SpaSeoExtensions.cs b/src/SlpModularCms.Core/Hosting/Website/SpaSeoExtensions.cs index 8c8948f..20c6844 100644 --- a/src/SlpModularCms.Core/Hosting/Website/SpaSeoExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/Website/SpaSeoExtensions.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; @@ -24,6 +25,9 @@ public static class SpaSeoExtensions services.AddOptions().Bind(configuration.GetSection(WebsiteOptions.SectionName)); services.AddSingleton(); services.AddSingleton(provider => provider.GetRequiredService()); + + // The shared CMS data block of the pages (siteUrl plus what each module contributes). + services.TryAddEnumerable(ServiceDescriptor.Scoped()); return services; } diff --git a/src/SlpModularCms.Modules.Hero.Tests/Golden/SOURCE.md b/src/SlpModularCms.Modules.Hero.Tests/Golden/SOURCE.md new file mode 100644 index 0000000..f7b15be --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/Golden/SOURCE.md @@ -0,0 +1,8 @@ +# Golden files of the website build (ASF): hero + +`host-injection/hero/` is a copy of `web/contract/host-injection/hero` of the Andrea Slop Fotografie website repository, +ASF commit `13f78c4` (branch `feature/hero-module`). It is the contract for the plain HTML the CMS host writes between the +CMS markers `CMS:HERO-HTML` (the hero) and `CMS:HERO-PRELOAD` (the preload links in the head); see +`host-injection/hero/README.md` for the rules. `HeroGoldenTests` runs `HeroPictureRenderer` against every input/expected +pair. When the website changes the contract it sends new files and the commit; replace the folder and note the new commit +here. `seed.json` is the seed data of the ASF test CMS (used by `scripts/Seed-Hero.ps1`). diff --git a/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/README.md b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/README.md new file mode 100644 index 0000000..43a989e --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/README.md @@ -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 ``. Same idea as the packages (`../README.md`): for every `NAME.input.json` the host's template must give exactly `NAME.expected.html` (between `` and ``) and `NAME.expected-preload.html` (between `` and `` 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 `
` (after escaping). + +## Output, HERO-HTML + +`` + (when a `tall` webp variant exists: ``) + `ALT` + `` + `

` + (tagline: `TAGLINE `) + `TITLE

` + (when there are buttons: `

` + `LABEL`... + `

`). + +`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: `` 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//wide-1600.webp`, `/media/hero//tall-960.avif`. diff --git a/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected-preload.html b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected-preload.html new file mode 100644 index 0000000..885e97e --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected-preload.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected.html b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected.html new file mode 100644 index 0000000..73166d9 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected.html @@ -0,0 +1 @@ +Een "foto" <script>

<i>x</i> <b>"Andrea" & 'Slop'</b>

<Goed>

diff --git a/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.input.json b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.input.json new file mode 100644 index 0000000..497bbbf --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.input.json @@ -0,0 +1,58 @@ +{ + "display": "slideshow", + "title": "\"Andrea\" & 'Slop'", + "tagline": "x", + "buttons": [ + { "label": "javascript", "target": "javascript:alert(1)" }, + { "label": "Protocolvrij", "target": "//evil.example/x" }, + { "label": "", "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\" \n\"x\" & 'y'", "", new HeroButtonDto("", "/ok?a=1&b=\"2\"")); + + var html = HeroPictureRenderer.Render(hero).Region; + + html.Should().NotContain(""); + html.Should().Contain("<script>alert(1)</script>
"x" & 'y'"); + } + + [Fact] + public void ARendererNeverThrows_OnArbitraryText() + => Prop.ForAll( + Gen.Elements("a", "<", ">", "&", "\"", "'", "\n", " ", "é", "\\", "/", "#").ArrayOf().Select(p => string.Concat(p)).ToArbitrary(), + text => + { + var hero = new PublicHeroDto("single", "T" + text, text, text, [new HeroButtonDto(text, "/" + text)], + [new PublicSlideDto("id", "a" + text, false, new PublicImageDto(10, 10, new FocusDto(0.5, 0.5, 1), "/media/x/" + text.Replace("\\", string.Empty), []))]); + var html = HeroPictureRenderer.Render(hero).Region; + html.Should().NotContain("baked preload" + + "baked hero

rest

"; + + private static PublicHeroDto Hero() => new("single", "Andrea Slop", null, null, [], + [new PublicSlideDto("s1", "Een foto", false, new PublicImageDto(1600, 1067, new FocusDto(0.5, 0.5, 1), "/media/hero/0123456789abcdef/wide-1600.webp", + [new HeroVariantDto("wide", 1600, 1067, "image/webp", "/media/hero/0123456789abcdef/wide-1600.webp")]))]); + + private static HeroHtmlTransform Sut(PublicHeroDto? hero) + { + var model = Substitute.For(); + model.GetAsync(default).ReturnsForAnyArgs(hero); + return new HeroHtmlTransform(model); + } + + [Theory] + [InlineData("

nothing

", false)] + [InlineData("", true)] + [InlineData("", true)] + [InlineData("", false)] + public void Wants_OnlyPagesWithHeroMarkers(string html, bool expected) => Sut(null).Wants(html).Should().Be(expected); + + [Fact] + public async Task TheRegions_AreFilled_AndTheMarkersStay() + { + var html = await Sut(Hero()).ApplyAsync(Page, Context, default); + + html.Should().Contain("").And.Contain(""); + html.Should().Contain(""); + html.Should().NotContain("baked").And.Contain("

rest

"); + } + + [Fact] + public async Task WithoutAHero_ThePageStaysAsItWasBuilt() + { + (await Sut(null).ApplyAsync(Page, Context, default)).Should().Be(Page); + } + + [Fact] + public async Task AHeroWithoutAUsableSlide_LeavesTheBakedHero() + { + var textOnly = new PublicHeroDto("single", "Titel", null, null, [], []); + + (await Sut(textOnly).ApplyAsync(Page, Context, default)).Should().Be(Page); + } + + [Fact] + public async Task APageWithOnlyOneMarker_OnlyGetsThatPart() + { + var html = await Sut(Hero()).ApplyAsync("x", Context, default); + + html.Should().Contain("cms-hero-picture").And.NotContain("preload"); + } +} + +public class HeroPageModelTests +{ + private static PublicHeroDto Hero(string src = "/media/hero/0123456789abcdef/wide-1600.webp") => new("single", "Titel", null, null, [], + [new PublicSlideDto("s1", "Foto", false, new PublicImageDto(1600, 1067, new FocusDto(0.5, 0.5, 1), src, + [new HeroVariantDto("wide", 1600, 1067, "image/webp", src), new HeroVariantDto("tall", 640, 800, "image/webp", "/media/hero/0123456789abcdef/tall-640.webp")]))]); + + private static (HeroPageModel Model, IMediaStore Store) Make(PublicHeroDto? hero) + { + var publicHero = Substitute.For(); + publicHero.GetActiveAsync(default).ReturnsForAnyArgs(hero); + var store = Substitute.For(); + store.ExistsAsync(default!, default).ReturnsForAnyArgs(true); + return (new HeroPageModel(publicHero, store, NullLogger.Instance), store); + } + + [Fact] + public async Task WhenTheFilesOfTheFirstSlideExist_TheHeroIsReturned() + { + var (model, _) = Make(Hero()); + + (await model.GetAsync(default)).Should().NotBeNull(); + } + + [Fact] + public async Task WhenAFileOfTheFirstSlideIsMissing_NothingIsReturned() + { + var (model, store) = Make(Hero()); + store.ExistsAsync("hero/0123456789abcdef/tall-640.webp", default).Returns(false); + + (await model.GetAsync(default)).Should().BeNull(); + } + + [Fact] + public async Task WithoutAHero_OrWithoutSlides_ThereIsNothingToCheck() + { + (await Make(null).Model.GetAsync(default)).Should().BeNull(); + var textOnly = new PublicHeroDto("single", "Titel", null, null, [], []); + var (model, store) = Make(textOnly); + + (await model.GetAsync(default)).Should().Be(textOnly); + await store.DidNotReceiveWithAnyArgs().ExistsAsync(default!, default); + } + + [Fact] + public async Task TheDataContributor_WritesTheHero_OrNull() + { + var withHero = Make(Hero()).Model; + var without = Make(null).Model; + + (await new HeroDataContributor(withHero).GetAsync(new HtmlTransformContext("https://x"), default)).Should().BeOfType(); + (await new HeroDataContributor(without).GetAsync(new HtmlTransformContext("https://x"), default)).Should().BeNull(); + new HeroDataContributor(withHero).Key.Should().Be("hero"); + } + + [Fact] + public async Task TheDataBlock_CarriesTheOfferingsFirst_ThenTheHero() + { + var offerings = Substitute.For(); + offerings.Key.Returns("offerings"); + offerings.Order.Returns(100); + offerings.GetAsync(default!, default).ReturnsForAnyArgs(new[] { 1 }); + var block = new CmsDataBlockTransform([new HeroDataContributor(Make(Hero()).Model), offerings]); + + var html = await block.ApplyAsync("", new HtmlTransformContext("https://x"), default); + + var json = html["".Length]; + using var doc = JsonDocument.Parse(json); + doc.RootElement.EnumerateObject().Select(p => p.Name).Should().Equal("siteUrl", "offerings", "hero"); + doc.RootElement.GetProperty("hero").GetProperty("slides")[0].GetProperty("image").GetProperty("variants").GetArrayLength().Should().Be(2); + } +} diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs index e50d165..ea3e5f0 100644 --- a/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs @@ -60,6 +60,24 @@ public class HeroImageServiceTests rig.Db.HeroImages.Count().Should().Be(1); } + [Fact] + public async Task TheSamePhotoAgain_RepairsLostFiles() + { + using var rig = new HeroTestRig(); + var photo = HeroTestRig.Photo(); + var first = await rig.Upload(photo); + System.IO.Directory.Delete(rig.Directory, recursive: true); + + var again = await rig.Upload(photo); + + again.Id.Should().Be(first.Id); + rig.Db.HeroImages.Count().Should().Be(1); + foreach (var variant in again.Variants) + { + (await rig.Store.ExistsAsync(variant.Url["/media/".Length..], CancellationToken.None)).Should().BeTrue(variant.Url); + } + } + [Fact] public async Task ADefaultFocus_IsTheCentre_ForEveryRatio() { diff --git a/src/SlpModularCms.Modules.Hero.Tests/SlpModularCms.Modules.Hero.Tests.csproj b/src/SlpModularCms.Modules.Hero.Tests/SlpModularCms.Modules.Hero.Tests.csproj index ce0a9f7..3d3e2ea 100644 --- a/src/SlpModularCms.Modules.Hero.Tests/SlpModularCms.Modules.Hero.Tests.csproj +++ b/src/SlpModularCms.Modules.Hero.Tests/SlpModularCms.Modules.Hero.Tests.csproj @@ -27,6 +27,10 @@ + + + + diff --git a/src/SlpModularCms.Modules.Hero/HeroModule.cs b/src/SlpModularCms.Modules.Hero/HeroModule.cs index 2a82eb6..e58411f 100644 --- a/src/SlpModularCms.Modules.Hero/HeroModule.cs +++ b/src/SlpModularCms.Modules.Hero/HeroModule.cs @@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Hosting.Website; using SlpModularCms.Core.Media; using SlpModularCms.Core.Media.Magick; using SlpModularCms.Core.Modules; @@ -43,6 +44,9 @@ public class HeroModule : IModule services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddHostedService(); } diff --git a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs index cb52681..68b26eb 100644 --- a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs +++ b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs @@ -55,7 +55,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository => context.HeroImages.FirstOrDefaultAsync(i => i.Id == id, cancellationToken); public async Task> GetImagesAsync(IReadOnlyCollection ids, CancellationToken cancellationToken) - => await context.HeroImages.Where(i => ids.Contains(i.Id)).ToListAsync(cancellationToken); + { + // The MySQL provider cannot map a Guid list parameter in an IN clause; there are only a few dozen images, so they + // are read and filtered here. + var wanted = ids.ToHashSet(); + return (await context.HeroImages.ToListAsync(cancellationToken)).Where(i => wanted.Contains(i.Id)).ToList(); + } public Task GetImageBySha256Async(string sha256, CancellationToken cancellationToken) => context.HeroImages.FirstOrDefaultAsync(i => i.OriginalSha256 == sha256, cancellationToken); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs index 29c2265..71ba1dc 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs @@ -48,8 +48,10 @@ public class HeroImageService( using var admitted = await guard.AdmitAsync(upload, declaredLength, cancellationToken); var sha = Convert.ToHexStringLower(SHA256.HashData(admitted.Bytes)); + // The same photo again is the same image. When its files are gone (a lost or restored media directory) the upload + // repairs them from the file that was just sent. var existing = await repository.GetImageBySha256Async(sha, cancellationToken); - if (existing is not null) + if (existing is not null && await FilesExistAsync(existing, cancellationToken)) { return HeroMapping.ToImageDto(existing); } @@ -62,7 +64,7 @@ public class HeroImageService( var original = stripped ?? admitted.Bytes; var storedFormat = stripped is not null && format == ImageFormat.Heic ? ImageFormat.Jpeg : format; - var image = new HeroImage + var image = existing ?? new HeroImage { Id = Guid.NewGuid(), OriginalSha256 = sha, @@ -79,13 +81,35 @@ public class HeroImageService( await store.PutAsync(image.OriginalKey, original, cancellationToken); await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken); - repository.AddImage(image); + if (existing is null) + { + repository.AddImage(image); + } + await repository.SaveChangesAsync(cancellationToken); - logger.LogInformation("Hero image {ImageId} uploaded by user {UserId} ({Width}x{Height}, {Variants} variants)", image.Id, callerId, image.Width, image.Height, image.Variants.Count); + logger.LogInformation("Hero image {ImageId} {Action} by user {UserId} ({Width}x{Height}, {Variants} variants)", image.Id, existing is null ? "uploaded" : "repaired", callerId, image.Width, image.Height, image.Variants.Count); return HeroMapping.ToImageDto(image); } + private async Task FilesExistAsync(HeroImage image, CancellationToken cancellationToken) + { + if (!await store.ExistsAsync(image.OriginalKey, cancellationToken)) + { + return false; + } + + foreach (var variant in image.Variants) + { + if (!await store.ExistsAsync($"{HeroMapping.Area}/{image.SetHash}/{variant.FileName}", cancellationToken)) + { + return false; + } + } + + return true; + } + public async Task SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken) { var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException(); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroInjection.cs b/src/SlpModularCms.Modules.Hero/Services/HeroInjection.cs new file mode 100644 index 0000000..c3fa1c1 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Services/HeroInjection.cs @@ -0,0 +1,80 @@ +using Microsoft.Extensions.Logging; +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Core.Media; +using SlpModularCms.Modules.Hero.Models; + +namespace SlpModularCms.Modules.Hero.Services; + +/// +/// The hero as a page may show it: the public hero, but only when the files of its first slide are really in the media +/// store. When they are not (a missing or restored directory) nothing of the hero is written, so a page never gets a broken +/// first image and the baked hero stays. One answer for the region, the preload and the data block. +/// +public interface IHeroPageModel +{ + Task GetAsync(CancellationToken cancellationToken); +} + +public sealed class HeroPageModel(IPublicHeroService publicHero, IMediaStore store, ILogger logger) : IHeroPageModel +{ + public async Task GetAsync(CancellationToken cancellationToken) + { + var hero = await publicHero.GetActiveAsync(cancellationToken); + if (hero is null) + { + return null; + } + + var first = hero.Slides.FirstOrDefault(); + if (first is null) + { + return hero; + } + + foreach (var url in new[] { first.Image.Src }.Concat(first.Image.Variants.Select(v => v.Url)).Distinct()) + { + if (url.StartsWith(MediaPaths.UrlPrefix, StringComparison.Ordinal) + && !await store.ExistsAsync(url[MediaPaths.UrlPrefix.Length..], cancellationToken)) + { + logger.LogWarning("The first hero slide has a file missing in the media store ({Address}); the hero is left out of the page.", url); + return null; + } + } + + return hero; + } +} + +/// Fills the hero regions of a page: <!--CMS:HERO-HTML--> in the body and <!--CMS:HERO-PRELOAD--> in the head. Fail-open: no hero means the baked page stays. +public sealed class HeroHtmlTransform(IHeroPageModel model) : IHtmlPageTransform +{ + public const string HtmlRegion = "CMS:HERO-HTML"; + public const string PreloadRegion = "CMS:HERO-PRELOAD"; + + public bool Wants(string html) + => html.Contains("", StringComparison.Ordinal) + || html.Contains("", StringComparison.Ordinal); + + public async Task ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken) + { + var rendered = HeroPictureRenderer.Render(await model.GetAsync(cancellationToken)); + if (rendered.IsEmpty) + { + return html; + } + + html = HtmlMarkerEditor.ReplaceRegion(html, HtmlRegion, rendered.Region); + return HtmlMarkerEditor.ReplaceRegion(html, PreloadRegion, rendered.Preload); + } +} + +/// The hero key of the page data block: the complete public hero (all slides), or null. +public sealed class HeroDataContributor(IHeroPageModel model) : ICmsDataBlockContributor +{ + public string Key => "hero"; + + public int Order => 200; + + public async Task GetAsync(HtmlTransformContext context, CancellationToken cancellationToken) + => await model.GetAsync(cancellationToken); +} diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs b/src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs new file mode 100644 index 0000000..62cc056 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs @@ -0,0 +1,213 @@ +using System.Globalization; +using System.Text; +using SlpModularCms.Modules.Hero.Models; + +namespace SlpModularCms.Modules.Hero.Services; + +/// The two pieces written into a page: the hero itself and the preload links for the head. Both empty = leave the baked page. +public sealed record HeroInjection(string Region, string Preload) +{ + public static readonly HeroInjection None = new(string.Empty, string.Empty); + + public bool IsEmpty => Region.Length == 0; +} + +/// +/// The plain HTML of the hero for the first response, written exactly as the website's golden files expect +/// (aidlc-docs/features/hero-module, site contract; ASF commit 13f78c4). One place produces the picture and the preload, +/// so the srcset, sizes and media values are the same text in both. Pure; everything is HTML-encoded. +/// +/// +/// The rules are those of the website: a hero needs a title and a usable first slide (an id, an own-host path, a size, and +/// an alt text or the decorative flag), only WebP is used for the first image (a preload cannot say "AVIF if supported"), +/// at most two buttons, and unusable parts are skipped, never repaired. They are deliberately a little wider than what the +/// CMS accepts when saving, because the renderer must also cope with data it did not validate itself. +/// +public static class HeroPictureRenderer +{ + private const string Webp = "image/webp"; + private const string Portrait = "(orientation: portrait)"; + private const string Landscape = "(orientation: landscape)"; + + public static HeroInjection Render(PublicHeroDto? hero) + { + if (hero is null || string.IsNullOrWhiteSpace(hero.Title)) + { + return HeroInjection.None; + } + + var slide = (hero.Slides ?? []).FirstOrDefault(IsUsable); + if (slide is null) + { + return HeroInjection.None; + } + + var image = slide.Image; + var variants = (image.Variants ?? []).Where(v => IsUsable(v) && v.Type == Webp).ToList(); + var wide = SrcSet(variants, "wide"); + var tall = SrcSet(variants, "tall"); + + return new HeroInjection(Region(hero, slide, wide, tall), Preload(image.Src, wide, tall)); + } + + private static string Region(PublicHeroDto hero, PublicSlideDto slide, string wide, string tall) + { + var image = slide.Image; + var html = new StringBuilder(); + html.Append(""); + if (tall.Length > 0) + { + html.Append(""); + } + + html.Append(" 0) + { + html.Append(" srcset=\"").Append(Encode(wide)).Append("\" sizes=\"100vw\""); + } + + html.Append(" width=\"").Append(image.Width.ToString(CultureInfo.InvariantCulture)).Append("\" height=\"").Append(image.Height.ToString(CultureInfo.InvariantCulture)).Append('"'); + html.Append(" alt=\"").Append(slide.Decorative ? string.Empty : Encode(slide.Alt)).Append('"'); + if (Position(image) is { } position) + { + html.Append(" style=\"object-position:").Append(position).Append('"'); + } + + html.Append(" fetchpriority=\"high\">"); + + html.Append("

"); + if (!string.IsNullOrWhiteSpace(hero.Tagline)) + { + html.Append("").Append(Encode(hero.Tagline)).Append(" "); + } + + html.Append("").Append(string.Join("
", hero.Title.Replace("\r\n", "\n").Split('\n').Select(Encode))).Append("

"); + + var buttons = (hero.Buttons ?? []).Where(IsUsable).Take(2).ToList(); + if (buttons.Count > 0) + { + html.Append("

"); + foreach (var button in buttons) + { + html.Append("").Append(Encode(button.Label)).Append(""); + } + + html.Append("

"); + } + + return html.ToString(); + } + + private static string Preload(string src, string wide, string tall) + { + const string head = ""; + + string Link(string set, string? media) + { + var link = new StringBuilder(head); + if (set.Length > 0) + { + link.Append(" imagesrcset=\"").Append(Encode(set)).Append("\" imagesizes=\"100vw\""); + } + else + { + link.Append(" href=\"").Append(Encode(src)).Append('"'); + } + + if (media is not null) + { + link.Append(" media=\"").Append(media).Append('"'); + } + + return link.Append(tail).ToString(); + } + + return tall.Length > 0 ? Link(tall, Portrait) + Link(wide, Landscape) : Link(wide, null); + } + + // ----- what counts as usable (the rules of the website) ------------------------------------------------------- + + private static bool IsUsable(PublicSlideDto? slide) + => slide is { Image: not null } + && !string.IsNullOrEmpty(slide.Id) + && IsHostPath(slide.Image.Src) + && slide.Image.Width > 0 + && slide.Image.Height > 0 + && (slide.Decorative || !string.IsNullOrWhiteSpace(slide.Alt)); + + private static bool IsUsable(HeroVariantDto variant) + => !string.IsNullOrEmpty(variant.Ratio) && !string.IsNullOrEmpty(variant.Type) && variant.Width > 0 && IsHostPath(variant.Url); + + private static bool IsUsable(HeroButtonDto button) + => !string.IsNullOrWhiteSpace(button.Label) && IsButtonTarget(button.Target); + + /// A path of this host: one leading slash, not a protocol-relative address, no backslash. + private static bool IsHostPath(string? value) + => !string.IsNullOrEmpty(value) && value[0] == '/' && !value.StartsWith("//", StringComparison.Ordinal) && !value.Contains('\\'); + + private static bool IsButtonTarget(string? target) + { + if (string.IsNullOrEmpty(target)) + { + return false; + } + + if (target[0] == '#') + { + return target.Length > 1 && !target.Any(char.IsWhiteSpace); + } + + if (target[0] == '/') + { + return IsHostPath(target); + } + + return target.StartsWith("https://", StringComparison.Ordinal) + && Uri.TryCreate(target, UriKind.Absolute, out var uri) + && uri.Scheme == Uri.UriSchemeHttps + && !string.IsNullOrEmpty(uri.Host); + } + + private static string SrcSet(IEnumerable variants, string ratio) + => string.Join(", ", variants.Where(v => v.Ratio == ratio).OrderBy(v => v.Width).Select(v => v.Url + " " + v.Width.ToString(CultureInfo.InvariantCulture) + "w")); + + /// X% Y% from a focus point inside the image (at most two decimals, no trailing zeros), or null without a valid one. + private static string? Position(PublicImageDto image) + { + var focus = image.Focus; + if (focus is null || focus.X is < 0 or > 1 || focus.Y is < 0 or > 1 || double.IsNaN(focus.X) || double.IsNaN(focus.Y)) + { + return null; + } + + return Percent(focus.X) + "% " + Percent(focus.Y) + "%"; + } + + private static string Percent(double fraction) + => Math.Round(fraction * 100, 2, MidpointRounding.AwayFromZero).ToString("0.##", CultureInfo.InvariantCulture); + + private static string Encode(string? value) + { + if (string.IsNullOrEmpty(value)) + { + return string.Empty; + } + + var builder = new StringBuilder(value.Length + 8); + foreach (var c in value) + { + switch (c) + { + case '&': builder.Append("&"); break; + case '<': builder.Append("<"); break; + case '>': builder.Append(">"); break; + case '"': builder.Append("""); break; + case '\'': builder.Append("'"); break; + default: builder.Append(c); break; + } + } + + return builder.ToString(); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsHtmlTransformTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsHtmlTransformTests.cs index 5c2ca35..d1f1b24 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsHtmlTransformTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsHtmlTransformTests.cs @@ -16,6 +16,9 @@ public class OfferingsHtmlTransformTests private OfferingsHtmlTransform Sut() => new(_offerings, _banners); + // The data block is composed by the Core transform from the contributors of the Offerings module (same output as before). + private CmsDataBlockTransform DataBlock() => new([new OfferingsDataContributor(_offerings), new BannersDataContributor(_banners)]); + private static OfferingDto Offering(string slug, string title, string price, int order = 0, bool featured = false) => new( Guid.NewGuid().ToString(), slug, title, "Beschrijving", price, "eenmalig", ["1 uur fotografie", "Online galerij"], "Boek", featured, order); @@ -92,7 +95,7 @@ public class OfferingsHtmlTransformTests Banner("top", top); Banner("bottom", null); - var html = await Sut().ApplyAsync("", Context, default); + var html = await DataBlock().ApplyAsync("", Context, default); html.Should().StartWith(""); var json = html["".Length]; @@ -114,7 +117,7 @@ public class OfferingsHtmlTransformTests Banner("top", null); Banner("bottom", null); - var html = await Sut().ApplyAsync("", Context, default); + var html = await DataBlock().ApplyAsync("", Context, default); var inner = html["".Length]; inner.Should().NotContain("<").And.NotContain(">").And.NotContain("&").And.NotContain("\u2028"); diff --git a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs index f665dd3..5d57abe 100644 --- a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs +++ b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs @@ -34,6 +34,8 @@ public class OfferingsModule : IModule services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsDataContributors.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsDataContributors.cs new file mode 100644 index 0000000..79b3462 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsDataContributors.cs @@ -0,0 +1,30 @@ +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Modules.Offerings.Data.Entities; + +namespace SlpModularCms.Modules.Offerings.Services; + +/// The offerings key of the page data block: the same list the public endpoint answers. +public sealed class OfferingsDataContributor(IOfferingsService offerings) : ICmsDataBlockContributor +{ + public string Key => "offerings"; + + public int Order => 100; + + public async Task GetAsync(HtmlTransformContext context, CancellationToken cancellationToken) + => await offerings.GetOfferingsAsync(); +} + +/// The banners key of the page data block: the active top and bottom banner (null when there is none). +public sealed class BannersDataContributor(IOfferingBannersService banners) : ICmsDataBlockContributor +{ + public string Key => "banners"; + + public int Order => 110; + + public async Task GetAsync(HtmlTransformContext context, CancellationToken cancellationToken) + { + var top = await banners.GetActiveAsync(OfferingBannerPositions.Top); + var bottom = await banners.GetActiveAsync(OfferingBannerPositions.Bottom); + return new { top, bottom }; + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs index f1aa52a..f4a1c2f 100644 --- a/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs @@ -18,14 +18,9 @@ public sealed class OfferingsHtmlTransform(IOfferingsService offerings, IOfferin public const string OfferingsRegion = "CMS:OFFERINGS-HTML"; public const string BannerTopRegion = "CMS:BANNER-TOP-HTML"; public const string BannerBottomRegion = "CMS:BANNER-BOTTOM-HTML"; - public const string DataMarker = "CMS:DATA"; - public const string DataBlockId = "cms-data"; public const string JsonLdMarker = "CMS:OFFER-JSON-LD"; public const string PriceAttribute = "data-cms-price"; - // The shape of GET /api/v1/offerings and /offerings/banner: camelCase, nulls written. - private static readonly JsonSerializerOptions ApiJson = new(JsonSerializerDefaults.Web); - private static readonly JsonSerializerOptions LdJson = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, @@ -35,13 +30,11 @@ public sealed class OfferingsHtmlTransform(IOfferingsService offerings, IOfferin public async Task ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken) { - var wantsData = html.Contains("", StringComparison.Ordinal); - var wantsOfferings = wantsData - || html.Contains("", StringComparison.Ordinal) + var wantsOfferings = html.Contains("", StringComparison.Ordinal) || html.Contains("", StringComparison.Ordinal); - var wantsBottom = wantsData || html.Contains("", StringComparison.Ordinal); + var wantsTop = html.Contains("", StringComparison.Ordinal); + var wantsBottom = html.Contains("", StringComparison.Ordinal); var live = wantsOfferings ? await offerings.GetOfferingsAsync() : []; var top = wantsTop ? await banners.GetActiveAsync(OfferingBannerPositions.Top) : null; @@ -65,22 +58,9 @@ public sealed class OfferingsHtmlTransform(IOfferingsService offerings, IOfferin html = HtmlMarkerEditor.ReplaceRegion(html, BannerBottomRegion, CmsPageHtml.Banner(bottom, OfferingBannerPositions.Bottom)); } - if (wantsData) - { - html = HtmlMarkerEditor.ReplaceDataBlock(html, DataMarker, DataBlockId, DataBlock(context.SiteUrl, live, top, bottom)); - } - return html; } - /// The data block: the answers of the public API plus the address of the site, safe inside a script element. - public static string DataBlock(string siteUrl, IReadOnlyList live, PublicOfferingBannerDto? top, PublicOfferingBannerDto? bottom) - { - var json = JsonSerializer.Serialize( - new { siteUrl, offerings = live, banners = new { top, bottom } }, ApiJson); - return ""; - } - private static int? FindPrice(IReadOnlyList live, string slug) => live.FirstOrDefault(o => string.Equals(o.Slug, slug, StringComparison.Ordinal)) is { } offering ? CmsPageHtml.WholeEuros(offering.Price) -- 2.39.5 From 5559d459c37611639c06864abfdfc70223445084 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 16:07:49 +0100 Subject: [PATCH 20/47] H5: admin-scherm voor de hero (formulier, slides, upload, focus-editor met voorbeeld, TypeScript-tweeling van FocusMath) Co-Authored-By: Claude Sonnet 5.5 --- .../features/hero-module/aidlc-state.md | 2 +- .../construction/h5-admin/code/summary.md | 20 ++ frontend/src/components/layout/Sidebar.tsx | 10 +- .../features/hero/components/FocusDialog.tsx | 253 ++++++++++++++ .../src/features/hero/lib/focusMath.test.ts | 61 ++++ frontend/src/features/hero/lib/focusMath.ts | 65 ++++ frontend/src/features/hero/lib/media.ts | 4 + frontend/src/features/hero/mocks/handlers.ts | 126 +++++++ .../src/features/hero/pages/HeroPage.test.tsx | 273 +++++++++++++++ frontend/src/features/hero/pages/HeroPage.tsx | 321 ++++++++++++++++++ .../src/features/hero/schemas/hero.test.ts | 60 ++++ frontend/src/features/hero/schemas/hero.ts | 96 ++++++ frontend/src/features/hero/services/hooks.ts | 51 +++ frontend/src/features/hero/services/types.ts | 83 +++++ .../src/features/system/mocks/handlers.ts | 2 +- frontend/src/i18n/locales/en/translation.json | 99 +++++- frontend/src/i18n/locales/nl/translation.json | 99 +++++- frontend/src/lib/api-client.ts | 6 +- frontend/src/mocks/index.ts | 4 +- frontend/src/router.tsx | 13 + .../HeroInjectionTests.cs | 2 +- 21 files changed, 1635 insertions(+), 15 deletions(-) create mode 100644 aidlc-docs/features/hero-module/construction/h5-admin/code/summary.md create mode 100644 frontend/src/features/hero/components/FocusDialog.tsx create mode 100644 frontend/src/features/hero/lib/focusMath.test.ts create mode 100644 frontend/src/features/hero/lib/focusMath.ts create mode 100644 frontend/src/features/hero/lib/media.ts create mode 100644 frontend/src/features/hero/mocks/handlers.ts create mode 100644 frontend/src/features/hero/pages/HeroPage.test.tsx create mode 100644 frontend/src/features/hero/pages/HeroPage.tsx create mode 100644 frontend/src/features/hero/schemas/hero.test.ts create mode 100644 frontend/src/features/hero/schemas/hero.ts create mode 100644 frontend/src/features/hero/services/hooks.ts create mode 100644 frontend/src/features/hero/services/types.ts diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index 998ffcd..6e346f9 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -53,7 +53,7 @@ - [x] NFR Requirements (construction/nfr-requirements/) - [x] NFR Design (construction/nfr-design/) - [x] Infrastructure Design (media directory; construction/infrastructure-design/) -- [ ] Code Generation - per unit: H0, H1, H2, H3, H4 done; H5 (admin) and H6 (seed, docs, smoke) open +- [ ] Code Generation - per unit: H0 to H5 done; H6 (seed, docs, smoke, LCP measure) open - [ ] Build and Test - EXECUTE ### 🟡 OPERATIONS PHASE - [ ] SKIP (Q19 = B; points go into the joint production checklist) diff --git a/aidlc-docs/features/hero-module/construction/h5-admin/code/summary.md b/aidlc-docs/features/hero-module/construction/h5-admin/code/summary.md new file mode 100644 index 0000000..069207d --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h5-admin/code/summary.md @@ -0,0 +1,20 @@ +# H5 Admin frontend: code summary + +Built 2026-11-16 on `feature/hero-module`. Frontend: 604 of 604 tests pass (73 new), `tsc` and `eslint` are clean. + +| Area | What | +|---|---| +| Navigation | route `/hero` (Owner and Administrator, module `Hero`), sidebar item "Hero", nl and en texts under `hero.*` | +| Screen | `features/hero/pages/HeroPage.tsx`: live or not-live badge (only a badge, Bryan, Q5), title (new line = line break, 5 lines), tagline, lead, display (single or slideshow), two buttons with label and target, schedule (on or off, from, until), slide list | +| Slides | upload (file picker, the server messages on refusal), alt text per slide or decorative, on or off, up and down, remove from the hero, a note when there are more slides than the publication ceiling; the number of slides has no limit in the screen | +| Focus | `FocusDialog`: the photo with a draggable and keyboard-movable focus point (arrow keys, Shift for bigger steps), numeric X and Y, a zoom slider, a general setting plus an optional own setting for the wide and the tall display with a reset, outlines of both crops on the photo and live previews of the two crops | +| Maths | `lib/focusMath.ts` is the twin of the host `FocusMath` (round half up); its tests use the same vectors as the C# tests plus a random check that the crop stays inside the image and holds the focus point | +| Validation | `schemas/hero.ts` (zod): title, tagline, lead, buttons (both or neither, target allow-list twin of the host validator, tested with the same cases), alt text unless decorative, schedule order; error texts are i18n keys in both languages | +| Client | `ApiClient` sends `FormData` as is (multipart upload) | +| Safety | unsaved changes trigger the browser warning when leaving | +| Tests | form, validation, navigation, saving, reorder, remove, switch off, decorative, upload and refused upload, ceiling note, focus dialog (stored values, keyboard, general plus own tall setting, reset, cancel), the shared maths vectors, the target validator cases | + +## Notes + +- Uploaded images that are never saved into a slide are removed by the host clean-up after 7 days; the screen has no separate delete for an image. +- Changing the focus of an image that is live changes the live hero at once (the images are shared by the hero), as the host re-cuts the variants. diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index f1680f3..539798e 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -1,6 +1,6 @@ import { Link } from '@tanstack/react-router'; import { useTranslation } from 'react-i18next'; -import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X } from 'lucide-react'; +import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon } from 'lucide-react'; import type { LucideIcon } from 'lucide-react'; import { cn } from '@/lib/utils'; import { useAuth } from '@/features/auth/context/auth-context'; @@ -29,6 +29,14 @@ const NAV_ITEMS: NavItem[] = [ { to: '/dashboard', labelKey: 'nav.dashboard', icon: LayoutDashboard, testId: 'nav-dashboard' }, { to: '/users', labelKey: 'nav.users', icon: Users, testId: 'nav-users', roles: ['Owner', 'Administrator'] }, { to: '/cms', labelKey: 'nav.cms', icon: FileText, testId: 'nav-cms', roles: ['Owner'], requiredModule: 'Master' }, + { + to: '/hero', + labelKey: 'nav.hero', + icon: ImageIcon, + testId: 'nav-hero', + roles: ['Owner', 'Administrator'], + requiredModule: 'Hero', + }, { to: '/offerings', labelKey: 'nav.offerings', diff --git a/frontend/src/features/hero/components/FocusDialog.tsx b/frontend/src/features/hero/components/FocusDialog.tsx new file mode 100644 index 0000000..af20cff --- /dev/null +++ b/frontend/src/features/hero/components/FocusDialog.tsx @@ -0,0 +1,253 @@ +import { useRef, useState, type KeyboardEvent, type PointerEvent } from 'react'; +import { useTranslation } from 'react-i18next'; +import { toast } from 'sonner'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { FormErrorBanner } from '@/components/ui/FormErrorBanner'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { mediaUrl } from '../lib/media'; +import { CENTRE, MAX_ZOOM, TALL, WIDE, cropFor, normalizeFocus, type Ratio } from '../lib/focusMath'; +import { useSetImageFocus } from '../services/hooks'; +import type { FocusDto, HeroImageDto } from '../services/types'; + +type Target = 'general' | 'wide' | 'tall'; + +interface FocusDialogProps { + /** The image to edit; null = closed. */ + image: HeroImageDto | null; + onClose: () => void; +} + +export function FocusDialog({ image, onClose }: FocusDialogProps) { + const { t } = useTranslation(); + return ( + { if (!next) onClose(); }}> + + + {t('hero.focus.title')} + + {/* Mounted only while open, so every opening starts from the stored values. */} + {image && } + + + ); +} + +const percent = (fraction: number) => Math.round(fraction * 1000) / 10; + +function FocusEditor({ image, onClose }: { image: HeroImageDto; onClose: () => void }) { + const { t } = useTranslation(); + const save = useSetImageFocus(); + const area = useRef(null); + const [serverError, setServerError] = useState(null); + const [target, setTarget] = useState('general'); + const [general, setGeneral] = useState(image.focus ?? CENTRE); + const [wide, setWide] = useState(image.wideFocus); + const [tall, setTall] = useState(image.tallFocus); + + const effective = { wide: wide ?? general, tall: tall ?? general }; + const active: FocusDto = target === 'general' ? general : (target === 'wide' ? wide : tall) ?? general; + const editable = target === 'general' || (target === 'wide' ? wide : tall) !== null; + + const update = (next: FocusDto) => { + const clean = normalizeFocus(next); + if (target === 'general') setGeneral(clean); + else if (target === 'wide') setWide(clean); + else setTall(clean); + }; + + const toggleOverride = (checked: boolean) => { + const value = checked ? { ...general } : null; + if (target === 'wide') setWide(value); + if (target === 'tall') setTall(value); + }; + + const moveTo = (event: PointerEvent) => { + const box = area.current?.getBoundingClientRect(); + if (!box || box.width === 0 || box.height === 0 || !editable) return; + update({ ...active, x: (event.clientX - box.left) / box.width, y: (event.clientY - box.top) / box.height }); + }; + + const onKeyDown = (event: KeyboardEvent) => { + if (!editable) return; + const step = event.shiftKey ? 0.05 : 0.01; + const moves: Record = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }; + const move = moves[event.key]; + if (!move) return; + event.preventDefault(); + update({ ...active, x: active.x + move[0], y: active.y + move[1] }); + }; + + const onSave = async () => { + setServerError(null); + try { + await save.mutateAsync({ imageId: image.id, body: { focus: general, wide, tall } }); + toast.success(t('hero.focus.savedToast')); + onClose(); + } catch (error) { + const message = (error as { problem?: { message?: unknown } }).problem?.message; + setServerError(typeof message === 'string' ? message : t('errors.generic')); + } + }; + + const outline = (ratio: Ratio, focus: FocusDto) => { + const c = cropFor(image.width, image.height, ratio, focus); + return { + left: `${(c.x / image.width) * 100}%`, + top: `${(c.y / image.height) * 100}%`, + width: `${(c.width / image.width) * 100}%`, + height: `${(c.height / image.height) * 100}%`, + }; + }; + + return ( +
+ setServerError(null)} /> +

{t('hero.focus.intro')}

+ +
+ {t('hero.focus.targetLegend')} + {(['general', 'wide', 'tall'] as const).map((value) => ( + + ))} +
+ + {target !== 'general' && ( + + )} + +
+
+
{ + event.currentTarget.setPointerCapture?.(event.pointerId); + moveTo(event); + }} + onPointerMove={(event) => { + if (event.buttons === 1) moveTo(event); + }} + onKeyDown={onKeyDown} + data-testid="focus-area" + > + +
+
+
+
+

{t('hero.focus.areaHint')}

+
+ +
+
+
+ + update({ ...active, x: Number(event.target.value) / 100 })} + data-testid="focus-x" + /> +
+
+ + update({ ...active, y: Number(event.target.value) / 100 })} + data-testid="focus-y" + /> +
+
+
+ + update({ ...active, zoom: Number(event.target.value) })} + className="w-full" + data-testid="focus-zoom" + /> +
+ + {([WIDE, TALL] as const).map((ratio) => { + const crop = cropFor(image.width, image.height, ratio, effective[ratio.name]); + return ( +
+

{t(`hero.focus.preview.${ratio.name}`)}

+
+ +
+
+ ); + })} +
+
+ +
+ + +
+
+ ); +} diff --git a/frontend/src/features/hero/lib/focusMath.test.ts b/frontend/src/features/hero/lib/focusMath.test.ts new file mode 100644 index 0000000..39ba846 --- /dev/null +++ b/frontend/src/features/hero/lib/focusMath.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest'; +import { CENTRE, TALL, WIDE, cropFor, normalizeFocus, roundHalfUp } from './focusMath'; + +// The same vectors as src/SlpModularCms.Core.Tests/Media/MediaPureFunctionTests.cs (FocusMathTests.KnownVectors). +const vectors: [number, number, 'wide' | 'tall', number, number, number, [number, number, number, number]][] = [ + [1600, 1067, 'wide', 0.5, 0.5, 1.0, [0, 0, 1600, 1067]], + [1600, 1067, 'tall', 0.5, 0.5, 1.0, [374, 1, 853, 1066]], + [1600, 1067, 'tall', 0.0, 0.5, 1.0, [0, 1, 853, 1066]], + [1600, 1067, 'tall', 1.0, 0.5, 1.0, [747, 1, 853, 1066]], + [1600, 1067, 'wide', 0.45, 0.35, 2.0, [320, 107, 800, 533]], + [2560, 1702, 'tall', 0.55, 0.6, 1.0, [728, 1, 1361, 1701]], + [1000, 2000, 'wide', 0.5, 0.5, 1.0, [0, 667, 1000, 667]], +]; + +describe('cropFor', () => { + it.each(vectors)('%i x %i %s at (%d, %d) zoom %d', (w, h, ratio, x, y, zoom, [cx, cy, cw, ch]) => { + expect(cropFor(w, h, ratio === 'tall' ? TALL : WIDE, { x, y, zoom })).toEqual({ x: cx, y: cy, width: cw, height: ch }); + }); + + it('always stays inside the image and keeps the focus point inside the crop', () => { + for (let i = 0; i < 2000; i++) { + const w = 1 + Math.floor(Math.random() * 6000); + const h = 1 + Math.floor(Math.random() * 6000); + const focus = { x: Math.random(), y: Math.random(), zoom: 1 + Math.random() * 3 }; + for (const ratio of [WIDE, TALL]) { + const c = cropFor(w, h, ratio, focus); + expect(c.x).toBeGreaterThanOrEqual(0); + expect(c.y).toBeGreaterThanOrEqual(0); + expect(c.x + c.width).toBeLessThanOrEqual(w); + expect(c.y + c.height).toBeLessThanOrEqual(h); + expect(focus.x * w).toBeGreaterThanOrEqual(c.x - 1); + expect(focus.x * w).toBeLessThanOrEqual(c.x + c.width + 1); + expect(focus.y * h).toBeGreaterThanOrEqual(c.y - 1); + expect(focus.y * h).toBeLessThanOrEqual(c.y + c.height + 1); + } + } + }); + + it('survives values that are out of range or not numbers', () => { + const c = cropFor(1600, 1067, TALL, { x: Number.NaN, y: Infinity, zoom: -Infinity }); + expect(c.x).toBeGreaterThanOrEqual(0); + expect(c.x + c.width).toBeLessThanOrEqual(1600); + }); + + it('rejects an image without a size', () => { + expect(() => cropFor(0, 100, WIDE, CENTRE)).toThrow(RangeError); + }); +}); + +describe('normalizeFocus and roundHalfUp', () => { + it('clamps and defaults', () => { + expect(normalizeFocus({ x: -1, y: 2, zoom: 9 })).toEqual({ x: 0, y: 1, zoom: 4 }); + expect(normalizeFocus({ x: Number.NaN, y: Number.NaN, zoom: Number.NaN })).toEqual({ x: 0.5, y: 0.5, zoom: 1 }); + }); + + it('rounds .5 up like the host', () => { + expect(roundHalfUp(373.5)).toBe(374); + expect(roundHalfUp(0.5)).toBe(1); + expect(roundHalfUp(2.4)).toBe(2); + }); +}); diff --git a/frontend/src/features/hero/lib/focusMath.ts b/frontend/src/features/hero/lib/focusMath.ts new file mode 100644 index 0000000..ebe4d3f --- /dev/null +++ b/frontend/src/features/hero/lib/focusMath.ts @@ -0,0 +1,65 @@ +import type { FocusDto } from '../services/types'; + +/** A named aspect ratio (width:height). The same two as the host cuts. */ +export interface Ratio { + name: 'wide' | 'tall'; + numerator: number; + denominator: number; +} + +export const WIDE: Ratio = { name: 'wide', numerator: 3, denominator: 2 }; +export const TALL: Ratio = { name: 'tall', numerator: 4, denominator: 5 }; + +export const MAX_ZOOM = 4; +export const CENTRE: FocusDto = { x: 0.5, y: 0.5, zoom: 1 }; + +export interface CropRect { + x: number; + y: number; + width: number; + height: number; +} + +/** Rounds .5 up, like the host (C# FocusMath.RoundHalfUp), so the preview is the same crop as the stored file. */ +export const roundHalfUp = (value: number): number => Math.floor(value + 0.5); + +const clamp = (value: number, min: number, max: number): number => Math.min(Math.max(value, min), max); + +/** Clamps every value into its valid range; anything that is not a number becomes the default. */ +export function normalizeFocus(focus: FocusDto): FocusDto { + const finite = (v: number, fallback: number) => (Number.isNaN(v) ? fallback : v); + return { + x: clamp(finite(focus.x, 0.5), 0, 1), + y: clamp(finite(focus.y, 0.5), 0, 1), + zoom: clamp(finite(focus.zoom, 1), 1, MAX_ZOOM), + }; +} + +/** + * The crop for a ratio around a focus point: the largest rectangle of the ratio that fits the image, shrunk by the + * zoom, centred on the point and moved the smallest amount needed to stay inside. Twin of the host's C# `FocusMath`; + * `focusMath.test.ts` and the C# tests share their vectors. + */ +export function cropFor(imageWidth: number, imageHeight: number, ratio: Ratio, focus: FocusDto): CropRect { + if (imageWidth <= 0 || imageHeight <= 0) { + throw new RangeError('The image must have a size.'); + } + + const f = normalizeFocus(focus); + // The largest crop of the ratio inside the image: as wide as the image, or as high as the image. + const cw0 = + imageWidth * ratio.denominator > imageHeight * ratio.numerator + ? (imageHeight * ratio.numerator) / ratio.denominator + : imageWidth; + + let cw = clamp(Math.floor(cw0 / f.zoom), 1, imageWidth); + let ch = Math.max(1, roundHalfUp((cw * ratio.denominator) / ratio.numerator)); + if (ch > imageHeight) { + ch = imageHeight; + cw = clamp(Math.floor((ch * ratio.numerator) / ratio.denominator), 1, imageWidth); + } + + const x = clamp(roundHalfUp(f.x * imageWidth - cw / 2), 0, imageWidth - cw); + const y = clamp(roundHalfUp(f.y * imageHeight - ch / 2), 0, imageHeight - ch); + return { x, y, width: cw, height: ch }; +} diff --git a/frontend/src/features/hero/lib/media.ts b/frontend/src/features/hero/lib/media.ts new file mode 100644 index 0000000..8d772e7 --- /dev/null +++ b/frontend/src/features/hero/lib/media.ts @@ -0,0 +1,4 @@ +import { getAppConfig } from '@/lib/config'; + +/** A media address of the host (/media/...) as the browser must request it from the admin. */ +export const mediaUrl = (path: string): string => `${getAppConfig().apiBaseUrl.replace(/\/$/, '')}${path}`; diff --git a/frontend/src/features/hero/mocks/handlers.ts b/frontend/src/features/hero/mocks/handlers.ts new file mode 100644 index 0000000..daf5a60 --- /dev/null +++ b/frontend/src/features/hero/mocks/handlers.ts @@ -0,0 +1,126 @@ +import { http, HttpResponse } from 'msw'; +import { API_BASE } from '@/features/auth/mocks/fixtures'; +import type { FocusDto, HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types'; + +const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({ + id, + width, + height, + focus: { x: 0.5, y: 0.5, zoom: 1 }, + wideFocus: null, + tallFocus: null, + src: `/media/hero/0123456789abcdef/wide-${width}.webp`, + variants: [ + { ratio: 'wide', width: 960, height: 640, type: 'image/webp', url: '/media/hero/0123456789abcdef/wide-960.webp' }, + { ratio: 'wide', width, height, type: 'image/webp', url: `/media/hero/0123456789abcdef/wide-${width}.webp` }, + { ratio: 'tall', width: 640, height: 800, type: 'image/webp', url: '/media/hero/0123456789abcdef/tall-640.webp' }, + ], +}); + +export const emptyHero = (): HeroAdminDto => ({ + id: null, + title: '', + tagline: null, + lead: null, + display: 'single', + buttons: [], + isActive: true, + startsAt: null, + endsAt: null, + slides: [], + isLive: false, + updatedAt: null, + maxPublishedSlides: 50, +}); + +export const slide = (index: number, over: Partial = {}): HeroSlideAdminDto => ({ + id: `00000000-0000-0000-0000-00000000000${index}`, + imageId: `10000000-0000-0000-0000-00000000000${index}`, + alt: `Foto ${index}`, + decorative: false, + isActive: true, + sortOrder: index - 1, + image: seedImage(`10000000-0000-0000-0000-00000000000${index}`), + ...over, +}); + +let hero: HeroAdminDto = emptyHero(); +let images: Record = {}; +let saved: HeroSaveRequest[] = []; +let uploads = 0; +let uploadFailure: { status: number; error: string; message: string } | null = null; + +export const resetMockHero = (): void => { + hero = emptyHero(); + images = {}; + saved = []; + uploads = 0; + uploadFailure = null; +}; + +export const setMockHero = (next: HeroAdminDto): void => { + hero = next; + images = Object.fromEntries(next.slides.map((s) => [s.imageId, s.image])); +}; + +export const getSavedHeroRequests = (): HeroSaveRequest[] => saved; + +export const failNextUpload = (failure: { status: number; error: string; message: string } | null): void => { + uploadFailure = failure; +}; + +export const heroHandlers = [ + http.get(`${API_BASE}/api/v1/hero/all`, () => HttpResponse.json(hero)), + + http.put(`${API_BASE}/api/v1/hero`, async ({ request }) => { + const body = (await request.json()) as HeroSaveRequest; + saved.push(body); + hero = { + ...hero, + id: hero.id ?? '99999999-9999-9999-9999-999999999999', + title: body.title, + tagline: body.tagline, + lead: body.lead, + display: body.display, + buttons: body.buttons, + isActive: body.isActive, + startsAt: body.startsAt, + endsAt: body.endsAt, + isLive: body.isActive && body.title.trim() !== '', + updatedAt: '2026-11-16T12:00:00Z', + slides: body.slides.map((s, i) => ({ + id: s.id ?? `20000000-0000-0000-0000-00000000000${i}`, + imageId: s.imageId, + alt: s.alt ?? '', + decorative: s.decorative, + isActive: s.isActive, + sortOrder: i, + image: images[s.imageId] ?? seedImage(s.imageId), + })), + }; + return HttpResponse.json(hero); + }), + + http.post(`${API_BASE}/api/v1/hero/images`, () => { + if (uploadFailure) { + const { status, error, message } = uploadFailure; + uploadFailure = null; + return HttpResponse.json({ error, message }, { status }); + } + uploads += 1; + const image = seedImage(`30000000-0000-0000-0000-00000000000${uploads}`); + images[image.id] = image; + return HttpResponse.json(image, { status: 201 }); + }), + + http.put(`${API_BASE}/api/v1/hero/images/:id/focus`, async ({ params, request }) => { + const body = (await request.json()) as HeroFocusRequest; + const id = String(params.id); + const current = images[id] ?? hero.slides.find((s) => s.imageId === id)?.image ?? seedImage(id); + const asDto = (f: FocusDto | null) => (f ? { ...f } : null); + const next: HeroImageDto = { ...current, focus: body.focus, wideFocus: asDto(body.wide), tallFocus: asDto(body.tall) }; + images[id] = next; + hero = { ...hero, slides: hero.slides.map((s) => (s.imageId === id ? { ...s, image: next } : s)) }; + return HttpResponse.json(next); + }), +]; diff --git a/frontend/src/features/hero/pages/HeroPage.test.tsx b/frontend/src/features/hero/pages/HeroPage.test.tsx new file mode 100644 index 0000000..7848137 --- /dev/null +++ b/frontend/src/features/hero/pages/HeroPage.test.tsx @@ -0,0 +1,273 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { fireEvent, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { renderApp, mockAuthenticated } from '@/test/utils'; +import { emptyHero, failNextUpload, getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers'; +import { _resetSetupStatusCache } from '@/router'; + +const T = { timeout: 10000 }; + +beforeEach(() => { + _resetSetupStatusCache(); + resetMockHero(); +}); + +async function openPage() { + mockAuthenticated(); + renderApp('/hero'); + return screen.findByTestId('hero-form', {}, T); +} + +describe('Hero page', () => { + it('shows an empty form and the not-live badge when there is no hero yet', async () => { + await openPage(); + + expect(screen.getByTestId('hero-live-badge')).toHaveTextContent(/Niet live|Not live/); + expect(screen.getByTestId('hero-slides-empty')).toBeInTheDocument(); + expect(screen.getByTestId('hero-title-input')).toHaveValue(''); + expect(screen.getByTestId('hero-display-single')).toBeChecked(); + }); + + it('is reachable from the navigation for an administrator', async () => { + mockAuthenticated(); + renderApp('/dashboard'); + + await userEvent.click(await screen.findByTestId('nav-hero', {}, T)); + + expect(await screen.findByTestId('hero-form', {}, T)).toBeInTheDocument(); + }); + + it('saves the texts, the buttons and the schedule, and shows the hero as live', async () => { + await openPage(); + + await userEvent.type(screen.getByTestId('hero-title-input'), 'Websites,{enter}apps{enter}& meer.'); + await userEvent.type(screen.getByTestId('hero-lead'), 'Een lead.'); + await userEvent.click(screen.getByTestId('hero-display-slideshow')); + await userEvent.type(screen.getByTestId('hero-button-0-label'), 'Bekijk pakketten'); + await userEvent.type(screen.getByTestId('hero-button-0-target'), '#pakketten'); + await userEvent.type(screen.getByTestId('hero-button-1-label'), 'Plan een gesprek'); + await userEvent.type(screen.getByTestId('hero-button-1-target'), '#contact'); + await userEvent.click(screen.getByTestId('hero-save')); + + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + expect(getSavedHeroRequests()[0]).toMatchObject({ + title: 'Websites,\napps\n& meer.', + tagline: null, + lead: 'Een lead.', + display: 'slideshow', + buttons: [ + { label: 'Bekijk pakketten', target: '#pakketten' }, + { label: 'Plan een gesprek', target: '#contact' }, + ], + isActive: true, + startsAt: null, + endsAt: null, + slides: [], + }); + }); + + it('does not save without a title and says why', async () => { + await openPage(); + + await userEvent.click(screen.getByTestId('hero-save')); + + expect(await screen.findByTestId('hero-title-error')).toHaveTextContent(/Een titel is verplicht\.|A title is required\./); + expect(getSavedHeroRequests()).toHaveLength(0); + }); + + it.each([ + ['javascript:alert(1)', 'hero-button-0-target-error', /Kies een #anker|Choose an #anchor/], + ['//evil.example', 'hero-button-0-target-error', /Kies een #anker|Choose an #anchor/], + ['http://example.com', 'hero-button-0-target-error', /Kies een #anker|Choose an #anchor/], + ])('rejects the button target %s', async (target, errorId, message) => { + await openPage(); + await userEvent.type(screen.getByTestId('hero-title-input'), 'Titel'); + await userEvent.type(screen.getByTestId('hero-button-0-label'), 'Knop'); + await userEvent.type(screen.getByTestId('hero-button-0-target'), target); + + await userEvent.click(screen.getByTestId('hero-save')); + + expect(await screen.findByTestId(errorId)).toHaveTextContent(message); + expect(getSavedHeroRequests()).toHaveLength(0); + }); + + it('wants a button text and a target together', async () => { + await openPage(); + await userEvent.type(screen.getByTestId('hero-title-input'), 'Titel'); + await userEvent.type(screen.getByTestId('hero-button-1-label'), 'Alleen een tekst'); + + await userEvent.click(screen.getByTestId('hero-save')); + + expect(await screen.findByTestId('hero-button-1-target-error')).toHaveTextContent(/Vul zowel de tekst als het doel|Fill in both the text and the target/); + }); + + it('wants the end after the start', async () => { + await openPage(); + await userEvent.type(screen.getByTestId('hero-title-input'), 'Titel'); + fireEvent.change(screen.getByTestId('hero-starts'), { target: { value: '2026-12-10T10:00' } }); + fireEvent.change(screen.getByTestId('hero-ends'), { target: { value: '2026-12-01T10:00' } }); + + await userEvent.click(screen.getByTestId('hero-save')); + + expect(await screen.findByTestId('hero-ends-error')).toHaveTextContent(/Het einde moet na het begin liggen\.|The end must be after the start\./); + }); +}); + +describe('Slides', () => { + const withTwoSlides = () => + setMockHero({ ...emptyHero(), id: 'h1', title: 'Andrea Slop', isLive: true, updatedAt: '2026-11-16T12:00:00Z', slides: [slide(1), slide(2)] }); + + it('lists the saved slides with their description, and the live badge', async () => { + withTwoSlides(); + + await openPage(); + + expect(screen.getByTestId('hero-live-badge')).toHaveTextContent(/^(Live)$/); + expect(screen.getByTestId('hero-slide-0-alt')).toHaveValue('Foto 1'); + expect(screen.getByTestId('hero-slide-1-alt')).toHaveValue('Foto 2'); + }); + + it('reorders slides and saves the new order with the slide ids', async () => { + withTwoSlides(); + await openPage(); + + await userEvent.click(screen.getByTestId('hero-slide-1-up')); + await userEvent.click(screen.getByTestId('hero-save')); + + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + const { slides } = getSavedHeroRequests()[0]; + expect(slides.map((s) => s.alt)).toEqual(['Foto 2', 'Foto 1']); + expect(slides[0].id).toBe('00000000-0000-0000-0000-000000000002'); + }); + + it('cannot move the first slide up or the last one down', async () => { + withTwoSlides(); + await openPage(); + + expect(screen.getByTestId('hero-slide-0-up')).toBeDisabled(); + expect(screen.getByTestId('hero-slide-1-down')).toBeDisabled(); + }); + + it('removes a slide from the hero, switches one off and marks one decorative', async () => { + withTwoSlides(); + await openPage(); + + await userEvent.click(screen.getByTestId('hero-slide-1-remove')); + await userEvent.click(screen.getByTestId('hero-slide-0-active')); + await userEvent.click(screen.getByTestId('hero-slide-0-decorative')); + expect(screen.getByTestId('hero-slide-0-alt')).toBeDisabled(); + await userEvent.click(screen.getByTestId('hero-save')); + + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + expect(getSavedHeroRequests()[0].slides).toEqual([ + { id: '00000000-0000-0000-0000-000000000001', imageId: '10000000-0000-0000-0000-000000000001', alt: null, decorative: true, isActive: false }, + ]); + }); + + it('adds an uploaded image as a slide that needs a description before it can be saved', async () => { + withTwoSlides(); + await openPage(); + + await userEvent.upload(screen.getByTestId('hero-upload'), new File(['x'], 'foto.jpg', { type: 'image/jpeg' })); + expect(await screen.findByTestId('hero-slide-2')).toBeInTheDocument(); + await userEvent.click(screen.getByTestId('hero-save')); + + expect(await screen.findByTestId('hero-slide-2-alt-error')).toHaveTextContent(/Geef een beschrijving|Give a description/); + expect(getSavedHeroRequests()).toHaveLength(0); + + await userEvent.type(screen.getByTestId('hero-slide-2-alt'), 'Nieuwe foto'); + await userEvent.click(screen.getByTestId('hero-save')); + + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + const slides = getSavedHeroRequests()[0].slides; + expect(slides).toHaveLength(3); + expect(slides[2]).toMatchObject({ id: null, alt: 'Nieuwe foto', decorative: false, isActive: true }); + }); + + it('shows the message of the server when an upload is refused', async () => { + await openPage(); + failNextUpload({ status: 400, error: 'unsupported_format', message: 'Dit bestandstype wordt niet ondersteund.' }); + + await userEvent.upload(screen.getByTestId('hero-upload'), new File(['x'], 'x.svg', { type: 'image/svg+xml' })); + + expect(await screen.findByTestId('hero-upload-error')).toHaveTextContent('Dit bestandstype wordt niet ondersteund.'); + expect(screen.getByTestId('hero-slides-empty')).toBeInTheDocument(); + }); + + it('notes that only the first slides are published when there are more than the ceiling', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', maxPublishedSlides: 1, slides: [slide(1), slide(2)] }); + + await openPage(); + + expect(screen.getByTestId('hero-ceiling-note')).toHaveTextContent(/Alleen de eerste 1 afbeeldingen|Only the first 1 images/); + }); +}); + +describe('Focus dialog', () => { + const open = async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'Andrea Slop', isLive: true, slides: [slide(1)] }); + await openPage(); + await userEvent.click(screen.getByTestId('hero-slide-0-focus')); + return screen.findByTestId('focus-dialog'); + }; + + it('starts with the stored point and shows both previews', async () => { + await open(); + + expect(screen.getByTestId('focus-x')).toHaveValue(50); + expect(screen.getByTestId('focus-y')).toHaveValue(50); + expect(screen.getByTestId('focus-preview-wide')).toBeInTheDocument(); + expect(screen.getByTestId('focus-preview-tall')).toBeInTheDocument(); + }); + + it('moves the point with the keyboard', async () => { + await open(); + + const area = screen.getByTestId('focus-area'); + area.focus(); + await userEvent.keyboard('{ArrowRight}{ArrowRight}{Shift>}{ArrowDown}{/Shift}'); + + expect(screen.getByTestId('focus-x')).toHaveValue(52); + expect(screen.getByTestId('focus-y')).toHaveValue(55); + }); + + it('saves a general point and an own setting for the tall display', async () => { + await open(); + + fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '30' } }); + await userEvent.click(screen.getByTestId('focus-target-tall')); + expect(screen.getByTestId('focus-x')).toBeDisabled(); + await userEvent.click(screen.getByTestId('focus-override-tall')); + fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '80' } }); + fireEvent.change(screen.getByTestId('focus-zoom'), { target: { value: '2' } }); + await userEvent.click(screen.getByTestId('focus-save')); + + await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument()); + // The dialog closed after the server accepted it; reopening shows the stored values. + await userEvent.click(screen.getByTestId('hero-slide-0-focus')); + expect(screen.getByTestId('focus-x')).toHaveValue(30); + await userEvent.click(screen.getByTestId('focus-target-tall')); + expect(screen.getByTestId('focus-override-tall')).toBeChecked(); + expect(screen.getByTestId('focus-x')).toHaveValue(80); + expect(screen.getByTestId('focus-zoom')).toHaveValue('2'); + }); + + it('goes back to the general point when the own setting is switched off', async () => { + await open(); + await userEvent.click(screen.getByTestId('focus-target-wide')); + await userEvent.click(screen.getByTestId('focus-override-wide')); + fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '10' } }); + await userEvent.click(screen.getByTestId('focus-override-wide')); + + expect(screen.getByTestId('focus-x')).toHaveValue(50); + expect(screen.getByTestId('focus-x')).toBeDisabled(); + }); + + it('closes without saving', async () => { + await open(); + + await userEvent.click(screen.getByTestId('focus-cancel')); + + await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument()); + }); +}); diff --git a/frontend/src/features/hero/pages/HeroPage.tsx b/frontend/src/features/hero/pages/HeroPage.tsx new file mode 100644 index 0000000..dba105f --- /dev/null +++ b/frontend/src/features/hero/pages/HeroPage.tsx @@ -0,0 +1,321 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { useFieldArray, useForm, useWatch } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { useTranslation } from 'react-i18next'; +import { toast } from 'sonner'; +import { ArrowDown, ArrowUp, Crosshair, ImagePlus, Trash2 } from 'lucide-react'; +import { Badge } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { FieldError } from '@/components/ui/FieldError'; +import { FormErrorBanner } from '@/components/ui/FormErrorBanner'; +import { NetworkError, ProblemDetailsError } from '@/lib/api-client'; +import { FocusDialog } from '../components/FocusDialog'; +import { mediaUrl } from '../lib/media'; +import { fromLocalInput, heroFormSchema, toLocalInput, type HeroFormData } from '../schemas/hero'; +import { useHero, useSaveHero, useUploadHeroImage } from '../services/hooks'; +import type { HeroAdminDto, HeroImageDto, HeroSaveRequest } from '../services/types'; + +const textareaClass = + 'w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; + +function toForm(hero: HeroAdminDto): HeroFormData { + const buttons = [0, 1].map((i) => ({ label: hero.buttons[i]?.label ?? '', target: hero.buttons[i]?.target ?? '' })); + return { + title: hero.title, + tagline: hero.tagline ?? '', + lead: hero.lead ?? '', + display: hero.display, + buttons, + isActive: hero.isActive, + startsAt: toLocalInput(hero.startsAt), + endsAt: toLocalInput(hero.endsAt), + slides: hero.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.alt, decorative: s.decorative, isActive: s.isActive })), + }; +} + +function toRequest(values: HeroFormData): HeroSaveRequest { + return { + title: values.title, + tagline: values.tagline || null, + lead: values.lead || null, + display: values.display, + buttons: values.buttons.filter((b) => b.label !== '' && b.target !== ''), + isActive: values.isActive, + startsAt: fromLocalInput(values.startsAt), + endsAt: fromLocalInput(values.endsAt), + slides: values.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.decorative ? null : s.alt, decorative: s.decorative, isActive: s.isActive })), + }; +} + +/** The messages a failed save carries: the field errors of a 400, or a generic text. */ +function serverMessage(error: unknown, generic: string, network: string): string { + if (error instanceof NetworkError) return network; + if (error instanceof ProblemDetailsError && error.status === 400) { + const errors = error.problem.errors; + if (errors && typeof errors === 'object') { + const messages = Object.values(errors as Record).flatMap((v) => (Array.isArray(v) ? v : [v])).filter((v): v is string => typeof v === 'string'); + if (messages.length > 0) return messages.join(' '); + } + } + return generic; +} + +/** The smallest WebP of the wide ratio for a thumbnail; the plain source when there is none. */ +function thumbnail(image: HeroImageDto): string { + const small = image.variants + .filter((v) => v.type === 'image/webp' && v.ratio === 'wide') + .sort((a, b) => a.width - b.width)[0]; + return mediaUrl(small?.url ?? image.src); +} + +export function HeroPage() { + const { t } = useTranslation(); + const { data: hero, isLoading, isError, refetch } = useHero(); + + return ( +
+
+

{t('hero.title')}

+ {hero && ( + + {hero.isLive ? t('hero.live') : t('hero.notLive')} + + )} +
+

{t('hero.intro')}

+ + {isLoading &&

{t('common.loading')}

} + {isError && ( +
+

{t('errors.generic')}

+ +
+ )} + {hero && } +
+ ); +} + +function HeroEditor({ hero }: { hero: HeroAdminDto }) { + const { t } = useTranslation(); + const save = useSaveHero(); + const upload = useUploadHeroImage(); + const [serverError, setServerError] = useState(null); + const [uploadError, setUploadError] = useState(null); + const [localImages, setLocalImages] = useState>({}); + const [focusImageId, setFocusImageId] = useState(null); + const fileInput = useRef(null); + + const { + register, + handleSubmit, + control, + formState: { errors, isDirty }, + } = useForm({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', defaultValues: toForm(hero) }); + const slides = useFieldArray({ control, name: 'slides' }); + const watchedSlides = useWatch({ control, name: 'slides' }) ?? []; + + // The images of the saved hero (always current: a change of focus refreshes them) plus the ones uploaded in this session. + const images = useMemo(() => { + const map: Record = { ...localImages }; + for (const s of hero.slides) map[s.imageId] = s.image; + return map; + }, [hero.slides, localImages]); + + useEffect(() => { + if (!isDirty) return undefined; + const warn = (event: BeforeUnloadEvent) => { + event.preventDefault(); + }; + window.addEventListener('beforeunload', warn); + return () => window.removeEventListener('beforeunload', warn); + }, [isDirty]); + + const onUpload = async (files: FileList | null) => { + const file = files?.[0]; + if (!file) return; + setUploadError(null); + try { + const image = await upload.mutateAsync(file); + setLocalImages((current) => ({ ...current, [image.id]: image })); + slides.append({ id: null, imageId: image.id, alt: '', decorative: false, isActive: true }, { shouldFocus: false }); + } catch (error) { + const message = error instanceof ProblemDetailsError ? error.problem.message : undefined; + setUploadError(typeof message === 'string' ? message : error instanceof NetworkError ? t('errors.network') : t('errors.generic')); + } finally { + if (fileInput.current) fileInput.current.value = ''; + } + }; + + const onSubmit = async (values: HeroFormData) => { + setServerError(null); + try { + await save.mutateAsync(toRequest(values)); + toast.success(t('hero.savedToast')); + } catch (error) { + setServerError(serverMessage(error, t('errors.generic'), t('errors.network'))); + } + }; + + const err = (message?: string) => (message ? t(message) : undefined); + const heroErrors = errors; + + return ( +
+ setServerError(null)} /> + +
+
+ +