Merge origin/master into feature/messages-badge
Continuous Integration / config-asf (pull_request) Successful in 7s
Continuous Integration / config-sls (pull_request) Successful in 8s
Continuous Integration / changes (pull_request) Successful in 11s
Continuous Integration / backend-build (pull_request) Successful in 1m46s
Continuous Integration / compile-sites (pull_request) Successful in 1m51s
Continuous Integration / frontend-prepare (pull_request) Successful in 1m57s
Continuous Integration / vulnerability-scan (pull_request) Successful in 2m2s
Continuous Integration / frontend-build (pull_request) Successful in 43s
Continuous Integration / frontend-test (pull_request) Successful in 2m30s
Continuous Integration / backend-test (pull_request) Successful in 2m43s
Continuous Integration / frontend-lint (pull_request) Successful in 2m28s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 12:58:12 +01:00
co-authored by Claude Sonnet 5.5
180 changed files with 17199 additions and 193 deletions
+11 -7
View File
@@ -228,20 +228,24 @@ jobs:
systemctl --user restart ${{ inputs.service_name }}"
# Verifies the restart actually produced a healthy process before this run is allowed to
# report success. Retries absorb ordinary process-startup time; a run that never turns healthy
# fails the job without touching `current` or pruning (see below) — no automatic rollback.
# A previous release is always still on disk to restore from manually (D-26).
# report success. Retries absorb process-startup time, which is about 10 seconds normally but
# 30 seconds or more when the host is busy (a migration step, two services restarting at once
# on one machine): up to 40 attempts, 3 seconds apart (about 2 minutes), each request limited
# to 5 seconds so one hanging attempt cannot eat the whole window. A run that never turns
# healthy fails the job without touching `current` or pruning (see below) - no automatic
# rollback. A previous release is always still on disk to restore from manually (D-26).
- name: Verify /health
run: |
for attempt in $(seq 1 10); do
if curl -f -s -o /dev/null "${{ inputs.health_check_url }}"; then
attempts=40
for attempt in $(seq 1 $attempts); do
if curl -f -s --max-time 5 -o /dev/null "${{ inputs.health_check_url }}"; then
echo "Health check passed on attempt $attempt"
exit 0
fi
echo "Health check attempt $attempt failed, retrying..."
echo "Health check attempt $attempt of $attempts failed, retrying..."
sleep 3
done
echo "Health check did not pass after 10 attempts"
echo "Health check did not pass after $attempts attempts"
exit 1
# Retention: keep `current` plus exactly one previous release, so a manual rollback is always
+3
View File
@@ -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",
@@ -14,6 +15,8 @@
"src\\SlpModularCms.Api.Tests\\SlpModularCms.Api.Tests.csproj",
"src\\SlpModularCms.Modules.Offerings\\SlpModularCms.Modules.Offerings.csproj",
"src\\SlpModularCms.Modules.Offerings.Tests\\SlpModularCms.Modules.Offerings.Tests.csproj",
"src\\SlpModularCms.Modules.Hero\\SlpModularCms.Modules.Hero.csproj",
"src\\SlpModularCms.Modules.Hero.Tests\\SlpModularCms.Modules.Hero.Tests.csproj",
"src\\SlpModularCms.Modules.Contact\\SlpModularCms.Modules.Contact.csproj",
"src\\SlpModularCms.Modules.Contact.Tests\\SlpModularCms.Modules.Contact.Tests.csproj"
]
+45
View File
@@ -44,6 +44,12 @@ 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
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Hero", "src\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj", "{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Hero.Tests", "src\SlpModularCms.Modules.Hero.Tests\SlpModularCms.Modules.Hero.Tests.csproj", "{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -258,6 +264,42 @@ 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
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|x64.ActiveCfg = Debug|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|x64.Build.0 = Debug|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|x86.ActiveCfg = Debug|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Debug|x86.Build.0 = Debug|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|Any CPU.Build.0 = Release|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|x64.ActiveCfg = Release|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|x64.Build.0 = Release|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|x86.ActiveCfg = Release|Any CPU
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867}.Release|x86.Build.0 = Release|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|x64.ActiveCfg = Debug|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|x64.Build.0 = Debug|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|x86.ActiveCfg = Debug|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Debug|x86.Build.0 = Debug|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|Any CPU.Build.0 = Release|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x64.ActiveCfg = Release|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x64.Build.0 = Release|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x86.ActiveCfg = Release|Any CPU
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -282,5 +324,8 @@ 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}
{4A7E3360-C7D0-4ADF-BC98-79AA912A8867} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
{838B2DA6-8B01-4C83-A696-D910AB2BC5D9} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
EndGlobalSection
EndGlobal
+2
View File
@@ -24,3 +24,5 @@
| 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) | ✅ Afgesloten 2026-11-17 (Build and Test gesloten, Operations in de gezamenlijke productie-checklist 4b; op test door Bryan geaccepteerd; merge naar master via SLS-Main, productie wacht op Bryans go) | feature/hero-module | Modules (new Hero), Core (Hosting/Website, host injection), CI (release/-regel voor SLS-productie), Frontend (admin) | 2026-11-16 |
| Feature | [Mediabibliotheek (media-library)](features/media-library/overview.md) | ⚪ Gepland (volgt na de Hero-merge; nog geen AI-DLC-stappen) | n.v.t. | Core (Media), Modules.Hero, later gallerij-module, Frontend (admin) | 2026-11-17 |
@@ -0,0 +1,59 @@
# 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**: CLOSED 2026-11-17 (Build and Test closed; Operations in the joint production checklist; merge to master by SLS-Main after green PR checks)
- **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 | Yes (blocking) | Requirements Analysis (Q17 = A) |
| Property-Based Testing | Partial (pure functions and round-trips) | Requirements Analysis (Q18 = B) |
## Operations Configuration
- **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)
- [x] Requirements Analysis (approved by Bryan 2026-11-16)
- [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)
- [x] Units Generation (unit-of-work.md, -dependency.md, -story-map.md; plan answered 2026-11-16)
### 🟢 CONSTRUCTION PHASE
- [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/)
- [x] Code Generation - H0 to H6 built (LCP measurement on the test hosts is part of Build and Test)
- [x] Build and Test - closed 2026-11-17 (construction/build-and-test/build-and-test-summary.md)
### 🟡 OPERATIONS PHASE
- [x] SKIP (Q19 = B; points are in section 4b of docs/release-checklist-productie.md)
@@ -0,0 +1,48 @@
# Assumptions and deferred questions: hero-module
Kept while Bryan was away (2026-11-16): no questions to him, a likely assumption or an easy-to-change placeholder instead. Per item: the question, the assumption made, what changes if Bryan chooses differently, and where in the code. To be put to Bryan by the SLS session.
| # | Question | Assumption made | If Bryan chooses differently | Where |
|---|---|---|---|---|
| 1 | Does a change of the **focus** of an image that is already live take effect at once? | **Decided by Bryan (2026-11-16): no, only when the hero is saved.** The admin keeps it locally (Apply in the focus dialog), sends it with the save (`imageFocus`), the host then cuts the variants again into new files and saves hero and images together; leaving the page drops it. | n/a | `HeroSaveRequest.ImageFocus`, `HeroService.SaveAsync`, `HeroImageService.StageFocusAsync`, `FocusDialog.tsx`, `HeroPage.tsx` |
| 2 | Is a photo uploaded but never put in a slide cleaned up, and when? | Yes, after the same 7 days as retired files (Bryan decided 7 days for old files; extended to unused uploads). | Another period, or never (then storage grows). | `HeroMediaCleanup` (step 1), `Media:RetentionDays` |
| 3 | Should an uploaded photo that is **identical** to an existing one be a new image? | No: same bytes = same image (and a re-upload repairs lost files). | Always a new image: drop the SHA-256 unique index and the lookup. | `HeroImageService.UploadAsync`, `HeroDbContext` (unique `OriginalSha256`) |
| 4 | Is the **alt text** per slide or per photo? | Per slide (the same photo may carry another description in another place). | Per photo: move `Alt` and `Decorative` from `HeroSlide` to `HeroImage`. | `HeroSlide`, `HeroSaveRequest`, `HeroPage.tsx` |
| 5 | Is the **focus** per photo or per slide? | Per photo (shared by every slide that uses it). | Per slide: move the six focus columns to `HeroSlide`; media sets would then be per slide. | `HeroImage.FocusFor`, `HeroImageService`, `FocusDialog.tsx` |
| 6 | Is a hero with a title but **no slides** live? | Yes (the SLP hero is text only). The ASF region stays empty without a usable slide (their rule), so their baked hero stays. | Require at least one slide: add to `HeroMapping.IsLive` and the validation. | `HeroMapping.IsLive`, `HeroPictureRenderer.Render` |
| 7 | Which **language** does the hero use? | Always `nl` (one language now; the column and the unique index allow more later without migrating rows). It is not tied to `Texts:DefaultLanguage`. | Use the site language, or expose a `?lang=` parameter and a language switch in the admin. | `HeroLanguages.Default`, `HeroService`, `PublicHeroService` |
| 8 | Stored **original** of a photo with metadata. | Stored without metadata (re-encoded at JPEG quality 92 or the source quality when it carried EXIF, XMP or IPTC; HEIC becomes JPEG); a photo without metadata is stored as received. | Keep the exact original bytes (then GPS stays in a file that is never served), or always re-encode. | `MagickImageProcessor.StripMetadata`, `HeroImageService.UploadAsync` |
| 9 | Image quality and widths. | WebP 80, AVIF 50, JPEG 82; wide 640 to 2560 and tall 480 to 1280, never upscaled (approved defaults). Bryan's ASF photos are only 1600 or 2048 wide, so larger variants do not exist. | Other numbers or ladders. | `VariantPlanner` |
| 10 | Is **AVIF** used on the page? | Only for slides 2 and up on the client; the first image and the preload are WebP only (ASF: a preload cannot say AVIF if supported). | Add `<source type="image/avif">` before the WebP source and a second preload per format (costs a double download in some browsers). | `HeroPictureRenderer` |
| 11 | Who may use the Hero screen? | Owner and Administrator, like Offerings. | Owner only: change the route and nav roles. | `router.tsx`, `Sidebar.tsx`, `[Authorize(Policy = "AdminOnly")]` |
| 12 | Upload limits. | 10 MB per file, 64 megapixels, at most 100 uploads per user per hour (was 20; raised 2026-11-16 so a batch of 8-10 photos does not use it up), 2 images processed at once, 2 GB in total. The proxy allows 15 MB (Bryan). | Other limits via `Media__*` and `RateLimiting__HeroUpload`; a higher file limit also needs the proxy limit. | `MediaOptions`, `ServiceCollectionExtensions` (policy `hero-upload`) |
| 13 | Can the admin **delete an image** itself? | **Decided: no button**; replacing the image of a slide or removing the slide is enough; unused photos go after 7 days. The API (`DELETE /hero/images/{id}`, 409 while in use) exists. | Add a media library screen with delete. | `HeroImagesController.Delete`, `HeroPage.tsx` |
| 14 | Wording of the **messages** (Dutch), for example the focus dialog and the validation texts. | My wording; the admin has nl and en. | Edit the texts. | `frontend/src/i18n/locales/*/translation.json` (`hero.*`), `SlpModularCms.Modules.Hero/Texts/*.json` |
| 15 | The **button target** rules. | The CMS accepts only `#anchor` (letters, digits, `-`, `_`, starting with a letter), `/path` (no `//`, no spaces) or `https://host/...`; the page renderer is a little wider (ASF rules) because it also copes with data it did not check. | Allow `mailto:` or `tel:` (add to both validators and the renderer, and agree it with the sites). | `ButtonTargetValidator`, `schemas/hero.ts`, `HeroPictureRenderer.IsButtonTarget` |
| 16 | Maximum **published** slides. | 50, a safety ceiling (not an administrator limit). | Another number or a hard limit shown in the admin. | `HeroOptions.MaxPublishedSlides` |
| 17 | When the **media directory is missing or restored without files**. | The page keeps the baked hero (checked per page build for the first slide) and uploads are off until the directory works; a re-upload of the same photo repairs the files. | A visible warning in the admin when files are missing. | `HeroPageModel`, `MediaDirectoryCheck`, `HeroImageService.UploadAsync` |
| 18 | **HEIC** input. | Accepted as a capability (the arm64 self-test confirms it); not tested with a real HEIC file yet. | If a real file fails, remove HEIC from `SupportedInput` for the allow-list. | `MagickImageProcessor.DetectInput`, `ImageSignature` |
| 19 | **LCP** measurement and the budget. | Lighthouse (mobile) before and after the markers; the hero must not make LCP worse than the baked page. A script is ready (`scripts/Measure-Lcp.ps1`); it was not run (the tooling refused to install Lighthouse), so there is no baseline yet. | Another budget or tool (WebPageTest, field data). | `scripts/Measure-Lcp.ps1`, `docs/hero-module.md` |
| 20 | **ASF production** hosting (IIS, MijnHostingPartner): can the application pool write a data directory, and is it backed up? | Unknown; Bryan tests with ASF. The storage sits behind `IMediaStore` so a database store can follow. | Build the database store (2 to 3 days). | `IMediaStore`, `FileSystemMediaStore` |
| 21 | **SLS title** on the page. | The CMS delivers one title with line breaks; the SLP site derives the screen-reader title from the lines and adds the brand prefix itself. | Another split (a separate `heading` field) would be a model change. | `HeroSaveRequest.Title`, `HeroPictureRenderer` (`<br>`), SLS site |
| 22 | **Production seed**. | Not done; only the test hosts, with Bryan's password, after his go. | n/a | `scripts/Seed-Hero.ps1`, `docs/release-checklist-productie.md` section 4b |
| 23 | What does the host write for a hero **without any slide** (SLP Software)? | A text-only region in the first HTML (so a CMS change is visible without JavaScript, LCP is the text): `h1.cms-hero-title` with an optional `span.cms-hero-tagline` and `span.cms-hero-title-lines` (title lines separated by `<br>`, no brand prefix), then `p.cms-hero-lead` (lead, line breaks as `<br>`) and `p.cms-hero-buttons` with `a.cms-hero-button`. Nothing to preload, and the preload region is left as built. A hero WITH slides but none usable stays empty (ASF unchanged). This is a per-site switch, `Hero:TextOnlyRegion`: on in the committed settings of the SLP site, off by default (so ASF keeps its baked hero when its CMS hero has no slide, as ASF asked). | A separate marker for the text region instead of a switch. | `HeroOptions.TextOnlyRegion`, `HeroPictureRenderer.Render` and `TextOnlyRegion`, `HeroHtmlTransform.ApplyAsync`, `Api.SlpSoftware/appsettings.json`, `HeroTextOnlyTests` |
| 24 | Does the data block carry the hero when it has no slides? | Yes (intended): the site reads the hero from the data block, the baked block is `{}`. | n/a | `HeroPageModel`, `HeroDataContributor` |
| 25 | **Variants are cut in the background**, not inside the upload or save request (2026-11-16, found on the ASF test host: saving 8 photos took 60 s+ on the Pi and the proxy cut it with a 504). | Upload and save return at once; `HeroRenderService` cuts one image at a time and switches an image to its new set when it is complete (old set stays live meanwhile); an image without a set is not published; a failing image is tried 3 times, then left until the next restart. Measured on a 20-core PC: upload 3.5-8.8 s and save of 8 changed focus points 39.6 s before, 0.1 s and 0.1 s after (the 37.5 s of cutting moved to the background, 4.7 s per photo). On the Pi: about 25-30 s per photo, 4 minutes for 8. | A longer proxy time-out is then not needed; if cutting should be faster, reduce the variant set or the AVIF effort. | `HeroImageService.RenderNextPendingAsync`, `HeroRenderService`, `HeroSaveTimingTests` |
| 26 | **A large photo never finished** (ASF test, 4.4 MB): every variant decoded the whole photo again and each ran under the 20 s decode limit, so on the Pi a variant timed out, the whole set was retried 3 times and the image was given up silently. | One decode for the whole set, a width is resized once for both formats and from the previous width; a job limit of 600 s for the set (the image library clock is set above it); a failing image waits for the next round instead of blocking the queue; progress per variant in the admin and the log; retry button. Measured on a 6000x4000 JPEG (3.1 MB): 21.1 s per set before, 6.4 s after, on a fast PC (thread limit made no difference). On the Pi roughly 6x: about 40 s. | Other limits via `Media__*`; skipping AVIF would save about half of the time again. | `MagickImageProcessor.RenderSet`, `HeroRenderService`, `HeroBigPhotoTimingTests` |
| 27 | The admin page must have **no inline script** (CSP `script-src 'self'`). | The theme script is `/theme-init.js`; a test and the smoke test check it. | n/a | `frontend/public/theme-init.js`, `frontend/src/csp.test.ts`, `scripts/smoke-site.sh` |
| 28 | **The focus dialog showed a stretched photo** for any photo that is not 3:2: it used the published wide crop (`image.src`) as if it were the whole photo. | Every set now also holds a full-frame preview (`full-<width>.webp`, the whole picture at its own shape, at most 1280 wide); the admin API gives it as `previewSrc`, it is not in `variants` and not published to websites. Sets made before it existed get only that file added by the background renderer (not shown as processing, no address changes). | Without a preview yet the dialog says so instead of showing a wrong picture. | `VariantPlanner.Preview`, `HeroMapping.PreviewSrc`, `FocusDialog` |
| 29 | **A photo could stay "processing" for ever** in the admin: a photo that was uploaded but not saved yet only had the state of the upload response. | The page now asks the server for those photos one by one (`GET /api/v1/hero/images/{id}`, every 5 s while processing, also in a background tab); each photo shows its own state and, when done, a short "Processing finished" note on that photo (no toast). A photo that was already in the CMS (`reused`, internal only) looks the same and is ready at once. | n/a | `heroImageQuery`, `DoneStatus` |
| 30 | **Planning (from/to) and the hero-wide on/off are gone** (Bryan, 2026-11-17): the hero is part of the design and always on; a planning per slide became too much trouble. | Removed from model, API (PUT/GET, OpenAPI), validation, host logic (`IsLive` = has a title), admin (fields, nl/en texts) and tests; migration `RemoveHeroScheduleAndSwitch` drops `StartsAt`, `EndsAt` and `IsActive` of the hero (the per-slide `IsActive` stays). The public JSON, golden files and both sites did not depend on them. Without hero data the host writes nothing. | Planning can be added later, probably per slide; a hero-wide switch likewise. | `HeroMapping.IsLive`, migration `RemoveHeroScheduleAndSwitch` |
## Decisions of 2026-11-17 (Bryan, via SLP Software - SLS - Main)
| # | Assumption | Decision | Follow-up |
|---|------------|----------|-----------|
| 12, 16 | Upload limits and the 50 published slides | Keep as they are (10 MB, 64 megapixels, 100 uploads per hour, 2 GB total, 50 slides). | None. |
| 10 | AVIF only for slides 2 and up | Bryan asks why the first slide cannot be AVIF only (WebP as fallback). To be evaluated with the ASF session **after the merges** (not in the Hero PR): first slide `<picture>` with `<source type="image/avif">` first and WebP as fallback, preload with `type="image/avif"` and `imagesrcset`; check in Chromium, Firefox and WebKit (Playwright) that there is no double download and that a browser without AVIF falls back to WebP; measure bytes and LCP (the LCP element is the hero text, the photo counts little). Golden files change with it, so agree with the ASF session; only adopt when it is not worse, and Bryan checks it later. | Open, after the merges. |
| ASF 11 | Slider markup for the first slide | Bryan chooses the full slider render (first photo with zoom-in); the ASF session does it as a follow-up. | Watch whether the host markup (preload/picture) must change for it. |
| 20 | ASF production hosting (write access, back-up) | Unchanged: Bryan tests with ASF later. | Open. |
| HEIC | iPhone HEIC upload | Still to be tested by Bryan with a real iPhone file (the build cannot write HEIC; only the library self-test ran). | Open. |
| other | Assumptions 2, 3, 6, 7, 9, 14, 17, 18, 20, 22 to 30 | Stay as documented. | None. |
+157
View File
@@ -0,0 +1,157 @@
# 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.
---
## 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.
---
## 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).
---
## 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.
---
## 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 <picture>. (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 <picture> + 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.
---
## 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.
---
## 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.
---
## 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.
---
## 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.
---
## 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.
---
## 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).
---
## Construction: H1 to H6 built
**Timestamp**: 2026-11-16T00:00:00Z
**User Input**: "Bryans antwoorden op de 4 Units-vragen ... alle vier de aanbevelingen ..." and "Bryans besluiten voor de SLS-hero (2026-11-16): (1) De huidige teksten zijn de seed, ongewijzigd ... (2) De kleine regel 'Web & .NET development' (eyebrow) blijft VASTE tekst in de SLP-site ... (3) Schermlezer/zoekmachine-h1 voor SLS: afgeleid uit de titelregels met merknaam ervoor ..." (relayed by SLP Software - SLS - Main)
**AI Response**: Built H1 (image pipeline, Magick.NET), H3 (media store and endpoint), H2 (Hero module backend), H4 (host injection, shared data block, ASF golden files, full pipeline test), H5 (admin) and H6 (seed script, docs, smoke test, checklist). Summaries per unit in construction/h*/code/summary.md. Backend CI solution filter and frontend suite green. The first test deploy waits for Pi-Main to create the media directory.
**Context**: Construction; Build and Test next (test hosts, LCP), then acceptance by Bryan.
---
@@ -0,0 +1,26 @@
# Build and Test summary: hero-module
- **Closed**: 2026-11-17 (Bryan: "the features work well"; accepted on the test hosts, relayed by SLP Software - SLS - Main)
- **Branch**: `feature/hero-module` (master merged in before the PR)
- **Scope**: Hero module H0 to H6 (image pipeline with background rendering, media store, backend, host injection, admin), including the changes made after the first test round: background renderer with progress and retry, tabs Content/Images, sticky save bar, per-photo "Processing finished", drag reorder, multi-upload, unsaved-changes guard, crop thumbnail with live preview, no hero-wide schedule or on/off (migration `RemoveHeroScheduleAndSwitch`), refresh-token race fix, renderer backlog log.
## Result
Counts of the last full run are in the PR (CI runs `SlpModularCms.Ci.slnf` against MariaDB and the frontend `pnpm run build`, `lint`, `test`). Local runs before this closing: Hero.Tests 173, Core.Tests 925, Contact, Identity, Offerings, Availability, Master all pass; Api.Tests pass against a local MariaDB; frontend build, lint and 671 tests pass.
## Verified on the test hosts
- Upload and save fast on the Raspberry Pi (background rendering); a 4.4 MB photo finishes; progress, failed state and retry in the admin.
- Anonymous smoke test (`scripts/smoke-site.sh`) on SLS-test and ASF-test: injected hero markers, no inline script in the admin, `/theme-init.js` served.
- LCP/CLS with Lighthouse (mobile, 5 runs, median, 2026-11-17): SLS 0.71 score, LCP about 5.0 s (text, SPA bundle bound), CLS 0.00 after the SLS-side fix of the static packages list (it was 0.35, not caused by the hero); ASF 0.78 score, LCP about 5.0 s against 6.0 s for the baked page, CLS 0.00.
## Not verified here (carried into the production checklist, section 4b)
- A real iPhone HEIC upload (the build cannot write HEIC; only the library self-test ran).
- Write access of the IIS application pool to the media directory on ASF production (Bryan to test with ASF).
- Real Raspberry Pi timings in production on the final renderer, and a browser check of the layout (light/dark, narrow/wide, collapsed menu) of the new tabs and save bar.
- The OpenAPI snapshot (`openapi/slpsoftware.v1.json`) was edited by hand after the schedule removal; CI regenerates and compares it.
## Operations
Not run as a separate stage (Q19 = B). The points are in [docs/release-checklist-productie.md](../../../../../docs/release-checklist-productie.md), section 4b.
@@ -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: `<ratio>-<width>.<ext>` (`wide-1600.webp`, `tall-960.avif`); address `/media/hero/<setHash>/<name>`.
### 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/<setHash>/<ratio>-<width>.<ext>`; originals `originals/<sha256>.<ext>` (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 `<br>`, tagline span, buttons, first kept slide as `<picture>`; 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.
@@ -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 | **Removed 2026-11-17 (no schedule, no hero-wide switch; see FR-05).** Was: 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 | **Since 2026-11-17 the hero exists as soon as it has a title (no switch, no schedule); the rest below still holds for slides.** Was: 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. |
@@ -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/<sha256>.<ext>` |
| `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 |
@@ -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.
@@ -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).
@@ -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.
@@ -0,0 +1,22 @@
# H2 Hero module backend: code summary
Built 2026-11-16 on `feature/hero-module`. The whole CI solution filter is green (Core 912, Hero 100, Offerings 212, Availability 171, Identity 145, Api 46, Contact 349, Master 61); Api and Contact tests ran against MariaDB, so the new migration is proven on a real database and `HasPendingModelChanges` is false.
| Area | What |
|---|---|
| Project | `SlpModularCms.Modules.Hero` (+ `.Tests`), in `SlpModularCms.sln` (Application/Modules and Tests/Modules) and `SlpModularCms.Ci.slnf`; referenced by `Api`, `Api.SlpSoftware` and `Api.AndreaSlopFotografie` (not the slave); `SiteContractTests` updated |
| Data | `HeroDbContext` with `Heroes`, `HeroSlides`, `HeroImages`, `HeroRetiredFiles`; migration `InitialCreate` generated with the EF tools; slides restrict deletion of an image in use; variants stored as a JSON list |
| Rules | `HeroSaveRequest.Validate` (title 200 characters and 5 lines, tagline 120, lead 600, display, 0 to 2 buttons both-or-neither with label 50 and target 500, schedule order, slides with an image and alt text or the decorative flag; no administrator limit on slides), `ButtonTargetValidator` (anchor, path or https only), `HeroText.Clean` (plain text, control characters and U+2028/9 removed) |
| Services | `HeroService` (whole-hero save in one transaction, stable slide ids, cache invalidation), `PublicHeroService` + `HeroMapping` (live when switched on, inside the schedule and with a title; only active slides with an image and alt text or decorative; ordered; safety ceiling `Hero:MaxPublishedSlides` 50; `src` is the largest wide WebP), `HeroImageService` (upload: guard, SHA-256 identity so the same photo is one image, metadata removed from the stored original, all variants cut around the focus, atomic set write; focus change: new set and addresses, old set retired; delete refused while in use; room check on size and free space), `HeroMediaCleanup` + `HeroMediaCleanupService` (daily: unused images, retired files after 7 days unless used again, unknown old sets) |
| API | `GET /api/v1/hero` (anonymous, public-site endpoint, `hero-public` limit, 204 when none, `max-age=60`), `GET /hero/all` and `PUT /hero` (AdminOnly), `POST /hero/images` (multipart, 12 MB body limit, `hero-upload` per user, rejection codes mapped to 400, 413, 429, 503), `PUT /hero/images/{id}/focus`, `DELETE /hero/images/{id}` (409 while in use) |
| Texts | `HeroTexts` and `Texts/nl.json`, `en.json` (validation, rejection and storage messages), audited by `TextAudit` |
| Registration | `HeroModule` adds the DbContext, texts, options, `AddCmsMediaArea("hero")`, `AddMagickImageProcessor`, services and the clean-up service; runs its migration at start-up |
| Tests | validators and rules (including property tests for the target validator and text cleaning), mapping (schedule matrix, ceiling, decorative, order, focus per ratio, JSON shape), the image service on the real library and a temporary media directory (variants, no upscaling, metadata, duplicates, focus cuts the chosen side, retire, delete rules, refused and truncated uploads store nothing, full storage), the service (create, replace keeping slide ids, reorder, decorative and inactive, bad references, plain text, text-only hero with two buttons, schedule by clock, ceiling), the clean-up (retention, reuse, unattached, in use, unknown sets) and, on the master host with MariaDB, capabilities, 204, authorisation of all management routes, 404 of the media endpoint and migration-matches-model |
| OpenAPI | `openapi/slpsoftware.v1.json` regenerated (new Hero paths and schemas) |
| Publish | a self-contained win-x64 publish of the ASF host contains only `Magick.Native-Q8-x64.dll` and the Hero assemblies |
## Notes
- A hero without slides is valid and live (the SLS hero is text only); the HTML region for ASF is empty without a usable slide (their rule), so the baked hero stays.
- `Media:Directory` is not committed anywhere; each host sets it in its environment (see the infrastructure design).
- Not yet: the HTML injection and the data block (H4), the admin screens (H5), the seed, docs and smoke test (H6).
@@ -0,0 +1,13 @@
# H3 Media store and serving: code summary
Built 2026-11-16. Core tests green (Core.Tests, Media area 115 tests; the whole Core suite passes).
| Area | What |
|---|---|
| Store | `IMediaStore` and `FileSystemMediaStore` (`Core/Media/MediaStore.cs`): atomic set writes (temp directory, then one move; a failed write leaves nothing visible), plain file writes for originals, strict key allow-list (segments of lower-case letters, digits, dot, underscore and dash; at most four; the result must stay inside the root), list and delete of sets, total bytes, free space, writable probe. A database store can replace it later |
| Serving | `MediaEndpoint.MapCmsMedia` (`GET` and `HEAD /media/{**path}`): anonymous and marked as a public-site endpoint, rate-limit policy `media-public`, only addresses of the exact scheme in a registered area, immutable cache header, strong ETag and 304, `nosniff`; every other case is the same empty 404; originals are never reachable |
| Registration | `AddCmsMedia` (options bound from `Media:*`, store, gate, status, guard, self-test and directory check) and `AddCmsMediaArea("hero")`; `MediaDirectoryCheck` probes the directory at start-up (uploads off when missing or not writable) and warns above 80 percent of `Media:MaxTotalBytes`; wired into `CmsHost` (after `MapControllers`) |
| Rate limits | policies `hero-public` (120 per 60 s), `media-public` (600 per 60 s) and `hero-upload` (20 per hour per signed-in user) added next to `offerings-public` |
| Tests | store (atomicity, traversal and bad keys, replace, list, count, probe, free space), endpoint (headers, avif type, 304, HEAD, ten kinds of 404 including encoded traversal, method not allowed, no endpoint without a registered area), directory check |
Not in this unit: the retire-and-clean-up service (needs the Hero tables, built with H2), the free-space and total-size checks at upload time (H2, `HeroImageService`).
@@ -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 `<picture>` region and the preload links exactly as the ASF golden files; `HeroHtmlTransform` fills `<!--CMS:HERO-HTML-->` and `<!--CMS:HERO-PRELOAD-->` 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).
@@ -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.
@@ -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/<asf test>/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/<ts>/` 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 |
@@ -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 |
@@ -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 `<picture>` 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. |
@@ -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.
@@ -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/<unit>/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]:
@@ -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`; region pairs `<!--CMS:HERO-HTML-->…<!--/CMS:HERO-HTML-->` (first slide as `<picture>`) and `<!--CMS:HERO-PRELOAD-->…<!--/CMS:HERO-PRELOAD-->` in the head (one or two preload links with `media`, byte-equal to the `<source>`/`<img>` attributes); only WebP in the LCP picture and the preload; addresses `/media/hero/<setHash>/<ratio>-<width>.<ext>`, 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<br/>(store, processor, guard, endpoint)"]
Hero --> Inj["Core.Hosting.Website<br/>(transforms, data block, cache)"]
Off["Modules.Offerings"] --> Inj
Inj --> Pages["Website pages (SLS, ASF)"]
Media --> Pages
Dir[("Media directory<br/>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 `<picture>` 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).
@@ -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`, `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<br/>(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<br/>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<br/>(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 `<picture>` 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 |
@@ -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<MediaFile?> OpenReadAsync(string key, CancellationToken ct); // null = not found; MediaFile has Stream, ContentType, Length, LastWriteTime
Task<bool> 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<ImageInfo> InspectAsync(Stream source, CancellationToken ct);
// Decode (orientation applied), crop around the focus for a ratio, resize without upscaling, strip metadata, encode.
Task<RenderedImage> RenderAsync(Stream source, RenderRequest request, CancellationToken ct);
IReadOnlySet<ImageFormat> SupportedInput { get; }
IReadOnlySet<ImageFormat> 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<GuardedUpload> 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<VariantSpec> Plan(int sourceWidth, int sourceHeight, IReadOnlyList<RatioPlan> ratios, IReadOnlySet<ImageFormat> 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/<setHash>/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<object?> GetAsync(HtmlTransformContext context, CancellationToken ct); // null is written as JSON null
}
public sealed class CmsDataBlockTransform(IEnumerable<ICmsDataBlockContributor> contributors) : IHtmlPageTransform
{
public bool Wants(string html); // page contains <!--CMS:DATA-->
public Task<string> ApplyAsync(string html, HtmlTransformContext context, CancellationToken ct);
}
```
## Modules.Hero
```csharp
public interface IHeroService
{
Task<HeroAdminDto?> GetAsync(string language, CancellationToken ct); // management read incl. inactive
Task<HeroAdminDto> SaveAsync(HeroSaveRequest request, string actor, CancellationToken ct);
}
public interface IHeroImageService
{
Task<HeroImageDto> UploadAsync(Stream upload, long length, string actor, CancellationToken ct);
Task<HeroImageDto> 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<PublicHeroDto?> 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 <picture>
public static string PreloadHtml(PublicHeroDto hero); // one or two <link rel="preload" as="image"> 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/<set>/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).
@@ -0,0 +1,75 @@
# 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 the two regions `<!--CMS:HERO-HTML-->…<!--/CMS:HERO-HTML-->` (title, tagline, buttons and the first active slide as `<picture>`) and `<!--CMS:HERO-PRELOAD-->…<!--/CMS:HERO-PRELOAD-->` in the head (one or two `<link rel="preload" as="image">`), 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 `<picture>`/`<img>` 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/<area>/<setHash>/<name>`; 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 `<!--CMS:DATA-->` marker: asks all contributors (ordered by `Order`) and writes `{"siteUrl": …, <key>: <value>, …}` 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 `<picture>`; contract in `site-contract-agreed-with-asf.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` | Writes the hero region and the preload region 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<br/>(offerings, banners, hero)"]
Inj --> T2["HeroHtmlTransform<br/>(region + first slide)"]
Inj --> T3["HeroHtmlTransform<br/>(preload region, 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.
@@ -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<br/>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.
@@ -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.
@@ -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.
@@ -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/<hash>/…`, 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`)
- [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
### 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]: 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?
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]: 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`?
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]: 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?
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]: B. Algemene mediadienst in Core.
### 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]: A. Eigen lichte component.
### 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]: 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).
@@ -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<br/>(Hero screen)"]
Hero["Modules.Hero<br/>(new)"]
Core["Core<br/>(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<br/><b>COMPLETED</b>"]
RE["Reverse Engineering<br/><b>SKIP</b>"]
RA["Requirements Analysis<br/><b>COMPLETED</b>"]
US["User Stories<br/><b>SKIP</b>"]
WP["Workflow Planning<br/><b>IN PROGRESS</b>"]
AD["Application Design<br/><b>EXECUTE</b>"]
UG["Units Generation<br/><b>EXECUTE</b>"]
end
subgraph CONSTRUCTION["🟢 CONSTRUCTION PHASE"]
FD["Functional Design<br/><b>EXECUTE</b>"]
NFRA["NFR Requirements<br/><b>EXECUTE</b>"]
NFRD["NFR Design<br/><b>EXECUTE</b>"]
ID["Infrastructure Design<br/><b>CONDITIONAL</b>"]
CG["Code Generation<br/>(Planning + Generation)<br/><b>EXECUTE</b>"]
BT["Build and Test<br/><b>EXECUTE</b>"]
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).
@@ -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
- [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
### 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]: A. Eén PR voor H1 t/m H6, pas gemerged na Bryans acceptatie op de testhosts.
### 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]: 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)?
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]: 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?
- 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]: A. Master-Api en beide sites verwijzen vanaf H2; de Slave niet.
@@ -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 `<img>`; 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 `<img>` with `fetchpriority="high"`, `width`/`height`, `srcset` and a matching `<link rel="preload" as="image">` |
| 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.
@@ -0,0 +1,190 @@
# 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.
**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)
- B) Meerdere heroes per site, waarvan er één tegelijk actief is (bijvoorbeeld seizoensgebonden), met aan/uit
- X) Other (please describe after [Answer]: tag below)
[Answer]:
## Vraag 2 — Hoe wordt de titel opgeslagen?
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 — 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 laat later talen toe zonder migratie van bestaande data
- X) Other (please describe after [Answer]: tag below)
[Answer]:
## 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
- X) Other (please describe after [Answer]: tag below)
[Answer]:
## 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
- X) Other (please describe after [Answer]: tag below)
[Answer]:
## 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 ingebakken hero
- X) Other (please describe after [Answer]: tag below)
[Answer]:
## Vraag 13 — 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 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)
- X) Other (please describe after [Answer]: tag below)
[Answer]:
## Vraag 15 — Wat doen we met de statische teksten die jij nog niet hebt bekeken?
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 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 16 — Startinhoud (seed)
- 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 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.)
- 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 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)
- C) Nee — sla alle PBT-regels over
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]:
## Vraag 19 — Operations-fase
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
- C) Nog niet zeker — vraag het opnieuw na Construction
- X) Other (please describe after [Answer]: tag below)
[Answer]:
@@ -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 `<img>` 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, 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) |
| 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~~ **Removed (Bryan, 2026-11-17).** No `startsAt`/`endsAt` and no hero-wide on/off (`isActive`): the hero is part of the design and always on; it is live as soon as it has a title, and without hero data the host writes nothing (the baked hero stays). Per-slide on/off stays. A schedule may come back later, then probably per slide. |
| 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, 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 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). |
| 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) | 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. |
## 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~~ 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 |
| 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.
@@ -0,0 +1,80 @@
# 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 `<picture>` 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).
## 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 / no hero data / 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/<hash>/…`, immutable; the CSP `img-src` does not change. |
| Markers | `<!--CMS:HERO-HTML-->…<!--/CMS:HERO-HTML-->` (title, tagline, button(s), the FIRST slide as `<picture>`), `<!--CMS:HERO-PRELOAD-->` 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 `<img>` without `<picture>`) can be delivered earlier. |
## Crop/focus model: B (decided)
The host cuts variants per named ratio around the focus point (or an administrator-set crop) and also delivers the focus point; sites use `<picture>` per ratio and may use the focus point as `object-position` for in-between shapes. (Option A, a focus point only, was not chosen.)
Ratios and widths (ASF proposal, accepted):
| 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 | `<source media="(orientation: portrait)">` |
- `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 `<source>`/`<img>` 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 `<picture>` 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.
## 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: `<source media="(orientation: portrait)" … type="image/webp">` for `tall` plus the `img` for `wide` inside `<picture class="cms-hero-picture">`; 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 `<!--CMS:HERO-PRELOAD-->…<!--/CMS:HERO-PRELOAD-->` 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 `<br>` after escaping.
6. Variant names `/media/hero/<hash>/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.
## Text-only hero (SLP Software), added 2026-11-16
A hero **without any slide** is written as text, **only on a site that asks for it** with the setting `Hero:TextOnlyRegion=true` (SLP Software: no images; it reads the same hero from the data block). The setting is off by default and off for ASF, so for ASF a hero without a slide changes nothing in the page (the baked hero stays, also in the preload region):
`<h1 class="cms-hero-title">` + (tagline: `<span class="cms-hero-tagline">TAGLINE</span> `) + `<span class="cms-hero-title-lines">LINE<br>LINE</span></h1>` + (lead: `<p class="cms-hero-lead">LEAD</p>`, line breaks as `<br>`) + (buttons: `<p class="cms-hero-buttons"><a class="cms-hero-button" href="TARGET">LABEL</a>...</p>`, at most two). An optional per-site setting `Hero:TitlePrefix` (default empty; SLP Software: `"SLP Software: "`) writes `<span class="cms-hero-title-prefix">SLP Software: </span>` (encoded) as the **first child of the h1**, before tagline and title lines, so crawlers and screen readers read "SLP Software: Websites, apps & meer."; the site styles that class visually hidden (sr-only). The visible title lines stay in `span.cms-hero-title-lines`. The prefix is only used in the text-only region (never for a hero with slides; ASF leaves it empty, so its golden files are unchanged). There is nothing to preload, so `CMS:HERO-PRELOAD` is left as the build made it. Everything is HTML-encoded. A hero with slides of which none is usable is still empty (the ASF golden files are unchanged).
@@ -0,0 +1,43 @@
# Mediabibliotheek (media-library)
**Status:** Gepland, nog niet gestart. Er zijn bewust geen AI-DLC-stappen uitgevoerd. De Hero-module (feature `hero-module`) wordt eerst afgerond: acceptatie door Bryan op test, daarna de merge. Besluit van Bryan, 2026-11-17.
**Doel:** een algemene Core-mediabibliotheek (niveau 3 uit de schatting) voor alle modules: Hero nu, later de gallerij-module. Foto's worden op één plek beheerd, bewaard en hergebruikt.
## Eisen van Bryan (invoer voor Requirements Analysis)
1. **Alles bewaren.** Een upload blijft staan tot de gebruiker hem zelf verwijdert. Geen automatische opruiming van ongebruikte foto's meer.
2. **Knop "Opruimen"** in de bibliotheek:
- standaard alles ouder dan 7 dagen, met een slider om meer of minder dagen terug te kijken;
- een checkbox "Alleen ongebruikte foto's", standaard AAN (uit = alle foto's in die periode).
3. **Overzicht voor het opruimen:** alle foto's die zouden worden opgeruimd, standaard allemaal geselecteerd, zodat de gebruiker er foto's uit kan zetten vóór bevestigen. Gesorteerd van nieuwste naar oudste. Per foto een indicator of hij nog gebruikt wordt, en liefst waar (module en plek, bv. "Hero, slide 3").
4. **Bulk-actie:** dit overzicht is meteen de manier om in de bibliotheek meerdere foto's te selecteren en te verwijderen.
5. **Opslag:** zichtbaar opslaggebruik en een melding bij de limiet.
6. **Bulkacties als eigen onderdeel** (aanvulling Bryan, 2026-11-17), los van het opruimoverzicht: in de bibliotheek zelf meerdere foto's selecteren (selectievakjes, alles selecteren/wissen, bereik met shift-klik, toetsenbord) en daar bulkacties op uitvoeren (verwijderen; later bv. taggen of verplaatsen). Het opruimoverzicht (eis 3) hergebruikt dezelfde selectie- en bulkcomponent. Eis 4 wordt hiermee: het opruimoverzicht is een voorgeselecteerde weergave van die component, niet de enige plek voor bulkacties.
7. **Uitsnede per gebruik, niet per foto** (aanvulling Bryan): gallerij en vooral het mozaïek op de fotoshoot-pagina's van ASF hebben per plek een eigen uitsnede/verhouding nodig. Een gallerij met masonry heeft geen eigen uitsneden nodig (foto in eigen verhouding).
## Datamodel-richting
- **Foto:** bron + metadata + standaardfocus.
- **Gebruik:** module/plek, verhouding, eigen focus/zoom. Een gebruik bepaalt de set varianten.
- De huidige Hero (focus per foto, wide/tall) moet hier zonder wijziging van de publieke adressen naartoe kunnen groeien (de Hero-focus wordt dan de standaardfocus plus een gebruik per slide).
## Randvoorwaarden
- De bestaande media-adressen (`/media/hero/<hash>/...`) en set-hashes blijven behouden, zodat ASF, SLS en de golden files niet veranderen.
- De huidige 7-daagse opruiming van ongebruikte uploads in de Hero blijft tot deze feature is gebouwd (eventueel eerder uit te zetten achter een instelling als dat veilig en klein kan; dan melden).
## Ontwerpvragen voor Bryan (niveau 3 niet ontwerpen vanuit alleen de Hero)
De behoeften van de gallerij-module moeten meewegen, zodat de abstractie niet op de verkeerde plek komt:
- Welke plekken en verhoudingen komen er? Mozaïek op de shoot-pagina's (welke verhoudingen per tegel?), hero wide/tall, masonry (eigen verhouding, geen uitsnede), thumbnails. Per-gebruik is vastgelegd als richting (eis 7); de vraag is welke gebruiken er zijn.
- Meerdere formaten/varianten per foto, en wie bepaalt de set?
- Rechten per module (wie mag welke foto's zien, gebruiken, verwijderen)?
- Publieke adressen: blijven die per module (`/media/<module>/...`) of komt er een gedeeld pad?
- Gebruiksregister: hoe weet de bibliotheek waar een foto wordt gebruikt (per module aanmelden of centraal)?
## Schatting (no-code, 2026-11-17)
Niveau 3: circa 12-18 dagen, 60-100 commits, plus 1-2 dagen ontwerp (±50%). Grootste risico: adresstabiliteit en de datamigratie van bestaande Hero-afbeeldingen.
+1 -1
View File
@@ -97,7 +97,7 @@ Variabelen:
| `VITE_UMAMI_SCRIPT_URL`, `VITE_UMAMI_WEBSITE_ID_TEST`, `VITE_UMAMI_WEBSITE_ID_PRODUCTION` | Umami voor de SlpSoftware-adminbuild (ASF gebruikt geen Umami) |
| `SECURITY_ALLOWED_SCRIPT_ORIGINS_TEST`, `SECURITY_ALLOWED_SCRIPT_ORIGINS_PRODUCTION` | Alleen gebruikt als controle in `publish-sls-test`/`publish-sls-production` wanneer `VITE_UMAMI_SCRIPT_URL` gevuld is: de Umami-origin moet in deze lijst staan, en de lijst moet overeenkomen met `SecurityHeaders__AllowedScriptOrigins__0` op de host |
Runtime-instellingen van de applicatie (verbindingsstring, JWT, mail, `Contact__*`, Sentry) zitten niet in de workflow maar in het omgevingsbestand op de host (`shared/env`, zie README en de hostdocumentatie).
Runtime-instellingen van de applicatie (verbindingsstring, JWT, mail, `Contact__*`, `Media__Directory`, Sentry) zitten niet in de workflow maar in het omgevingsbestand op de host (`shared/env`, zie README en de hostdocumentatie). Voor de afbeeldingen van de Hero-module hoort daar `Media__Directory` bij, een map buiten de release (`shared/media`), die de deploy niet aanraakt; zie [hero-module.md](hero-module.md).
## Runners
+67
View File
@@ -0,0 +1,67 @@
# Hero-module
Levend document (2026-11-16). De hero van een website (titel, tagline, lead, knoppen, afbeeldingen) staat in het CMS. Het CMS levert alleen **inhoud**; elke site houdt zijn eigen opmaak. Ontwerp en besluiten: `aidlc-docs/features/hero-module/`. Contract met de websites: `aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md`.
## Wat beheer je
Admin > **Hero** (Owner en Administrator, module `Hero`):
- Titel (een nieuwe regel is een regelafbreking, maximaal 5 regels), tagline, lead, weergave (`single` of `slideshow`).
- Maximaal twee knoppen met tekst en doel. Een doel is een `#anker`, een `/pad` of een `https://`-adres; andere waarden worden geweigerd.
- Geen planning en geen aan/uit voor de hero zelf (Bryan, 2026-11-17): de hero is onderdeel van het design en altijd aan. Hij is live zodra er een titel is; zonder hero-gegevens schrijft de host niets en toont de website zijn eigen ingebakken hero. Planning (later eventueel per slide) en een hero-brede aan/uit kunnen later terugkomen. Per slide blijft aan/uit bestaan.
- Slides: een afbeelding met verplichte beschrijving (alt-tekst) of de markering decoratief, volgorde, aan of uit per slide. Er is geen grens op het aantal slides; technisch publiceert de host er hoogstens `Hero:MaxPublishedSlides` (50).
- Focus: per afbeelding een algemeen punt en zoom, en optioneel een eigen punt voor de liggende (`wide`, 3:2) en de staande (`tall`, 4:5) weergave. De host snijdt de varianten daaromheen uit. **Een wijziging van het focuspunt geldt pas als je de hero opslaat** (Bryan, 2026-11-16): het focus-venster houdt de wijziging lokaal in de admin (knop Toepassen, een markering bij de slide); bij Opslaan gaat ze mee in dezelfde aanvraag (`imageFocus`); de host bewaart hero en focus direct (onder een seconde) en snijdt de varianten daarna op de achtergrond in nieuwe bestanden. De afbeelding schakelt over naar de nieuwe set zodra die compleet is; tot die tijd blijft de oude set in beeld. Verlaat je de pagina zonder op te slaan, dan vervalt de wijziging en is er niets aan de server veranderd. Mislukt een opslag nadat nieuwe bestanden zijn geschreven, dan verwijst niets ernaar en ruimt de opschoning ze na 7 dagen op; de oude bestanden blijven ook 7 dagen staan voor sites die nog oude data hebben.
De admin toont alleen een badge Live of Niet live.
## Wat de website krijgt
- `GET /api/v1/hero`: anoniem, `Cache-Control: public, max-age=60`, `204` als er niets te tonen is (dan blijft de ingebakken hero staan). Dezelfde JSON staat onder `hero` in het datablok `#cms-data`.
- Markers in de pagina: `<!--CMS:HERO-HTML-->…<!--/CMS:HERO-HTML-->` (titel, tagline, knoppen, eerste slide als `<picture>`) en `<!--CMS:HERO-PRELOAD-->…<!--/CMS:HERO-PRELOAD-->` in de head (een of twee preload-links). Alleen WebP komt in de eerste afbeelding en de preload. Zonder bruikbare hero, bij een fout of als de bestanden van de eerste slide ontbreken blijft de pagina zoals gebouwd.
- Afbeeldingen: `/media/hero/<set>/<ratio>-<breedte>.<webp|avif>`, onder het eigen adres van de site (de CSP verandert niet), `immutable` gecachet; een andere focus geeft een nieuw adres.
- De golden files van ASF (commit 13f78c4) leggen de HTML byte voor byte vast: `src/SlpModularCms.Modules.Hero.Tests/Golden`.
## Instellen op een host
| Instelling | Betekenis |
|---|---|
| `Media__Directory` | De map voor de afbeeldingen, **buiten de release** en buiten de webroot. Zonder deze instelling (of als de map niet beschrijfbaar is) staan uploads uit; bestaande bestanden en de publieke hero blijven werken. Niet in een committed appsettings-bestand. |
| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. |
| `Hero__TextOnlyRegion` | `true` voor een site waarvan de hero geen afbeeldingen heeft (SLP Software; staat in de committed instellingen van die site): een hero zonder slides wordt dan als tekst (titelregels, lead, knoppen) in de eerste HTML geschreven. Uit (standaard, ook voor ASF): een hero zonder slides laat de pagina ongemoeid. |
| `Hero__TitlePrefix` | Merktekst die in de tekst-only-regio als eerste, visueel te verbergen deel van de h1 wordt geschreven (`<span class="cms-hero-title-prefix">`), zodat crawlers en schermlezers de volledige titel lezen. SLP Software: `"SLP Software: "` (committed instelling); leeg (standaard, ook ASF) schrijft niets. De site verbergt de klasse zelf visueel. |
| `Media__RenderSetTimeoutSeconds` (600), `Media__StripTimeoutSeconds` (60) | De tijd die het knippen van alle varianten van één foto in de achtergrond mag duren, en het verwijderen van metadata bij een upload. Ruim gekozen: een grote foto op een Raspberry Pi kost minuten. |
| `Hero__MaxPublishedSlides` | Technische bovengrens op het aantal gepubliceerde slides (standaard 50). |
| `RateLimiting__HeroPublic`, `__MediaPublic`, `__HeroUpload` | Snelheidsbeleid (standaard 120 per 60 s, 600 per 60 s, 100 uploads per uur per gebruiker: een reeks van 8-10 foto's mag de limiet niet opmaken). |
### Pi (test en later productie van SLP)
1. Eenmalig, als het service-account: `mkdir -p ~/apps/slpsoftware/<omgeving>/shared/media && chmod 700 ~/apps/slpsoftware/<omgeving>/shared/media` (voor ASF-test hetzelfde in zijn eigen map).
2. In `shared/env`: `Media__Directory=%h/apps/slpsoftware/<omgeving>/shared/media` (let op: systemd verwacht een volledig pad; vervang `%h` door het thuispad als de EnvironmentFile dat niet uitbreidt).
3. De map hoort bij de back-up van de site (het back-upscript van de database neemt hem niet mee).
4. Na de eerste deploy: kijk in het log naar `Image library Magick.NET self-test passed` (met de lijst formaten). Staat daar een fout, dan zijn uploads uitgezet en is de bibliotheek op deze machine niet bruikbaar (linux-arm64 is niet vooraf getest).
5. Het deployartefact is ongeveer 35 MB groter door de beeldbibliotheek; meet de grootte bij de eerste deploy tegen de uploadlimiet van de proxy.
### IIS (ASF-productie, later)
Een gegevensmap naast de site, buiten de webroot, waarin het account van de application pool mag schrijven. **Of dat op MijnHostingPartner kan, is nog niet getest** (Bryan test het met ASF). Faalt het, dan komt er een opslag in de database achter dezelfde koppeling (`IMediaStore`). De self-contained win-x64-publish bevat alleen `Magick.Native-Q8-x64.dll`.
## Startinhoud (alleen test)
```powershell
./scripts/Seed-Hero.ps1 -BaseUrl https://test.andreaslop.nl -ImagesDirectory <web/src/assets van de ASF-repository>
./scripts/Seed-Hero.ps1 -BaseUrl https://test.slpsoftware.nl -SeedFile ./scripts/hero-sls.json
```
`hero-asf.json` bevat de 8 huidige foto's met alt-teksten en een eerste schatting van de focuspunten (door de ASF-sessie); Bryan past ze aan in de admin. `hero-sls.json` is de huidige SLP-hero (alleen tekst, twee knoppen). Het script uploadt eerst alle foto's (de varianten worden daarna op de achtergrond gemaakt; het script wacht tot alles klaar is) (dezelfde foto is dezelfde afbeelding, dus een tweede run dupliceert niets) en slaat dan de hero in een keer op, met de focuspunten in dezelfde aanvraag (`imageFocus`): een focuspunt geldt pas bij het opslaan van de hero. Het slaat een CMS over dat al een hero heeft (`-Force` vervangt), vraagt het wachtwoord interactief (alleen voor een lokale host of testrun leest het `SEED_HERO_PASSWORD`) en gebruikt voor productie niets zonder Bryans go. Getest op PowerShell 7 en Windows PowerShell 5.1 tegen een lokale host, met de ASF-seed en `hero-sls.json`.
## Wat er achter de schermen gebeurt
- Verwerking op de achtergrond: een upload bewaart het origineel en geeft direct antwoord (`processing: true`, nog geen varianten, de afbeelding wordt niet gepubliceerd); `HeroRenderService` knipt de varianten, een afbeelding per keer (op een Raspberry Pi 4 ongeveer 25-30 s per foto), en pikt bij het opstarten en elke minuut werk op dat nog openstaat. Daardoor kapt de proxy-time-out (60 s) nooit een upload of een opslag af, en laat een afgebroken verzoek niets half bewaard achter (bestanden eerst, rij als laatste; een herhaling doet het gewoon opnieuw). De admin ververst zelf zolang er afbeeldingen worden verwerkt.
- Upload: echt bestandstype aan de inhoud (geen SVG), grenzen op bytes, pixels, tijd en gelijktijdigheid; metadata (GPS) uit het opgeslagen origineel en alle varianten; varianten per verhouding rond het focuspunt, nooit groter dan de bron, in WebP (en AVIF waar het platform dat kan). Dezelfde foto nog een keer is hetzelfde plaatje (en herstelt verloren bestanden).
- Oude bestanden (nieuwe focus, vervangen of ongebruikte foto) blijven 7 dagen en worden dan opgeschoond; een bestand dat nog gebruikt wordt, verdwijnt nooit.
- Ondersteunde invoer: JPEG, PNG, WebP, GIF, BMP, TIFF en AVIF; HEIC alleen als aangegeven mogelijkheid van de bibliotheek (nog niet met een echt bestand getest).
## Controleren na een deploy
- `scripts/smoke-site.sh` (in de CI na elke test-deploy): module `Hero` geladen, `GET /api/v1/hero` is 200 of 204, het beheer is beschermd, een niet-bestaand mediaadres is een gewone 404.
- LCP: Lighthouse (mobiel profiel) op de testsite vóór en na het plaatsen van de markers in de website; de LCP van de gerenderde pagina mag niet slechter zijn dan die van de ingebakken pagina en de hero veroorzaakt geen layoutverschuiving (`width` en `height` staan op de afbeelding). Zie `release-checklist-productie.md`.
+14
View File
@@ -38,6 +38,20 @@ Achtergrond per onderwerp: [deploy-en-testomgevingen.md](deploy-en-testomgevinge
| `Contact__Enabled` | pas `true` als het formulier live moet | Het contactformulier staat standaard uit. |
| `Texts__DefaultLanguage` | `nl` (standaard) | De vaste teksten van de backend zijn Nederlands. |
## 4b. Hero (module `Hero`)
- [ ] `Media__Directory` staat in de omgeving van de productiehost, de map bestaat buiten de release en de webroot en is beschrijfbaar door het service-account (Pi: `shared/media`; ASF op IIS: een gegevensmap naast de site, schrijfrechten voor de application pool: **door Bryan met ASF getest voor de release**).
- [ ] De map zit in de back-up van de site (het database-back-upscript neemt hem niet mee).
- [ ] Het log toont na de start `Image library Magick.NET self-test passed`; zo niet, dan zijn uploads uitgezet.
- [ ] De hero staat in het CMS van productie (seed alleen met Bryans go: `scripts/Seed-Hero.ps1`), de focuspunten kloppen en de ASF-foto's zijn gecontroleerd.
- [ ] De websites zijn gebouwd met de markers (`CMS:HERO-HTML`, `CMS:HERO-PRELOAD`, `CMS:DATA`); de rooktest slaagt en de LCP van de gerenderde pagina is niet slechter dan die van de ingebakken pagina (Lighthouse, mobiel).
- [ ] Het deployartefact past binnen de uploadlimiet van de proxy (de beeldbibliotheek voegt ongeveer 35 MB toe).
- [ ] **Migratie `RemoveHeroScheduleAndSwitch`** (Hero-database): laat de kolommen `StartsAt`, `EndsAt` en `IsActive` van de hero vallen (de planning en de hero-brede aan/uit bestaan niet meer; Bryan, 2026-11-17). Hij draait bij het opstarten; controleer vooraf dat er een recente back-up is. De per-slide aan/uit blijft.
- [ ] **Uploadgrootte van de proxy**: `client_max_body_size` (nginx) staat boven de uploadlimiet van de hero (standaard 10 MB per foto); de proxy-timeout (`proxy_read_timeout`) hoeft niet hoog: een upload slaat alleen het origineel op en de varianten worden op de achtergrond gemaakt.
- [ ] **Per site**: `Hero__TextOnlyRegion=true` en `Hero__TitlePrefix` voor een site zonder hero-afbeeldingen (SLP Software: staan in de committed instellingen); ASF laat beide leeg. `Hero__MaxPublishedSlides` alleen aanpassen als 50 niet past.
- [ ] Na de eerste start staat in het log `Hero image renderer started.` en de samenvattingsregel `Hero image renderer: N images, X waiting for their variants, Y lacking the full-frame preview.`; bij `X`>0 verdwijnt dat binnen enkele minuten (op de Pi rekenen met ongeveer een minuut per grote foto).
- [ ] Vraag in de admin (Hero, Afbeeldingen) na de seed of alle foto's klaar zijn ("Verwerking afgerond"); een foto die blijft hangen heeft een knop Opnieuw proberen.
## 5. Contact-retentie en privacy
- [ ] `Contact:RetentionMonths` (standaard 12) en `Contact:SpamRetentionDays` (standaard 30) kloppen met de privacyverklaring van de site.
+2 -7
View File
@@ -5,13 +5,8 @@
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SlpModularCms</title>
<script>
(function () {
var s = localStorage.getItem('cms-theme');
var t = s === 'light' || s === 'dark' ? s : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.classList.add(t);
})();
</script>
<!-- A file of its own, loaded before the app: the host only allows scripts from its own origin (no inline scripts). -->
<script src="/theme-init.js"></script>
</head>
<body>
<div id="root"></div>
+12
View File
@@ -0,0 +1,12 @@
// Sets the light or dark theme before the first paint, so the page does not flash in the wrong theme. A file of its own
// (not an inline script) because the host allows scripts from its own origin only (Content-Security-Policy script-src 'self').
(function () {
var stored = null;
try {
stored = localStorage.getItem('cms-theme');
} catch (e) {
stored = null;
}
var theme = stored === 'light' || stored === 'dark' ? stored : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.classList.add(theme);
})();
+9 -1
View File
@@ -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';
@@ -30,6 +30,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',
@@ -0,0 +1,82 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import i18n from '@/i18n/config';
import { ThemeToggle } from './ThemeToggle';
const media = (dark: boolean) =>
vi.spyOn(window, 'matchMedia').mockImplementation(
() => ({ matches: dark, addEventListener: () => undefined, removeEventListener: () => undefined }) as unknown as MediaQueryList,
);
beforeEach(async () => {
localStorage.clear();
document.documentElement.className = '';
vi.restoreAllMocks();
await i18n.changeLanguage('nl');
});
describe('ThemeToggle', () => {
it.each([
['light', 'Thema: licht'],
['dark', 'Thema: donker'],
])('shows the CURRENT %s theme in its name (not the action)', (mode, name) => {
localStorage.setItem('cms-theme', mode);
media(false);
render(<ThemeToggle />);
const button = screen.getByTestId('theme-toggle');
expect(button).toHaveAccessibleName(name);
expect(button).toHaveAttribute('data-mode', mode);
expect(button).toHaveAttribute('title', name);
});
it('says in words what automatic currently is', () => {
media(true);
render(<ThemeToggle />);
expect(screen.getByTestId('theme-toggle')).toHaveAccessibleName('Thema: automatisch (nu donker)');
expect(screen.getByTestId('theme-toggle')).toHaveAttribute('data-mode', 'auto');
});
it('opens a menu with three options, the current one marked, and chooses with the keyboard', async () => {
media(false);
localStorage.setItem('cms-theme', 'light');
render(<ThemeToggle />);
screen.getByTestId('theme-toggle').focus();
await userEvent.keyboard('{Enter}');
expect(await screen.findByTestId('theme-option-light')).toHaveAttribute('aria-current', 'true');
expect(screen.getByTestId('theme-option-dark')).not.toHaveAttribute('aria-current');
expect(screen.getByTestId('theme-option-auto')).toHaveTextContent('Automatisch');
await userEvent.click(screen.getByTestId('theme-option-dark'));
expect(localStorage.getItem('cms-theme')).toBe('dark');
expect(document.documentElement.classList.contains('dark')).toBe(true);
expect(screen.getByTestId('theme-toggle')).toHaveAccessibleName('Thema: donker');
});
it('works on the first click: automatic to dark flips what is shown at once', async () => {
media(false);
render(<ThemeToggle />);
await userEvent.click(screen.getByTestId('theme-toggle'));
await userEvent.click(await screen.findByTestId('theme-option-dark'));
expect(document.documentElement.classList.contains('dark')).toBe(true);
expect(document.documentElement.classList.contains('light')).toBe(false);
});
it('has English texts too', async () => {
await i18n.changeLanguage('en');
media(true);
render(<ThemeToggle />);
expect(screen.getByTestId('theme-toggle')).toHaveAccessibleName('Theme: automatic (now dark)');
});
});
+58 -12
View File
@@ -1,20 +1,66 @@
import { Sun, Moon } from 'lucide-react';
import { Monitor, Moon, Sun } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useTheme } from '@/hooks/useTheme';
import {
DropdownMenu,
DropdownMenuCheck,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useTheme, type ThemeMode } from '@/hooks/useTheme';
const MODES: { mode: ThemeMode; icon: typeof Sun }[] = [
{ mode: 'light', icon: Sun },
{ mode: 'dark', icon: Moon },
{ mode: 'auto', icon: Monitor },
];
/**
* Three states: light, dark, automatic (follow the system). The button shows the CURRENT choice (sun = light, moon =
* dark, monitor = automatic), its name says it in words ("Theme: automatic (now dark)"), and a small menu with the three
* options (the current one marked) changes it.
*/
export function ThemeToggle() {
const { t } = useTranslation();
const { isDark, toggleTheme } = useTheme();
const { mode, theme, setMode } = useTheme();
const Icon = MODES.find((m) => m.mode === mode)!.icon;
const label =
mode === 'auto'
? t('theme.labelAuto', { now: t(`theme.mode.${theme}`).toLowerCase() })
: t('theme.label', { mode: t(`theme.mode.${mode}`).toLowerCase() });
return (
<button
type="button"
onClick={toggleTheme}
aria-label={isDark ? t('theme.switchToLight') : t('theme.switchToDark')}
data-testid="theme-toggle"
className="flex items-center justify-center rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
>
{isDark ? <Sun className="size-4" /> : <Moon className="size-4" />}
</button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label={label}
title={label}
data-testid="theme-toggle"
data-mode={mode}
className="flex items-center justify-center rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<Icon className="size-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuLabel>{t('theme.title')}</DropdownMenuLabel>
<DropdownMenuSeparator />
{MODES.map(({ mode: option, icon: OptionIcon }) => (
<DropdownMenuItem
key={option}
onSelect={() => setMode(option)}
aria-current={mode === option ? 'true' : undefined}
data-testid={`theme-option-${option}`}
>
<OptionIcon className="size-4" />
{t(`theme.mode.${option}`)}
<DropdownMenuCheck checked={mode === option} />
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -0,0 +1,105 @@
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import { Checkbox, CheckboxField } from './checkbox';
import { Radio, RadioField, RadioGroup } from './radio';
describe('Checkbox', () => {
it('is a real checkbox: Space toggles it and the label is clickable', async () => {
render(<CheckboxField label="Uitgelicht" data-testid="box" />);
const box = screen.getByRole('checkbox', { name: 'Uitgelicht' });
box.focus();
await userEvent.keyboard(' ');
expect(box).toBeChecked();
await userEvent.click(screen.getByText('Uitgelicht'));
expect(box).not.toBeChecked();
});
it('shows the in-between state and does not change its value', () => {
render(<Checkbox aria-label="alles" indeterminate />);
const box = screen.getByRole('checkbox', { name: 'alles' }) as HTMLInputElement;
expect(box.indeterminate).toBe(true);
expect(box).not.toBeChecked();
});
it('can be disabled and marked invalid', async () => {
render(<Checkbox aria-label="x" disabled invalid />);
const box = screen.getByRole('checkbox', { name: 'x' });
expect(box).toBeDisabled();
expect(box).toHaveAttribute('aria-invalid', 'true');
await userEvent.click(box);
expect(box).not.toBeChecked();
});
it('draws with the colours of the theme (accent when checked, a visible border, a focus ring)', () => {
render(<Checkbox aria-label="x" />);
const cls = screen.getByRole('checkbox').className;
expect(cls).toContain('checked:bg-primary');
expect(cls).toContain('border-muted-foreground');
expect(cls).toContain('focus-visible:ring-ring');
expect(cls).toContain('forced-colors:checked:bg-[Highlight]');
});
it('works with react-hook-form register, like the native input it replaces', async () => {
function Form({ onSubmit }: { onSubmit: (v: { on: boolean }) => void }) {
const { register, handleSubmit } = useForm<{ on: boolean }>({ defaultValues: { on: false } });
return (
<form onSubmit={handleSubmit(onSubmit)}>
<CheckboxField label="Aan" {...register('on')} />
<button type="submit">go</button>
</form>
);
}
let saved: { on: boolean } | null = null;
render(
<Form
onSubmit={(v) => {
saved = v;
}}
/>,
);
await userEvent.click(screen.getByLabelText('Aan'));
await userEvent.click(screen.getByText('go'));
await screen.findByText('go');
expect(saved).toEqual({ on: true });
});
});
describe('Radio', () => {
it('is a real radio group: the arrow keys move and select, with a name for the group', async () => {
render(
<RadioGroup label="Weergave">
<RadioField name="d" value="single" label="Enkel" defaultChecked />
<RadioField name="d" value="slideshow" label="Diavoorstelling" />
</RadioGroup>,
);
expect(screen.getByRole('radiogroup', { name: 'Weergave' })).toBeInTheDocument();
const first = screen.getByRole('radio', { name: 'Enkel' });
const second = screen.getByRole('radio', { name: 'Diavoorstelling' });
first.focus();
await userEvent.keyboard('{ArrowDown}');
expect(second).toBeChecked();
expect(first).not.toBeChecked();
expect(second).toHaveFocus();
});
it('can be disabled and marked invalid, and uses theme colours', () => {
render(<Radio aria-label="r" name="g" value="a" disabled invalid />);
const radio = screen.getByRole('radio');
expect(radio).toBeDisabled();
expect(radio).toHaveAttribute('aria-invalid', 'true');
expect(radio.className).toContain('checked:border-primary');
expect(radio.className).toContain('forced-colors:checked:border-[Highlight]');
});
});
+77
View File
@@ -0,0 +1,77 @@
import * as React from 'react';
import { Check, Minus } from 'lucide-react';
import { cn } from '@/lib/utils';
export interface CheckboxProps extends Omit<React.ComponentProps<'input'>, 'type' | 'size'> {
/** The "some of them" state of a parent checkbox. It is shown with a minus; the value of the box itself does not change. */
indeterminate?: boolean;
/** The field has an error: a red border (and aria-invalid for screen readers). */
invalid?: boolean;
}
/**
* A real checkbox (a native input: Space toggles it, it works with a label, with react-hook-form's register and in forms),
* drawn in the colours of the theme: a clear border, the accent colour with a check mark when checked, a minus for the
* in-between state, hover, a focus ring, disabled and error states. The check mark is an icon over the input in the
* "primary foreground" colour; in forced-colors (high contrast) mode the system colours take over.
*/
export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
({ className, indeterminate = false, invalid = false, ...props }, forwardedRef) => {
const inner = React.useRef<HTMLInputElement | null>(null);
const setRef = (element: HTMLInputElement | null) => {
inner.current = element;
if (typeof forwardedRef === 'function') forwardedRef(element);
else if (forwardedRef) forwardedRef.current = element;
};
React.useEffect(() => {
if (inner.current) inner.current.indeterminate = indeterminate;
}, [indeterminate]);
return (
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
<input
ref={setRef}
type="checkbox"
aria-invalid={invalid || undefined}
className={cn(
'peer size-5 shrink-0 cursor-pointer appearance-none rounded border-2 border-muted-foreground bg-background transition-colors',
'hover:border-primary checked:border-primary checked:bg-primary indeterminate:border-primary indeterminate:bg-primary',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ring-offset-background',
'disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:border-destructive',
'forced-colors:checked:bg-[Highlight] forced-colors:checked:border-[Highlight]',
className,
)}
{...props}
/>
<Check
className="pointer-events-none absolute size-3.5 text-primary-foreground opacity-0 peer-checked:opacity-100 peer-indeterminate:opacity-0 peer-disabled:opacity-50 forced-colors:text-[HighlightText]"
strokeWidth={3}
aria-hidden="true"
/>
<Minus
className="pointer-events-none absolute size-3.5 text-primary-foreground opacity-0 peer-indeterminate:opacity-100 peer-disabled:opacity-50 forced-colors:text-[HighlightText]"
strokeWidth={3}
aria-hidden="true"
/>
</span>
);
},
);
Checkbox.displayName = 'Checkbox';
interface CheckboxFieldProps extends CheckboxProps {
label: React.ReactNode;
}
/** A checkbox with its label: the whole line is clickable and at least 24 px high. */
export const CheckboxField = React.forwardRef<HTMLInputElement, CheckboxFieldProps>(({ label, id, disabled, ...props }, ref) => {
const generated = React.useId();
const inputId = id ?? generated;
return (
<label htmlFor={inputId} className={cn('inline-flex min-h-6 cursor-pointer items-center gap-2 py-0.5 text-sm', disabled && 'cursor-not-allowed opacity-70')}>
<Checkbox ref={ref} id={inputId} disabled={disabled} {...props} />
<span>{label}</span>
</label>
);
});
CheckboxField.displayName = 'CheckboxField';
+61
View File
@@ -0,0 +1,61 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
export interface RadioProps extends Omit<React.ComponentProps<'input'>, 'type' | 'size'> {
invalid?: boolean;
}
/**
* A real radio button (a native input: with the same name the arrow keys move and select inside the group, Space selects),
* drawn in the colours of the theme: a clear round border, the accent colour with a dot when selected, hover, a focus
* ring, disabled and error states, and system colours in forced-colors (high contrast) mode.
*/
export const Radio = React.forwardRef<HTMLInputElement, RadioProps>(({ className, invalid = false, ...props }, ref) => (
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
<input
ref={ref}
type="radio"
aria-invalid={invalid || undefined}
className={cn(
'peer size-5 shrink-0 cursor-pointer appearance-none rounded-full border-2 border-muted-foreground bg-background transition-colors',
'hover:border-primary checked:border-primary',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ring-offset-background',
'disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:border-destructive',
'forced-colors:checked:border-[Highlight]',
className,
)}
{...props}
/>
<span
className="pointer-events-none absolute size-2.5 rounded-full bg-primary opacity-0 peer-checked:opacity-100 peer-disabled:opacity-50 forced-colors:bg-[Highlight]"
aria-hidden="true"
/>
</span>
));
Radio.displayName = 'Radio';
interface RadioFieldProps extends RadioProps {
label: React.ReactNode;
}
/** A radio button with its label: the whole line is clickable and at least 24 px high. */
export const RadioField = React.forwardRef<HTMLInputElement, RadioFieldProps>(({ label, id, disabled, ...props }, ref) => {
const generated = React.useId();
const inputId = id ?? generated;
return (
<label htmlFor={inputId} className={cn('inline-flex min-h-6 cursor-pointer items-center gap-2 py-0.5 text-sm', disabled && 'cursor-not-allowed opacity-70')}>
<Radio ref={ref} id={inputId} disabled={disabled} {...props} />
<span>{label}</span>
</label>
);
});
RadioField.displayName = 'RadioField';
/** The group around related radio buttons: role radiogroup with a name, so a screen reader announces what is chosen. */
export function RadioGroup({ label, className, children, ...props }: { label: string } & Omit<React.ComponentProps<'div'>, 'aria-label'>) {
return (
<div role="radiogroup" aria-label={label} className={cn('flex flex-wrap gap-x-6 gap-y-1', className)} {...props}>
{children}
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import html from '../index.html?raw';
import themeScript from '../public/theme-init.js?raw';
// The host sends Content-Security-Policy "script-src 'self'": an inline script in the admin page is blocked there, so the
// page must have none (the theme is set by /theme-init.js, a file of its own).
describe('the admin page and the Content-Security-Policy', () => {
it('has no inline script', () => {
const inline = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].filter(([, attributes]) => !/\bsrc\s*=/.test(attributes));
expect(inline).toEqual([]);
});
it('sets the theme from a file of its own, before the app', () => {
expect(html.indexOf('src="/theme-init.js"')).toBeGreaterThan(-1);
expect(html.indexOf('src="/theme-init.js"')).toBeLessThan(html.indexOf('src="/src/main.tsx"'));
expect(themeScript).toContain("localStorage.getItem('cms-theme')");
expect(themeScript).toContain('classList.add');
});
it('has no inline event handlers or javascript: links either', () => {
expect(html).not.toMatch(/\son[a-z]+\s*=/i);
expect(html).not.toMatch(/javascript:/i);
});
});
@@ -0,0 +1,74 @@
import { Crop } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { WIDE, cropFor } from '../lib/focusMath';
import { mediaUrl } from '../lib/media';
import type { HeroFocusRequest, HeroImageDto } from '../services/types';
interface CropThumbnailProps {
image: HeroImageDto;
/** The small picture of the published (saved) crop. */
savedSrc: string;
/** A focus change that was applied in the dialog and is not saved yet: the thumbnail then shows that crop already. */
edit?: HeroFocusRequest;
onClick: () => void;
testId: string;
}
/**
* The picture of a slide, and at the same time the way to change its crop: a real button (so keyboard and screen reader
* users have it too). A hint with a crop icon and "Adjust crop" shows on hover and on keyboard focus, and a small crop
* icon is always there, so it can be found on a touch screen as well. After "Apply" in the dialog the thumbnail shows
* the new crop right away (the same calculation as the host) with a clear "not saved yet" note.
*/
export function CropThumbnail({ image, savedSrc, edit, onClick, testId }: CropThumbnailProps) {
const { t } = useTranslation();
const local = edit && image.previewSrc ? localCrop(image, edit) : null;
return (
<button
type="button"
onClick={onClick}
aria-label={t('hero.slides.cropEdit')}
className={`group relative block aspect-[3/2] w-28 shrink-0 cursor-pointer overflow-hidden rounded bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${edit ? 'ring-2 ring-amber-500' : ''}`}
data-testid={testId}
>
{local && image.previewSrc ? (
<img src={mediaUrl(image.previewSrc)} alt="" draggable={false} className="absolute max-w-none" style={local} data-testid={`${testId}-local`} />
) : (
<img src={savedSrc} alt="" draggable={false} className="h-full w-full object-cover" />
)}
{/* Always there, so it is found without hovering (touch screens). */}
<span className="pointer-events-none absolute right-1 top-1 rounded bg-black/55 p-1 text-white" aria-hidden="true">
<Crop className="size-3" />
</span>
{/* The explanation on hover and keyboard focus. */}
<span
className="pointer-events-none absolute inset-0 flex items-center justify-center gap-1 bg-black/55 px-1 text-center text-[11px] font-medium leading-tight text-white opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100 motion-reduce:transition-none"
aria-hidden="true"
>
<Crop className="size-4 shrink-0" />
{t('hero.slides.cropEdit')}
</span>
{edit && (
<span
className="pointer-events-none absolute inset-x-0 bottom-0 bg-amber-500 px-1 py-0.5 text-center text-[10px] font-medium leading-tight text-black"
data-testid={`${testId}-pending`}
>
{t('hero.slides.focusPending')}
</span>
)}
</button>
);
}
/** Places the whole picture in the box so exactly the crop of the host shows (the same calculation as the dialog). */
function localCrop(image: HeroImageDto, edit: HeroFocusRequest) {
const focus = edit.wide ?? edit.focus;
const crop = cropFor(image.width, image.height, WIDE, focus);
return {
width: `${(image.width / crop.width) * 100}%`,
left: `${(-crop.x / crop.width) * 100}%`,
// top is a percentage of the box height: the box width times denominator over numerator.
top: `${(-crop.y / crop.width) * (WIDE.numerator / WIDE.denominator) * 100}%`,
};
}
@@ -0,0 +1,251 @@
import { useRef, useState, type KeyboardEvent, type PointerEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
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 type { FocusDto, HeroFocusRequest, HeroImageDto } from '../services/types';
type Target = 'general' | 'wide' | 'tall';
interface FocusDialogProps {
/** The image to edit, with a not yet saved change of its focus already applied; null = closed. */
image: HeroImageDto | null;
/** Keeps the change locally: it is sent and made live when the hero is saved, and dropped when the page is left. */
onApply: (imageId: string, request: HeroFocusRequest) => void;
onClose: () => void;
}
export function FocusDialog({ image, onApply, onClose }: FocusDialogProps) {
const { t } = useTranslation();
return (
<Dialog open={image !== null} onOpenChange={(next) => { if (!next) onClose(); }}>
<DialogContent className="max-h-[92vh] overflow-y-auto sm:max-w-3xl">
<DialogHeader>
<DialogTitle>{t('hero.focus.title')}</DialogTitle>
</DialogHeader>
{/* Mounted only while open, so every opening starts from the stored values. */}
{image && <FocusEditor image={image} onApply={onApply} onClose={onClose} />}
</DialogContent>
</Dialog>
);
}
const percent = (fraction: number) => Math.round(fraction * 1000) / 10;
function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply: (imageId: string, request: HeroFocusRequest) => void; onClose: () => void }) {
const { t } = useTranslation();
const area = useRef<HTMLDivElement>(null);
// The whole picture: image.src is already a crop of the wide shape and would be shown stretched and out of place.
const previewUrl = image.previewSrc ? mediaUrl(image.previewSrc) : null;
const [target, setTarget] = useState<Target>('general');
const [general, setGeneral] = useState<FocusDto>(image.focus ?? CENTRE);
const [wide, setWide] = useState<FocusDto | null>(image.wideFocus);
const [tall, setTall] = useState<FocusDto | null>(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<HTMLDivElement>) => {
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<HTMLDivElement>) => {
if (!editable) return;
const step = event.shiftKey ? 0.05 : 0.01;
const moves: Record<string, [number, number]> = { 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 = () => {
onApply(image.id, { focus: general, wide, tall });
onClose();
};
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 (
<div className="space-y-4" data-testid="focus-dialog">
<p className="text-sm text-muted-foreground">{t('hero.focus.intro')}</p>
<p className="text-sm font-medium" data-testid="focus-apply-hint">{t('hero.focus.applyHint')}</p>
<fieldset className="flex flex-wrap gap-4">
<legend className="sr-only">{t('hero.focus.targetLegend')}</legend>
{(['general', 'wide', 'tall'] as const).map((value) => (
<label key={value} className="flex items-center gap-2 text-sm">
<input
type="radio"
name="focus-target"
checked={target === value}
onChange={() => setTarget(value)}
data-testid={`focus-target-${value}`}
/>
{t(`hero.focus.target.${value}`)}
</label>
))}
</fieldset>
{target !== 'general' && (
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={editable}
onChange={(event) => toggleOverride(event.target.checked)}
data-testid={`focus-override-${target}`}
/>
{t('hero.focus.override')}
</label>
)}
<div className="grid gap-4 md:grid-cols-[2fr_1fr]">
<div>
<div
ref={area}
role="group"
tabIndex={0}
aria-label={t('hero.focus.areaLabel')}
className="relative touch-none select-none overflow-hidden rounded-md border"
style={{ aspectRatio: `${image.width} / ${image.height}` }}
onPointerDown={(event) => {
event.currentTarget.setPointerCapture?.(event.pointerId);
moveTo(event);
}}
onPointerMove={(event) => {
if (event.buttons === 1) moveTo(event);
}}
onKeyDown={onKeyDown}
data-testid="focus-area"
>
{previewUrl ? (
<img src={previewUrl} alt="" draggable={false} className="pointer-events-none absolute inset-0 h-full w-full object-cover" />
) : (
<p className="absolute inset-0 flex items-center justify-center bg-muted p-4 text-center text-sm text-muted-foreground" role="status" data-testid="focus-preview-pending">
{t('hero.focus.previewPending')}
</p>
)}
<div className="pointer-events-none absolute border-2 border-sky-400" style={outline(WIDE, effective.wide)} data-testid="focus-outline-wide" />
<div className="pointer-events-none absolute border-2 border-amber-400" style={outline(TALL, effective.tall)} data-testid="focus-outline-tall" />
<div
className="pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-red-500/80 shadow"
style={{ left: `${active.x * 100}%`, top: `${active.y * 100}%` }}
data-testid="focus-marker"
/>
</div>
<p className="mt-1 text-xs text-muted-foreground">{t('hero.focus.areaHint')}</p>
</div>
<div className="space-y-3">
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label htmlFor="focus-x">{t('hero.focus.x')}</Label>
<Input
id="focus-x"
type="number"
min={0}
max={100}
step={0.5}
disabled={!editable}
value={percent(active.x)}
onChange={(event) => update({ ...active, x: Number(event.target.value) / 100 })}
data-testid="focus-x"
/>
</div>
<div className="space-y-1">
<Label htmlFor="focus-y">{t('hero.focus.y')}</Label>
<Input
id="focus-y"
type="number"
min={0}
max={100}
step={0.5}
disabled={!editable}
value={percent(active.y)}
onChange={(event) => update({ ...active, y: Number(event.target.value) / 100 })}
data-testid="focus-y"
/>
</div>
</div>
<div className="space-y-1">
<Label htmlFor="focus-zoom">{t('hero.focus.zoom', { value: active.zoom.toFixed(2) })}</Label>
<input
id="focus-zoom"
type="range"
min={1}
max={MAX_ZOOM}
step={0.05}
disabled={!editable}
value={active.zoom}
onChange={(event) => update({ ...active, zoom: Number(event.target.value) })}
className="w-full"
data-testid="focus-zoom"
/>
</div>
{([WIDE, TALL] as const).map((ratio) => {
const crop = cropFor(image.width, image.height, ratio, effective[ratio.name]);
return (
<div key={ratio.name}>
<p className="mb-1 text-xs font-medium">{t(`hero.focus.preview.${ratio.name}`)}</p>
<div
className="relative overflow-hidden rounded border bg-muted"
style={{ aspectRatio: `${ratio.numerator} / ${ratio.denominator}`, maxWidth: ratio.name === 'tall' ? '8rem' : '12rem' }}
data-testid={`focus-preview-${ratio.name}`}
>
{previewUrl && <img
src={previewUrl}
alt=""
className="absolute max-w-none"
style={{
width: `${(image.width / crop.width) * 100}%`,
left: `${(-crop.x / crop.width) * 100}%`,
// top is a percentage of the box height, which is the box width times denominator over numerator.
top: `${(-crop.y / crop.width) * (ratio.numerator / ratio.denominator) * 100}%`,
}}
/>}
</div>
</div>
);
})}
</div>
</div>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose} data-testid="focus-cancel">
{t('common.cancel')}
</Button>
<Button type="button" onClick={onSave} data-testid="focus-save">
{t('hero.focus.apply')}
</Button>
</div>
</div>
);
}
@@ -0,0 +1,106 @@
import { useRef, type KeyboardEvent, type ReactNode } from 'react';
export interface HeroTab<Id extends string> {
id: Id;
label: ReactNode;
/** Short note after the label, for example "2 busy". */
note?: string;
/** There are unsaved changes in this tab: a dot and a text for screen readers. */
changed?: boolean;
changedText?: string;
/** This tab holds a field with an error: a red mark and a text for screen readers. */
invalid?: boolean;
invalidText?: string;
}
interface HeroTabsProps<Id extends string> {
label: string;
tabs: HeroTab<Id>[];
selected: Id;
onSelect: (id: Id) => void;
idPrefix: string;
}
/**
* Accessible tabs (role tablist, tab, tabpanel): the arrow keys move between the tabs (and select, "automatic activation"),
* Home and End go to the first and the last, only the selected tab is in the tab order. The panels themselves are rendered
* by the page, with <c>id="{idPrefix}-panel-{id}"</c> and <c>aria-labelledby="{idPrefix}-tab-{id}"</c>.
*/
export function HeroTabs<Id extends string>({ label, tabs, selected, onSelect, idPrefix }: HeroTabsProps<Id>) {
const refs = useRef<Record<string, HTMLButtonElement | null>>({});
const move = (index: number) => {
const next = tabs[(index + tabs.length) % tabs.length];
onSelect(next.id);
refs.current[next.id]?.focus();
};
const onKeyDown = (event: KeyboardEvent, index: number) => {
switch (event.key) {
case 'ArrowRight':
case 'ArrowDown':
event.preventDefault();
move(index + 1);
break;
case 'ArrowLeft':
case 'ArrowUp':
event.preventDefault();
move(index - 1);
break;
case 'Home':
event.preventDefault();
move(0);
break;
case 'End':
event.preventDefault();
move(tabs.length - 1);
break;
default:
}
};
return (
<div role="tablist" aria-label={label} className="flex gap-1 border-b" data-testid="hero-tabs">
{tabs.map((tab, index) => {
const active = tab.id === selected;
return (
<button
key={tab.id}
ref={(element) => {
refs.current[tab.id] = element;
}}
type="button"
role="tab"
id={`${idPrefix}-tab-${tab.id}`}
aria-selected={active}
aria-controls={`${idPrefix}-panel-${tab.id}`}
tabIndex={active ? 0 : -1}
onClick={() => onSelect(tab.id)}
onKeyDown={(event) => onKeyDown(event, index)}
className={`-mb-px inline-flex items-center gap-2 rounded-t-md border-b-2 px-4 py-2 text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${
active ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'
}`}
data-testid={`hero-tab-${tab.id}`}
>
{tab.label}
{tab.note && <span className="text-xs font-normal text-muted-foreground">({tab.note})</span>}
{tab.changed && (
<>
<span className="size-2 rounded-full bg-amber-500" aria-hidden="true" data-testid={`hero-tab-${tab.id}-changed`} />
<span className="sr-only">{tab.changedText}</span>
</>
)}
{tab.invalid && (
<>
<span className="inline-flex size-4 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-destructive-foreground" aria-hidden="true" data-testid={`hero-tab-${tab.id}-invalid`}>
!
</span>
<span className="sr-only">{tab.invalidText}</span>
</>
)}
</button>
);
})}
</div>
);
}
@@ -0,0 +1,156 @@
import { Check, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { useRetryHeroImage } from '../services/hooks';
import type { HeroImageDto } from '../services/types';
/** A spinner that stands still for people who asked for less motion. */
export function Spinner({ className = 'size-4' }: { className?: string }) {
return <Loader2 className={`${className} animate-spin motion-reduce:animate-none`} aria-hidden="true" />;
}
/**
* Shown above the form while photos of the saved hero are still being prepared in the background: how many are ready,
* what that means for the website, and a way to try again for a photo that failed.
*/
export function ProcessingStatus({ images }: { images: HeroImageDto[] }) {
const { t } = useTranslation();
const retry = useRetryHeroImage();
const total = images.length;
const waiting = images.filter((image) => image.processing);
if (waiting.length === 0) return null;
const done = total - waiting.length;
const failed = waiting.filter((image) => image.failed);
const working = waiting.length - failed.length;
// The photo the server is busy with right now, and how far along it is (a photo that waits has no step yet).
const busy = waiting.find((image) => image.renderTotal) ?? null;
const fraction = busy && busy.renderTotal ? (busy.renderDone ?? 0) / busy.renderTotal : 0;
const percent = total === 0 ? 0 : Math.min(100, ((done + fraction) / total) * 100);
return (
<div className="space-y-3 rounded-md border bg-muted/40 p-4" data-testid="hero-processing">
{working > 0 && (
<div className="space-y-2" role="status">
<p className="flex items-center gap-2 text-sm font-medium">
<Spinner />
<span data-testid="hero-processing-count">{t('hero.processing.count', { done, total })}</span>
</p>
<div
role="progressbar"
aria-label={t('hero.processing.label')}
aria-valuemin={0}
aria-valuemax={total}
aria-valuenow={done}
aria-valuetext={t('hero.processing.count', { done, total })}
className="h-2 w-full overflow-hidden rounded bg-muted"
data-testid="hero-processing-bar"
>
<div className="h-full bg-primary transition-all" style={{ width: `${percent}%` }} />
</div>
{busy && (
<p className="text-sm" data-testid="hero-processing-current">
{t('hero.processing.current', { n: done + 1, total, step: busy.renderDone ?? 0, steps: busy.renderTotal })}
</p>
)}
<p className="text-sm text-muted-foreground">{t('hero.processing.explain')}</p>
<p className="text-sm text-muted-foreground">
{t('hero.processing.stuck')}{' '}
<button
type="button"
className="underline underline-offset-2 hover:text-foreground disabled:opacity-50"
disabled={retry.isPending}
onClick={() => waiting.forEach((image) => retry.mutate(image.id))}
data-testid="hero-processing-retry-all"
>
{t('hero.processing.retry')}
</button>
</p>
</div>
)}
{failed.length > 0 && (
<div className="space-y-2" role="alert" data-testid="hero-processing-failed">
<p className="text-sm font-medium text-destructive">{t('hero.processing.failed', { count: failed.length })}</p>
<p className="text-sm text-muted-foreground">{t('hero.processing.failedHint')}</p>
<Button
type="button"
variant="outline"
size="sm"
disabled={retry.isPending}
onClick={() => failed.forEach((image) => retry.mutate(image.id))}
data-testid="hero-processing-retry"
>
{t('hero.processing.retry')}
</Button>
</div>
)}
</div>
);
}
/**
* The place of a photo that has no pictures yet: one calm shimmer (hidden from assistive technology) and a readable
* text. It lives in the row of the slide, so it stays mounted (and the animation keeps running) while the page asks the
* server again every few seconds, and it disappears when the photo is ready.
*/
export function PhotoPlaceholder({ failed, testId, step }: { failed: boolean; testId: string; step?: { done: number; total: number } | null }) {
const { t } = useTranslation();
return (
<div
className={`flex h-20 w-28 flex-col items-center justify-center gap-1 rounded p-1 text-center text-xs ${failed ? 'bg-destructive/10 text-destructive' : 'hero-shimmer bg-muted'}`}
role="status"
aria-busy={!failed}
title={t('hero.slides.processingHint')}
data-testid={testId}
>
{failed ? null : <Spinner className="size-3.5" />}
<span>{failed ? t('hero.slides.failed') : t('hero.slides.processing')}</span>
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
{!failed && !step ? <span className="opacity-70" data-testid={`${testId}-queued`}>{t('hero.slides.queued')}</span> : null}
</div>
);
}
/**
* The photo of a slide whose crop is being made again (a changed focus point): the old picture stays visible underneath,
* with the same calm shimmer and a short text, so it is clear that the change is not on the website yet.
*/
export function RecutThumbnail({ src, failed, testId, step }: { src: string; failed: boolean; testId: string; step?: { done: number; total: number } | null }) {
const { t } = useTranslation();
return (
<div
className={`relative h-20 w-28 shrink-0 overflow-hidden rounded ${failed ? 'ring-2 ring-destructive' : 'hero-shimmer'}`}
role="status"
aria-busy={!failed}
title={t('hero.slides.recutHint')}
data-testid={testId}
>
<img src={src} alt="" className="h-full w-full object-cover" />
<span className={`absolute inset-x-0 bottom-0 flex items-center justify-center gap-1 px-1 py-0.5 text-center text-[10px] leading-tight ${failed ? 'bg-destructive text-destructive-foreground' : 'bg-background/85 text-foreground'}`}>
{failed ? null : <Spinner className="size-3" />}
<span>{failed ? t('hero.slides.failed') : t('hero.slides.recut')}</span>
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
</span>
</div>
);
}
/**
* Per photo: shortly after its processing is done a check mark with "Processing finished" shows on that photo itself and
* fades away. The region is always there (empty) so a screen reader announces the text when it appears; the text names
* the slide. With reduced motion it does not fade but disappears after the same time.
*/
export function DoneStatus({ done, slideNumber, testId }: { done: boolean; slideNumber: number; testId: string }) {
const { t } = useTranslation();
return (
<div role="status" aria-live="polite" className="min-h-4 text-[11px] leading-tight" data-testid={testId}>
{done && (
<span className="hero-done inline-flex items-center gap-1 font-medium text-green-700 dark:text-green-400" data-testid={`${testId}-text`}>
<Check className="size-3.5" aria-hidden="true" />
<span className="sr-only">{t('hero.slides.doneFor', { n: slideNumber })}</span>
<span aria-hidden="true">{t('hero.slides.done')}</span>
</span>
)}
</div>
);
}
@@ -0,0 +1,33 @@
import { useTranslation } from 'react-i18next';
interface SlideSwitchProps {
checked: boolean;
onChange: (checked: boolean) => void;
testId: string;
/** What a screen reader says besides the visible text, so the switch is clearly about this slide. */
slideNumber: number;
}
/** A switch (role="switch") that turns a slide on or off; the text next to it says the current state. */
export function SlideSwitch({ checked, onChange, testId, slideNumber }: SlideSwitchProps) {
const { t } = useTranslation();
return (
<button
type="button"
role="switch"
aria-checked={checked}
onClick={() => onChange(!checked)}
className="flex items-center gap-2 rounded-md px-1 py-1 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
data-testid={testId}
>
<span
aria-hidden="true"
className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border transition-colors ${checked ? 'border-primary bg-primary' : 'border-input bg-muted'}`}
>
<span className={`inline-block size-4 rounded-full bg-background shadow transition-transform motion-reduce:transition-none ${checked ? 'translate-x-[1.1rem]' : 'translate-x-0.5'}`} />
</span>
<span className="min-w-[4.5rem] text-left">{checked ? t('hero.slides.activeOn') : t('hero.slides.activeOff')}</span>
<span className="sr-only">{t('hero.slides.activeFor', { n: slideNumber })}</span>
</button>
);
}
@@ -0,0 +1,48 @@
import type { ReactNode } from 'react';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { GripVertical } from 'lucide-react';
import { useTranslation } from 'react-i18next';
interface SortableSlideProps {
/** The id of the form field of this slide (stable while the order changes). */
id: string;
index: number;
/** A slide that is switched off is shown dimmed. */
dimmed?: boolean;
children: ReactNode;
}
/**
* One row of the image list that can be dragged by its handle (mouse, touch or keyboard: focus the handle, press Space,
* use the arrow keys, press Space again). The arrow buttons of the row stay as another way to change the order. While
* dragging, the row gets a frame and a shadow and the other rows make room, so it is clear where it will land.
*/
export function SortableSlide({ id, index, dimmed = false, children }: SortableSlideProps) {
const { t } = useTranslation();
const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id });
return (
<li
ref={setNodeRef}
style={{ transform: CSS.Transform.toString(transform), transition, position: 'relative', zIndex: isDragging ? 10 : undefined }}
className={`flex flex-wrap items-start gap-3 rounded-md border bg-background p-3 ${isDragging ? 'shadow-lg ring-2 ring-primary' : ''} ${dimmed ? 'opacity-60' : ''}`}
data-testid={`hero-slide-${index}`}
data-dragging={isDragging ? 'true' : undefined}
data-inactive={dimmed ? 'true' : undefined}
>
<button
type="button"
ref={setActivatorNodeRef}
className="mt-1 cursor-grab touch-none rounded p-1 text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
aria-label={t('hero.slides.drag', { n: index + 1 })}
data-testid={`hero-slide-${index}-drag`}
{...attributes}
{...listeners}
>
<GripVertical className="size-5" aria-hidden="true" />
</button>
{children}
</li>
);
}
@@ -0,0 +1,37 @@
import { useBlocker } from '@tanstack/react-router';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
/**
* Asks for confirmation before the administrator leaves the page through the menu or a link while the form holds changes
* that are not saved. (Closing the tab or reloading is covered by the browser warning in the page itself.)
*/
export function UnsavedChangesGuard({ dirty }: { dirty: boolean }) {
const { t } = useTranslation();
const blocker = useBlocker({
shouldBlockFn: () => dirty,
disabled: !dirty,
enableBeforeUnload: false,
withResolver: true,
});
return (
<Dialog open={blocker.status === 'blocked'} onOpenChange={(open) => { if (!open) blocker.reset?.(); }}>
<DialogContent data-testid="hero-leave-dialog">
<DialogHeader>
<DialogTitle>{t('hero.unsaved.leaveTitle')}</DialogTitle>
<DialogDescription>{t('hero.unsaved.leaveText')}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button type="button" onClick={() => blocker.reset?.()} data-testid="hero-leave-stay">
{t('hero.unsaved.stay')}
</Button>
<Button type="button" variant="destructive" onClick={() => blocker.proceed?.()} data-testid="hero-leave-discard">
{t('hero.unsaved.discard')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,54 @@
import { AlertCircle, Check, Clock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Spinner } from './ProcessingStatus';
export interface UploadItem {
key: number;
name: string;
status: 'waiting' | 'uploading' | 'done' | 'failed';
/** Why it failed, in words for the administrator. */
message?: string;
}
/** The files of the last choice, one row each: waiting, busy (spinner), added, or failed with the reason. */
export function UploadProgress({ items, busy, onClose }: { items: UploadItem[]; busy: boolean; onClose: () => void }) {
const { t } = useTranslation();
if (items.length === 0) return null;
const finished = items.filter((i) => i.status === 'done' || i.status === 'failed').length;
const added = items.filter((i) => i.status === 'done').length;
return (
<div className="space-y-2 rounded-md border p-3" data-testid="hero-upload-list" aria-busy={busy}>
<p className="text-sm font-medium" role="status" data-testid="hero-upload-summary">
{busy ? t('hero.upload.progress', { done: finished, total: items.length }) : t('hero.upload.summary', { ok: added, total: items.length })}
</p>
<ul className="space-y-1 text-sm">
{items.map((item) => (
<li key={item.key} className="flex items-start gap-2" data-testid={`hero-upload-item-${item.key}`} data-status={item.status}>
<span className="mt-0.5 shrink-0">
{item.status === 'uploading' && <Spinner />}
{item.status === 'waiting' && <Clock className="size-4 text-muted-foreground" aria-hidden="true" />}
{item.status === 'done' && <Check className="size-4 text-green-600" aria-hidden="true" />}
{item.status === 'failed' && <AlertCircle className="size-4 text-destructive" aria-hidden="true" />}
</span>
<span className="min-w-0 flex-1 break-words">
<span className="font-medium">{item.name}</span>
{' – '}
{item.status === 'failed' ? (
<span className="text-destructive" role="alert" data-testid="hero-upload-error">{item.message}</span>
) : (
<span className="text-muted-foreground">{t(`hero.upload.${item.status}`)}</span>
)}
</span>
</li>
))}
</ul>
{!busy && (
<Button type="button" variant="outline" size="sm" onClick={onClose} data-testid="hero-upload-close">
{t('hero.upload.close')}
</Button>
)}
</div>
);
}
@@ -0,0 +1,107 @@
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);
});
});
describe('the crop of both shapes for every kind of picture', () => {
// landscape 3:2, the two common cameras, portrait, square, a panorama and a very tall strip
const sources: [string, number, number][] = [
['landscape 3:2', 3000, 2000],
['landscape 4:3', 2048, 1536],
['portrait 2:3', 2000, 3000],
['square', 1500, 1500],
['panorama 3:1', 6000, 2000],
['tall strip 1:3', 800, 2400],
];
const points = [CENTRE, { x: 0, y: 0, zoom: 1 }, { x: 1, y: 1, zoom: 1 }, { x: 0.2, y: 0.8, zoom: 2 }, { x: 0.5, y: 0.5, zoom: 4 }];
it.each(sources)('%s: both crops have exactly their shape (to the pixel), lie inside the picture and keep the point', (_name, width, height) => {
for (const ratio of [WIDE, TALL]) {
for (const focus of points) {
const crop = cropFor(width, height, ratio, focus);
// One pixel of rounding at most: the crop is never stretched to another shape.
expect(Math.abs(crop.width * ratio.denominator - crop.height * ratio.numerator)).toBeLessThanOrEqual(Math.max(ratio.numerator, ratio.denominator));
expect(crop.x).toBeGreaterThanOrEqual(0);
expect(crop.y).toBeGreaterThanOrEqual(0);
expect(crop.x + crop.width).toBeLessThanOrEqual(width);
expect(crop.y + crop.height).toBeLessThanOrEqual(height);
}
}
});
it.each(sources)('%s: the preview box shows the crop at its own shape (no stretching)', (_name, width, height) => {
// The preview places the WHOLE picture inside a box of the crop shape: scale = box width / crop width, so the
// picture keeps its own shape when its height follows from its width.
for (const ratio of [WIDE, TALL]) {
const crop = cropFor(width, height, ratio, CENTRE);
const boxWidth = 100;
const scale = boxWidth / crop.width;
const pictureWidth = width * scale;
const pictureHeight = pictureWidth * (height / width);
const boxHeight = (boxWidth * ratio.denominator) / ratio.numerator;
// What is visible of the picture in the box is exactly the crop rectangle (same shape as the box).
const visibleWidth = boxWidth / (pictureWidth / width);
const visibleHeight = boxHeight / (pictureHeight / height);
expect(visibleWidth).toBeCloseTo(crop.width, 6);
expect(visibleHeight / visibleWidth).toBeCloseTo(ratio.denominator / ratio.numerator, 2);
}
});
});
@@ -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 };
}
+4
View File
@@ -0,0 +1,4 @@
import { getAppConfig } from '@/lib/config';
/** A media address of the host (<c>/media/...</c>) as the browser must request it from the admin. */
export const mediaUrl = (path: string): string => `${getAppConfig().apiBaseUrl.replace(/\/$/, '')}${path}`;
@@ -0,0 +1,146 @@
import { http, HttpResponse } from 'msw';
import { API_BASE } from '@/features/auth/mocks/fixtures';
import type { HeroAdminDto, 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' },
],
processing: false,
failed: false,
previewSrc: '/media/hero/0123456789abcdef/full-1280.webp',
});
export const emptyHero = (): HeroAdminDto => ({
id: null,
title: '',
tagline: null,
lead: null,
display: 'single',
buttons: [],
slides: [],
isLive: false,
updatedAt: null,
maxPublishedSlides: 50,
});
export const slide = (index: number, over: Partial<HeroSlideAdminDto> = {}): 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<string, HeroImageDto> = {};
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;
retried = [];
recutting = new Set();
};
export const setMockHero = (next: HeroAdminDto): void => {
hero = next;
images = Object.fromEntries(next.slides.map((s) => [s.imageId, s.image]));
};
let retried: string[] = [];
let recutting = new Set<string>();
/** The background work of the mock server is done: images whose crop was being made are ready. */
export const finishMockRecut = (): void => {
recutting.forEach((id) => {
if (images[id]) images[id] = { ...images[id], processing: false };
hero = { ...hero, slides: hero.slides.map((s) => (s.imageId === id ? { ...s, image: { ...s.image, processing: false } } : s)) };
});
recutting = new Set();
};
export const getRetriedImages = (): string[] => retried;
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);
// A changed focus takes effect with the save of the hero.
for (const edit of body.imageFocus ?? []) {
const current = images[edit.imageId] ?? hero.slides.find((s) => s.imageId === edit.imageId)?.image ?? seedImage(edit.imageId);
images[edit.imageId] = { ...current, focus: edit.focus, wideFocus: edit.wide, tallFocus: edit.tall, processing: true };
recutting.add(edit.imageId);
}
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,
isLive: 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.get(`${API_BASE}/api/v1/hero/images/limits`, () =>
HttpResponse.json({ formats: ['JPEG', 'PNG', 'GIF', 'BMP', 'TIFF', 'WebP', 'AVIF'], maxUploadBytes: 10 * 1024 * 1024, maxMegapixels: 64 }),
),
http.get(`${API_BASE}/api/v1/hero/images/:id`, ({ params }) => {
const image = images[String(params.id)];
return image ? HttpResponse.json(image) : new HttpResponse(null, { status: 404 });
}),
http.post(`${API_BASE}/api/v1/hero/images/:id/retry`, ({ params }) => {
retried.push(String(params.id));
return new HttpResponse(null, { status: 204 });
}),
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 });
}),
];
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,629 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useQueries } from '@tanstack/react-query';
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, ImagePlus, Trash2 } from 'lucide-react';
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core';
import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable';
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 { CropThumbnail } from '../components/CropThumbnail';
import { DoneStatus, PhotoPlaceholder, ProcessingStatus, RecutThumbnail, Spinner } from '../components/ProcessingStatus';
import { SlideSwitch } from '../components/SlideSwitch';
import { SortableSlide } from '../components/SortableSlide';
import { HeroTabs } from '../components/HeroTabs';
import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard';
import { UploadProgress, type UploadItem } from '../components/UploadProgress';
import { mediaUrl } from '../lib/media';
import { heroFormSchema, type HeroFormData } from '../schemas/hero';
import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks';
import type { HeroAdminDto, HeroFocusRequest, 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,
slides: hero.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.alt, decorative: s.decorative, isActive: s.isActive })),
};
}
function toRequest(values: HeroFormData, focusEdits: Record<string, HeroFocusRequest>): 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 !== ''),
slides: values.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.decorative ? null : s.alt, decorative: s.decorative, isActive: s.isActive })),
imageFocus: Object.entries(focusEdits).map(([imageId, edit]) => ({ imageId, ...edit })),
};
}
/** 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<string, unknown>).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 most the host accepts for one image (Media:MaxUploadBytes). */
const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
/**
* What to tell the administrator when an upload fails: the message of the host when it sent one, a clear text for a
* refusal by the proxy (413, which has no JSON body) or a rate limit, and a retry hint when the connection broke off.
*/
function uploadMessage(error: unknown, t: (key: string, options?: Record<string, unknown>) => string): string {
if (error instanceof ProblemDetailsError) {
const message = error.problem.message;
if (typeof message === 'string' && message !== '') return message;
if (error.status === 413) return t('hero.upload.tooLarge', { max: MAX_UPLOAD_BYTES / (1024 * 1024) });
if (error.status === 429) return t('hero.upload.busy');
return t('errors.generic');
}
if (error instanceof NetworkError) return t('hero.upload.interrupted');
return t('errors.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 (
<div className="space-y-6" data-testid="hero-page">
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-2xl font-semibold" data-testid="hero-title">{t('hero.title')}</h1>
{hero && (
<Badge variant={hero.isLive ? 'default' : 'secondary'} data-testid="hero-live-badge">
{hero.isLive ? t('hero.live') : t('hero.notLive')}
</Badge>
)}
</div>
<p className="max-w-3xl text-sm text-muted-foreground">{t('hero.intro')}</p>
<details className="max-w-3xl rounded-md border p-3 text-sm" data-testid="hero-help">
<summary className="cursor-pointer font-medium">{t('hero.help.heading')}</summary>
<dl className="mt-3 space-y-2">
{(['title', 'tagline', 'lead', 'buttons', 'display', 'slides', 'focus'] as const).map((key) => (
<div key={key}>
<dt className="font-medium">{t(`hero.help.${key}.name`)}</dt>
<dd className="text-muted-foreground">{t(`hero.help.${key}.text`)}</dd>
</div>
))}
</dl>
<p className="mt-3 text-muted-foreground">{t('hero.help.save')}</p>
</details>
{isLoading && <p data-testid="hero-loading">{t('common.loading')}</p>}
{isError && (
<div className="space-y-2" data-testid="hero-error">
<p>{t('errors.generic')}</p>
<Button variant="outline" onClick={() => void refetch()}>{t('common.retry')}</Button>
</div>
)}
{hero && <HeroEditor key={hero.id ?? 'new'} hero={hero} />}
</div>
);
}
function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const { t } = useTranslation();
const save = useSaveHero();
const upload = useUploadHeroImage();
const [serverError, setServerError] = useState<string | null>(null);
const [uploads, setUploads] = useState<UploadItem[]>([]);
const [uploading, setUploading] = useState(false);
const [draggingFiles, setDraggingFiles] = useState(false);
const nextUploadKey = useRef(0);
const limits = useHeroUploadLimits().data;
const [localImages, setLocalImages] = useState<Record<string, HeroImageDto>>({});
const [focusImageId, setFocusImageId] = useState<string | null>(null);
// Changed focus points are kept here until the hero is saved: they are sent with the save and dropped when the page is left.
const [focusEdits, setFocusEdits] = useState<Record<string, HeroFocusRequest>>({});
const fileInput = useRef<HTMLInputElement>(null);
const {
register,
setValue,
handleSubmit,
control,
formState: { errors, isDirty, dirtyFields },
setFocus,
reset,
} = useForm<HeroFormData>({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', shouldFocusError: false, defaultValues: toForm(hero) });
const slides = useFieldArray({ control, name: 'slides' });
const watchedSlides = useWatch({ control, name: 'slides' }) ?? [];
// The two tabs share one form, one Save button and one "unsaved changes" state. The chosen tab is remembered for this
// browser session.
type TabId = 'content' | 'images';
const [tab, setTabState] = useState<TabId>(() => {
try {
return window.sessionStorage.getItem('cms-hero-tab') === 'images' ? 'images' : 'content';
} catch {
return 'content';
}
});
const setTab = (next: TabId) => {
setTabState(next);
try {
window.sessionStorage.setItem('cms-hero-tab', next);
} catch {
// Remembering the tab is a convenience only.
}
};
// After a failed save: go to the tab of the first field with an error and put the cursor in that field.
const pendingFocus = useRef<{ name: string; tab: TabId } | null>(null);
useEffect(() => {
if (pendingFocus.current && tab === pendingFocus.current.tab) {
setFocus(pendingFocus.current.name as never);
pendingFocus.current = null;
}
}, [tab, setFocus]);
const goToField = (name: string, target: TabId) => {
if (target === tab) {
setFocus(name as never);
return;
}
pendingFocus.current = { name, tab: target };
setTab(target);
};
// The images of the saved hero (always current: a change of focus refreshes them) plus the ones uploaded in this session.
// Photos uploaded here and not saved yet are not in the saved hero: they are asked for one by one until they are ready,
// so a photo that is finished never stays "processing" because nothing refreshed it.
const unsavedIds = useMemo(
() => Object.keys(localImages).filter((id) => !hero.slides.some((s) => s.imageId === id)),
[hero.slides, localImages],
);
const polled = useQueries({
queries: unsavedIds.map((id) => heroImageQuery(id)),
combine: (results) => results.map((r) => r.data),
});
const images = useMemo(() => {
const map: Record<string, HeroImageDto> = { ...localImages };
for (const image of polled) if (image) map[image.id] = image;
for (const s of hero.slides) map[s.imageId] = s.image;
return map;
}, [hero.slides, localImages, polled]);
// Per photo: when its processing is done it shows "Processing finished" for a few seconds, and can be worked on at once.
// A photo that was ready at once (the same photo was already in the CMS) shows the same note, without a placeholder.
const [justDone, setJustDone] = useState<Record<string, true>>({});
const wasProcessing = useRef<Record<string, boolean>>({});
const markDone = (imageId: string) => {
setJustDone((current) => ({ ...current, [imageId]: true }));
window.setTimeout(() => {
setJustDone((current) => {
const { [imageId]: _removed, ...rest } = current;
return rest;
});
}, 4500);
};
useEffect(() => {
for (const field of slides.fields) {
const image = images[field.imageId];
if (!image) continue;
if (image.processing) {
wasProcessing.current[image.id] = true;
} else if (wasProcessing.current[image.id]) {
wasProcessing.current[image.id] = false;
markDone(image.id);
}
}
}, [images, slides.fields]);
// A focus change counts as unsaved only while it differs from what is saved (applying the old point again is no change).
const samePoint = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
const hasPendingFocus = Object.entries(focusEdits).some(([imageId, edit]) => {
const saved = images[imageId];
return !saved || !samePoint(saved.focus, edit.focus) || !samePoint(saved.wideFocus, edit.wide) || !samePoint(saved.tallFocus, edit.tall);
});
// The form is compared with the last saved state (react-hook-form keeps it), so a change that is undone no longer counts.
// Photos still being prepared on the server and the background refresh are not changes of the administrator.
const hasUnsaved = isDirty || hasPendingFocus;
const contentChanged = Object.keys(dirtyFields).some((key) => key !== 'slides');
const imagesChanged = Boolean(dirtyFields.slides?.some?.(Boolean)) || hasPendingFocus;
const contentInvalid = Object.keys(errors).some((key) => key !== 'slides');
const imagesInvalid = Boolean(errors.slides);
const busyCount = slides.fields.filter((f) => images[f.imageId]?.processing).length;
useEffect(() => {
if (!hasUnsaved) return undefined;
const warn = (event: BeforeUnloadEvent) => {
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [hasUnsaved]);
// The image as the dialog shows it: the saved one with a not yet saved change of its focus applied.
const withPendingFocus = (image: HeroImageDto | null): HeroImageDto | null => {
const edit = image ? focusEdits[image.id] : undefined;
return image && edit ? { ...image, focus: edit.focus, wideFocus: edit.wide, tallFocus: edit.tall } : image;
};
// Up to this many files go to the host at the same time; the variants are cut in the background, so an upload itself
// is quick, and two at a time keeps the memory use of a small server in check.
const UPLOAD_PARALLEL = 2;
const onFiles = async (chosen: FileList | File[] | null) => {
const files = Array.from(chosen ?? []);
if (files.length === 0 || uploading) return;
const maxBytes = limits?.maxUploadBytes ?? MAX_UPLOAD_BYTES;
const maxMb = Math.round(maxBytes / (1024 * 1024));
const items: UploadItem[] = files.map((file) => ({ key: nextUploadKey.current++, name: file.name, status: 'waiting' }));
setUploads(items);
setUploading(true);
const update = (i: number, patch: Partial<UploadItem>) =>
setUploads((current) => current.map((u) => (u.key === items[i].key ? { ...u, ...patch } : u)));
// The images are added to the list in the order they were chosen, whichever upload finishes first.
const results: (HeroImageDto | 'failed' | undefined)[] = new Array<HeroImageDto | 'failed' | undefined>(files.length).fill(undefined);
let flushed = 0;
let cursor = 0;
const flush = () => {
while (flushed < files.length && results[flushed] !== undefined) {
const result = results[flushed];
if (result && result !== 'failed') {
setLocalImages((current) => ({ ...current, [result.id]: result }));
// Ready at once (the same photo was already in the CMS): the same note as after a photo that took a while.
if (!result.processing) markDone(result.id);
slides.append({ id: null, imageId: result.id, alt: '', decorative: false, isActive: true }, { shouldFocus: false });
}
flushed += 1;
}
};
const worker = async () => {
while (cursor < files.length) {
const i = cursor++;
const file = files[i];
// Refuse what the host would refuse without sending the whole file first.
if (file.type !== '' && !file.type.startsWith('image/')) {
results[i] = 'failed';
update(i, { status: 'failed', message: t('hero.upload.notAnImage') });
} else if (file.size > maxBytes) {
results[i] = 'failed';
update(i, { status: 'failed', message: t('hero.upload.tooLarge', { max: maxMb }) });
} else {
update(i, { status: 'uploading' });
try {
const image = await upload.mutateAsync(file);
results[i] = image;
update(i, { status: 'done' });
} catch (error) {
results[i] = 'failed';
update(i, { status: 'failed', message: uploadMessage(error, t) });
}
}
flush();
}
};
try {
await Promise.all(Array.from({ length: Math.min(UPLOAD_PARALLEL, files.length) }, () => worker()));
} finally {
setUploading(false);
if (fileInput.current) fileInput.current.value = '';
}
};
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
// The order changes in the form only; it goes live when the hero is saved, like every other change.
const onDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
const from = slides.fields.findIndex((f) => f.id === active.id);
const to = slides.fields.findIndex((f) => f.id === over.id);
if (from !== -1 && to !== -1) slides.move(from, to);
};
const isFileDrag = (event: React.DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes('Files');
const onSubmit = async (values: HeroFormData) => {
setServerError(null);
try {
const savedHero = await save.mutateAsync(toRequest(values, focusEdits));
setFocusEdits({});
// What was just saved is the new starting point: nothing is unsaved any more.
reset(toForm(savedHero));
toast.success(t('hero.savedToast'));
} catch (error) {
setServerError(serverMessage(error, t('errors.generic'), t('errors.network')));
}
};
const onInvalid = (formErrors: typeof errors) => {
const order = ['title', 'tagline', 'lead', 'display', 'buttons', 'slides'] as const;
for (const key of order) {
const entry = formErrors[key] as unknown;
if (!entry) continue;
if (Array.isArray(entry)) {
const index = entry.findIndex(Boolean);
const field = Object.keys(entry[index] ?? {})[0] ?? 'alt';
goToField(`${key}.${index}.${field}`, key === 'slides' ? 'images' : 'content');
} else {
goToField(key, 'content');
}
return;
}
};
const err = (message?: string) => (message ? t(message) : undefined);
const heroErrors = errors;
return (
<form onSubmit={(event) => void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8 pb-4" noValidate data-testid="hero-form">
<ProcessingStatus images={slides.fields.map((f) => images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} />
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
<HeroTabs
idPrefix="hero"
label={t('hero.tabs.label')}
selected={tab}
onSelect={setTab}
tabs={[
{ id: 'content', label: t('hero.tabs.content'), changed: contentChanged, changedText: t('hero.tabs.hasChanges'), invalid: contentInvalid, invalidText: t('hero.tabs.hasErrors') },
{
id: 'images',
label: t('hero.tabs.images'),
note: busyCount > 0 ? t('hero.tabs.busy', { count: busyCount }) : undefined,
changed: imagesChanged,
changedText: t('hero.tabs.hasChanges'),
invalid: imagesInvalid,
invalidText: t('hero.tabs.hasErrors'),
},
]}
/>
<div role="tabpanel" id="hero-panel-content" aria-labelledby="hero-tab-content" hidden={tab !== 'content'} className="space-y-8">
<section className="space-y-4">
<div className="space-y-2">
<Label htmlFor="hero-title-input">{t('hero.fields.title')}</Label>
<textarea id="hero-title-input" rows={3} className={textareaClass} data-testid="hero-title-input" {...register('title')} />
<p className="text-xs text-muted-foreground">{t('hero.fields.titleHint')}</p>
<FieldError message={err(heroErrors.title?.message)} testId="hero-title-error" />
</div>
<div className="space-y-2">
<Label htmlFor="hero-tagline">{t('hero.fields.tagline')}</Label>
<Input id="hero-tagline" maxLength={120} data-testid="hero-tagline" {...register('tagline')} />
<FieldError message={err(heroErrors.tagline?.message)} />
</div>
<div className="space-y-2">
<Label htmlFor="hero-lead">{t('hero.fields.lead')}</Label>
<textarea id="hero-lead" rows={3} className={textareaClass} data-testid="hero-lead" {...register('lead')} />
<FieldError message={err(heroErrors.lead?.message)} />
</div>
<fieldset className="space-y-2">
<legend className="text-sm font-medium">{t('hero.fields.display')}</legend>
<div className="flex flex-wrap gap-4 text-sm">
{(['single', 'slideshow'] as const).map((value) => (
<label key={value} className="flex items-center gap-2">
<input type="radio" value={value} data-testid={`hero-display-${value}`} {...register('display')} />
{t(`hero.display.${value}`)}
</label>
))}
</div>
</fieldset>
</section>
<section className="space-y-3">
<h2 className="text-lg font-medium">{t('hero.buttons.title')}</h2>
<p className="text-xs text-muted-foreground">{t('hero.buttons.hint')}</p>
{[0, 1].map((i) => (
<div key={i} className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1">
<Label htmlFor={`hero-button-${i}-label`}>{t('hero.buttons.label', { n: i + 1 })}</Label>
<Input id={`hero-button-${i}-label`} maxLength={50} data-testid={`hero-button-${i}-label`} {...register(`buttons.${i}.label` as const)} />
<FieldError message={err(heroErrors.buttons?.[i]?.label?.message)} testId={`hero-button-${i}-label-error`} />
</div>
<div className="space-y-1">
<Label htmlFor={`hero-button-${i}-target`}>{t('hero.buttons.target', { n: i + 1 })}</Label>
<Input id={`hero-button-${i}-target`} maxLength={500} placeholder="#contact, /over-mij, https://…" data-testid={`hero-button-${i}-target`} {...register(`buttons.${i}.target` as const)} />
<FieldError message={err(heroErrors.buttons?.[i]?.target?.message)} testId={`hero-button-${i}-target-error`} />
</div>
</div>
))}
</section>
</div>
<div role="tabpanel" id="hero-panel-images" aria-labelledby="hero-tab-images" hidden={tab !== 'images'}>
<section
className={`space-y-3 rounded-md ${draggingFiles ? 'ring-2 ring-primary ring-offset-4' : ''}`}
onDragOver={(event) => {
if (!isFileDrag(event)) return;
event.preventDefault();
setDraggingFiles(true);
}}
onDragLeave={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDraggingFiles(false);
}}
onDrop={(event) => {
if (!isFileDrag(event)) return;
event.preventDefault();
setDraggingFiles(false);
void onFiles(event.dataTransfer.files);
}}
data-testid="hero-slides-section"
>
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-medium">{t('hero.slides.title')}</h2>
<div>
<input
ref={fileInput}
id="hero-upload"
type="file"
accept="image/*"
multiple
className="sr-only"
aria-label={t('hero.slides.add')}
data-testid="hero-upload"
onChange={(event) => void onFiles(event.target.files)}
/>
<Button type="button" variant="outline" disabled={uploading} onClick={() => fileInput.current?.click()} data-testid="hero-upload-button">
<ImagePlus className="mr-2 size-4" aria-hidden="true" />
{uploading ? t('hero.slides.uploading') : t('hero.slides.add')}
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">{t('hero.slides.hint')}</p>
{limits && (
<p className="text-xs text-muted-foreground" data-testid="hero-upload-limits">
{t('hero.slides.limits', { formats: limits.formats.join(', '), size: Math.round(limits.maxUploadBytes / (1024 * 1024)), megapixels: limits.maxMegapixels })}
</p>
)}
<UploadProgress items={uploads} busy={uploading} onClose={() => setUploads([])} />
{slides.fields.length === 0 && <p className="text-sm text-muted-foreground" data-testid="hero-slides-empty">{t('hero.slides.empty')}</p>}
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={onDragEnd}
accessibility={{ screenReaderInstructions: { draggable: t('hero.slides.dragInstructions') } }}
>
<SortableContext items={slides.fields.map((f) => f.id)} strategy={verticalListSortingStrategy}>
<ol className="space-y-3" data-testid="hero-slides">
{slides.fields.map((field, index) => {
const image = images[field.imageId];
const decorative = watchedSlides[index]?.decorative ?? false;
return (
<SortableSlide key={field.id} id={field.id} index={index} dimmed={!(watchedSlides[index]?.isActive ?? true)}>
<div className="flex shrink-0 flex-col gap-1">
{image && image.variants.length === 0 ? (
<PhotoPlaceholder failed={image.failed} testId={`hero-slide-${index}-processing`} step={image.renderTotal ? { done: image.renderDone ?? 0, total: image.renderTotal } : null} />
) : image?.processing ? (
<RecutThumbnail src={thumbnail(image)} failed={image.failed} testId={`hero-slide-${index}-recut`} step={image.renderTotal ? { done: image.renderDone ?? 0, total: image.renderTotal } : null} />
) : image ? (
<CropThumbnail
image={image}
savedSrc={thumbnail(image)}
edit={focusEdits[field.imageId]}
onClick={() => setFocusImageId(field.imageId)}
testId={`hero-slide-${index}-focus`}
/>
) : (
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted text-xs">?</div>
)}
<DoneStatus done={Boolean(image && justDone[image.id] && !image.processing)} slideNumber={index + 1} testId={`hero-slide-${index}-done`} />
</div>
<div className="min-w-[12rem] flex-1 space-y-2" role="group" aria-labelledby={`hero-slide-title-${field.id}`}>
<h3 id={`hero-slide-title-${field.id}`} className="text-xs font-medium uppercase tracking-wide text-muted-foreground" data-testid={`hero-slide-${index}-title`}>
{t('hero.slides.number', { n: index + 1 })}
</h3>
<Label htmlFor={`hero-slide-${index}-alt`}>{t('hero.slides.alt')}</Label>
<Input id={`hero-slide-${index}-alt`} maxLength={300} disabled={decorative} aria-describedby={`hero-slide-${index}-alt-hint`} data-testid={`hero-slide-${index}-alt`} {...register(`slides.${index}.alt` as const)} />
<p id={`hero-slide-${index}-alt-hint`} className="text-xs text-muted-foreground">{t('hero.slides.altHint')}</p>
<FieldError message={err(heroErrors.slides?.[index]?.alt?.message)} testId={`hero-slide-${index}-alt-error`} />
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" className="size-4 rounded border-input" data-testid={`hero-slide-${index}-decorative`} {...register(`slides.${index}.decorative` as const)} />
{t('hero.slides.decorative')}
</label>
</div>
<div className="flex flex-wrap items-center gap-1">
<SlideSwitch
checked={watchedSlides[index]?.isActive ?? true}
onChange={(value) => setValue(`slides.${index}.isActive` as const, value, { shouldDirty: true })}
testId={`hero-slide-${index}-active`}
slideNumber={index + 1}
/>
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.up')} disabled={index === 0} onClick={() => slides.move(index, index - 1)} data-testid={`hero-slide-${index}-up`}>
<ArrowUp className="size-4" aria-hidden="true" />
</Button>
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.down')} disabled={index === slides.fields.length - 1} onClick={() => slides.move(index, index + 1)} data-testid={`hero-slide-${index}-down`}>
<ArrowDown className="size-4" aria-hidden="true" />
</Button>
<Button type="button" variant="destructive" size="icon" aria-label={t('hero.slides.remove')} title={t('hero.slides.remove')} onClick={() => slides.remove(index)} data-testid={`hero-slide-${index}-remove`}>
<Trash2 className="size-4" aria-hidden="true" />
</Button>
</div>
</SortableSlide>
);
})}
</ol>
</SortableContext>
</DndContext>
{slides.fields.length > hero.maxPublishedSlides && (
<p className="text-xs text-muted-foreground" data-testid="hero-ceiling-note">
{t('hero.slides.ceiling', { max: hero.maxPublishedSlides })}
</p>
)}
</section>
</div>
<UnsavedChangesGuard dirty={hasUnsaved} />
{/* Full width of the content area (no gap at the sides or below), opaque, with a clear top edge and a shadow; the
bottom padding keeps clear of the home bar of a phone. */}
<div
className="sticky bottom-0 z-20 -mx-6 -mb-6 flex flex-wrap items-center justify-end gap-3 border-t bg-background px-6 pt-3 shadow-[0_-4px_8px_-4px_rgba(0,0,0,0.15)]"
style={{ paddingBottom: 'calc(0.75rem + env(safe-area-inset-bottom))' }}
data-testid="hero-save-bar"
>
<div role="status" aria-live="polite" className="min-h-5 flex-1 text-sm" data-testid="hero-unsaved-region">
{hasUnsaved && (
<span className="inline-flex items-center gap-2" data-testid="hero-unsaved">
<Badge variant="secondary">{t('hero.unsaved.badge')}</Badge>
<span className="text-muted-foreground">{t('hero.unsaved.text')}</span>
</span>
)}
</div>
<Button
type="submit"
disabled={save.isPending || !hasUnsaved}
aria-disabled={save.isPending || !hasUnsaved}
aria-busy={save.isPending}
className={hasUnsaved && !save.isPending ? 'ring-2 ring-primary ring-offset-2' : undefined}
data-testid="hero-save"
>
{save.isPending ? (
<>
<Spinner className="mr-2 size-4" />
{t('hero.saving')}
</>
) : (
t('common.save')
)}
</Button>
</div>
<FocusDialog
image={withPendingFocus(focusImageId ? images[focusImageId] ?? null : null)}
onApply={(imageId, edit) => setFocusEdits((current) => ({ ...current, [imageId]: edit }))}
onClose={() => setFocusImageId(null)}
/>
</form>
);
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest';
import { heroFormSchema, isAllowedButtonTarget } from './hero';
// The same cases as ButtonTargetValidatorTests in src/SlpModularCms.Modules.Hero.Tests/HeroRulesTests.cs.
describe('isAllowedButtonTarget', () => {
it.each(['#contact', '#pakketten', '#a-b_c9', '/over-mij', '/', '/a/b/c?x=1&y=2', 'https://andreaslop.nl/portfolio', 'https://sub.example.com:8443/p?q=1#top'])(
'accepts %s',
(target) => expect(isAllowedButtonTarget(target)).toBe(true),
);
it.each([
'', ' ', 'contact', '#', '#1abc', '# contact', '#a b', '//evil.example/x', '/\\evil.example', '/a b', 'http://example.com', 'HTTPS://example.com',
'https://user:pw@example.com', 'https://', 'https:///path', 'javascript:alert(1)', 'JaVaScRiPt:alert(1)', 'data:text/html;base64,AAAA', 'mailto:a@b.nl',
'tel:+31612345678', 'ftp://example.com/x', '/ok"onmouseover="x', '/ok<script>', ' /leading-space', '/trailing-space ', '/tab\tx', '/new\nline',
])('rejects %j', (target) => expect(isAllowedButtonTarget(target)).toBe(false));
});
const base = {
title: 'Titel',
tagline: '',
lead: '',
display: 'single' as const,
buttons: [{ label: '', target: '' }, { label: '', target: '' }],
slides: [],
};
describe('heroFormSchema', () => {
it('accepts a minimal hero', () => expect(heroFormSchema.safeParse(base).success).toBe(true));
it('wants a title of at most 200 characters and 5 lines', () => {
expect(heroFormSchema.safeParse({ ...base, title: ' ' }).success).toBe(false);
expect(heroFormSchema.safeParse({ ...base, title: 'x'.repeat(201) }).success).toBe(false);
expect(heroFormSchema.safeParse({ ...base, title: 'a\nb\nc\nd\ne\nf' }).success).toBe(false);
expect(heroFormSchema.safeParse({ ...base, title: 'a\nb\nc\nd\ne' }).success).toBe(true);
});
it('wants an alt text unless the slide is decorative', () => {
const slide = { id: null, imageId: 'i1', alt: '', decorative: false, isActive: true };
expect(heroFormSchema.safeParse({ ...base, slides: [slide] }).success).toBe(false);
expect(heroFormSchema.safeParse({ ...base, slides: [{ ...slide, decorative: true }] }).success).toBe(true);
expect(heroFormSchema.safeParse({ ...base, slides: [{ ...slide, alt: 'Een foto' }] }).success).toBe(true);
});
it('allows any number of slides', () => {
const slides = Array.from({ length: 80 }, (_, i) => ({ id: null, imageId: `i${i}`, alt: 'foto', decorative: false, isActive: true }));
expect(heroFormSchema.safeParse({ ...base, slides }).success).toBe(true);
});
});
@@ -0,0 +1,73 @@
import { z } from 'zod';
export const TITLE_MAX = 200;
export const TITLE_MAX_LINES = 5;
export const TAGLINE_MAX = 120;
export const LEAD_MAX = 600;
export const BUTTON_LABEL_MAX = 50;
export const BUTTON_TARGET_MAX = 500;
export const ALT_MAX = 300;
/**
* Twin of the host's `ButtonTargetValidator`: 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: or a protocol-relative address.
*/
export function isAllowedButtonTarget(target: string): boolean {
if (target === '' || target !== target.trim()) return false;
if ([...target].some((c) => /\s/.test(c) || c.charCodeAt(0) < 32 || '\\"<>`'.includes(c))) return false;
if (target.startsWith('#')) return /^#[A-Za-z][A-Za-z0-9_-]{0,99}$/.test(target);
if (target.startsWith('/')) return target.length === 1 || target[1] !== '/';
try {
const url = new URL(target);
// A host must follow the two slashes directly ("https:///path" is no address, even where a parser repairs it).
return /^https:[/][/][^/?#]/.test(target) && url.protocol === 'https:' && url.hostname !== '' && url.username === '';
} catch {
return false;
}
}
const buttonSchema = z
.object({
label: z.string().trim().max(BUTTON_LABEL_MAX, 'hero.errors.buttonLabelTooLong'),
target: z.string().trim().max(BUTTON_TARGET_MAX, 'hero.errors.buttonTargetTooLong'),
})
.superRefine((b, ctx) => {
const hasLabel = b.label !== '';
const hasTarget = b.target !== '';
if (hasLabel !== hasTarget) {
ctx.addIssue({ code: 'custom', path: [hasTarget ? 'label' : 'target'], message: 'hero.errors.buttonIncomplete' });
} else if (hasTarget && !isAllowedButtonTarget(b.target)) {
ctx.addIssue({ code: 'custom', path: ['target'], message: 'hero.errors.buttonTargetInvalid' });
}
});
const slideSchema = z
.object({
id: z.string().nullable(),
imageId: z.string().min(1),
alt: z.string().trim().max(ALT_MAX, 'hero.errors.altTooLong'),
decorative: z.boolean(),
isActive: z.boolean(),
})
.superRefine((s, ctx) => {
if (!s.decorative && s.alt === '') {
ctx.addIssue({ code: 'custom', path: ['alt'], message: 'hero.errors.altRequired' });
}
});
export const heroFormSchema = z
.object({
title: z.string().trim().min(1, 'hero.errors.titleRequired').max(TITLE_MAX, 'hero.errors.titleTooLong'),
tagline: z.string().trim().max(TAGLINE_MAX, 'hero.errors.taglineTooLong'),
lead: z.string().trim().max(LEAD_MAX, 'hero.errors.leadTooLong'),
display: z.enum(['single', 'slideshow']),
buttons: z.array(buttonSchema).length(2),
slides: z.array(slideSchema),
})
.superRefine((v, ctx) => {
if (v.title.replace(/\r\n/g, '\n').split('\n').length > TITLE_MAX_LINES) {
ctx.addIssue({ code: 'custom', path: ['title'], message: 'hero.errors.titleTooManyLines' });
}
});
export type HeroFormData = z.infer<typeof heroFormSchema>;
@@ -0,0 +1,70 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroUploadLimits } from './types';
export const HERO_KEY = ['hero'];
/** The hero as the admin edits it (also the image variants of every slide). */
export function useHero() {
return useQuery<HeroAdminDto, Error>({
queryKey: HERO_KEY,
queryFn: () => api.get<HeroAdminDto>('/api/v1/hero/all'),
// Images are cut in the background after an upload or a saved focus change: look again until they are all ready.
refetchInterval: (query) => (query.state.data?.slides.some((s) => s.image.processing) ? 5000 : false),
// Also while the tab is in the background or the connection came back: the state must never stay stale.
refetchIntervalInBackground: true,
});
}
export function useSaveHero() {
const queryClient = useQueryClient();
return useMutation<HeroAdminDto, Error, HeroSaveRequest>({
mutationFn: (body) => api.put<HeroAdminDto>('/api/v1/hero', body),
onSuccess: (hero) => {
queryClient.setQueryData(HERO_KEY, hero);
},
});
}
/** Uploads one image file; the server answers with the image and its variants. */
export function useUploadHeroImage() {
return useMutation<HeroImageDto, Error, File>({
mutationFn: (file) => {
const form = new FormData();
form.append('file', file);
return api.post<HeroImageDto>('/api/v1/hero/images', form);
},
});
}
export function useDeleteHeroImage() {
return useMutation<void, Error, string>({
mutationFn: (imageId) => api.delete<void>(`/api/v1/hero/images/${imageId}`),
});
}
/** Asks the server to try an image again that the background renderer gave up on. */
export function useRetryHeroImage() {
const queryClient = useQueryClient();
return useMutation<void, Error, string>({
mutationFn: (imageId) => api.post<void>(`/api/v1/hero/images/${imageId}/retry`, {}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: HERO_KEY }),
});
}
/** The formats and limits an upload has to meet on this host. */
export function useHeroUploadLimits() {
return useQuery<HeroUploadLimits, Error>({
queryKey: ['hero', 'upload-limits'],
queryFn: () => api.get<HeroUploadLimits>('/api/v1/hero/images/limits'),
staleTime: 10 * 60 * 1000,
});
}
/** The query of one image: the page asks it for photos that were uploaded but not saved yet, until they are ready. */
export const heroImageQuery = (imageId: string) => ({
queryKey: ['hero', 'image', imageId],
queryFn: () => api.get<HeroImageDto>(`/api/v1/hero/images/${imageId}`),
refetchInterval: (query: { state: { data?: HeroImageDto } }) => (query.state.data?.processing ? 5000 : false),
refetchIntervalInBackground: true,
});
@@ -0,0 +1,100 @@
export type HeroDisplay = 'single' | 'slideshow';
export interface FocusDto {
x: number;
y: number;
zoom: number;
}
export interface HeroVariantDto {
ratio: string;
width: number;
height: number;
type: string;
url: string;
}
export interface HeroImageDto {
id: string;
width: number;
height: number;
focus: FocusDto;
wideFocus: FocusDto | null;
tallFocus: FocusDto | null;
src: string;
variants: HeroVariantDto[];
/** The variants of this image are still being cut in the background; it is not published yet. */
processing: boolean;
/** The background renderer gave up on this image after a few tries; it can be retried. */
failed: boolean;
/** While the image is being cut: the step it is at, out of how many (null when it is not being cut right now). */
renderDone?: number | null;
renderTotal?: number | null;
/** The whole picture (not cut around a point), for choosing the focus point; null while the server has not made it yet. */
previewSrc?: string | null;
/** The photo was already in the CMS (same bytes). For internal use: the administrator sees no difference. */
reused?: boolean;
}
export interface HeroButtonDto {
label: string;
target: string;
}
export interface HeroSlideAdminDto {
id: string;
imageId: string;
alt: string;
decorative: boolean;
isActive: boolean;
sortOrder: number;
image: HeroImageDto;
}
export interface HeroAdminDto {
id: string | null;
title: string;
tagline: string | null;
lead: string | null;
display: HeroDisplay;
buttons: HeroButtonDto[];
slides: HeroSlideAdminDto[];
isLive: boolean;
updatedAt: string | null;
maxPublishedSlides: number;
}
export interface HeroSlideRequest {
id?: string | null;
imageId: string;
alt: string | null;
decorative: boolean;
isActive: boolean;
}
export interface HeroSaveRequest {
title: string;
tagline: string | null;
lead: string | null;
display: HeroDisplay;
buttons: HeroButtonDto[];
slides: HeroSlideRequest[];
/** Changed focus points of images; they take effect with this save. */
imageFocus: HeroImageFocusRequest[];
}
export interface HeroImageFocusRequest extends HeroFocusRequest {
imageId: string;
}
export interface HeroFocusRequest {
focus: FocusDto;
wide: FocusDto | null;
tall: FocusDto | null;
}
export interface HeroUploadLimits {
formats: string[];
maxUploadBytes: number;
maxMegapixels: number;
}
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckboxField } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { FieldError } from '@/components/ui/FieldError';
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
@@ -211,16 +212,12 @@ function OfferingBannerForm({
</div>
<p className="text-xs text-muted-foreground">{t('offerings.banners.scheduleHint')}</p>
<div className="flex items-center gap-2">
<input
id="banner-active"
type="checkbox"
data-testid="banner-active"
className="size-4 rounded border-input"
{...register('isActive')}
/>
<Label htmlFor="banner-active">{t('offerings.banners.activeLabel')}</Label>
</div>
<CheckboxField
id="banner-active"
data-testid="banner-active"
label={t('offerings.banners.activeLabel')}
{...register('isActive')}
/>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose} data-testid="banner-cancel">
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { Check, Pencil, Plus, Trash2, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckboxField } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { FieldError } from '@/components/ui/FieldError';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
@@ -293,28 +294,20 @@ export function OfferingForm({ initialValues, onSubmit, onCancel, isSubmitting }
{errors.ctaLabel && <FieldError message={errors.ctaLabel.message} testId="offering-cta-label-error" />}
</div>
<div className="flex items-center gap-2">
<input
id="offering-featured"
type="checkbox"
data-testid="offering-featured"
className="size-4 rounded border-input"
{...register('featured')}
/>
<Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label>
</div>
<CheckboxField
id="offering-featured"
data-testid="offering-featured"
label={t('offerings.form.featuredLabel')}
{...register('featured')}
/>
<div className="space-y-3 rounded-md border p-3" data-testid="offering-schedule">
<div className="flex items-center gap-2">
<input
id="offering-active"
type="checkbox"
data-testid="offering-active"
className="size-4 rounded border-input"
{...register('isActive')}
/>
<Label htmlFor="offering-active">{t('offerings.form.activeLabel')}</Label>
</div>
<CheckboxField
id="offering-active"
data-testid="offering-active"
label={t('offerings.form.activeLabel')}
{...register('isActive')}
/>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="offering-starts">{t('offerings.form.startsLabel')}</Label>
@@ -3,7 +3,7 @@ import { http, HttpResponse } from 'msw';
export const systemHandlers = [
http.get('*/System/capabilities', () =>
HttpResponse.json({
modules: ['Availability', 'Identity', 'Master', 'Offerings'],
modules: ['Availability', 'Identity', 'Master', 'Offerings', 'Hero'],
emailEnabled: false,
defaultLanguage: 'nl',
}),
+105 -62
View File
@@ -2,6 +2,33 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useTheme } from './useTheme';
type Listener = () => void;
/** A matchMedia that can change its answer and tell its listeners, like the system preference does. */
function system(initialDark: boolean) {
let dark = initialDark;
const listeners = new Set<Listener>();
vi.spyOn(window, 'matchMedia').mockImplementation(
() =>
({
get matches() {
return dark;
},
addEventListener: (_: string, l: Listener) => listeners.add(l),
removeEventListener: (_: string, l: Listener) => listeners.delete(l),
}) as unknown as MediaQueryList,
);
return {
change(next: boolean) {
dark = next;
listeners.forEach((l) => l());
},
listenerCount: () => listeners.size,
};
}
const shown = () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light');
beforeEach(() => {
localStorage.clear();
document.documentElement.className = '';
@@ -9,96 +36,112 @@ beforeEach(() => {
});
describe('useTheme', () => {
it('defaults to light when no preference is stored and OS prefers light', () => {
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: false } as MediaQueryList);
it('is automatic when nothing is stored, and follows the system', () => {
system(true);
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe('light');
expect(result.current.isDark).toBe(false);
});
it('defaults to dark when OS prefers dark and nothing is stored', () => {
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: true } as MediaQueryList);
const { result } = renderHook(() => useTheme());
expect(result.current.mode).toBe('auto');
expect(result.current.theme).toBe('dark');
expect(result.current.isDark).toBe(true);
expect(shown()).toBe('dark');
});
it('uses stored localStorage value over OS preference', () => {
localStorage.setItem('cms-theme', 'dark');
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: false } as MediaQueryList);
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe('dark');
});
it('toggleTheme switches from light to dark', () => {
localStorage.setItem('cms-theme', 'light');
const { result } = renderHook(() => useTheme());
act(() => { result.current.toggleTheme(); });
expect(result.current.theme).toBe('dark');
expect(localStorage.getItem('cms-theme')).toBe('dark');
expect(document.documentElement.classList.contains('dark')).toBe(true);
});
it('toggleTheme switches from dark to light', () => {
localStorage.setItem('cms-theme', 'dark');
const { result } = renderHook(() => useTheme());
act(() => { result.current.toggleTheme(); });
expect(result.current.theme).toBe('light');
expect(localStorage.getItem('cms-theme')).toBe('light');
expect(document.documentElement.classList.contains('light')).toBe(true);
});
});
describe('first click', () => {
const media = (dark: boolean) => vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: dark } as MediaQueryList);
const shown = () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light');
it.each([
['light', 'dark'],
['dark', 'light'],
])('flips the shown theme straight away when the OS prefers %s and nothing is stored or applied', (os, expected) => {
media(os === 'dark');
['light', true, 'light'],
['dark', false, 'dark'],
])('a stored %s wins over the system (dark=%s)', (stored, osDark, expected) => {
localStorage.setItem('cms-theme', stored);
system(osDark);
const { result } = renderHook(() => useTheme());
expect(shown()).toBe(os);
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe(expected);
expect(result.current.mode).toBe(stored);
expect(result.current.theme).toBe(expected);
expect(shown()).toBe(expected);
});
it('flips from what is shown even when the stored value is unusable', () => {
it('treats an unusable stored value as automatic', () => {
localStorage.setItem('cms-theme', 'system');
media(true);
document.documentElement.className = 'system';
system(true);
const { result } = renderHook(() => useTheme());
expect(result.current.mode).toBe('auto');
expect(shown()).toBe('dark');
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe('light');
});
it('follows the shown theme when it differs from the stored one', () => {
localStorage.setItem('cms-theme', 'light');
it.each([
['light', false],
['dark', false],
['auto', true],
] as const)('setMode(%s) applies it at the very first call and stores it', (mode, osDark) => {
system(osDark);
const { result } = renderHook(() => useTheme());
act(() => result.current.setMode(mode));
expect(localStorage.getItem('cms-theme')).toBe(mode);
expect(result.current.mode).toBe(mode);
expect(shown()).toBe(mode === 'auto' ? (osDark ? 'dark' : 'light') : mode);
});
it('the first choice works at once, whatever the page carried before', () => {
system(true);
document.documentElement.className = 'dark';
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe('dark');
act(() => { result.current.toggleTheme(); });
act(() => result.current.setMode('light'));
expect(shown()).toBe('light');
expect(localStorage.getItem('cms-theme')).toBe('light');
expect(result.current.theme).toBe('light');
});
it('keeps two toggles on the page in step', () => {
it('in automatic mode it follows a change of the system preference live, without reload', () => {
const os = system(false);
const { result } = renderHook(() => useTheme());
expect(shown()).toBe('light');
act(() => os.change(true));
expect(result.current.theme).toBe('dark');
expect(shown()).toBe('dark');
});
it('with a fixed theme a change of the system preference changes nothing', () => {
localStorage.setItem('cms-theme', 'light');
const os = system(false);
const { result } = renderHook(() => useTheme());
act(() => os.change(true));
expect(result.current.theme).toBe('light');
expect(shown()).toBe('light');
});
it('keeps two toggles on the page in step, and stops listening when they are gone', () => {
const os = system(false);
const a = renderHook(() => useTheme());
const b = renderHook(() => useTheme());
act(() => { a.result.current.toggleTheme(); });
expect(b.result.current.theme).toBe('dark');
act(() => a.result.current.setMode('dark'));
expect(b.result.current.mode).toBe('dark');
expect(os.listenerCount()).toBeGreaterThan(0);
act(() => { b.result.current.toggleTheme(); });
expect(shown()).toBe('light');
expect(a.result.current.theme).toBe('light');
a.unmount();
b.unmount();
expect(os.listenerCount()).toBe(0);
});
it('still works for this page view when the storage cannot be written', () => {
system(false);
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('private mode');
});
const { result } = renderHook(() => useTheme());
act(() => result.current.setMode('dark'));
expect(result.current.mode).toBe('dark');
expect(shown()).toBe('dark');
});
});
+55 -28
View File
@@ -1,63 +1,90 @@
import { useCallback, useSyncExternalStore } from 'react';
type Theme = 'light' | 'dark';
/** What the user chose: a fixed theme, or follow the system (also the default when nothing is stored). */
export type ThemeMode = 'light' | 'dark' | 'auto';
/** The theme that is actually shown. */
export type Theme = 'light' | 'dark';
const STORAGE_KEY = 'cms-theme';
const DARK_QUERY = '(prefers-color-scheme: dark)';
const listeners = new Set<() => void>();
function isTheme(value: string | null): value is Theme {
return value === 'light' || value === 'dark';
/** Only used when storage cannot be written (private mode): the choice then lasts for this page view. */
let memoryMode: ThemeMode | null = null;
function storedMode(): ThemeMode {
if (memoryMode) return memoryMode;
try {
const stored = localStorage.getItem(STORAGE_KEY);
return stored === 'light' || stored === 'dark' ? stored : 'auto';
} catch {
return memoryMode ?? 'auto';
}
}
function preferredTheme(): Theme {
const stored = localStorage.getItem(STORAGE_KEY);
if (isTheme(stored)) return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
function systemTheme(): Theme {
return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light';
}
function apply(theme: Theme) {
document.documentElement.classList.remove('light', 'dark');
document.documentElement.classList.add(theme);
const classes = document.documentElement.classList;
if (!classes.contains(theme) || classes.contains(theme === 'dark' ? 'light' : 'dark')) {
classes.remove('light', 'dark');
classes.add(theme);
}
}
/**
* The theme that is actually shown, which is what the <html> class says: the stylesheet only
* knows that class. The stored value and the OS preference are only the way to pick a theme when
* the page carries none (or an unusable one); in that case it is applied right away, so the state
* we report and what the user sees can never differ. A first click then always flips what is shown.
*/
function currentTheme(): Theme {
const classes = document.documentElement.classList;
if (classes.contains('dark')) return 'dark';
if (classes.contains('light')) return 'light';
const theme = preferredTheme();
/** The shown theme for a mode; it is put on <html> right away, so what we report is what the user sees. */
function resolve(mode: ThemeMode): Theme {
const theme = mode === 'auto' ? systemTheme() : mode;
apply(theme);
return theme;
}
/** One primitive per state, so useSyncExternalStore sees no change while nothing changed. */
function snapshot(): string {
const mode = storedMode();
return `${mode}:${resolve(mode)}`;
}
function notifyAll() {
listeners.forEach((notify) => notify());
}
function subscribe(listener: () => void) {
listeners.add(listener);
// In automatic mode the page follows a change of the system preference live, without a reload; another tab that
// changes the choice is followed as well.
const media = typeof window.matchMedia === 'function' ? window.matchMedia(DARK_QUERY) : null;
media?.addEventListener?.('change', listener);
const onStorage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY || event.key === null) listener();
};
window.addEventListener('storage', onStorage);
return () => {
listeners.delete(listener);
media?.removeEventListener?.('change', listener);
window.removeEventListener('storage', onStorage);
};
}
export function useTheme() {
// One source of truth shared by every toggle on the page (desktop sidebar, mobile overlay).
const theme = useSyncExternalStore(subscribe, currentTheme, () => 'light' as Theme);
const state = useSyncExternalStore(subscribe, snapshot, () => 'auto:light');
const [mode, theme] = state.split(':') as [ThemeMode, Theme];
const toggleTheme = useCallback(() => {
const next: Theme = currentTheme() === 'dark' ? 'light' : 'dark';
const setMode = useCallback((next: ThemeMode) => {
try {
localStorage.setItem(STORAGE_KEY, next);
memoryMode = null;
} catch {
// Storage can be unavailable (private mode); the switch itself still works.
// Storage can be unavailable (private mode); the switch itself still works for this page view.
memoryMode = next;
}
apply(next);
listeners.forEach((notify) => notify());
resolve(next);
notifyAll();
}, []);
return { theme, isDark: theme === 'dark', toggleTheme };
return { mode, theme, isDark: theme === 'dark', setMode };
}
+184 -5
View File
@@ -16,12 +16,19 @@
"settings": "Settings",
"openMenu": "Open navigation",
"closeMenu": "Close navigation",
"hero": "Hero",
"unreadMessages_one": "{{count}} new message",
"unreadMessages_other": "{{count}} new messages"
},
"theme": {
"switchToLight": "Switch to light theme",
"switchToDark": "Switch to dark theme"
"title": "Theme",
"label": "Theme: {{mode}}",
"labelAuto": "Theme: automatic (now {{now}})",
"mode": {
"light": "Light",
"dark": "Dark",
"auto": "Automatic"
}
},
"session": {
"unreachable": {
@@ -275,9 +282,18 @@
"masterControlled": "This instance has been disabled by the Master CMS. Availability cannot be changed here until the Master releases it.",
"masterControlledSaveError": "Cannot be changed: the Master CMS controls this status."
},
"modules": { "title": "Module Management", "comingSoon": "Coming soon" },
"systemConfig": { "title": "System Configuration", "comingSoon": "Coming soon" },
"branding": { "title": "Branding / Theme", "comingSoon": "Coming soon" }
"modules": {
"title": "Module Management",
"comingSoon": "Coming soon"
},
"systemConfig": {
"title": "System Configuration",
"comingSoon": "Coming soon"
},
"branding": {
"title": "Branding / Theme",
"comingSoon": "Coming soon"
}
},
"cms": {
"title": "CMS Instances",
@@ -602,5 +618,168 @@
"none": "There is no recipient address yet: messages are kept but not mailed."
}
}
},
"hero": {
"title": "Hero",
"live": "Live",
"notLive": "Not live",
"intro": "The hero is the first thing visitors of the website see: a large heading with one or more photos. Here you manage the texts, the buttons and the photos. A change is visible within about a minute.",
"savedToast": "Hero saved",
"fields": {
"title": "Title",
"titleHint": "A new line in this field is a line break in the title (at most 5 lines).",
"tagline": "Short text above the title (optional)",
"lead": "Introduction (optional)",
"display": "Display"
},
"display": {
"single": "Single",
"slideshow": "Slideshow"
},
"buttons": {
"title": "Buttons",
"hint": "At most two buttons. As the target, choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…).",
"label": "Button {{n}}: text",
"target": "Button {{n}}: target"
},
"slides": {
"title": "Images",
"add": "Add image",
"uploading": "Uploading…",
"hint": "Choose several files at once or drag them into this box. New photos are added at the bottom of the list. Drag a photo by its handle, or use the arrows, to change the order; visitors see the first photo first. With the Focus button you show where the subject is.",
"empty": "No images yet.",
"alt": "Description",
"decorative": "Hide from screen readers",
"up": "Move up",
"down": "Move down",
"remove": "Remove slide",
"ceiling": "Only the first {{max}} images are shown on the website.",
"focusPending": "Focus changed, not saved yet.",
"processing": "Processing…",
"processingHint": "The image is being prepared in the background; it appears on the website as soon as it is ready.",
"failed": "Failed",
"limits": "Allowed: {{formats}}. At most {{size}} MB per file and {{megapixels}} megapixels.",
"altHint": "Describes the photo for people who cannot see it and for search engines.",
"drag": "Move image {{n}}",
"dragInstructions": "Press space to pick up the image, use the arrow keys to move it and press space again to drop it. Escape cancels.",
"recut": "Making the new crop…",
"recutHint": "You still see the old crop. The change is only on the website when this is done.",
"activeOn": "Active",
"activeOff": "Not active",
"activeFor": "show image {{n}} on the website",
"queued": "in the queue",
"number": "Slide {{n}}",
"done": "Processing finished",
"doneFor": "Slide {{n}}: processing finished",
"cropEdit": "Adjust crop"
},
"processing": {
"count": "{{done}} of {{total}} photos processed",
"label": "Progress of processing the photos",
"explain": "The hero has been saved. The photos are prepared one by one and go live as soon as they are ready. Until the first photo is ready the website keeps its standard hero. You do not have to keep this page open.",
"failed_one": "Processing {{count}} photo failed.",
"failed_other": "Processing {{count}} photos failed.",
"failedHint": "The server tried three times. Try again, or upload the photo once more (the same photo is the same image).",
"retry": "Try again",
"current": "Working on photo {{n}} of {{total}}: step {{step}} of {{steps}}. A large photo can take a few minutes.",
"stuck": "Taking long?"
},
"focus": {
"title": "Focus and crop",
"intro": "Click or drag on the photo to show where the subject is. The website crops the photo for landscape and portrait screens so that the subject stays in view.",
"targetLegend": "For which display",
"target": {
"general": "General",
"wide": "Landscape (3:2)",
"tall": "Portrait (4:5)"
},
"override": "Own setting for this display",
"areaLabel": "Photo: choose the point of the subject",
"areaHint": "The arrow keys move the point (faster with Shift).",
"x": "Horizontal (%)",
"y": "Vertical (%)",
"zoom": "Zoom ({{value}}×)",
"preview": {
"wide": "Landscape preview",
"tall": "Portrait preview"
},
"apply": "Apply",
"applyHint": "The change only takes effect when you save the hero. If you leave the page without saving it is dropped.",
"previewPending": "The preview of this photo is being prepared. Close this window and try again in a few seconds."
},
"errors": {
"titleRequired": "A title is required.",
"titleTooLong": "The title can have at most 200 characters.",
"titleTooManyLines": "The title can have at most 5 lines.",
"taglineTooLong": "The short text above the title can have at most 120 characters.",
"leadTooLong": "The introduction can have at most 600 characters.",
"buttonLabelTooLong": "The button text can have at most 50 characters.",
"buttonTargetTooLong": "The target can have at most 500 characters.",
"buttonIncomplete": "Fill in both the text and the target of the button, or leave both empty.",
"buttonTargetInvalid": "Choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…).",
"altTooLong": "The description can have at most 300 characters.",
"altRequired": "Give a description or choose ‘Decoration only’."
},
"upload": {
"tooLarge": "The image is too large (at most {{max}} MB).",
"interrupted": "The upload was interrupted. Check the connection and try again.",
"busy": "Too many uploads in a row. Try again in a few minutes.",
"notAnImage": "This file is not an image.",
"progress": "Uploading: {{done}} of {{total}}",
"summary": "{{ok}} of {{total}} photos added",
"waiting": "waiting",
"uploading": "uploading…",
"done": "added",
"close": "Close"
},
"help": {
"heading": "Explanation of each part",
"save": "Changes only take effect after you save the hero.",
"title": {
"name": "Title",
"text": "The large heading. A new line in the field is a new line in the heading."
},
"tagline": {
"name": "Short text above the title",
"text": "A short label above or before the title. Can stay empty."
},
"lead": {
"name": "Introduction",
"text": "One or two sentences below the title. Can stay empty."
},
"buttons": {
"name": "Buttons",
"text": "At most two, each with a text and a target. As the target, choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…)."
},
"display": {
"name": "Display",
"text": "‘Single’ shows one photo, ‘Slideshow’ switches between the photos."
},
"slides": {
"name": "Images",
"text": "Upload photos, describe what is in them and set the order (drag or use the arrows). The switch makes a photo active or not active. Choose ‘Hide from screen readers’ for a photo that adds nothing to the content."
},
"focus": {
"name": "Focus",
"text": "Show where the subject is in the photo, so a crop never cuts it off. For portrait screens, such as a phone, you can choose a separate point."
}
},
"unsaved": {
"badge": "Unsaved changes",
"text": "Save the hero to put them on the website.",
"leaveTitle": "Changes not saved",
"leaveText": "You have made changes that are not saved yet. If you leave this page they will be lost.",
"stay": "Stay",
"discard": "Discard changes"
},
"saving": "Saving…",
"tabs": {
"label": "Hero sections",
"content": "Content",
"images": "Images",
"busy": "{{count}} busy",
"hasChanges": "unsaved changes",
"hasErrors": "has errors"
}
}
}
+184 -5
View File
@@ -16,12 +16,19 @@
"settings": "Instellingen",
"openMenu": "Navigatie openen",
"closeMenu": "Navigatie sluiten",
"hero": "Hero",
"unreadMessages_one": "{{count}} nieuw bericht",
"unreadMessages_other": "{{count}} nieuwe berichten"
},
"theme": {
"switchToLight": "Overschakelen naar licht thema",
"switchToDark": "Overschakelen naar donker thema"
"title": "Thema",
"label": "Thema: {{mode}}",
"labelAuto": "Thema: automatisch (nu {{now}})",
"mode": {
"light": "Licht",
"dark": "Donker",
"auto": "Automatisch"
}
},
"session": {
"unreachable": {
@@ -275,9 +282,18 @@
"masterControlled": "Deze instantie is door de Master-CMS uitgeschakeld. De beschikbaarheid kan hier niet worden gewijzigd totdat de Master de status weer vrijgeeft.",
"masterControlledSaveError": "Kan niet worden gewijzigd: de Master-CMS beheert deze status."
},
"modules": { "title": "Modulebeheer", "comingSoon": "Binnenkort beschikbaar" },
"systemConfig": { "title": "Systeemconfiguratie", "comingSoon": "Binnenkort beschikbaar" },
"branding": { "title": "Huisstijl / Thema", "comingSoon": "Binnenkort beschikbaar" }
"modules": {
"title": "Modulebeheer",
"comingSoon": "Binnenkort beschikbaar"
},
"systemConfig": {
"title": "Systeemconfiguratie",
"comingSoon": "Binnenkort beschikbaar"
},
"branding": {
"title": "Huisstijl / Thema",
"comingSoon": "Binnenkort beschikbaar"
}
},
"cms": {
"title": "CMS-instanties",
@@ -602,5 +618,168 @@
"none": "Er is nog geen ontvangstadres: berichten worden bewaard maar niet gemaild."
}
}
},
"hero": {
"title": "Hero",
"live": "Live",
"notLive": "Niet live",
"intro": "De hero is het eerste wat bezoekers van de website zien: een grote kop met een of meer foto’s. Hier beheer je de teksten, de knoppen en de foto’s. Een wijziging is binnen ongeveer een minuut zichtbaar.",
"savedToast": "Hero opgeslagen",
"fields": {
"title": "Titel",
"titleHint": "Een nieuwe regel in dit veld is een regelafbreking in de titel (maximaal 5 regels).",
"tagline": "Korte tekst boven de titel (optioneel)",
"lead": "Introductietekst (optioneel)",
"display": "Weergave"
},
"display": {
"single": "Enkel",
"slideshow": "Diavoorstelling"
},
"buttons": {
"title": "Knoppen",
"hint": "Maximaal twee knoppen. Als doel kies je een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…).",
"label": "Knop {{n}}: tekst",
"target": "Knop {{n}}: doel"
},
"slides": {
"title": "Afbeeldingen",
"add": "Afbeelding toevoegen",
"uploading": "Bezig met uploaden…",
"hint": "Kies meerdere bestanden tegelijk of sleep ze naar dit vak. Nieuwe foto’s komen onderaan de lijst. Sleep een foto aan het greepje, of gebruik de pijltjes, om de volgorde te wijzigen; de eerste foto zien bezoekers als eerste. Met de knop Focus geef je aan waar het onderwerp staat.",
"empty": "Nog geen afbeeldingen.",
"alt": "Beschrijving",
"decorative": "Verberg voor schermlezers",
"up": "Omhoog",
"down": "Omlaag",
"remove": "Slide verwijderen",
"ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website.",
"focusPending": "Focus gewijzigd, nog niet opgeslagen.",
"processing": "Wordt verwerkt…",
"processingHint": "De afbeelding wordt klaargezet op de achtergrond; hij verschijnt op de website zodra hij klaar is.",
"failed": "Mislukt",
"limits": "Toegestaan: {{formats}}. Maximaal {{size}} MB per bestand en {{megapixels}} megapixel.",
"altHint": "Beschrijft de foto voor mensen die hem niet kunnen zien en voor zoekmachines.",
"drag": "Verplaats afbeelding {{n}}",
"dragInstructions": "Druk op spatie om de afbeelding op te pakken, gebruik de pijltjestoetsen om hem te verplaatsen en druk nogmaals op spatie om hem neer te zetten. Escape annuleert.",
"recut": "Nieuwe uitsnede wordt gemaakt…",
"recutHint": "Je ziet nog de oude uitsnede. De wijziging staat pas op de website als dit klaar is.",
"activeOn": "Actief",
"activeOff": "Niet actief",
"activeFor": "afbeelding {{n}} tonen op de website",
"queued": "in de wachtrij",
"number": "Slide {{n}}",
"done": "Verwerking afgerond",
"doneFor": "Slide {{n}}: verwerking afgerond",
"cropEdit": "Uitsnede aanpassen"
},
"processing": {
"count": "{{done}} van {{total}} foto’s verwerkt",
"label": "Voortgang van het verwerken van de foto’s",
"explain": "De hero is al opgeslagen. De foto’s worden één voor één klaargezet en gaan live zodra ze klaar zijn. Tot de eerste foto klaar is, blijft de standaard hero van de website staan. Je hoeft deze pagina niet open te houden.",
"failed_one": "Het verwerken van {{count}} foto is mislukt.",
"failed_other": "Het verwerken van {{count}} foto’s is mislukt.",
"failedHint": "De server heeft het drie keer geprobeerd. Probeer het opnieuw, of upload de foto nog een keer (dezelfde foto is dezelfde afbeelding).",
"retry": "Opnieuw proberen",
"current": "Bezig met foto {{n}} van {{total}}: stap {{step}} van {{steps}}. Een grote foto kan enkele minuten duren.",
"stuck": "Duurt het lang?"
},
"focus": {
"title": "Focus en uitsnede",
"intro": "Klik of sleep op de foto om aan te geven waar het onderwerp staat. De website snijdt de foto voor liggende en staande schermen zo uit dat het onderwerp in beeld blijft.",
"targetLegend": "Voor welke weergave",
"target": {
"general": "Algemeen",
"wide": "Liggend (3:2)",
"tall": "Staand (4:5)"
},
"override": "Eigen instelling voor deze weergave",
"areaLabel": "Foto: kies het punt van het onderwerp",
"areaHint": "Pijltjestoetsen verplaatsen het punt (met Shift sneller).",
"x": "Horizontaal (%)",
"y": "Verticaal (%)",
"zoom": "Inzoomen ({{value}}×)",
"preview": {
"wide": "Voorbeeld liggend",
"tall": "Voorbeeld staand"
},
"apply": "Toepassen",
"applyHint": "De wijziging geldt pas nadat je de hero opslaat. Verlaat je de pagina zonder op te slaan, dan vervalt ze.",
"previewPending": "Het voorbeeld van deze foto wordt klaargezet. Sluit dit venster en probeer het over een paar seconden opnieuw."
},
"errors": {
"titleRequired": "Een titel is verplicht.",
"titleTooLong": "De titel mag maximaal 200 tekens bevatten.",
"titleTooManyLines": "De titel mag maximaal 5 regels hebben.",
"taglineTooLong": "De korte tekst boven de titel mag maximaal 120 tekens bevatten.",
"leadTooLong": "De introductietekst mag maximaal 600 tekens bevatten.",
"buttonLabelTooLong": "De knoptekst mag maximaal 50 tekens bevatten.",
"buttonTargetTooLong": "Het doel mag maximaal 500 tekens bevatten.",
"buttonIncomplete": "Vul zowel de tekst als het doel van de knop in, of laat beide leeg.",
"buttonTargetInvalid": "Kies een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…).",
"altTooLong": "De beschrijving mag maximaal 300 tekens bevatten.",
"altRequired": "Geef een beschrijving of kies ‘Alleen versiering’."
},
"upload": {
"tooLarge": "De afbeelding is te groot (maximaal {{max}} MB).",
"interrupted": "De upload is afgebroken. Controleer de verbinding en probeer het opnieuw.",
"busy": "Er zijn te veel uploads achter elkaar. Probeer het over een paar minuten opnieuw.",
"notAnImage": "Dit bestand is geen afbeelding.",
"progress": "Bezig met uploaden: {{done}} van {{total}}",
"summary": "{{ok}} van {{total}} foto’s toegevoegd",
"waiting": "wacht",
"uploading": "bezig…",
"done": "toegevoegd",
"close": "Sluiten"
},
"help": {
"heading": "Uitleg per onderdeel",
"save": "Wijzigingen gelden pas nadat je de hero opslaat.",
"title": {
"name": "Titel",
"text": "De grote kop. Een nieuwe regel in het veld is een nieuwe regel in de kop."
},
"tagline": {
"name": "Korte tekst boven de titel",
"text": "Een kort label dat boven of voor de titel staat. Mag leeg blijven."
},
"lead": {
"name": "Introductietekst",
"text": "Een of twee zinnen onder de titel. Mag leeg blijven."
},
"buttons": {
"name": "Knoppen",
"text": "Maximaal twee, elk met een tekst en een doel. Als doel kies je een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…)."
},
"display": {
"name": "Weergave",
"text": "‘Enkel’ toont één foto, ‘Diavoorstelling’ wisselt tussen de foto’s."
},
"slides": {
"name": "Afbeeldingen",
"text": "Upload foto’s, beschrijf wat erop staat en bepaal de volgorde (slepen of de pijltjes). Met de schakelaar zet je een foto actief of niet actief. Kies ‘Verberg voor schermlezers’ voor een foto die niets toevoegt aan de inhoud."
},
"focus": {
"name": "Focus",
"text": "Geef aan waar het onderwerp op de foto staat, zodat een uitsnede er niets van afhakt. Voor staande schermen, zoals een telefoon, kun je een apart punt kiezen."
}
},
"unsaved": {
"badge": "Niet-opgeslagen wijzigingen",
"text": "Sla de hero op om ze door te voeren op de website.",
"leaveTitle": "Wijzigingen niet opgeslagen",
"leaveText": "Je hebt wijzigingen gemaakt die nog niet zijn opgeslagen. Als je deze pagina verlaat, gaan ze verloren.",
"stay": "Blijven",
"discard": "Wijzigingen weggooien"
},
"saving": "Bezig met opslaan…",
"tabs": {
"label": "Onderdelen van de hero",
"content": "Inhoud",
"images": "Afbeeldingen",
"busy": "{{count}} bezig",
"hasChanges": "niet-opgeslagen wijzigingen",
"hasErrors": "bevat fouten"
}
}
}
+50
View File
@@ -120,3 +120,53 @@
outline-offset: 2px;
}
}
/* A calm light band that sweeps over a photo that is still being prepared. Pure CSS, follows the text colour so it suits
the light and the dark theme, and stands still for people who asked for less motion. */
@keyframes hero-shimmer {
to {
transform: translateX(100%);
}
}
.hero-shimmer {
position: relative;
overflow: hidden;
}
.hero-shimmer::after {
content: '';
position: absolute;
inset: 0;
transform: translateX(-100%);
background: linear-gradient(90deg, transparent, color-mix(in oklab, currentColor 14%, transparent), transparent);
animation: hero-shimmer 1.8s ease-in-out infinite;
}
@media (prefers-reduced-motion: reduce) {
.hero-shimmer::after {
animation: none;
display: none;
}
}
/* The "processing finished" note of a photo: visible for a few seconds, then it fades (the page removes it after that). */
@keyframes hero-done-fade {
0%,
70% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.hero-done {
animation: hero-done-fade 4s ease-in forwards;
}
@media (prefers-reduced-motion: reduce) {
.hero-done {
animation: none;
}
}
+4 -2
View File
@@ -129,7 +129,9 @@ export class ApiClient {
const { body, skipAuthRefresh: _skip, headers, ...rest } = options;
const finalHeaders = new Headers(headers);
if (body !== undefined && body !== null) {
// A FormData body (file upload) is sent as is: the browser sets the multipart content type and boundary.
const isForm = typeof FormData !== 'undefined' && body instanceof FormData;
if (body !== undefined && body !== null && !isForm) {
finalHeaders.set('Content-Type', 'application/json');
}
if (this.accessToken !== null) {
@@ -143,7 +145,7 @@ export class ApiClient {
credentials: 'include',
// A list read after a change must come from the server, never from an intermediate cache.
...(rest.method === 'GET' ? { cache: 'no-store' as const } : {}),
body: body !== undefined && body !== null ? JSON.stringify(body) : undefined,
body: body !== undefined && body !== null ? (isForm ? (body as FormData) : JSON.stringify(body)) : undefined,
});
} catch (cause) {
throw new NetworkError(cause instanceof Error ? cause.message : undefined);
+3 -1
View File
@@ -7,9 +7,10 @@ import { cmsHandlers } from '@/features/cms/mocks/handlers';
import { systemHandlers } from '@/features/system/mocks/handlers';
import { offeringsHandlers } from '@/features/offerings/mocks/handlers';
import { contactHandlers } from '@/features/contact/mocks/handlers';
import { heroHandlers } from '@/features/hero/mocks/handlers';
/** All default MSW handlers, composed from feature folders (Q3-B). */
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers];
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers, ...heroHandlers];
export { authHandlers } from '@/features/auth/mocks/handlers';
export { userHandlers } from '@/features/users/mocks/handlers';
@@ -20,4 +21,5 @@ export { cmsHandlers, resetMockCmsInstances, getMockCmsInstances } from '@/featu
export { systemHandlers } from '@/features/system/mocks/handlers';
export { offeringsHandlers, resetMockOfferings, getMockOfferings } from '@/features/offerings/mocks/handlers';
export { contactHandlers, resetMockContact, getMockContactMessages } from '@/features/contact/mocks/handlers';
export { heroHandlers, resetMockHero } from '@/features/hero/mocks/handlers';
export * from '@/features/auth/mocks/fixtures';
+13
View File
@@ -233,6 +233,18 @@ const cmsRoute = createRoute({
),
});
const heroRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/hero',
component: () => (
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
<ModuleGuard requiredModule="Hero">
{lazyPage(() => import('@/features/hero/pages/HeroPage'), 'HeroPage')()}
</ModuleGuard>
</RoleGuard>
),
});
const offeringsRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/offerings',
@@ -320,6 +332,7 @@ export const routeTree = rootRoute.addChildren([
dashboardRoute,
usersRoute,
cmsRoute,
heroRoute,
offeringsRoute,
offeringsNewRoute,
offeringsEditRoute,
+957
View File
@@ -522,6 +522,40 @@
],
"type": "object"
},
"FocusDto": {
"properties": {
"x": {
"format": "double",
"pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$",
"type": [
"number",
"string"
]
},
"y": {
"format": "double",
"pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$",
"type": [
"number",
"string"
]
},
"zoom": {
"format": "double",
"pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$",
"type": [
"number",
"string"
]
}
},
"required": [
"x",
"y",
"zoom"
],
"type": "object"
},
"ForgotPasswordRequest": {
"properties": {
"email": {
@@ -533,6 +567,463 @@
],
"type": "object"
},
"HeroAdminDto": {
"properties": {
"buttons": {
"items": {
"$ref": "#/components/schemas/HeroButtonDto"
},
"type": "array"
},
"display": {
"type": "string"
},
"id": {
"type": [
"null",
"string"
]
},
"isLive": {
"type": "boolean"
},
"lead": {
"type": [
"null",
"string"
]
},
"maxPublishedSlides": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"integer",
"string"
]
},
"slides": {
"items": {
"$ref": "#/components/schemas/HeroSlideAdminDto"
},
"type": "array"
},
"tagline": {
"type": [
"null",
"string"
]
},
"title": {
"type": "string"
},
"updatedAt": {
"format": "date-time",
"type": [
"null",
"string"
]
}
},
"required": [
"id",
"title",
"tagline",
"lead",
"display",
"buttons",
"slides",
"isLive",
"updatedAt",
"maxPublishedSlides"
],
"type": "object"
},
"HeroButtonDto": {
"properties": {
"label": {
"type": "string"
},
"target": {
"type": "string"
}
},
"required": [
"label",
"target"
],
"type": "object"
},
"HeroButtonRequest": {
"properties": {
"label": {
"type": [
"null",
"string"
]
},
"target": {
"type": [
"null",
"string"
]
}
},
"required": [
"label",
"target"
],
"type": "object"
},
"HeroImageDto": {
"properties": {
"failed": {
"default": false,
"type": "boolean"
},
"focus": {
"$ref": "#/components/schemas/FocusDto"
},
"height": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"integer",
"string"
]
},
"id": {
"type": "string"
},
"previewSrc": {
"type": [
"null",
"string"
]
},
"processing": {
"default": false,
"type": "boolean"
},
"renderDone": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"null",
"integer",
"string"
]
},
"renderTotal": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"null",
"integer",
"string"
]
},
"reused": {
"default": false,
"type": "boolean"
},
"src": {
"type": "string"
},
"tallFocus": {
"oneOf": [
{
"type": "null"
},
{
"$ref": "#/components/schemas/FocusDto"
}
]
},
"variants": {
"items": {
"$ref": "#/components/schemas/HeroVariantDto"
},
"type": "array"
},
"wideFocus": {
"oneOf": [
{
"type": "null"
},
{
"$ref": "#/components/schemas/FocusDto"
}
]
},
"width": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"integer",
"string"
]
}
},
"required": [
"id",
"width",
"height",
"focus",
"wideFocus",
"tallFocus",
"src",
"variants"
],
"type": "object"
},
"HeroImageFocusRequest": {
"properties": {
"focus": {
"$ref": "#/components/schemas/FocusDto"
},
"imageId": {
"format": "uuid",
"type": "string"
},
"tall": {
"oneOf": [
{
"type": "null"
},
{
"$ref": "#/components/schemas/FocusDto"
}
]
},
"wide": {
"oneOf": [
{
"type": "null"
},
{
"$ref": "#/components/schemas/FocusDto"
}
]
}
},
"required": [
"imageId",
"focus"
],
"type": "object"
},
"HeroSaveRequest": {
"properties": {
"buttons": {
"items": {
"$ref": "#/components/schemas/HeroButtonRequest"
},
"type": [
"null",
"array"
]
},
"display": {
"type": [
"null",
"string"
]
},
"imageFocus": {
"items": {
"$ref": "#/components/schemas/HeroImageFocusRequest"
},
"type": [
"null",
"array"
]
},
"lead": {
"type": [
"null",
"string"
]
},
"slides": {
"items": {
"$ref": "#/components/schemas/HeroSlideRequest"
},
"type": [
"null",
"array"
]
},
"tagline": {
"type": [
"null",
"string"
]
},
"title": {
"type": [
"null",
"string"
]
}
},
"required": [
"title",
"tagline",
"lead",
"display",
"buttons",
"slides"
],
"type": "object"
},
"HeroSlideAdminDto": {
"properties": {
"alt": {
"type": "string"
},
"decorative": {
"type": "boolean"
},
"id": {
"type": "string"
},
"image": {
"$ref": "#/components/schemas/HeroImageDto"
},
"imageId": {
"type": "string"
},
"isActive": {
"type": "boolean"
},
"sortOrder": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"integer",
"string"
]
}
},
"required": [
"id",
"imageId",
"alt",
"decorative",
"isActive",
"sortOrder",
"image"
],
"type": "object"
},
"HeroSlideRequest": {
"properties": {
"alt": {
"type": [
"null",
"string"
]
},
"decorative": {
"default": false,
"type": "boolean"
},
"id": {
"format": "uuid",
"type": [
"null",
"string"
]
},
"imageId": {
"format": "uuid",
"type": "string"
},
"isActive": {
"default": true,
"type": "boolean"
}
},
"required": [
"id",
"imageId",
"alt"
],
"type": "object"
},
"HeroUploadLimitsDto": {
"properties": {
"formats": {
"items": {
"type": "string"
},
"type": "array"
},
"maxMegapixels": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"integer",
"string"
]
},
"maxUploadBytes": {
"format": "int64",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"integer",
"string"
]
}
},
"required": [
"formats",
"maxUploadBytes",
"maxMegapixels"
],
"type": "object"
},
"HeroVariantDto": {
"properties": {
"height": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"integer",
"string"
]
},
"ratio": {
"type": "string"
},
"type": {
"type": "string"
},
"url": {
"type": "string"
},
"width": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"integer",
"string"
]
}
},
"required": [
"ratio",
"width",
"height",
"type",
"url"
],
"type": "object"
},
"IFormFile": {
"format": "binary",
"type": "string"
},
"InviteUserRequest": {
"properties": {
"email": {
@@ -683,6 +1174,121 @@
},
"type": "object"
},
"PublicHeroDto": {
"properties": {
"buttons": {
"items": {
"$ref": "#/components/schemas/HeroButtonDto"
},
"type": "array"
},
"display": {
"type": "string"
},
"lead": {
"type": [
"null",
"string"
]
},
"slides": {
"items": {
"$ref": "#/components/schemas/PublicSlideDto"
},
"type": "array"
},
"tagline": {
"type": [
"null",
"string"
]
},
"title": {
"type": "string"
}
},
"required": [
"display",
"title",
"tagline",
"lead",
"buttons",
"slides"
],
"type": "object"
},
"PublicImageDto": {
"properties": {
"focus": {
"$ref": "#/components/schemas/FocusDto"
},
"focusByRatio": {
"additionalProperties": {
"$ref": "#/components/schemas/FocusDto"
},
"type": [
"null",
"object"
]
},
"height": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"integer",
"string"
]
},
"src": {
"type": "string"
},
"variants": {
"items": {
"$ref": "#/components/schemas/HeroVariantDto"
},
"type": "array"
},
"width": {
"format": "int32",
"pattern": "^-?(?:0|[1-9]\\d*)$",
"type": [
"integer",
"string"
]
}
},
"required": [
"width",
"height",
"focus",
"src",
"variants"
],
"type": "object"
},
"PublicSlideDto": {
"properties": {
"alt": {
"type": "string"
},
"decorative": {
"type": "boolean"
},
"id": {
"type": "string"
},
"image": {
"$ref": "#/components/schemas/PublicImageDto"
}
},
"required": [
"id",
"alt",
"decorative",
"image"
],
"type": "object"
},
"PushStatusRequest": {
"properties": {
"disableMessage": {
@@ -2301,6 +2907,351 @@
]
}
},
"/api/v1/hero": {
"get": {
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PublicHeroDto"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/PublicHeroDto"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/PublicHeroDto"
}
}
},
"description": "OK"
},
"204": {
"description": "No Content"
}
},
"tags": [
"Hero"
]
},
"put": {
"requestBody": {
"content": {
"application/*+json": {
"schema": {
"$ref": "#/components/schemas/HeroSaveRequest"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroSaveRequest"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/HeroSaveRequest"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroAdminDto"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/HeroAdminDto"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/HeroAdminDto"
}
}
},
"description": "OK"
},
"400": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Bad Request"
}
},
"tags": [
"Hero"
]
}
},
"/api/v1/hero/all": {
"get": {
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroAdminDto"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/HeroAdminDto"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/HeroAdminDto"
}
}
},
"description": "OK"
}
},
"tags": [
"Hero"
]
}
},
"/api/v1/hero/images": {
"post": {
"requestBody": {
"content": {
"multipart/form-data": {
"schema": {
"properties": {
"file": {
"$ref": "#/components/schemas/IFormFile"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroImageDto"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/HeroImageDto"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/HeroImageDto"
}
}
},
"description": "Created"
}
},
"tags": [
"HeroImages"
]
}
},
"/api/v1/hero/images/limits": {
"get": {
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroUploadLimitsDto"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/HeroUploadLimitsDto"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/HeroUploadLimitsDto"
}
}
},
"description": "OK"
}
},
"tags": [
"HeroImages"
]
}
},
"/api/v1/hero/images/{id}": {
"delete": {
"parameters": [
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"format": "uuid",
"type": "string"
}
}
],
"responses": {
"204": {
"description": "No Content"
},
"409": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Conflict"
}
},
"tags": [
"HeroImages"
]
},
"get": {
"parameters": [
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"format": "uuid",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroImageDto"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/HeroImageDto"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/HeroImageDto"
}
}
},
"description": "OK"
},
"404": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Not Found"
}
},
"tags": [
"HeroImages"
]
}
},
"/api/v1/hero/images/{id}/retry": {
"post": {
"parameters": [
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"format": "uuid",
"type": "string"
}
}
],
"responses": {
"204": {
"description": "No Content"
},
"404": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Not Found"
}
},
"tags": [
"HeroImages"
]
}
},
"/api/v1/offerings": {
"get": {
"responses": {
@@ -2720,6 +3671,12 @@
{
"name": "ContactSettings"
},
{
"name": "Hero"
},
{
"name": "HeroImages"
},
{
"name": "Auth"
},
+51
View File
@@ -0,0 +1,51 @@
<#
.SYNOPSIS
Measures the Largest Contentful Paint (and layout shift) of a page with Lighthouse, mobile profile, a few runs, and
prints the median. Use it before and after the hero markers are in a website, on the TEST hosts.
.DESCRIPTION
Runs `npx lighthouse` (performance category only, mobile emulation with the default throttling) -Runs times against
-Url and reports the LCP element, the LCP time, CLS and total blocking time per run and the median LCP. Needs Node
(npx) and Chrome or Edge. Nothing is written to the repository; the JSON reports go to -OutDirectory (default: a
temporary folder).
.PARAMETER Url
The page, e.g. https://test.andreaslop.nl/
.PARAMETER Runs
Number of runs (default 3; the median is what counts, a single run varies).
.PARAMETER OutDirectory
Where the Lighthouse JSON reports are kept.
.EXAMPLE
./scripts/Measure-Lcp.ps1 -Url https://test.andreaslop.nl/ -Runs 5
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string] $Url,
[int] $Runs = 3,
[string] $OutDirectory = (Join-Path ([IO.Path]::GetTempPath()) 'lcp-measure')
)
$ErrorActionPreference = 'Stop'
New-Item -ItemType Directory -Force -Path $OutDirectory | Out-Null
$results = @()
for ($i = 1; $i -le $Runs; $i++) {
$file = Join-Path $OutDirectory ("lh-{0}-{1}.json" -f ([uri]$Url).Host, $i)
& npx --yes lighthouse@12 $Url --only-categories=performance --form-factor=mobile --output=json --output-path=$file `
--chrome-flags="--headless=new --no-sandbox" --quiet | Out-Null
$report = Get-Content -LiteralPath $file -Raw | ConvertFrom-Json
$audits = $report.audits
$element = $audits.'largest-contentful-paint-element'.details.items[0].items[0].node.snippet
$results += [pscustomobject]@{
Run = $i
LcpMs = [math]::Round($audits.'largest-contentful-paint'.numericValue)
Cls = [math]::Round($audits.'cumulative-layout-shift'.numericValue, 3)
TbtMs = [math]::Round($audits.'total-blocking-time'.numericValue)
Element = $element
}
}
$results | Format-Table -AutoSize
$sorted = $results.LcpMs | Sort-Object
Write-Host ("Median LCP: {0} ms (reports in {1})" -f $sorted[[int][math]::Floor(($sorted.Count - 1) / 2)], $OutDirectory)
+170
View File
@@ -0,0 +1,170 @@
<#
.SYNOPSIS
Puts the hero of a site into a CMS through the admin API: uploads the photos, sets their focus points and saves the
hero. Test hosts only unless you deliberately point it somewhere else. Skips a CMS that already has a hero.
.DESCRIPTION
Logs in with an admin account (the password is asked interactively, as a secure string; it is never written to disk,
to the console or to a log). Then, from -SeedFile: uploads every slide photo from -ImagesDirectory (the same photo
again is the same image, so a second run does not duplicate anything), sets the focus point of each photo, and saves
the hero (texts, buttons, display and the slides with their alt texts) in one go.
.PARAMETER BaseUrl
Root of the host, e.g. https://test.andreaslop.nl (no trailing /api).
.PARAMETER SeedFile
JSON: title (new lines as \n), tagline, lead, display (single or slideshow), buttons [{label, target}],
slides [{file, alt, decorative, focus {x, y}}]. Default: hero-asf.json next to this script. hero-sls.json is the
text-only hero of SLP Software (no slides).
.PARAMETER ImagesDirectory
The folder that holds the files named in the slides (required when the seed has slides). For ASF these are the
existing exports hero-1.jpg to hero-8.jpg of the website repository (web/src/assets).
.PARAMETER Email
Admin e-mail address. Asked when omitted.
.PARAMETER Force
Replace an existing hero as well (the photos stay; the slide list is replaced).
.PARAMETER WhatIf
Shows what would be done without logging in or writing anything.
.EXAMPLE
./scripts/Seed-Hero.ps1 -BaseUrl https://test.andreaslop.nl -ImagesDirectory K:\Development\SlpSoftware\Projects\AndreaSlopFotografie\web\src\assets
.EXAMPLE
./scripts/Seed-Hero.ps1 -BaseUrl https://test.slpsoftware.nl -SeedFile ./scripts/hero-sls.json
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)] [string] $BaseUrl,
[string] $SeedFile,
[string] $ImagesDirectory,
[string] $Email,
[switch] $Force
)
$ErrorActionPreference = 'Stop'
# $PSScriptRoot is empty in a param default under Windows PowerShell 5.1, so it is read here.
$here = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
if (-not $SeedFile) { $SeedFile = Join-Path $here 'hero-asf.json' }
$BaseUrl = $BaseUrl.TrimEnd('/')
$api = "$BaseUrl/api/v1"
$seed = Get-Content -LiteralPath $SeedFile -Raw -Encoding UTF8 | ConvertFrom-Json
if ([string]::IsNullOrWhiteSpace($seed.title) -or $seed.title -like 'TODO*') { throw "The seed has no title (or it is still TODO)." }
$slides = @($seed.slides | Where-Object { $_ })
if ($slides.Count -gt 0) {
if (-not $ImagesDirectory) { throw 'The seed has slides: give -ImagesDirectory (the folder with the photos).' }
foreach ($s in $slides) {
$path = Join-Path $ImagesDirectory $s.file
if (-not (Test-Path -LiteralPath $path)) { throw "Photo not found: $path" }
if ([string]::IsNullOrWhiteSpace($s.alt) -and -not $s.decorative) { throw "Slide '$($s.file)' has no alt text and is not decorative." }
}
}
if ($WhatIfPreference) {
Write-Host "Would save the hero '$($seed.title -replace "`n", ' / ')' on $BaseUrl with $($slides.Count) slide(s):"
$slides | ForEach-Object { Write-Host " $($_.file) focus $($_.focus.x),$($_.focus.y) alt: $($_.alt)" }
return
}
if (-not $Email) { $Email = Read-Host 'Admin e-mail' }
# The password is asked interactively. For an unattended run on a LOCAL host only (a test or CI job), the environment
# variable SEED_HERO_PASSWORD is used instead when it is set; it is never printed.
if ($env:SEED_HERO_PASSWORD) {
$plain = $env:SEED_HERO_PASSWORD
try {
$body = @{ email = $Email; password = $plain } | ConvertTo-Json -Compress
$login = Invoke-RestMethod -Method Post -Uri "$api/auth/login" -ContentType 'application/json' -Body $body
}
finally { $plain = $null; $body = $null }
}
else {
$secure = Read-Host "Password for $Email" -AsSecureString
$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
try {
$plain = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
$body = @{ email = $Email; password = $plain } | ConvertTo-Json -Compress
$login = Invoke-RestMethod -Method Post -Uri "$api/auth/login" -ContentType 'application/json' -Body $body
}
finally {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
$plain = $null; $body = $null
}
}
$token = $login.accessToken
$headers = @{ Authorization = "Bearer $token" }
$current = Invoke-RestMethod -Method Get -Uri "$api/hero/all" -Headers $headers
if ($current.id -and -not $Force) {
Write-Host "skip a hero already exists on $BaseUrl (use -Force to replace it)"
return
}
Add-Type -AssemblyName System.Net.Http
function Send-Photo([string] $path) {
$client = [System.Net.Http.HttpClient]::new()
try {
$client.DefaultRequestHeaders.Authorization = [System.Net.Http.Headers.AuthenticationHeaderValue]::new('Bearer', $token)
$form = [System.Net.Http.MultipartFormDataContent]::new()
$bytes = [System.IO.File]::ReadAllBytes($path)
$content = [System.Net.Http.ByteArrayContent]::new($bytes)
$form.Add($content, 'file', [System.IO.Path]::GetFileName($path))
$response = $client.PostAsync("$api/hero/images", $form).GetAwaiter().GetResult()
$text = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
if (-not $response.IsSuccessStatusCode) { throw "Upload of '$path' failed ($([int]$response.StatusCode)): $text" }
return ($text | ConvertFrom-Json)
}
finally { $client.Dispose() }
}
# First every photo is uploaded (the same photo again is the same image, so a second run duplicates nothing). The focus
# point of a photo is not a call of its own: a changed focus takes effect when the hero is saved, so it travels in the
# same request as the hero (imageFocus).
$requestSlides = @()
$imageFocus = @()
foreach ($s in $slides) {
$image = Send-Photo (Join-Path $ImagesDirectory $s.file)
Write-Host "upload $($s.file) -> image $($image.id)"
if ($s.focus -and -not ($imageFocus | Where-Object { $_.imageId -eq $image.id })) {
$imageFocus += [ordered]@{
imageId = $image.id
focus = [ordered]@{ x = [double]$s.focus.x; y = [double]$s.focus.y; zoom = 1.0 }
wide = $null
tall = $null
}
Write-Host "focus $($s.file) at $($s.focus.x), $($s.focus.y) (saved with the hero)"
}
$requestSlides += [ordered]@{ imageId = $image.id; alt = $(if ($s.decorative) { $null } else { $s.alt }); decorative = [bool]$s.decorative; isActive = $true }
}
$payload = [ordered]@{
title = $seed.title
tagline = $(if ($seed.tagline) { $seed.tagline } else { $null })
lead = $(if ($seed.lead) { $seed.lead } else { $null })
display = $(if ($seed.display) { $seed.display } else { 'single' })
buttons = @($seed.buttons | Where-Object { $_ } | ForEach-Object { [ordered]@{ label = $_.label; target = $_.target } })
slides = $requestSlides
imageFocus = $imageFocus
} | ConvertTo-Json -Depth 6
try {
$saved = Invoke-RestMethod -Method Put -Uri "$api/hero" -Headers $headers -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($payload))
Write-Host "saved hero $($saved.id) with $($saved.slides.Count) slide(s); live: $($saved.isLive)"
# The variants of the photos are cut in the background (about half a minute per photo on a Raspberry Pi); a photo goes
# live as soon as its set is ready. Wait for them so the script ends when the site shows everything (at most 15 minutes).
$deadline = (Get-Date).AddMinutes(15)
do {
$state = Invoke-RestMethod -Method Get -Uri "$api/hero/all" -Headers $headers
$waiting = @($state.slides | Where-Object { $_.image.processing }).Count
if ($waiting -eq 0) { break }
Write-Host "wait $waiting photo(s) are still being prepared in the background"
Start-Sleep -Seconds 15
} while ((Get-Date) -lt $deadline)
if ($waiting -eq 0) { Write-Host "ready all photos are prepared" } else { Write-Warning "$waiting photo(s) are still being prepared; they appear on the site by themselves." }
}
catch {
Write-Error "Saving the hero failed: $($_.Exception.Message) $($_.ErrorDetails.Message)"
}
+87
View File
@@ -0,0 +1,87 @@
{
"note": "Seed of the ASF hero for the TEST CMS (ASF commit 13f78c4, web/contract/host-injection/hero/seed.json). Photos: the existing exports in the website repository (web/src/assets, hero-1.jpg to hero-8.jpg); never upscaled. The focus points are a first estimate by looking at the photos (x and y from the top left, 0 to 1); Bryan adjusts them in the admin.",
"display": "slideshow",
"title": "Andrea Slop",
"tagline": "Lifestyle fotograaf · Huizen",
"lead": null,
"buttons": [
{
"label": "Lees meer",
"target": "/over-mij"
}
],
"slides": [
{
"file": "hero-8.jpg",
"alt": "Zwangerschapsfoto in de duinen",
"decorative": false,
"focus": {
"x": 0.5,
"y": 0.55
}
},
{
"file": "hero-7.jpg",
"alt": "Knusse newbornfoto met de familie",
"decorative": false,
"focus": {
"x": 0.45,
"y": 0.5
}
},
{
"file": "hero-1.jpg",
"alt": "Lifestyle fotografie",
"decorative": false,
"focus": {
"x": 0.55,
"y": 0.6
}
},
{
"file": "hero-2.jpg",
"alt": "Zwangerschapsshoot in de buitenlucht",
"decorative": false,
"focus": {
"x": 0.45,
"y": 0.45
}
},
{
"file": "hero-3.jpg",
"alt": "Newbornshoot van een pasgeboren baby",
"decorative": false,
"focus": {
"x": 0.45,
"y": 0.4
}
},
{
"file": "hero-4.jpg",
"alt": "Spontaan portret buiten",
"decorative": false,
"focus": {
"x": 0.45,
"y": 0.35
}
},
{
"file": "hero-5.jpg",
"alt": "Natuurlijke lifestylefoto",
"decorative": false,
"focus": {
"x": 0.5,
"y": 0.55
}
},
{
"file": "hero-6.jpg",
"alt": "Portret in de natuur",
"decorative": false,
"focus": {
"x": 0.5,
"y": 0.35
}
}
]
}
+18
View File
@@ -0,0 +1,18 @@
{
"note": "Seed of the SLP Software hero for the TEST CMS: the current texts, unchanged (Bryan, 2026-11-16). The small line 'Web & .NET development' and the code line stay fixed text in the SLP website. The title is one field with line breaks; the website derives the screen-reader title from the lines.",
"display": "single",
"title": "Websites,\napps\n& meer.",
"tagline": null,
"lead": "Bij SLP Software kun je terecht voor maatwerk oplossingen. Of het nou gaat om een website, cms of app: wij bouwen het allemaal. Voor ondernemers die geen verrassingen willen — niet in de code, niet op de factuur.",
"buttons": [
{
"label": "Bekijk pakketten",
"target": "#pakketten"
},
{
"label": "Plan een gesprek",
"target": "#contact"
}
],
"slides": []
}
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# Finds inline scripts in an HTML page (read from stdin): the ones a Content-Security-Policy with script-src 'self' blocks.
#
# An inline script is a <script> WITHOUT a src attribute (wherever the attribute stands in the tag) whose content is not
# empty. Not counted: <script src="..."> (also with type="module", crossorigin, defer, ... in any order), an empty
# <script></script>, and data blocks that are not executed (type="application/json", "application/ld+json",
# "importmap" and the like). Prints the opening tag of every inline script found; no output means none.
# Plain POSIX tools only (no grep -P), so it behaves the same on every runner.
inline_scripts() {
tr '\r\n' ' ' \
| grep -oiE '<script[^>]*>[[:space:]]*[^[:space:]<]' \
| grep -viE '<script[^>]*[[:space:]]src[[:space:]]*=' \
| grep -viE '<script[^>]*type[[:space:]]*=[[:space:]]*["'\'']?(application/(ld\+)?json|importmap|speculationrules)' \
|| true
}
+21 -2
View File
@@ -10,6 +10,8 @@
# master CMS only; this script is the check that the deployed composition of a site is the one that was intended.
# A failing check makes the CI run fail.
set -u
# shellcheck source=lib-inline-script.sh
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib-inline-script.sh"
base="$(printf '%s' "${1:?usage: smoke-site.sh <url-on-the-host> <profile>}" | sed -E 's#^(https?://[^/]+).*#\1#')"
profile="${2:?profile (sls-test | asf-test) is required}"
@@ -50,6 +52,23 @@ banner="$(status_of '/api/v1/offerings/banner')"
if [ "$banner" = "200" ] || [ "$banner" = "204" ]; then pass "public banner (/api/v1/offerings/banner -> $banner)"; else fail "public banner (-> $banner, expected 200 or 204)"; fi
expect_status /api/v1/offerings/all 401 "the administrator list is protected"
# The hero: 204 = no hero to show (the website keeps its own), 200 = there is one; the management routes are protected and
# the media endpoint answers a plain 404 for something that is not stored.
hero="$(status_of '/api/v1/hero')"
if [ "$hero" = "200" ] || [ "$hero" = "204" ]; then pass "public hero (/api/v1/hero -> $hero)"; else fail "public hero (-> $hero, expected 200 or 204)"; fi
expect_status /api/v1/hero/all 401 "the hero management read is protected"
expect_status /media/hero/0123456789abcdef/wide-960.webp 404 "media that is not stored is a plain 404"
# The admin page must have no inline script: the host only allows scripts from its own origin (script-src 'self').
# The check lives in lib-inline-script.sh (and is tested by test-inline-script-check.sh); it prints what it found.
admin_html="$(curl_get "$base/admin/" || true)"
if printf '%s' "$admin_html" | grep -q 'id="root"'; then
inline_found="$(printf '%s' "$admin_html" | inline_scripts)"
if [ -n "$inline_found" ]; then fail "the admin page has an inline script (blocked by the Content-Security-Policy): $(printf '%s' "$inline_found" | head -3 | tr '
' ' ')"; else pass "the admin page has no inline script"; fi
expect_status /admin/theme-init.js 200 "the theme script is a file of its own"
fi
# A test host is never indexed.
expect_header / X-Robots-Tag noindex "noindex on the website"
expect_body /robots.txt "Disallow: /" "robots.txt disallows everything"
@@ -75,11 +94,11 @@ fi
case "$profile" in
sls-test)
for m in Identity Availability Offerings Contact Master; do expect_module "$m"; done
for m in Identity Availability Offerings Contact Hero Master; do expect_module "$m"; done
expect_status /sitemap.xml 404 "no sitemap on a test host"
;;
asf-test)
for m in Identity Availability Offerings Contact; do expect_module "$m"; done
for m in Identity Availability Offerings Contact Hero; do expect_module "$m"; done
expect_no_module Master
# Prerendered website: an unknown path is a real 404 (an SPA would answer 200).
expect_status /smoke-test-path-that-does-not-exist 404 "unknown website path is a 404"
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
# Tests inline_scripts (scripts/lib-inline-script.sh) against HTML as the admin page looks. Run: bash scripts/test-inline-script-check.sh
set -u
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib-inline-script.sh
. "$here/lib-inline-script.sh"
failures=0
expect() { # description expected(clean|inline) html
local found; found="$(printf '%s' "$3" | inline_scripts)"
if [ "$2" = "clean" ] && [ -z "$found" ]; then echo "ok $1"
elif [ "$2" = "inline" ] && [ -n "$found" ]; then echo "ok $1"
else echo "FAIL $1 (expected $2, found: ${found:-nothing})"; failures=$((failures + 1)); fi
}
expect "the built admin page (module script with crossorigin before src)" clean '<!doctype html><html><head>
<link rel="icon" href="/admin/favicon.svg" />
<script src="/admin/theme-init.js"></script>
<script type="module" crossorigin src="/admin/assets/index-Da0WHZBX.js"></script>
<link rel="modulepreload" crossorigin href="/admin/assets/button.js">
<link rel="stylesheet" crossorigin href="/admin/assets/index.css">
</head><body><div id="root"></div></body></html>'
expect "src in the middle of the tag, single quotes, defer" clean "<script defer src='/a.js' data-x=\"1\"></script><script async crossorigin src = \"/b.js\"></script>"
expect "a tag over several lines" clean '<script
type="module"
crossorigin
src="/admin/assets/index.js"
></script>'
expect "an empty script" clean '<script></script><script> </script>'
expect "a JSON data block" clean '<script type="application/json" id="cms-data">{"a":1}</script>'
expect "a JSON-LD block and an import map" clean '<script type="application/ld+json">{"@context":"https://schema.org"}</script><script type="importmap">{"imports":{}}</script>'
expect "the old inline theme script" inline '<head><script>
(function () { document.documentElement.classList.add("dark"); })();
</script></head>'
expect "an inline module script" inline '<script type="module">import "/x.js"</script>'
expect "an inline script after good ones" inline '<script src="/a.js"></script><div></div><script nonce="abc">window.x = 1</script>'
expect "an inline script that starts with a comparison" inline '<script>if (a < b) { go(); }</script>'
expect "text that only mentions the word script" clean '<p>Use a script tag with a src attribute.</p><script src="/ok.js"></script>'
if [ "$failures" -ne 0 ]; then echo "$failures check(s) failed"; exit 1; fi
echo "all checks passed"
@@ -30,6 +30,7 @@
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Availability\SlpModularCms.Modules.Availability.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
</ItemGroup>
@@ -24,6 +24,7 @@
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj" />
</ItemGroup>
<!--
@@ -9,6 +9,9 @@
}
},
"AllowedHosts": "*",
// The SLP hero has no images: the host writes its title, lead and buttons as text into the first HTML.
// TitlePrefix: visually hidden brand text before the title lines in the h1 (for crawlers and screen readers).
"Hero": { "TextOnlyRegion": true, "TitlePrefix": "SLP Software: " },
"Website": {
// Secure default: every response carries noindex and /robots.txt disallows all. A production
// instance must set Website__NoIndex=false and Website__PublicBaseUrl=https://slpsoftware.nl explicitly;
@@ -0,0 +1,168 @@
using System.Net;
using System.Text.Json;
using FluentAssertions;
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;
/// <summary>
/// Runs the real master host with ASF settings over the REAL build of the ASF website (its <c>dist/client</c>), with the
/// hero of ASF's seed made through the module's services. Optional: it only runs when <c>ASF_WEB_DIR</c> points at the
/// <c>web</c> folder of the ASF website repository (with a build in <c>dist/client</c>); otherwise it does nothing.
/// With <c>HERO_E2E_OUT</c> set it also writes the served page and the API answer there, so they can be compared
/// with the website's own renderer.
/// </summary>
public sealed class AsfSiteFactory : AsfVariantFactory, IDisposable
{
public string WebRoot { get; } = Path.Combine(Path.GetTempPath(), "slp-asf-site-" + Guid.NewGuid().ToString("N"));
public string MediaDirectory { get; } = Path.Combine(Path.GetTempPath(), "slp-asf-media-" + Guid.NewGuid().ToString("N"));
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
var web = Environment.GetEnvironmentVariable("ASF_WEB_DIR");
if (!string.IsNullOrEmpty(web))
{
CopyDirectory(Path.Combine(web, "dist", "client"), Path.Combine(WebRoot, "web"));
}
builder.UseWebRoot(WebRoot);
builder.ConfigureAppConfiguration((_, config) =>
config.AddInMemoryCollection(new Dictionary<string, string?> { ["Media:Directory"] = MediaDirectory, ["Website:PublicBaseUrl"] = "https://test.andreaslop.nl" }));
}
private static void CopyDirectory(string from, string to)
{
Directory.CreateDirectory(to);
foreach (var file in Directory.GetFiles(from)) File.Copy(file, Path.Combine(to, Path.GetFileName(file)), overwrite: true);
foreach (var dir in Directory.GetDirectories(from)) CopyDirectory(dir, Path.Combine(to, Path.GetFileName(dir)));
}
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 HeroAsfSiteE2ETests : IClassFixture<AsfSiteFactory>
{
private readonly AsfSiteFactory _factory;
public HeroAsfSiteE2ETests(AsfSiteFactory factory) => _factory = factory;
private async Task<T> InScope<T>(Func<IServiceProvider, Task<T>> action)
{
await using var scope = _factory.Services.CreateAsyncScope();
return await action(scope.ServiceProvider);
}
[Fact]
public async Task TheRealAsfBuild_GetsTheSeededHero_InItsFirstHtml()
{
var web = Environment.GetEnvironmentVariable("ASF_WEB_DIR");
if (string.IsNullOrEmpty(web) || !File.Exists(Path.Combine(web, "dist", "client", "index.html")))
{
return; // optional check: needs the ASF website repository and its build
}
var client = _factory.CreateClient();
var caller = Guid.NewGuid();
// The image library self-test and the media directory check run in the background after start-up.
var status = _factory.Services.GetRequiredService<SlpModularCms.Core.Media.MediaStatus>();
for (var i = 0; i < 300 && !status.UploadsAvailable; i++) await Task.Delay(100);
await InScope(async sp =>
{
var db = sp.GetRequiredService<HeroDbContext>();
db.Heroes.RemoveRange(await db.Heroes.ToListAsync());
await db.SaveChangesAsync();
return 0;
});
try
{
var seed = JsonDocument.Parse(File.ReadAllText(Path.Combine(web, "contract", "host-injection", "hero", "seed.json"))).RootElement;
var slides = new List<HeroSlideRequest>();
var focusEdits = new List<HeroImageFocusRequest>();
foreach (var slide in seed.GetProperty("slides").EnumerateArray())
{
var photo = File.ReadAllBytes(Path.Combine(web, "src", "assets", slide.GetProperty("file").GetString()!));
var image = await InScope(sp => sp.GetRequiredService<IHeroImageService>().UploadAsync(new MemoryStream(photo), photo.Length, caller, default));
var focus = slide.GetProperty("focus");
// The focus travels with the save of the hero, like the admin does it.
focusEdits.Add(new HeroImageFocusRequest(Guid.Parse(image.Id), new FocusDto(focus.GetProperty("x").GetDouble(), focus.GetProperty("y").GetDouble(), 1)));
slides.Add(new HeroSlideRequest(null, Guid.Parse(image.Id), slide.GetProperty("alt").GetString()));
}
await InScope(sp => sp.GetRequiredService<IHeroService>().SaveAsync(
new HeroSaveRequest(seed.GetProperty("title").GetString(), seed.GetProperty("tagline").GetString(), null, seed.GetProperty("display").GetString(),
seed.GetProperty("buttons").EnumerateArray().Select(b => new HeroButtonRequest(b.GetProperty("label").GetString(), b.GetProperty("target").GetString())).ToList(),
slides, focusEdits), caller, default));
await InScope(async sp =>
{
// The variants are cut by the background renderer in production; here it is run to the end at once.
// The shared test database may hold rows of earlier runs whose files are gone: those fail and are skipped,
// the way the background renderer gives up on them.
var skip = new HashSet<Guid>();
while (true)
{
try
{
if (await sp.GetRequiredService<IHeroImageService>().RenderNextPendingAsync(skip, default) is null)
{
break;
}
}
catch (HeroImageRenderException failure)
{
skip.Add(failure.ImageId);
}
}
return true;
});
var response = await client.GetAsync("/");
var page = await response.Content.ReadAsStringAsync();
var api = await client.GetStringAsync("/api/v1/hero");
response.StatusCode.Should().Be(HttpStatusCode.OK);
page.Should().Contain("<picture class=\"cms-hero-picture\">").And.Contain("<link rel=\"preload\" as=\"image\"");
page.Should().Contain("<!--CMS:HERO-HTML--><picture").And.Contain("</p><!--/CMS:HERO-HTML-->");
page.Should().NotContain("<!--CMS:DATA-->").And.Contain("\"hero\":{");
JsonDocument.Parse(api).RootElement.GetProperty("slides").GetArrayLength().Should().Be(8);
var outDir = Environment.GetEnvironmentVariable("HERO_E2E_OUT");
if (!string.IsNullOrEmpty(outDir))
{
Directory.CreateDirectory(outDir);
File.WriteAllText(Path.Combine(outDir, "page.html"), page);
File.WriteAllText(Path.Combine(outDir, "api.json"), api);
}
}
finally
{
await InScope(async sp =>
{
var db = sp.GetRequiredService<HeroDbContext>();
db.Heroes.RemoveRange(await db.Heroes.ToListAsync());
await db.SaveChangesAsync();
return 0;
});
}
}
}
@@ -0,0 +1,207 @@
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;
/// <summary>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.</summary>
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<string, string?> { ["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<HeroInjectionFactory>
{
private const string Page =
"<!doctype html><html><head><!--CMS:HERO-PRELOAD-->baked preload<!--/CMS:HERO-PRELOAD-->" +
"<!--CMS:DATA--><script type=\"application/json\" id=\"cms-data\">{\"baked\":true}</script></head>" +
"<body><!--CMS:HERO-HTML-->baked hero<!--/CMS:HERO-HTML--></body></html>";
private readonly HeroInjectionFactory _factory;
public HeroInjectionPipelineTests(HeroInjectionFactory factory)
{
_factory = factory;
File.WriteAllText(Path.Combine(factory.WebRoot, "web", "hero.html"), Page);
}
private async Task<T> InScope<T>(Func<IServiceProvider, Task<T>> action)
{
_ = _factory.CreateClient(); // starts the host, migrates and starts the start-up checks
// The image library self-test and the media directory check run in the background after start-up.
var status = _factory.Services.GetRequiredService<SlpModularCms.Core.Media.MediaStatus>();
for (var i = 0; i < 300 && !status.UploadsAvailable; i++) await Task.Delay(100);
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 = "<script type=\"application/json\" id=\"cms-data\">";
var start = body.IndexOf(open, StringComparison.Ordinal) + open.Length;
return body[start..body.IndexOf("</script>", 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<HeroDbContext>();
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<HeroDbContext>();
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<IHeroImageService>().UploadAsync(new MemoryStream(Photo()), Photo().Length, caller, default));
await InScope(async sp => await sp.GetRequiredService<IHeroService>().SaveAsync(
new HeroSaveRequest("Andrea Slop", "Lifestyle fotograaf · Huizen", null, "slideshow", [new HeroButtonRequest("Lees meer", "/over-mij")],
[new HeroSlideRequest(null, Guid.Parse(image.Id), "Zwangerschapsfoto in de duinen")]), caller, default));
await InScope(async sp =>
{
// The variants are cut by the background renderer in production; here it is run to the end at once.
// The shared test database may hold rows of earlier runs whose files are gone: those fail and are skipped,
// the way the background renderer gives up on them.
var skip = new HashSet<Guid>();
while (true)
{
try
{
if (await sp.GetRequiredService<IHeroImageService>().RenderNextPendingAsync(skip, default) is null)
{
break;
}
}
catch (HeroImageRenderException failure)
{
skip.Add(failure.ImageId);
}
}
return true;
});
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("<picture class=\"cms-hero-picture\"><source media=\"(orientation: portrait)\"");
body.Should().Contain("alt=\"Zwangerschapsfoto in de duinen\"").And.Contain("<span class=\"cms-hero-name\">Andrea Slop</span>");
body.Should().Contain("<a class=\"cms-hero-button\" href=\"/over-mij\">Lees meer</a>");
body.Should().Contain("<link rel=\"preload\" as=\"image\"").And.Contain("media=\"(orientation: landscape)\"");
// The data block carries the same hero as the public endpoint, after the site address.
var data = JsonDocument.Parse(DataBlock(body)).RootElement;
data.EnumerateObject().Select(p => 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);
// A media directory that lost its files leaves the baked hero too (no broken first image).
Directory.Delete(Path.Combine(_factory.MediaDirectory, "hero"), recursive: true);
await InScope(sp => { sp.GetRequiredService<SlpModularCms.Core.Hosting.Website.IIndexHtmlCache>().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<HeroDbContext>();
db.Heroes.RemoveRange(await db.Heroes.ToListAsync());
await db.SaveChangesAsync();
return 0;
});
}
}
@@ -0,0 +1,82 @@
using System.Net;
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SlpModularCms.Modules.Hero.Data;
namespace SlpModularCms.Api.Tests;
/// <summary>The Hero module on the real master host and the real, migrated database.</summary>
[Collection("HeroDatabase")]
public class HeroOnTheMasterHostTests : IClassFixture<ApiWebApplicationFactory>
{
private readonly ApiWebApplicationFactory _factory;
public HeroOnTheMasterHostTests(ApiWebApplicationFactory factory) => _factory = factory;
[Fact]
public async Task Capabilities_ListTheHeroModule()
{
var response = await _factory.CreateClient().GetAsync("/api/v1/System/capabilities");
using var doc = System.Text.Json.JsonDocument.Parse(await response.Content.ReadAsStringAsync());
doc.RootElement.GetProperty("modules").EnumerateArray().Select(e => e.GetString()).Should().Contain("Hero");
}
[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<HeroDbContext>();
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);
response.Headers.CacheControl!.ToString().Should().Be("public, max-age=60");
}
[Theory]
[InlineData("GET", "/api/v1/hero/all")]
[InlineData("PUT", "/api/v1/hero")]
[InlineData("POST", "/api/v1/hero/images")]
[InlineData("DELETE", "/api/v1/hero/images/11111111-2222-3333-4444-555555555555")]
public async Task Management_RequiresAnAdministrator(string method, string url)
{
var request = new HttpRequestMessage(new HttpMethod(method), url);
if (method == "POST")
{
request.Content = new MultipartFormDataContent { { new ByteArrayContent([1, 2, 3]), "file", "x.jpg" } };
}
var response = await _factory.CreateClient().SendAsync(request);
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Theory]
[InlineData("/media/hero/0123456789abcdef/wide-960.webp")]
[InlineData("/media/hero/0123456789abcdef/../../secret")]
[InlineData("/media/originals/anything.jpg")]
public async Task TheMediaEndpoint_AnswersAPlain404_ForAnythingNotStored(string url)
{
var response = await _factory.CreateClient().GetAsync(url);
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public void HeroMigrations_MatchTheModel()
{
_ = _factory.CreateClient(); // starts the host and migrates
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<HeroDbContext>();
db.Database.HasPendingModelChanges().Should().BeFalse("every model change needs its migration and snapshot");
}
}
@@ -21,7 +21,7 @@ public class SiteContractTests
public void TheMasterCms_ReferencesEveryModule()
{
SiteFiles.Modules("SlpModularCms.Api").Should().BeEquivalentTo(
["Availability", "Contact", "Identity", "Master", "Offerings"],
["Availability", "Contact", "Hero", "Identity", "Master", "Offerings"],
"the master Api is the all-modules composition the CI builds and tests");
}
@@ -29,7 +29,7 @@ public class SiteContractTests
public void SlpSoftware_IsTheFullComposition()
{
SiteFiles.Modules(SiteFiles.SlpSoftware).Should().BeEquivalentTo(
["Availability", "Contact", "Identity", "Master", "Offerings"]);
["Availability", "Contact", "Hero", "Identity", "Master", "Offerings"]);
}
[Fact]
@@ -37,7 +37,7 @@ public class SiteContractTests
{
// Not a master/slave setup: no Master module, so /System/capabilities does not list it.
SiteFiles.Modules(SiteFiles.AndreaSlopFotografie).Should().BeEquivalentTo(
["Availability", "Contact", "Identity", "Offerings"]);
["Availability", "Contact", "Hero", "Identity", "Offerings"]);
}
[Theory]
@@ -59,6 +59,23 @@ public class SiteContractTests
(configured ?? "SpaFallback").Should().Be(mode);
}
[Theory]
[InlineData(SiteFiles.SlpSoftware, true)]
[InlineData(SiteFiles.AndreaSlopFotografie, false)]
public void TheHeroIsWrittenAsTextOnlyForTheSiteWithoutHeroImages(string site, bool textOnly)
{
// SLP Software's hero has no images, so the host writes it as text; ASF's baked hero is a picture and stays when the CMS hero has no slide.
SiteFiles.Committed(site).GetValue<bool>("Hero:TextOnlyRegion").Should().Be(textOnly);
}
[Theory]
[InlineData(SiteFiles.SlpSoftware, "SLP Software: ")]
[InlineData(SiteFiles.AndreaSlopFotografie, "")]
public void TheHeroTitlePrefix_IsSetForSlpSoftware_AndEmptyForAsf(string site, string prefix)
{
(SiteFiles.Committed(site)["Hero:TitlePrefix"] ?? string.Empty).Should().Be(prefix);
}
[Theory]
[MemberData(nameof(Sites))]
public void WebsiteIsNoIndex_ByDefault(string site)
@@ -24,6 +24,7 @@
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj" />
</ItemGroup>
<!--
@@ -0,0 +1,398 @@
using ImageMagick;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Media;
namespace SlpModularCms.Core.Media.Magick;
/// <summary>
/// <see cref="IImageProcessor"/> 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 <see cref="MediaOptions"/>.
/// </summary>
public sealed class MagickImageProcessor : IImageProcessor
{
private static readonly object LimitsLock = new();
private static bool _limitsSet;
private readonly MediaOptions _options;
private readonly ILogger<MagickImageProcessor> _logger;
public MagickImageProcessor(IOptions<MediaOptions> options, ILogger<MagickImageProcessor> logger)
{
_options = options.Value;
_logger = logger;
SetLimits(_options);
SupportedInput = DetectInput();
SupportedOutput = DetectOutput();
}
public IReadOnlySet<ImageFormat> SupportedInput { get; }
public IReadOnlySet<ImageFormat> SupportedOutput { get; }
public Task<ImageInfo> InspectAsync(ReadOnlyMemory<byte> data, ImageFormat declared, CancellationToken cancellationToken)
=> RunAsync(() => Inspect(data, declared), cancellationToken);
public Task<RenderedImage> RenderAsync(ReadOnlyMemory<byte> data, ImageFormat declared, VariantSpec variant, CancellationToken cancellationToken)
=> RunAsync(() => Render(data, declared, variant), cancellationToken);
public Task<IReadOnlyList<RenderedImage>> RenderSetAsync(ReadOnlyMemory<byte> data, ImageFormat declared, IReadOnlyList<VariantSpec> variants, Action<int, int>? progress, CancellationToken cancellationToken)
=> RunAsync(() => RenderSet(data, declared, variants, progress, cancellationToken), cancellationToken, _options.RenderSetTimeoutSeconds);
public Task<byte[]?> StripMetadataAsync(ReadOnlyMemory<byte> data, ImageFormat declared, CancellationToken cancellationToken)
=> RunAsync(() => StripMetadata(data, declared), cancellationToken, _options.StripTimeoutSeconds);
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<T> RunAsync<T>(Func<T> work, CancellationToken cancellationToken, int? timeoutSeconds = null)
{
try
{
return await Task.Run(work, cancellationToken)
.WaitAsync(TimeSpan.FromSeconds(Math.Max(1, timeoutSeconds ?? _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<byte> 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<byte> data, ImageFormat declared, VariantSpec variant)
{
using var image = DecodeOriented(data, declared);
return Cut(image, variant);
}
/// <summary>
/// One decode for the whole set, and as little repeated work as possible: per crop the widths are cut from large to
/// small, each from the previous (smaller input than the full picture), and a width is resized once for all of its
/// formats (WebP and AVIF are encoded from the same pixels).
/// </summary>
private IReadOnlyList<RenderedImage> RenderSet(ReadOnlyMemory<byte> data, ImageFormat declared, IReadOnlyList<VariantSpec> variants, Action<int, int>? progress, CancellationToken cancellationToken)
{
using var image = DecodeOriented(data, declared);
var results = new RenderedImage?[variants.Count];
var done = 0;
foreach (var group in variants.Select((spec, index) => (spec, index)).GroupBy(x => (x.spec.Ratio.Name, x.spec.Crop)))
{
var crop = group.Key.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.");
}
// A copy of the decoded pixels is a plain memory copy, cheap next to decoding or encoding.
IMagickImage<byte> current = image.Clone();
try
{
current.Crop(new MagickGeometry(crop.X, crop.Y, (uint)crop.Width, (uint)crop.Height));
current.ResetPage();
ToSrgb(current);
current.Strip();
foreach (var width in group.GroupBy(x => x.spec.Width).OrderByDescending(g => g.Key))
{
// A cancelled or timed-out job stops at the next width; the native library itself cannot be interrupted.
cancellationToken.ThrowIfCancellationRequested();
var first = width.First().spec;
if (current.Width != (uint)first.Width || current.Height != (uint)first.Height)
{
current.Resize(new MagickGeometry((uint)first.Width, (uint)first.Height) { IgnoreAspectRatio = true });
}
foreach (var (spec, index) in width)
{
results[index] = Encode(current, spec);
progress?.Invoke(++done, variants.Count);
}
}
}
finally
{
current.Dispose();
}
}
return results.Select(r => r!).ToList();
}
/// <summary>Writes already cut and resized pixels in the format and quality of the variant.</summary>
private static RenderedImage Encode(IMagickImage<byte> pixels, VariantSpec variant)
{
pixels.Quality = (uint)variant.Quality;
if (variant.Format == ImageFormat.Avif)
{
pixels.Settings.SetDefine(MagickFormat.Avif, "speed", "6");
}
using var stream = new MemoryStream();
pixels.Write(stream, ToMagick(variant.Format));
return new RenderedImage(stream.ToArray(), (int)pixels.Width, (int)pixels.Height, variant.Format);
}
private static MagickImage DecodeOriented(ReadOnlyMemory<byte> data, ImageFormat declared)
{
var settings = new MagickReadSettings { Format = ToMagick(declared), FrameIndex = 0, FrameCount = 1 };
var image = ReadStrict(data, settings);
image.AutoOrient();
return image;
}
/// <summary>Crops a copy of the decoded picture, resizes and encodes it.</summary>
private static RenderedImage Cut(IMagickImage<byte> source, VariantSpec variant)
{
var crop = variant.Crop;
if (crop.X < 0 || crop.Y < 0 || crop.Width < 1 || crop.Height < 1
|| crop.X + crop.Width > source.Width || crop.Y + crop.Height > source.Height)
{
throw new ImageRejectedException(ImageRejection.Corrupt, "The planned crop does not fit the decoded image.");
}
// A copy of the decoded pixels is a plain memory copy, cheap next to decoding or encoding.
using var part = source.Clone();
part.Crop(new MagickGeometry(crop.X, crop.Y, (uint)crop.Width, (uint)crop.Height));
part.ResetPage();
part.Resize(new MagickGeometry((uint)variant.Width, (uint)variant.Height) { IgnoreAspectRatio = true });
ToSrgb(part);
part.Strip();
part.Quality = (uint)variant.Quality;
var format = ToMagick(variant.Format);
if (variant.Format == ImageFormat.Avif)
{
part.Settings.SetDefine(MagickFormat.Avif, "speed", "6");
}
using var stream = new MemoryStream();
part.Write(stream, format);
return new RenderedImage(stream.ToArray(), (int)part.Width, (int)part.Height, variant.Format);
}
private static byte[]? StripMetadata(ReadOnlyMemory<byte> 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<byte> 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(IMagickImage<byte> 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;
// The library's own clock runs per picture from its creation: it must not end a set that the job timeout allows.
ResourceLimits.Time = (ulong)Math.Max(1, Math.Max(options.DecodeTimeoutSeconds, Math.Max(options.StripTimeoutSeconds, options.RenderSetTimeoutSeconds)) + 30);
_limitsSet = true;
}
}
private static HashSet<ImageFormat> DetectInput()
{
var wanted = new Dictionary<MagickFormat, ImageFormat>
{
[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<ImageFormat> DetectOutput()
{
var writable = MagickNET.SupportedFormats.Where(f => f.SupportsWriting).Select(f => f.Format).ToHashSet();
var result = new HashSet<ImageFormat> { 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."),
};
}
@@ -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
{
/// <summary>Registers the Magick.NET implementation of <see cref="IImageProcessor"/> (stateless, thread-safe).</summary>
public static IServiceCollection AddMagickImageProcessor(this IServiceCollection services)
{
services.TryAddSingleton<IImageProcessor, MagickImageProcessor>();
return services;
}
}
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<!-- The image library behind IImageProcessor (Apache-2.0). Chosen in the library proof of the hero-module feature
(aidlc-docs/features/hero-module/construction/h1-image-pipeline/nfr-requirements/library-proof.md). Kept in its own
project so hosts that never process images (the slave) do not carry the 35 MB native library. -->
<PackageReference Include="Magick.NET-Q8-AnyCPU" Version="15.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
</ItemGroup>
</Project>
@@ -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 = "<script type=\"application/json\" id=\"cms-data\">";
private static ICmsDataBlockContributor Contributor(string key, int order, object? value)
{
var c = Substitute.For<ICmsDataBlockContributor>();
c.Key.Returns(key);
c.Order.Returns(order);
c.GetAsync(default!, default).ReturnsForAnyArgs(value);
return c;
}
private static JsonElement Data(string html)
{
var start = html.IndexOf(Open, StringComparison.Ordinal) + Open.Length;
return JsonDocument.Parse(html[start..html.IndexOf("</script>", start, StringComparison.Ordinal)]).RootElement;
}
[Theory]
[InlineData("<!--CMS:DATA-->", true)]
[InlineData("<p>nothing</p>", false)]
[InlineData("<!--CMS:OFFERINGS-HTML--><!--/CMS:OFFERINGS-HTML-->", 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("<head><!--CMS:DATA--><script type=\"application/json\" id=\"cms-data\">{\"baked\":true}</script></head>", Context, default);
html.Should().StartWith("<head>" + Open).And.EndWith("</script></head>").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("<!--CMS:DATA-->", 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("<!--CMS:DATA-->", 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 = "</script><img src=x onerror=alert(1)> & \u2028" })]).ApplyAsync("<!--CMS:DATA-->", Context, default);
var inner = html[Open.Length..^"</script>".Length];
inner.Should().NotContain("<").And.NotContain(">").And.NotContain("&").And.NotContain("\u2028");
JsonDocument.Parse(inner).RootElement.GetProperty("x").GetProperty("text").GetString().Should().Be("</script><img src=x onerror=alert(1)> & \u2028");
}
[Fact]
public async Task AFailingContributor_FailsTheWholeBlock_SoThePageKeepsItsBakedBlock()
{
var failing = Substitute.For<ICmsDataBlockContributor>();
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("<!--CMS:DATA-->", Context, default);
await act.Should().ThrowAsync<InvalidOperationException>();
}
[Fact]
public async Task WithoutContributors_TheBlockHoldsTheSiteUrlOnly()
{
var html = await new CmsDataBlockTransform([]).ApplyAsync("<!--CMS:DATA-->", Context, default);
Data(html).EnumerateObject().Select(p => p.Name).Should().Equal("siteUrl");
}
}

Some files were not shown because too many files have changed in this diff Show More