diff --git a/.gitea/workflows/deploy-scp.yaml b/.gitea/workflows/deploy-scp.yaml index 2db2680..7bb47a1 100644 --- a/.gitea/workflows/deploy-scp.yaml +++ b/.gitea/workflows/deploy-scp.yaml @@ -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 diff --git a/SlpModularCms.Ci.slnf b/SlpModularCms.Ci.slnf index a5045cf..1265755 100644 --- a/SlpModularCms.Ci.slnf +++ b/SlpModularCms.Ci.slnf @@ -4,6 +4,7 @@ "projects": [ "src\\SlpModularCms.Api\\SlpModularCms.Api.csproj", "src\\SlpModularCms.Core\\SlpModularCms.Core.csproj", + "src\\SlpModularCms.Core.Media.Magick\\SlpModularCms.Core.Media.Magick.csproj", "src\\SlpModularCms.Core.Tests\\SlpModularCms.Core.Tests.csproj", "src\\SlpModularCms.Modules.Availability\\SlpModularCms.Modules.Availability.csproj", "src\\SlpModularCms.Modules.Availability.Tests\\SlpModularCms.Modules.Availability.Tests.csproj", @@ -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" ] diff --git a/SlpModularCms.sln b/SlpModularCms.sln index 6576ff6..836c7b3 100644 --- a/SlpModularCms.sln +++ b/SlpModularCms.sln @@ -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 diff --git a/aidlc-docs/active-features.md b/aidlc-docs/active-features.md index 36736b6..54eb947 100644 --- a/aidlc-docs/active-features.md +++ b/aidlc-docs/active-features.md @@ -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 | diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md new file mode 100644 index 0000000..a85d2aa --- /dev/null +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -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) diff --git a/aidlc-docs/features/hero-module/assumptions-and-open-questions.md b/aidlc-docs/features/hero-module/assumptions-and-open-questions.md new file mode 100644 index 0000000..b67b3c4 --- /dev/null +++ b/aidlc-docs/features/hero-module/assumptions-and-open-questions.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 `` 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` (`
`), 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 `
`, no brand prefix), then `p.cms-hero-lead` (lead, line breaks as `
`) 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-.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 `` with `` 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. | diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md new file mode 100644 index 0000000..1d2d20f --- /dev/null +++ b/aidlc-docs/features/hero-module/audit.md @@ -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 . (3) Bronfoto's ASF: begin met de huidige 8 exports, geen grotere originelen aanleveren; later uploaden via de admin kan altijd. (4) Focuspunten van de 8 ASF-foto's: de ASF-sessie zet een voorstel ... Maak het contract-document definitief en laat de ASF-sessie de golden files voor + preload leveren." (relayed by SLP Software - SLS - Main) + +**AI Response**: Made the contract document final. H0 built on its own branch from master (458229f). Application Design starts next. + +**Context**: Workflow Planning approved; Application Design. + +--- + +## 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. + +--- diff --git a/aidlc-docs/features/hero-module/construction/build-and-test/build-and-test-summary.md b/aidlc-docs/features/hero-module/construction/build-and-test/build-and-test-summary.md new file mode 100644 index 0000000..3540246 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/build-and-test/build-and-test-summary.md @@ -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. diff --git a/aidlc-docs/features/hero-module/construction/functional-design/business-logic-model.md b/aidlc-docs/features/hero-module/construction/functional-design/business-logic-model.md new file mode 100644 index 0000000..13656aa --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/functional-design/business-logic-model.md @@ -0,0 +1,72 @@ +# Functional Design: business logic model (units H1 to H5) + +Bundled for all units; answers of Bryan (2026-11-16) are applied. Names refer to `application-design/`. HTML for the region and preload is defined by the ASF golden files (`web/contract/host-injection/hero/`, commit 13f78c4), which are authoritative. + +## H1. Image pipeline + +### Upload admission (`IMediaUploadGuard.AdmitAsync`) + +1. Reject at once when the declared length is above the maximum (10 MB) or the stream turns out longer (read through a counting stream, stop at the limit). +2. Read the first bytes and decide the format from the **signature**, never from a name or `Content-Type`: JPEG, PNG, GIF, BMP, TIFF (both byte orders), WebP (`RIFF....WEBP`), and the ISO-BMFF family for AVIF and HEIC/HEIF (`ftyp` with brand `avif`, `avis`, `heic`, `heix`, `hevc`, `mif1`, `msf1`). Anything else (SVG, PDF, executables, text) is rejected as `unsupported_format`. +3. Inspect through the library with an explicit format and resource limits: pixel size, frame count. Reject `too_many_pixels` (above the pixel ceiling), `corrupt` (decode error), `timeout`. +4. Animated input (GIF, WebP, AVIF sequences) is reduced to the first frame. +5. Wait for a free processing slot (at most `MaxParallelJobs`); when none frees within a few seconds answer `busy` (HTTP 429). + +### Render planning (pure) + +For an image of `W x H` pixels, a ratio `r = n:d`, a focus setting `(fx, fy, z)` (centre `0.5, 0.5` and `z = 1` by default; a ratio may have its own setting, otherwise the general one applies): + +- The **largest crop** of ratio `r` inside the image: `cw0 x ch0` (if `W/H > n/d` then `ch0 = H`, `cw0 = ch0 * n / d`, else `cw0 = W`, `ch0 = cw0 * d / n`). +- With zoom `z >= 1` the crop is `cw = cw0 / z` by `ch = ch0 / z`. +- The crop is centred on the point `(fx * W, fy * H)` and then moved the smallest amount needed to lie inside the image. So the subject stays as close to the centre of the crop as the image allows, and a crop never leaves the image. +- Widths: from the configured steps for the ratio (`wide`: 640, 960, 1280, 1600, 2560; `tall`: 480, 640, 960, 1280) keep those `<= cw` (never upscale). If none is `<= cw`, one variant at `cw` is made. The height is `round(width * d / n)`. +- Formats per width: WebP always; AVIF when the processor reports AVIF output; the page-critical HTML uses WebP only (contract). +- Quality: WebP 80, AVIF 50. Metadata is removed from every output; EXIF orientation is applied before cropping. + +### Set hash and addresses + +`setHash` = first 16 hex characters of SHA-256 over the canonical string `sha256-of-original | wide:fx,fy,z | tall:fx,fy,z` (numbers rounded to 4 decimals, invariant culture). A change of focus therefore gives a new set and new addresses; an identical upload of the same photo with the same focus gives the same set (no second copy is stored). Variant file name: `-.` (`wide-1600.webp`, `tall-960.avif`); address `/media/hero//`. + +### Self-test at start-up + +The processor decodes and encodes a tiny embedded image in every supported format and logs the capability list (input and output formats, library version). A failure marks the processor unavailable: uploads answer 503 with a generic message; reading and publishing are unaffected. + +## H3. Media store and serving + +- **Keys**: variants `hero//-.`; originals `originals/.` (never served). Only keys made by the code exist; a client file name is never used in a path. +- **Write**: a set is written to a temporary directory next to the target and moved into place with one rename; a half-written set is never visible. +- **Serve** `GET|HEAD /media/{**path}`: the path must match `^hero/[0-9a-f]{16}/(wide|tall)-[0-9]{2,5}\.(webp|avif|jpg)$` (area pattern from a registered allow-list, so other areas can register their own); otherwise 404. Headers: `Content-Type` from the extension, `Cache-Control: public, max-age=31536000, immutable`, strong `ETag` (from the set hash and name), `X-Content-Type-Options: nosniff`, `Vary: Accept-Encoding` not needed (images are not recompressed). `If-None-Match` equal gives 304. Rate limit policy `media-public`. +- **Clean-up** (hosted service, daily): removes sets and originals that no image row references and that are older than 7 days (a retired set is stamped when it stops being referenced; the files go 7 days later). Never removes a referenced file. +- **Free space and size**: before writing, check free space (at least the expected output plus a margin) and the total size of the media directory against the safety limit `Media:MaxTotalBytes`; refuse with a generic message when exceeded. + +## H2. Hero backend + +### Save (`PUT /api/v1/hero`, whole hero replaced) + +Input: hero fields, buttons, display, schedule, slide list in order (`id` optional for a new slide, `imageId`, `alt`, `decorative`, `isActive`). In one transaction: validate everything, update the hero, upsert slides, remove slides no longer listed, renumber the order, record actor and time. Afterwards `IIndexHtmlCache.Invalidate()`. + +### Public read model (`PublicHeroService.GetActiveAsync`) + +Returns null (204) when: no hero row for the language, `IsActive` false, `now` before `StartsAt` or at or after `EndsAt`, or the hero has no title. Otherwise: only active slides that have a stored image; a slide without alt that is not decorative is **not** published (the admin does not allow saving it anyway); order as saved. Each slide carries the general focus, plus the per-ratio overrides, and all stored variants (WebP and AVIF) with their ratio, width, type and address. The result is also what the HTML transform and the data block use, so the three always agree. + +### Image operations + +- **Upload** (`POST /api/v1/hero/images`): guard, store original, render the planned sets for the default focus, save the row, return the image with its variants. +- **Set focus** (`PUT /api/v1/hero/images/{id}/focus`): validate ranges (`0..1`, zoom `1..4`), compute the new set hash, render the sets into new addresses, update the row, stamp the old set as retired; the slides keep pointing at the same image id. +- **Delete** (`DELETE /api/v1/hero/images/{id}`): refused with 409 and a clear message while any slide uses the image (Bryan, Q1); otherwise the row goes and its set and original are stamped retired. + +## H4. Injection + +Order of work for a page that mentions hero markers: get `PublicHeroDto?` once per request cycle; if null, leave regions and preload as baked (and the data block carries `"hero": null`); otherwise: + +1. `HERO-HTML` region: exactly the ASF golden rules (title lines with `
`, tagline span, buttons, first kept slide as ``; slides skipped when they have no alt and are not decorative, a path outside our host, or no size; WebP only; `object-position` from the focus of the ratio that the `img` shows, i.e. the general focus). +2. `HERO-PRELOAD` region in the head: one preload for `tall` with `media="(orientation: portrait)"` and one for `wide` with `media="(orientation: landscape)"` when both exist; one without `media` when only one ratio exists; `srcset`, `sizes`, `media` byte-equal to the picture. +3. Data block: key `hero` with the whole `PublicHeroDto` (all slides) in the shared block. + +Fail-open: any exception, an unreadable hero or a missing marker leaves that part as baked; a failing data-block contributor leaves the whole block as baked. + +**Safety ceiling for unlimited slides** (Bryan: no administrator limit, a technical ceiling only): the hero endpoint, the HTML transform and the data block never emit more than `Hero:MaxPublishedSlides` slides (default 50, configurable) so the first HTML and the data block cannot grow without bound; when a hero has more active slides the first 50 in order are published and the admin shows a notice. The ceiling is reported to Bryan; LCP and page weight stay leading (the first HTML contains only the first slide). + +## H5. Admin + +Screens and states are in `frontend-components.md`; the admin only shows a **live badge** (Bryan, Q5): "Live" or "Niet live" with the schedule dates, no long reason text. Uploads are limited per user (20 per hour). Every validation message comes from the server (`ProblemDetails`-style error with a field) and is shown at the field. diff --git a/aidlc-docs/features/hero-module/construction/functional-design/business-rules.md b/aidlc-docs/features/hero-module/construction/functional-design/business-rules.md new file mode 100644 index 0000000..318fcc0 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/functional-design/business-rules.md @@ -0,0 +1,70 @@ +# Functional Design: business rules (units H1 to H5) + +IDs are used in the code, tests and the build and test summary. + +## Hero content (H2) + +| ID | Rule | +|---|---| +| BR-H01 | One hero per language; the language defaults to `nl`. `Language` is unique. Only `nl` is exposed and edited now. | +| BR-H02 | `title` required (after trimming), at most 200 characters and at most 5 lines; line breaks are `\n` (`\r\n` is normalised). Plain text. | +| BR-H03 | `tagline` optional, at most 120 characters, single line (line breaks are replaced by a space). `lead` optional, at most 600 characters, line breaks kept. | +| BR-H04 | `display` is `single` or `slideshow`; default `single`; any other value is rejected. | +| BR-H05 | 0 to 2 buttons. Both `label` (1 to 50 characters) and `target` (at most 500) are required for a button; a half-filled button is rejected. | +| BR-H06 | A target is exactly one of: **anchor** `#` followed by a letter and then letters, digits, `-` or `_` (at most 100 characters); **path** starting with a single `/` (not `//`), no `\`, no control characters, no whitespace, no `:` before the first `/`; **https address** with the scheme `https`, a host, no user info, parsed as an absolute URI. Anything else is rejected with the message "Kies een #anker, een /pad of een https://-adres." | +| BR-H07 | **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. | diff --git a/aidlc-docs/features/hero-module/construction/functional-design/domain-entities.md b/aidlc-docs/features/hero-module/construction/functional-design/domain-entities.md new file mode 100644 index 0000000..0a9bf5c --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/functional-design/domain-entities.md @@ -0,0 +1,75 @@ +# Functional Design: domain entities (units H1 to H5) + +Database: one new migration in the Hero module's own DbContext (MariaDB, hand-written like the Offerings migrations). Tables use the prefix `Hero`. + +## Tables + +### `Heroes` + +| Column | Type | Notes | +|---|---|---| +| `Id` | `char(36)` | primary key | +| `Language` | `varchar(10)` | default `nl`, unique | +| `Title` | `varchar(1000)` | max 200 chars by validation; room for 5 lines | +| `Tagline` | `varchar(200)` | max 120 | +| `Lead` | `varchar(1000)` | max 600 | +| `Display` | `varchar(20)` | `single` or `slideshow` | +| `Button1Label`, `Button1Target`, `Button2Label`, `Button2Target` | `varchar(100)` / `varchar(500)` | nullable pairs | +| `StartsAt`, `EndsAt` | `datetime(6)` | nullable, UTC | +| `IsActive` | `bit` | default true | +| `UpdatedAt` | `datetime(6)` | UTC | +| `UpdatedBy` | `varchar(256)` | actor id or name | + +### `HeroImages` + +| Column | Type | Notes | +|---|---|---| +| `Id` | `char(36)` | primary key | +| `OriginalSha256` | `char(64)` | content hash of the stored original | +| `OriginalKey` | `varchar(200)` | `originals/.` | +| `SourceFormat` | `varchar(10)` | `jpeg`, `png`, ... | +| `Width`, `Height` | `int` | original pixel size | +| `Bytes` | `bigint` | size of the stored original | +| `FocusX`, `FocusY`, `Zoom` | `double` | general setting; default 0.5, 0.5, 1 | +| `WideFocusX`, `WideFocusY`, `WideZoom` | `double?` | optional override | +| `TallFocusX`, `TallFocusY`, `TallZoom` | `double?` | optional override | +| `SetHash` | `char(16)` | current set | +| `VariantsJson` | `json`/`longtext` | list of `{ratio, width, height, type, key, bytes}` of the current set | +| `RetiredSetsJson` | `longtext` | previous sets with their retire time (for the 7-day clean-up) | +| `CreatedAt`, `CreatedBy` | `datetime(6)`, `varchar(256)` | | + +### `HeroSlides` + +| Column | Type | Notes | +|---|---|---| +| `Id` | `char(36)` | primary key, stable id used by the sites | +| `HeroId` | `char(36)` | foreign key, cascade delete | +| `ImageId` | `char(36)` | foreign key, restrict (deleting an image in use is refused) | +| `Alt` | `varchar(600)` | max 300 chars by validation | +| `Decorative` | `bit` | | +| `SortOrder` | `int` | unique per hero | +| `IsActive` | `bit` | | + +Indexes: `Heroes(Language)` unique; `HeroSlides(HeroId, SortOrder)` unique; `HeroSlides(ImageId)`. + +## Public DTOs (shape fixed in `component-methods.md`) + +`PublicHeroDto { display, title, tagline, lead, buttons[], slides[] }`, `PublicSlideDto { id, alt, decorative, image }`, `PublicImageDto { width, height, focus{x,y,zoom}, focusByRatio?, src, srcset?, variants[] }`, `PublicVariantDto { ratio, width, height, type, url }`. `focusByRatio` is present only when an override exists. Fields that are null are written as JSON null (like the offerings data); the shapes match the ASF golden inputs (`web/contract/host-injection/hero/*.input.json`). + +## Pure value types (H1, Core.Media) + +`ImageFormat` (enum), `ImageInfo { Format, Width, Height, FrameCount }`, `Ratio`, `FocusSetting`, `CropRect { X, Y, Width, Height }`, `VariantSpec { Ratio, Width, Height, Format, Quality }`, `RenderedImage { Bytes, Width, Height, Format }`, `MediaAddress { Area, SetHash, Name }`. + +## Configuration + +| Key | Default | Meaning | +|---|---|---| +| `Media:Directory` | none (required for uploads) | the media directory outside the release | +| `Media:MaxUploadBytes` | 10 485 760 | upload limit | +| `Media:MaxPixels` | 64 000 000 | pixel ceiling | +| `Media:MaxParallelJobs` | 2 | processing slots | +| `Media:DecodeTimeoutSeconds` | 20 | per image | +| `Media:MaxTotalBytes` | 2 147 483 648 | safety limit of the directory | +| `Media:RetentionDays` | 7 | retired files | +| `Hero:MaxPublishedSlides` | 50 | technical ceiling on published slides | +| `RateLimiting:HeroPublic`, `MediaPublic`, `HeroUpload` | 120/60 s, 600/60 s, 20/hour per user | policies | diff --git a/aidlc-docs/features/hero-module/construction/functional-design/frontend-components.md b/aidlc-docs/features/hero-module/construction/functional-design/frontend-components.md new file mode 100644 index 0000000..43cd6bf --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/functional-design/frontend-components.md @@ -0,0 +1,44 @@ +# Functional Design: admin screens (unit H5) + +New navigation item "Hero" (visible when `/api/v1/System/capabilities` lists the Hero module; for the Administrator role and higher). Follows the existing admin conventions (React Query, `nl` and `en` translation files, the Offerings feature as the pattern). Admin texts live in the frontend translation files. + +## Screen: Hero + +``` +[Hero] [Live | Niet live van .. tot ..] +------------------------------------------------------------------------------- +Tekst Titel (meerdere regels) Tagline Lead +Weergave ( ) Enkel ( ) Diavoorstelling +Knoppen Knop 1: label + doel Knop 2: label + doel (0 tot 2) +Planning Aan/uit Van ... Tot ... +------------------------------------------------------------------------------- +Slides [+ Afbeelding toevoegen] + #1 [thumb] alt-tekst / decoratief aan/uit omhoog omlaag [Focus] [Verwijder] + #2 ... +------------------------------------------------------------------------------- + [Opslaan] +``` + +- **Badge** (Bryan, Q5): "Live" or "Niet live" with the schedule dates; no reason text. It reflects the public rules (active, within the schedule, a title, at least one usable slide) as computed by the server (`GET /hero/all` returns `isLive`). +- **Form** validates on the server; messages come back per field and are shown at the field. A button target hint shows the three accepted forms. A slide without alt text and not marked decorative blocks saving, with the message at that slide. +- **Slides** are listed in order; reorder with up and down buttons (keyboard accessible); on/off per slide; the number is not limited in the screen (a notice appears above the safety ceiling). +- **Upload**: a file picker and a drop area; shows the accepted formats (from the server's capability list) and the 10 MB limit; progress; the server message on rejection (`unsupported_format`, `too_large`, `corrupt`, `too_many_pixels`, `busy`, `unavailable`). +- **Delete** of an image or slide: a confirmation; the server refuses an image still in use (409) and the screen shows the message. + +## Dialog: Focus + +- The image with a draggable focus point (keyboard: arrow keys move by 1%, with shift by 5%), a zoom slider (1 to 4), the numeric values, and two live previews: `wide` (3:2) and `tall` (4:5), each cut exactly as the host will cut (shared maths, TypeScript twin of `FocusMath` with the same test vectors). +- Tabs or toggles: "Algemeen punt" (default centre) and optional "Alleen wide" / "Alleen tall" overrides; a "Gebruik algemeen punt" reset per ratio. +- Save sends `PUT /api/v1/hero/images/{id}/focus`; the previews update from the response variants. + +## States + +Loading, empty (no hero yet: an empty form with the button "Opslaan"), saving, error (server messages), saved. Unsaved-changes warning when leaving the screen. + +## API used + +`GET /api/v1/hero/all`, `PUT /api/v1/hero`, `POST /api/v1/hero/images` (multipart), `PUT /api/v1/hero/images/{id}/focus`, `DELETE /api/v1/hero/images/{id}`, `GET /api/v1/System/capabilities`. + +## Accessibility and tests + +Labels and descriptions on all fields, focus management in the dialog, keyboard operation of reorder and focus point, `aria-live` for save and upload results. Tests: component tests (form validation display, slide reorder, upload errors, badge), the `focusMath` vectors shared with the C# tests, and an interaction test for the focus dialog. diff --git a/aidlc-docs/features/hero-module/construction/h1-image-pipeline/code/summary.md b/aidlc-docs/features/hero-module/construction/h1-image-pipeline/code/summary.md new file mode 100644 index 0000000..2208b0a --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h1-image-pipeline/code/summary.md @@ -0,0 +1,26 @@ +# H1 Image pipeline: code summary + +Built 2026-11-16 on `feature/hero-module`. Build and tests of the unit run green (Core tests 876 of 876, of which 79 are new; the CI solution filter builds). + +## What was built + +| Area | Files | +|---|---| +| Types, options, rejection | `Core/Media/MediaTypes.cs` (`ImageFormat`, `ImageInfo`, `Ratio` wide 3:2 and tall 4:5, `FocusSetting`, `CropRect`, `VariantSpec`, `RatioPlan`, `RenderedImage`, `MediaAddress`), `Core/Media/ImageProcessing.cs` (`ImageRejection`, `ImageRejectedException` with stable codes, `MediaOptions`, `IImageProcessor`, `MediaStatus`, `MediaProcessingGate`) | +| Pure functions | `ImageSignature` (format from the first bytes; SVG, PDF, executables never recognised), `FocusMath` (crop around the focus, round-half-up so the TypeScript twin matches), `VariantPlanner` (widths never above the crop, WebP always, AVIF when possible, JPEG when WebP is missing), `MediaPaths` (set hash, address, strict allow-listed parser) | +| Guard | `MediaUploadGuard` (availability, counted byte limit, signature, library inspection with pixel and side limits, processing slot), `GuardedUpload` | +| Registration and self-test | `MediaServiceCollectionExtensions.AddCmsMedia`, `ImageProcessorSelfTest` (hosted; a failed self-test only turns uploads off) | +| Library | new project `SlpModularCms.Core.Media.Magick` (`MagickImageProcessor`, `AddMagickImageProcessor`), Magick.NET-Q8-AnyCPU 15.1.0. Deviation from the design text: the library lives in its own project so that hosts that never process images (the slave) do not carry the 35 MB native library; the abstractions stay in Core | +| Tests | `Core.Tests/Media/`: pure functions with FsCheck properties (crop inside the image, focus inside the crop, ratio kept, zoom monotonic, planner never upscales, ladder ascending, signature never throws on random input), known vectors shared with the future TypeScript twin, address tests (including path tricks), signature tests, guard tests (limits, busy, unavailable), Magick processor tests on generated fixtures (formats, orientation, animated GIF, metadata stripped, crop keeps the chosen side, AVIF output, truncated and garbage files, mismatched format, strip of metadata) | +| Solution | project added to `SlpModularCms.sln` (folder Application) and `SlpModularCms.Ci.slnf` | + +## Decisions made while building + +- Truncated or damaged files are rejected as `corrupt`: the library returns a partly decoded picture with a warning for them, so decode warnings that mean damage (premature end, truncated, corrupt, ...) are turned into a rejection. +- The orientation is applied before cropping and `InspectAsync` reports the oriented size, so the plan and the crop always use the same numbers. +- HEIC stays a declared capability only; no real HEIC test photo yet (to add when one is available, per Bryan). +- The original is stored as received unless it carries metadata: `StripMetadataAsync` removes it (the pixels are re-encoded at quality 92 or the source quality, whichever is higher). + +## Not done in this unit (planned elsewhere) + +Media store, endpoint and directory check (H3); the `Hero:*` options and the rate-limit policies (H2/H3); the self-contained publish check of the native library (done with the first project that references it, H2). diff --git a/aidlc-docs/features/hero-module/construction/h1-image-pipeline/nfr-requirements/library-proof.md b/aidlc-docs/features/hero-module/construction/h1-image-pipeline/nfr-requirements/library-proof.md new file mode 100644 index 0000000..8b12469 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h1-image-pipeline/nfr-requirements/library-proof.md @@ -0,0 +1,28 @@ +# Image library proof (H1), 2026-11-16 + +Question: which library behind `IImageProcessor` decodes the widest set of input formats, writes WebP (required) and AVIF (when possible), keeps memory bounded for a 10 MB upload, has a licence that suits a commercial site, and works on win-x64 (IIS production), linux-x64 (CI) and linux-arm64 (Pi test hosts)? + +Method: a throw-away console project (not in the repository; sources in the session scratchpad) with the candidates; input is the ASF photo `hero-1.jpg` (2560x1702), converted by Magick to PNG, WebP, GIF, BMP, TIFF and AVIF as decode samples; per library: decode of every sample, crop for `wide` 3:2 and `tall` 4:5 around a focus point, resize to 960/1600 and 640/960 wide, WebP quality 80, metadata stripped, AVIF encode at 960 wide. A 24 MP stress image (6000x4000, 30 MB, noisy) measured peak memory. + +## Candidates and findings + +| Library | Licence | Result | +|---|---|---| +| **SixLabors.ImageSharp 4.1.3** | Six Labors Split License | **Excluded.** The package fails the build without a paid licence key (`No Six Labors license found ... obtain a licence from sixlabors.com/pricing`). A commercial closed-source site needs the paid licence, and CI would need the key as a secret. No AVIF or HEIC types in the assembly either. | +| **SkiaSharp 4.156.1** | MIT | **Excluded.** Cannot decode TIFF or AVIF (decode returns null), no HEIC, WebP only; on slim Linux images the native library failed to initialise without extra system libraries. | +| **NetVips 3.2.0** (libvips 8.18.7) | wrapper MIT; native `NetVips.Native` LGPL-3.0-or-later | Works on win-x64 and linux-x64. Decodes PNG, WebP, GIF, TIFF, AVIF, JPEG; **no BMP** (needs ImageMagick loader). Writes WebP and AVIF (`heifsave`). Fast (about 330 to 490 ms for four WebP variants). Peak memory 303 MB for the 24 MP stress image. Native libraries for linux-arm64 are in the package (`libvips.so.42`, 18 MB) but could not be executed here. HEIC is unverified (no sample). | +| **Magick.NET-Q8-AnyCPU 15.1.0** (ImageMagick) | wrapper Apache-2.0 | Works on win-x64 and linux-x64. Reports readable and writable: AVIF, BMP, GIF, JXL, TIFF, WebP; **HEIC and HEIF readable**. Decodes every sample (PNG, WebP, GIF, BMP, TIFF, AVIF, JPEG). Writes WebP and AVIF. Slower (about 0.7 to 1.3 s for four WebP variants, 1.5 to 2 times NetVips), but peak memory only 128 MB for the 24 MP stress image. A native arm64 build is in the package (`Magick.Native-Q8-arm64.dll.so`, 35 MB), not executed here. Has resource limits (`ResourceLimits`: width, height, area, memory, time) that fit decompression-bomb protection. | + +Output equality: WebP at quality 80 gave the same sizes in NetVips and Magick.NET (wide 960 about 38 KB, wide 1600 about 74 KB, tall 640 about 37 KB, tall 960 about 64 KB), against 220 to 440 KB for the ASF JPEGs today. AVIF at 960 wide: about 22 to 23 KB. + +## What could not be verified + +1. **linux-arm64 (Pi) was not executed.** Running an arm64 container on this machine needs an emulator registration (a privileged binfmt container) that the tooling refused; no change was made. The packages do contain native arm64 libraries for both candidates. The real Pi confirms at the first test deploy (agreed). To make that quick the host will run an image-library self-test at start-up (decode and encode a tiny embedded image in every supported format; log the capabilities; refuse uploads when it fails; public reads unaffected). +2. **HEIC** was verified only as a declared capability of Magick.NET (`Heic:r`), not with a real HEIC file. +3. The `AnyCPU` Magick package carries natives for several platforms; a self-contained win-x64 publish keeps only the matching one (to be checked in the H1 publish test). + +## Recommendation + +**Magick.NET-Q8 (Apache-2.0) behind `IImageProcessor`**: the widest input list (incl. BMP, TIFF, HEIC read, AVIF read and write), WebP and AVIF output, bounded memory with built-in resource limits, a licence without keys or LGPL obligations, native builds for all three platforms. NetVips stays the documented fallback (faster, lower licence friction on the wrapper, but no BMP and LGPL natives) and the interface makes switching small. ImageSharp and SkiaSharp are out. + +Residual risks: ImageMagick has a history of CVEs, so the package is kept current and covered by the CI vulnerability scan (SECURITY-10); only the allow-listed formats are decoded (our own signature check first, then the library with an explicit format); the process gets pixel, memory and time limits. diff --git a/aidlc-docs/features/hero-module/construction/h2-hero-backend/code/summary.md b/aidlc-docs/features/hero-module/construction/h2-hero-backend/code/summary.md new file mode 100644 index 0000000..758e554 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h2-hero-backend/code/summary.md @@ -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). diff --git a/aidlc-docs/features/hero-module/construction/h3-media-store/code/summary.md b/aidlc-docs/features/hero-module/construction/h3-media-store/code/summary.md new file mode 100644 index 0000000..18cf75c --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h3-media-store/code/summary.md @@ -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`). diff --git a/aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md b/aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md new file mode 100644 index 0000000..56aa2b0 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md @@ -0,0 +1,22 @@ +# H4 Host injection: code summary + +Built 2026-11-16 on `feature/hero-module`. The CI solution filter is green (Core 921, Hero 141, Offerings 212, Availability 171, Identity 145, Api 47, Contact 349, Master 61). The Api tests run the whole chain on the master host with a real MariaDB. + +| Area | What | +|---|---| +| Shared data block | `ICmsDataBlockContributor` and `CmsDataBlockTransform` in Core (`Hosting/Website/CmsDataBlock.cs`), registered next to the injector in both website modes. Keys follow the contributors order (100 offerings, 110 banners, 200 hero); a failing contributor fails the whole block, so the page keeps its baked block | +| Offerings | `OfferingsHtmlTransform` no longer writes the block; `OfferingsDataContributor` and `BannersDataContributor` supply `offerings` and `banners`. The block is byte-for-byte what it was (the existing assertions on shape, escaping and the ASF pipeline test pass unchanged apart from calling the new transform) | +| Hero regions | `HeroPictureRenderer` (pure) writes the `` region and the preload links exactly as the ASF golden files; `HeroHtmlTransform` fills `` and `` and leaves the page alone when the hero is unusable | +| Hero data | `HeroDataContributor` adds `hero` (the full public hero with all slides, or null) | +| Missing files | `HeroPageModel` checks that the files of the first slide exist in the media store; when they do not, region, preload and data are left baked (no broken first image) | +| Golden files | ASF commit 13f78c4 copied to `Hero.Tests/Golden/host-injection/hero` (6 cases, region and preload byte-exact) | +| Tests | golden files, renderer details (focus, no tall, no AVIF, first usable slide, encoding, property test that nothing breaks out of the HTML), transform behaviour, page model (files present or missing), data block order and escaping (Core), and a full pipeline test on the master host: no hero leaves the baked page and `hero: null`; a hero made through the services shows in the first HTML with the preload and the data block (same JSON as `GET /api/v1/hero`), every variant address is served immutable, 304 works, switching the hero off and losing the media directory both restore the baked page | + +## Found and fixed while building + +- The EF MySQL provider cannot translate `IN` on a Guid list parameter (found only by the real-database test; the in-memory tests hid it): the images of a save are now read and filtered in memory (a few dozen rows). +- Re-uploading a photo whose row exists but whose files were lost (a restored database without the media directory) now repairs the files instead of returning the broken image. + +## Not yet + +The admin screens (H5), the seed script, the smoke test and the docs (H6), the LCP measurement on the test hosts (needs the sites with the markers). diff --git a/aidlc-docs/features/hero-module/construction/h5-admin/code/summary.md b/aidlc-docs/features/hero-module/construction/h5-admin/code/summary.md new file mode 100644 index 0000000..069207d --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h5-admin/code/summary.md @@ -0,0 +1,20 @@ +# H5 Admin frontend: code summary + +Built 2026-11-16 on `feature/hero-module`. Frontend: 604 of 604 tests pass (73 new), `tsc` and `eslint` are clean. + +| Area | What | +|---|---| +| Navigation | route `/hero` (Owner and Administrator, module `Hero`), sidebar item "Hero", nl and en texts under `hero.*` | +| Screen | `features/hero/pages/HeroPage.tsx`: live or not-live badge (only a badge, Bryan, Q5), title (new line = line break, 5 lines), tagline, lead, display (single or slideshow), two buttons with label and target, schedule (on or off, from, until), slide list | +| Slides | upload (file picker, the server messages on refusal), alt text per slide or decorative, on or off, up and down, remove from the hero, a note when there are more slides than the publication ceiling; the number of slides has no limit in the screen | +| Focus | `FocusDialog`: the photo with a draggable and keyboard-movable focus point (arrow keys, Shift for bigger steps), numeric X and Y, a zoom slider, a general setting plus an optional own setting for the wide and the tall display with a reset, outlines of both crops on the photo and live previews of the two crops | +| Maths | `lib/focusMath.ts` is the twin of the host `FocusMath` (round half up); its tests use the same vectors as the C# tests plus a random check that the crop stays inside the image and holds the focus point | +| Validation | `schemas/hero.ts` (zod): title, tagline, lead, buttons (both or neither, target allow-list twin of the host validator, tested with the same cases), alt text unless decorative, schedule order; error texts are i18n keys in both languages | +| Client | `ApiClient` sends `FormData` as is (multipart upload) | +| Safety | unsaved changes trigger the browser warning when leaving | +| Tests | form, validation, navigation, saving, reorder, remove, switch off, decorative, upload and refused upload, ceiling note, focus dialog (stored values, keyboard, general plus own tall setting, reset, cancel), the shared maths vectors, the target validator cases | + +## Notes + +- Uploaded images that are never saved into a slide are removed by the host clean-up after 7 days; the screen has no separate delete for an image. +- Changing the focus of an image that is live changes the live hero at once (the images are shared by the hero), as the host re-cuts the variants. diff --git a/aidlc-docs/features/hero-module/construction/infrastructure-design/infrastructure-design.md b/aidlc-docs/features/hero-module/construction/infrastructure-design/infrastructure-design.md new file mode 100644 index 0000000..7ee44c6 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/infrastructure-design/infrastructure-design.md @@ -0,0 +1,40 @@ +# Infrastructure Design: media directory (unit H3) + +Bryan's decision: images live in a **directory outside the release**. This stage records how the directory is provided on each host and what is still unknown. + +## Requirements on the directory + +1. Outside the release and outside the web root (not served by IIS or nginx as static content; only the host's `/media/...` endpoint serves from it). +2. Survives deploys (the release directory is replaced on every deploy). +3. Writable by the account the host runs as; nothing else writes to it. +4. Included in the backup of the site. +5. Large enough: default safety limit `Media:MaxTotalBytes` 2 GB; expected use well below 100 MB. + +## Per host + +| Host | Directory | Setting | Backup | Status | +|---|---|---|---|---| +| **Pi test, SLP** (`~/apps/slpsoftware/test`) | `~/apps/slpsoftware/test/shared/media` (next to `shared/env`, `shared/wwwroot-web`) | `Media__Directory=%h/apps/slpsoftware/test/shared/media` in `shared/env` | Add the directory to the host backup routine for test (a test site may also be re-seeded) | To do by Pi-Main with the first test deploy: `mkdir -p`, mode 700, owner the service account | +| **Pi test, ASF** | `~/apps//shared/media` (same pattern, its own env file) | `Media__Directory=…` | as above | same | +| **SLP production** (Pi, later) | `~/apps/slpsoftware/production/shared/media` | `shared/env` | The production backup script (`backup-slpsoftware-db.sh` covers the database only): the directory must be added | Open until the release; listed in the production checklist | +| **ASF production** (MijnHostingPartner, IIS, self-contained win-x64) | A data directory beside the site, outside the web root (for example `..\data\media`), writable by the application pool identity | environment variable or `appsettings.Production.json` | The hosting provider's file backup, or an FTP copy; to confirm | **Unknown: write permission and backup on this hosting are not known.** Bryan tests with ASF (hosting package, application pool identity). If the test fails, Bryan is asked again and the database store (behind `IMediaStore`) is built. | + +## Deployment behaviour + +- `deploy-scp.yaml` builds `releases//` and switches `current`; `shared/` is not touched, so `shared/media` survives. No workflow change is needed for the Pi. +- The directory is created by Pi-Main once (documented in `docs/hero-module.md` and in the checklist); the host also creates it at start-up when it is missing and the account may. +- Release artifact size: Magick.NET adds about 35 MB native per platform; the upload limit of the deploy path (`deployment-instructions.md` 1.7.3, the nginx `client_max_body_size` for artifact upload) must allow the artifact; to be measured at the first deploy (the current artifact size is the reference). + +## Backup and restore + +- Files are immutable and content-addressed; a restore of the directory plus the database brings the site back; a restore needs both. A restored database without the directory leaves slides without files. Two safeguards: the start-up check logs a warning with the count of sets that the database refers to but the directory lacks, and the page injection (H4) checks that the first slide's files exist (through `IMediaStore.ExistsAsync`, cached with the page for 60 seconds) and leaves the baked hero in place when they do not, so a missing directory never produces a broken first image. +- Test hosts: the seed script can rebuild the hero and images from the ASF sources, so a test restore is optional. + +## Risks + +| Risk | Handling | +|---|---| +| Write permission or backup unavailable on the ASF production hosting | Bryan tests with ASF before the release; `IMediaStore` allows a database implementation; Bryan is asked again when the test fails | +| Disk fills | `Media:MaxTotalBytes`, free-space check before writing, clean-up of retired files, an error log line when 80% is reached | +| Directory missing after a server move | Start-up check disables uploads and logs; the injection sees the missing first-slide files and leaves the baked hero (no broken image); documented in the checklist | +| Deploy artifact too large for the proxy limit | Measured at the first deploy; the limit is raised on the proxy when needed | diff --git a/aidlc-docs/features/hero-module/construction/nfr-design/nfr-design-patterns.md b/aidlc-docs/features/hero-module/construction/nfr-design/nfr-design-patterns.md new file mode 100644 index 0000000..4161b8e --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/nfr-design/nfr-design-patterns.md @@ -0,0 +1,50 @@ +# NFR Design: patterns for the hero-module (H1, H3, H4) + +Each NFR of `nfr-requirements.md` is mapped to a pattern and the component that carries it. + +## Patterns + +| Pattern | Applies to | Where it lives | Notes | +|---|---|---|---| +| **Defence in depth for uploads**: size gate, signature allow-list, library decode with resource limits, parallelism gate, per-user rate limit, timeout, rejection codes | SEC-01, SEC-07, R-02 | `IMediaUploadGuard` (Core.Media), `HeroImagesController` (size limit attribute and `hero-upload` policy) | Each layer rejects alone; no single check is the only protection. A counting stream enforces the byte limit even when the declared length lies. | +| **Resource limits in the library**: `ResourceLimits.Width/Height/Area/Memory/Time` set once at start-up from `Media:*` options | SEC-01, P-03 | `MagickImageProcessor` initialisation | Process-wide limits, not per call; documented because Magick's limits are global. Format policy: decode only the allow-listed formats by passing the explicit `MagickFormat` after the signature check. | +| **Bulkhead**: a semaphore with `MaxParallelJobs` slots and a short wait; when full the answer is `busy` (429) | SEC-01, S-01 | `MediaProcessingGate` | Protects the host's CPU and memory on the Pi. | +| **Atomic publish of a set**: write to a temp directory, then one rename into place; clean the temp on failure (`try/finally`) | R-02, BR-M03 | `FileSystemMediaStore.PutSetAsync` | Nothing half-written is ever addressable. | +| **Content-addressed, immutable addresses** | P-05, FR-14 | `MediaPaths` | The set hash contains the original's SHA-256 and the crop parameters; a change gives a new address; long immutable caching is safe. | +| **Retire, then delete** (grace of 7 days) | R-04, BR-I08 | `HeroMediaCleanupService` (hosted, daily) | Sets are stamped when they stop being referenced; deleted later; idempotent; never deletes a referenced key (checked against the database right before deleting). | +| **Single read model** | NFR-09, BR-P04 | `PublicHeroService` | The endpoint, the region, the preload and the data block cannot disagree. | +| **One renderer for picture and preload** | P-01, BR-J01 | `HeroPictureRenderer` | Same inputs and the same formatting functions produce `srcset`, `sizes`, `media`; golden-tested. | +| **Fail-open injection, fail-closed upload** | R-01, R-02 | transforms catch and log; upload throws typed rejections | Documented deliberate asymmetry (SECURITY-15). | +| **Composable data block** | C-01 | `CmsDataBlockTransform` + contributors | Output of Offerings unchanged; contributors ordered by `Order`; a throwing contributor leaves the block baked. | +| **Self-test and capability reporting** | R-03, C-02 | `ImageProcessorSelfTest` hosted service; `GET /api/v1/System/capabilities` lists the accepted input formats | A failed self-test disables uploads only. | +| **Start-up directory check** | R-03, BR-M04 | `MediaDirectoryCheck` hosted service | Creates the directory when missing (when permitted), writes and deletes a probe file; logs the result; a failed check disables uploads. | +| **Output encoding at the edge** | SEC-03, BR-H08 | `HeroPictureRenderer` and the data contributor | Text stored as typed, encoded when written; the JSON for the script element uses the existing `HtmlMarkerEditor.EscapeForScript`. | +| **Allow-listed addresses** | SEC-03, BR-M01 | `MediaPaths.TryParse` and the endpoint's area registry | Anything else is a 404. | +| **Audit trail** | SEC-05 | `HeroService`, `HeroImageService` | Log line per change with actor, entity and id (no content), plus `UpdatedBy`/`CreatedBy` columns. | +| **Rate-limit policies** | SEC-07 | `ServiceCollectionExtensions` of the module and Core | `hero-public` 120/60 s per client address, `media-public` 600/60 s, `hero-upload` 20 per hour per user. | + +## Logical components added by this stage + +| Component | Role | +|---|---| +| `MagickImageProcessor` | The `IImageProcessor` implementation (sets limits, decodes, crops, resizes, strips, encodes) | +| `MediaProcessingGate` | The bulkhead | +| `ImageProcessorSelfTest` | Hosted self-test and capability list | +| `MediaDirectoryCheck` | Hosted start-up check of the directory | +| `HeroMediaCleanupService` | Daily clean-up of retired files | +| `MediaAreaRegistry` | The allow-list of media areas and their path patterns (`hero`) | + +## Security compliance summary (this stage) + +| Rule | Status | Evidence | +|---|---|---| +| SECURITY-03 | Compliant (design) | structured logs with request id and actor, no contents or client names | +| SECURITY-04 | Compliant | `nosniff` on media; existing headers on pages | +| SECURITY-05 | Compliant | validation of every field, signature allow-list, target allow-list, encoding | +| SECURITY-08 | Compliant | `AdminOnly`, object checks, public endpoints expose published data only | +| SECURITY-09 | Compliant | generic errors, no listing, media outside the web root | +| SECURITY-10 | Compliant | pinned package, vulnerability scan covers it | +| SECURITY-11 | Compliant | rate limits, gate, abuse cases listed in the tests | +| SECURITY-13 | Compliant | audit logs and columns; no unsafe deserialization (typed JSON only) | +| SECURITY-15 | Compliant | explicit error handling, global handler, deliberate fail-open and fail-closed split | +| SECURITY-01, 02, 06, 07, 12, 14 | N/A | no new infrastructure or authentication | diff --git a/aidlc-docs/features/hero-module/construction/nfr-requirements/nfr-requirements.md b/aidlc-docs/features/hero-module/construction/nfr-requirements/nfr-requirements.md new file mode 100644 index 0000000..79d0410 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/nfr-requirements/nfr-requirements.md @@ -0,0 +1,68 @@ +# NFR Requirements: hero-module (units H1, H3, H4; applies to H2 and H5 where noted) + +Derived from `requirements.md` section 5, the security extension (blocking), the functional design and the library proof. Bryan approved the library, the defaults and the safety approach on 2026-11-16. + +## Performance + +| ID | Requirement | Measure | +|---|---|---| +| P-01 | **LCP**: the LCP element is in the first HTML and does not regress against the baked version: ASF the first slide `` with `fetchpriority="high"`, `width`/`height`, and the matching preload; SLS the title text. | Lighthouse (lab) on the test hosts before and after, mobile profile: LCP not worse than the baked page; no layout shift from the hero (CLS contribution 0). | +| P-02 | **Weight**: the first slide image sent to a phone is the `tall` variant; target at most 80 KB WebP at 960 wide for a photo like the ASF ones (measured 37 to 64 KB), at most 250 KB for the largest desktop variant. | Recorded in the build and test summary. | +| P-03 | **Processing time**: an upload of a 10 MB photo is processed (all sets) within 10 seconds on the Pi and 5 seconds on a workstation; the request does not time out. | Timed in the integration test and on the test host. | +| P-04 | **Page build**: the hero adds at most 5 ms (cached) to building an injected page; the 60-second cache and ETag/304 behaviour stay as for the other parts. | Unit and integration tests. | +| P-05 | **Media serving**: a media file answers from disk with a strong ETag and 304; no processing on the request path. | Integration test. | + +## Scalability and capacity + +| ID | Requirement | +|---|---| +| S-01 | Expected size: one hero per site, tens of slides at most, a few uploads per day; the design must stay correct under concurrent uploads (processing gate) but is not built for throughput. | +| S-02 | Disk: the media directory is limited by `Media:MaxTotalBytes` (2 GB default); uploads refused with a generic message above it; free space checked before writing. | +| S-03 | The data block and the hero JSON are bounded by `Hero:MaxPublishedSlides` (50): the first HTML does not grow without bound. | + +## Reliability and availability + +| ID | Requirement | +|---|---| +| R-01 | Page injection is fail-open per part; a failing media directory, library or database read never takes a page down. | +| R-02 | Uploads fail closed with a stable code and a generic message; nothing partial is visible (atomic set writes); a crash during processing leaves no referenced half-set. | +| R-03 | Start-up self-test of the image library and a writability check of the media directory; when they fail, uploads answer 503 and a clear error is logged; public reads continue. | +| R-04 | Orphan clean-up never deletes referenced files and tolerates being interrupted (idempotent, daily). | +| R-05 | A restart or deploy keeps all images (directory outside the release) and the metadata (database). | + +## Security (blocking, extension enabled) + +| ID | Requirement | Rule | +|---|---|---| +| SEC-01 | Upload hardening: size limit at framework level, signature allow-list, library decode with explicit format and resource limits (pixels, side length, memory, time), parallelism gate, per-user rate limit, no client file names in paths, no SVG. | SECURITY-05, 11 | +| SEC-02 | Management endpoints require `AdminOnly` server side; object ids are verified against the hero; the public endpoints expose only published data. | SECURITY-08 | +| SEC-03 | Output encoding: all text encoded for HTML and for JSON in script; the button target allow-list prevents `javascript:` and other schemes; the media endpoint only serves registered path patterns; `X-Content-Type-Options: nosniff`. | SECURITY-04, 05 | +| SEC-04 | Generic error responses; no stack traces or paths; the global handler stays. | SECURITY-09, 15 | +| SEC-05 | Logging with request id and actor, no file contents and no client file names; changes auditable (who, what, when). | SECURITY-03, 13 | +| SEC-06 | Dependencies pinned and scanned: `Magick.NET-Q8-AnyCPU` 15.1.0 (Apache-2.0) is added to the vulnerability scan; the package is kept current; no unused packages. | SECURITY-10 | +| SEC-07 | Rate limiting on `hero-public`, `media-public` and `hero-upload`; abuse cases covered by tests (oversized, decompression bomb, polyglot, path tricks, repeated uploads). | SECURITY-11 | +| SEC-08 | Media directory permissions: only the host's service account writes; no directory listing; files are never executed (no handler mapping in IIS for the media directory when it lives under a web root; it lives outside the web root). | SECURITY-09 | + +## Maintainability and testability + +| ID | Requirement | +|---|---| +| M-01 | The image library only behind `IImageProcessor`; the store only behind `IMediaStore`; both replaceable. | +| M-02 | Pure functions (`FocusMath`, `VariantPlanner`, `MediaPaths`, `ButtonTargetValidator`, `HeroPictureRenderer`) property-tested (extension partial): crop inside the image; widths monotonic and never above the source; the set hash changes iff the crop parameters change; targets accepted are of the three forms; encoded text round-trips; the first slide and the preload attributes equal the picture attributes. | +| M-03 | Golden files for the region and the preload (ASF), for the data block and for the Offerings output stay byte-exact. | +| M-04 | Image fixtures for each input format, including corrupt, truncated, oversized and polyglot files; a real HEIC photo is added when one can be obtained (HEIC is a declared capability only until then, per Bryan). | +| M-05 | Texts per `docs/translation-files.md`; OpenAPI snapshot regenerated. | + +## Usability and accessibility + +| ID | Requirement | +|---|---| +| U-01 | Admin: keyboard operation of reorder and focus point, labels, live regions, a clear badge; the server messages in Dutch. | +| U-02 | Sites: alt text required (or decorative), slider accessibility kept in the site (contract). | + +## Compatibility + +| ID | Requirement | +|---|---| +| C-01 | The existing public contracts and markers do not change; the Offerings data block output is byte-identical. | +| C-02 | Platforms: win-x64 self-contained (IIS), linux-x64 (CI), linux-arm64 (Pi); proven on the first two, confirmed on the Pi at the first test deploy by the start-up self-test. | diff --git a/aidlc-docs/features/hero-module/construction/nfr-requirements/tech-stack-decisions.md b/aidlc-docs/features/hero-module/construction/nfr-requirements/tech-stack-decisions.md new file mode 100644 index 0000000..b4e5f58 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/nfr-requirements/tech-stack-decisions.md @@ -0,0 +1,19 @@ +# Tech stack decisions: hero-module + +| # | Decision | Rationale | Alternatives and why not | +|---|---|---|---| +| T1 | **Magick.NET-Q8-AnyCPU 15.1.0** (Apache-2.0) behind `IImageProcessor` | Widest formats (JPEG, PNG, GIF, BMP, TIFF, WebP, AVIF read and write; HEIC/HEIF read as a declared capability), WebP and AVIF output, 128 MB peak for 24 MP, resource limits; proven on win-x64 and linux-x64 (library-proof.md) | NetVips (reserve; no BMP, LGPL natives); ImageSharp 4 (paid licence key needed to build); SkiaSharp (no TIFF or AVIF) | +| T2 | Q8 build (8 bit per channel) | Enough for web output, half the memory of Q16 | Q16 | +| T3 | `IMediaStore` with a **file-system store** in a directory outside the release (`Media:Directory`) | Bryan's decision; database store possible later behind the interface | Database blobs (rejected by Bryan; `max_allowed_packet` risk) | +| T4 | New module project `SlpModularCms.Modules.Hero` + test project; `Core.Media` in the existing Core project | Follows the existing module layout and the decision for a general media service | A separate Media assembly (not needed yet) | +| T5 | EF Core with the existing MySQL provider and hand-written migration, `NonLockingMySQLHistoryRepository` | Same as Offerings | n/a | +| T6 | Frontend: existing React, React Query, i18n; focus editor an own component; `focusMath` TypeScript twin | Bryan's choice (no cropping package) | react-easy-crop | +| T7 | Property-based tests: **FsCheck** (xUnit integration) for the pure functions in C#; **fast-check** if already present in the frontend, otherwise example vectors shared between C# and TypeScript | Extension partial; check the existing test dependencies in H1 and add only what is missing | Hand-written random loops | +| T8 | Start-up self-test as a hosted service; clean-up as a hosted `BackgroundService` (daily) | Same pattern as `ContactRetentionService` | A cron outside the host | +| T9 | Rate limiting through the existing ASP.NET Core rate limiter policies (`hero-public`, `media-public`, `hero-upload`) | Existing mechanism | n/a | + +## Package and publish notes + +- `Magick.NET-Q8-AnyCPU` carries natives for several platforms; the self-contained win-x64 publish must keep only the matching native (to be verified in a publish test in H1) and the Linux publish must include `Magick.Native-Q8-x64.dll.so` or `-arm64`. +- The CI vulnerability scan covers the new package automatically (transitive and direct). +- The package size (about 35 MB per platform native) is acceptable for the release artifacts; checked against the SCP upload limit (see `deployment-instructions.md` 1.7.3) in Infrastructure Design. diff --git a/aidlc-docs/features/hero-module/construction/plans/functional-design-plan.md b/aidlc-docs/features/hero-module/construction/plans/functional-design-plan.md new file mode 100644 index 0000000..40a0a05 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/plans/functional-design-plan.md @@ -0,0 +1,92 @@ +# Functional Design Plan: hero-module (units H1 tot en met H5) + +Gebundeld voor alle units, zodat Bryan één keer antwoordt. De uitkomst wordt per unit uitgewerkt in `construction//functional-design/` (bedrijfslogica, regels, entiteiten). Vul de letter in na `[Answer]:`, of "alle aanbevelingen". + +H0 is klaar (master-run #121 groen, alleen test). De bibliotheek is gekozen (Magick.NET, zie `h1-image-pipeline/nfr-requirements/library-proof.md`). + +## Plan + +- [x] 1. Context geladen (requirements, ontwerp, units, contract met ASF, golden files 13f78c4, bibliotheekproef) +- [ ] 2. Vragen hieronder beantwoord +- [ ] 3. Antwoorden geanalyseerd +- [ ] 4. H1 Beeldpijplijn: `business-logic-model.md`, `business-rules.md`, `domain-entities.md` +- [ ] 5. H3 Mediaopslag en -serving: idem +- [ ] 6. H2 Hero-backend: idem +- [ ] 7. H4 Injectie: idem, inclusief de byte-exacte HTML volgens de ASF-golden files +- [ ] 8. H5 Admin: `frontend-components.md`, schermen en validatie +- [ ] 9. Controle: elk FR/NFR gedekt; regels consistent over de units + +## Wat ik zonder vraag vastleg (zeg het als het anders moet) + +- Kwaliteit: WebP 80, AVIF 50, JPEG als terugval 82; bredere uitvoer dan de bron wordt niet gemaakt. +- Breedtes: `wide` 640, 960, 1280, 1600, 2560 en `tall` 480, 640, 960, 1280, alleen tot de breedte van de bron die na de uitsnede overblijft; er is altijd minstens één variant per verhouding (de grootste mogelijke). +- Een upload telt als één beeldset; een foto wordt nooit twee keer opgeslagen (dezelfde inhoud + focus geeft dezelfde set). +- Tekst is platte tekst; de host codeert bij het schrijven (HTML en JSON). Lengtes: titel 200 (max 5 regels), tagline 120, lead 600, knoplabel 50, doel 500, alt 300. +- Het publieke antwoord is er alleen als er een actieve hero met minstens één bruikbare slide of een titel is; anders 204. +- Beheer slaat de hele hero in één keer op (volledig vervangen, met de slidelijst en volgorde); afbeeldingen worden apart geüpload. + +## Vragen + +### Vraag 1 — Wat gebeurt er met een afbeelding die een slide nog gebruikt, bij verwijderen? + +- A) Het CMS weigert (409) met een duidelijke melding; eerst de slide verwijderen of een andere afbeelding kiezen +- B) Het CMS haalt de afbeelding van de slide af en laat de slide zonder afbeelding staan (die dan niet gepubliceerd wordt) +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. Dat voorkomt dat per ongeluk een slide uit de hero verdwijnt. + +[Answer]: + +### Vraag 2 — Hoe lang blijven oude afbeeldingsbestanden bestaan na een nieuwe focus of een vervangen foto? + +Een website die de oude data nog in de cache heeft, verwijst nog naar de oude adressen. + +- A) 7 dagen, daarna worden ze door een opschoontaak verwijderd +- B) Direct verwijderen +- C) 24 uur +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. Een paar dagen dekt browsercaches en gecachete prerender-pagina's; de opslag is klein. + +[Answer]: + +### Vraag 3 — Hoeveel slides mag een hero hebben? + +- A) Maximaal 12 +- B) Maximaal 8 (de huidige ASF-hero heeft er 8) +- C) Geen vaste grens, alleen de totale opslaglimiet +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. Ruimte boven de huidige 8 zonder dat de pagina te zwaar wordt. + +[Answer]: + +### Vraag 4 — Hoe gaan we om met HTML of speciale tekens in de teksten? + +- A) Toegestaan als platte tekst en altijd gecodeerd bij het schrijven (een `<` blijft zichtbaar als `<`; er komt nooit opmaak of script uit een tekstveld) +- B) Het CMS weigert tekens als `<` en `>` in de velden +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. + +[Answer]: + +### Vraag 5 — Wat toont de admin als de hero (nog) niet live is? + +- A) Een duidelijke melding bovenaan met de reden (buiten de planning, uitgezet, geen bruikbare slide, geen titel) en wat de sites dan tonen (de ingebakken hero) +- B) Alleen een kleine status-badge +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. + +[Answer]: + +### Vraag 6 — Wie mag een afbeelding uploaden? + +- A) Dezelfde rol als de hero wijzigen (Administrator en hoger); uploads zijn beperkt per gebruiker (bijvoorbeeld 20 per uur) +- B) Alleen de eigenaar +- X) Other (please describe after [Answer]: tag below) + +Aanbeveling: A. + +[Answer]: diff --git a/aidlc-docs/features/hero-module/inception/application-design/application-design.md b/aidlc-docs/features/hero-module/inception/application-design/application-design.md new file mode 100644 index 0000000..d68c183 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/application-design.md @@ -0,0 +1,55 @@ +# Application Design: hero-module (consolidated) + +Details: [components.md](components.md), [component-methods.md](component-methods.md), [services.md](services.md), [component-dependency.md](component-dependency.md). Inputs: `requirements.md`, `site-contract-agreed-with-asf.md`, answers to `application-design-plan.md` (2026-11-16). + +## Decisions + +| # | Decision | Source | +|---|---|---| +| D1 | One module `SlpModularCms.Modules.Hero` (own DbContext, migrations, texts); on or off per site | Q14 (requirements) | +| D2 | A general media service in `Core.Media`: storage interface, image processor interface, upload guard, pure `FocusMath` and `VariantPlanner`, address scheme, media endpoint. Usable later for a gallery | Design Q4 = B | +| D3 | Images are stored in a **directory outside the release** behind `IMediaStore`; a database store can follow if the hosting requires it. Risk R1 recorded; Bryan tests write access on the ASF hosting and is asked again if it fails | Design Q1 = B | +| D4 | Input formats: as many as the library can decode (jpg/jpeg, png, webp always; gif, bmp, tiff, heic/avif where possible), real-signature check, metadata stripped, animation reduced to the first frame; output chosen by the system per platform (WebP required, AVIF when possible) | Design Q2 | +| D5 | `#cms-data` is composed by a Core `CmsDataBlockTransform` from `ICmsDataBlockContributor`s; Offerings becomes a contributor with byte-identical output; the Hero adds `hero` | Design Q3 = A | +| D6 | Crop model B: the host cuts `wide` (3:2) and `tall` (4:5) variants around the focus point and zoom. The focus defaults to the centre for all ratios; a separate focus (and zoom) per ratio is optional and falls back on the general one | Design Q6, contract | +| D7 | The admin focus editor is an own light component (draggable point, zoom, live `wide` and `tall` previews using a TypeScript twin of `FocusMath` with shared test vectors) | Design Q5 = A | +| D8 | Public contract: `GET /api/v1/hero` (204 = none), the same shape under `hero` in `#cms-data`; region pairs `…` (first slide as ``) and `…` in the head (one or two preload links with `media`, byte-equal to the ``/`` attributes); only WebP in the LCP picture and the preload; addresses `/media/hero//-.`, immutable | Contract with ASF | +| D9 | One renderer (`HeroPictureRenderer`) produces both the region attributes and the preload attributes; one read model (`PublicHeroService`) feeds the API, the region, the preload and the data block | LCP requirement | +| D10 | Fail-open for page injection, fail-closed for uploads | Requirements, SECURITY-15 | +| D11 | Language: the hero row carries a `Language` (default `nl`, unique), so adding a language needs no migration of existing rows; only one is exposed and edited now | Q9 | + +## Architecture overview + +```mermaid +flowchart LR + Admin["Admin (Hero screen)"] --> Hero["Modules.Hero"] + Hero --> Media["Core.Media
(store, processor, guard, endpoint)"] + Hero --> Inj["Core.Hosting.Website
(transforms, data block, cache)"] + Off["Modules.Offerings"] --> Inj + Inj --> Pages["Website pages (SLS, ASF)"] + Media --> Pages + Dir[("Media directory
outside the release")] --- Media + Db[("MariaDB")] --- Hero + classDef new fill:#FFA726,stroke:#E65100,color:#000; + classDef chg fill:#BBDEFB,stroke:#1565C0,color:#000; + classDef ext fill:#C8E6C9,stroke:#2E7D32,color:#000; + class Hero,Media new; + class Inj,Off,Admin chg; + class Pages,Dir,Db ext; +``` + +Text alternative: the new Hero module and Core.Media (orange) work with the changed injection layer and Offerings (blue); media files live in a directory outside the release and metadata in the database; pages get the hero injected. + +## Open items carried to the next stages + +| Item | Stage | +|---|---| +| Choice and proof of the image library (win-x64, linux-arm64, formats, AVIF, licence), limits (pixels, memory, parallelism, timeouts), budgets for LCP and weight, maximum slides, grace period for old sets | NFR Requirements and NFR Design | +| Whether deleting an image used by a slide refuses or detaches; exact validation messages; byte-exact HTML of the region | Functional Design | +| Write permission of the directory on MijnHostingPartner (IIS) and the backup of the directory | Bryan with ASF; Infrastructure Design (storage is a directory, so this stage now executes for the media unit) | +| Golden files for `` and the preload; focus estimates for the 8 photos | ASF session | +| SLS rendering of the three-line title and its screen-reader text | SLS session | + +## Units (confirmed from the execution plan, adjusted) + +H0 (done, PR #16 merged, 0824bfa) · H1 image pipeline (`Core.Media` processor, guard, `FocusMath`, `VariantPlanner`) · H2 Hero module backend · H3 media store, endpoint, address scheme · H4 injection (data block contributor and Offerings change, region, preload, golden files) · H5 admin frontend · H6 seed, docs, smoke test. Infrastructure Design is now needed for H3 (directory storage). diff --git a/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md b/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md new file mode 100644 index 0000000..1548291 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md @@ -0,0 +1,70 @@ +# Component dependencies: hero-module + +## Dependency matrix + +Rows depend on columns (X = direct use). + +| | Core.Media | Core.Hosting.Website | Core.Texts | Modules.Hero | Modules.Offerings | Frontend admin | +|---|---|---|---|---|---|---| +| **Modules.Hero** | X (store, processor, guard, paths, math) | X (`IHtmlPageTransform`, `ICmsDataBlockContributor`, `IIndexHtmlCache`) | X | n/a | none | none | +| **Modules.Offerings** | none | X (adds `OfferingsDataContributor`; loses the data block write) | X | none | n/a | none | +| **Core.Media** | n/a | none (endpoint is mapped by the host) | none | none (knows no module) | none | none | +| **Core.Hosting.Website** | none | n/a | none | none | none | none | +| **Frontend admin** | none | none | none | HTTP only (OpenAPI) | HTTP only | n/a | +| **Api / site projects** | X (host registers the media endpoint and options) | X | X | X (project reference) | X | n/a | + +Rules: Core never references a module; the Hero module never references the Offerings module (the data block is composed through the Core contributor interface, so no module knows another). + +## Data flow + +```mermaid +flowchart TD + Admin["Admin browser
(HeroPage, FocusEditor)"] -->|"multipart upload, JSON"| HeroCtl["Hero controllers"] + HeroCtl --> HeroSvc["HeroService / HeroImageService"] + HeroSvc --> Guard["MediaUploadGuard"] + HeroSvc --> Proc["ImageProcessor (library)"] + HeroSvc --> Store["MediaStore (directory)"] + HeroSvc --> Db[("Hero tables
MariaDB")] + HeroSvc --> Cache["IIndexHtmlCache"] + Db --> PubSvc["PublicHeroService"] + PubSvc --> PubApi["GET /api/v1/hero"] + PubSvc --> Tr["Hero transform, preload, data contributor"] + Tr --> Inj["HtmlMarkerInjector"] + Inj --> Page["Website page
(first HTML)"] + Store --> MediaEp["GET /media/..."] + Page -->|"img, picture, preload"| MediaEp + Site["Website (SLS, ASF)"] -->|"refresh after load"| PubApi + Page --> Site + classDef user fill:#f6e05e,stroke:#c05621,color:#000; + classDef host fill:#63b3ed,stroke:#2b6cb0,color:#000; + classDef data fill:#9ae6b4,stroke:#2f855a,color:#000; + classDef ext fill:#CE93D8,stroke:#6A1B9A,color:#000; + class Admin user; + class HeroCtl,HeroSvc,Guard,Proc,PubSvc,PubApi,Tr,Inj,MediaEp,Cache host; + class Store,Db data; + class Page,Site ext; +``` + +Text alternative: the admin uploads through the Hero services into the media directory and the database; the public read model feeds the public endpoint and the page injection; the browser loads images from the media endpoint and the site refreshes from the public endpoint. + +## Communication patterns + +| From to | Pattern | +|---|---| +| Admin to host | REST over HTTPS, cookie/JWT as the other admin screens; multipart for the image | +| Host internal | Dependency injection; services scoped, `IMediaStore` and `IImageProcessor` singletons (stateless, thread-safe) | +| Page build | The injector (singleton with scoped providers) asks transforms in registration order; the data block contributor order fixes the key order | +| Site to host | Anonymous GET of `/api/v1/hero` and `/media/...`; ETag and 304 for pages and media | +| Change notification | Direct call `IIndexHtmlCache.Invalidate()` after commit | + +## Risks and consequences of the design choices + +| # | Risk or consequence | Mitigation | +|---|---|---| +| R1 | **Storage in a directory** (Bryan's choice): the directory must survive a deploy, be in the backup and be writable. Pi: place it in the `shared` directory next to `releases/current` and set `Media__Directory`; IIS (MijnHostingPartner, ASF production): write permission is unknown | The store sits behind `IMediaStore`, so a database store can be added without touching the Hero module. Bryan tests directory write access with ASF; if it fails Bryan is asked again. Startup check: the host logs an error and the hero admin upload is refused (public reads unaffected) when the directory is not writable. Backup: add the directory to the host's back-up script and to the release checklist | +| R2 | Image library: AVIF encoder and native binaries on win-x64 and linux-arm64, licence | Proof in NFR Requirements; processing behind `IImageProcessor`; WebP is the required output, AVIF optional | +| R3 | Wide input list (gif, bmp, tiff, heic/avif) enlarges the attack surface and the library requirements | Allow-list by real signature; decode only through the library inside the guard (pixel, memory and time limits); formats the platform cannot decode are reported as unsupported in the admin; animated input is reduced to the first frame | +| R4 | Two writers of `#cms-data` would conflict | Solved by the Core contributor; the Offerings output stays byte-identical (golden files prove it) | +| R5 | Variant addresses change when the focus changes; an old page cached by a site may point to removed files | Old set kept for a grace period after a change; sites refresh from the API after load | +| R6 | LCP regression if preload and `` differ | One renderer for both, golden-tested with the ASF files | +| R7 | Two preload links (portrait, landscape) double the first request when a browser ignores `media` on preload | Verified in the LCP measurement on both test hosts | diff --git a/aidlc-docs/features/hero-module/inception/application-design/component-methods.md b/aidlc-docs/features/hero-module/inception/application-design/component-methods.md new file mode 100644 index 0000000..c83c9e7 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/component-methods.md @@ -0,0 +1,125 @@ +# Component methods: hero-module + +Signatures and purposes only; business rules are detailed in Functional Design per unit. Types are C# sketches. + +## Core.Media + +```csharp +public interface IMediaStore +{ + Task PutAsync(string key, Stream content, string contentType, CancellationToken ct); + Task OpenReadAsync(string key, CancellationToken ct); // null = not found; MediaFile has Stream, ContentType, Length, LastWriteTime + Task ExistsAsync(string key, CancellationToken ct); + Task DeleteAsync(string key, CancellationToken ct); + Task DeletePrefixAsync(string prefix, CancellationToken ct); // removes every file below an area/hash directory +} + +public interface IImageProcessor +{ + // Real format, pixel size and frame count; throws ImageRejectedException (reason code) for anything unsafe or unsupported. + Task InspectAsync(Stream source, CancellationToken ct); + + // Decode (orientation applied), crop around the focus for a ratio, resize without upscaling, strip metadata, encode. + Task RenderAsync(Stream source, RenderRequest request, CancellationToken ct); + + IReadOnlySet SupportedInput { get; } + IReadOnlySet SupportedOutput { get; } // WebP always; AVIF when the platform can +} + +public sealed record RenderRequest(Ratio Ratio, int Width, ImageFormat Format, int Quality, FocusSetting Focus); +public sealed record FocusSetting(double X, double Y, double Zoom); // 0..1, 0..1, >= 1; default (0.5, 0.5, 1) +public sealed record Ratio(string Name, int Numerator, int Denominator); // wide 3:2, tall 4:5 + +public interface IMediaUploadGuard +{ + // Size, real format, pixel/memory bounds, timeout and parallel gate; returns ImageInfo or throws ImageRejectedException. + Task AdmitAsync(Stream upload, long declaredLength, CancellationToken ct); +} + +public static class FocusMath // pure, property-tested +{ + public static CropRect CropFor(int imageWidth, int imageHeight, Ratio ratio, FocusSetting focus); + public static FocusSetting Normalize(FocusSetting focus); // clamps to valid ranges +} + +public static class VariantPlanner // pure, property-tested +{ + public static IReadOnlyList Plan(int sourceWidth, int sourceHeight, IReadOnlyList ratios, IReadOnlySet outputs); +} + +public static class MediaPaths // pure +{ + public static string SetHash(string originalSha256, IEnumerable<(string Ratio, FocusSetting Focus)> crops); + public static string Url(string area, string setHash, string name); // "/media/hero//wide-1600.webp" + public static bool TryParse(string path, out MediaAddress address); // strict allow-list of characters +} +``` + +`MediaEndpoint` is a minimal-API/endpoint mapping `GET|HEAD /media/{**path}`: parse, open from the store, answer with the immutable headers and `304` on a matching `If-None-Match`; any failure is a plain 404. + +## Core.Hosting.Website + +```csharp +public interface ICmsDataBlockContributor +{ + string Key { get; } // "offerings", "banners", "hero" + int Order { get; } // 100 Offerings, 200 Hero: fixes the key order in the block + Task GetAsync(HtmlTransformContext context, CancellationToken ct); // null is written as JSON null +} + +public sealed class CmsDataBlockTransform(IEnumerable contributors) : IHtmlPageTransform +{ + public bool Wants(string html); // page contains + public Task ApplyAsync(string html, HtmlTransformContext context, CancellationToken ct); +} +``` + +## Modules.Hero + +```csharp +public interface IHeroService +{ + Task GetAsync(string language, CancellationToken ct); // management read incl. inactive + Task SaveAsync(HeroSaveRequest request, string actor, CancellationToken ct); +} + +public interface IHeroImageService +{ + Task UploadAsync(Stream upload, long length, string actor, CancellationToken ct); + Task SetFocusAsync(Guid imageId, HeroFocusRequest request, string actor, CancellationToken ct); // general + optional per ratio + Task DeleteAsync(Guid imageId, string actor, CancellationToken ct); // refuses while a slide uses it, or detaches (decided in Functional Design) + Task RemoveOrphansAsync(CancellationToken ct); +} + +public interface IPublicHeroService +{ + Task GetActiveAsync(string language, DateTimeOffset now, CancellationToken ct); // null = 204 +} + +public static class ButtonTargetValidator +{ + public static ButtonTargetResult Validate(string? target); // Anchor | Path | Https | Invalid(reason) +} + +public static class HeroPictureRenderer +{ + public static string RegionHtml(PublicHeroDto hero, ITextCatalog texts); // title, tagline, buttons, first slide + public static string PreloadHtml(PublicHeroDto hero); // one or two elements +} +``` + +DTO shape (public, `GET /api/v1/hero` and `hero` in `#cms-data`): + +```json +{ "display": "slideshow", "title": "…", "tagline": "…", "lead": null, + "buttons": [ { "label": "…", "target": "/over-mij" } ], + "slides": [ { "id": "guid", "alt": "…", "decorative": false, + "image": { "width": 1600, "height": 1067, "focus": { "x": 0.5, "y": 0.5, "zoom": 1 }, + "src": "/media/hero//wide-1600.webp", + "variants": [ { "ratio": "wide", "width": 1600, "type": "image/webp", "url": "…" }, + { "ratio": "tall", "width": 960, "type": "image/webp", "url": "…" } ] } } ] } +``` + +## Frontend + +`heroApi.getHero()`, `saveHero()`, `uploadImage(file, onProgress)`, `setFocus(imageId, …)`, `deleteImage(imageId)`; `focusMath.cropFor(...)` (TypeScript twin of `FocusMath`, same test vectors). diff --git a/aidlc-docs/features/hero-module/inception/application-design/components.md b/aidlc-docs/features/hero-module/inception/application-design/components.md new file mode 100644 index 0000000..9f1452e --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/components.md @@ -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 `…` (title, tagline, buttons and the first active slide as ``) and `…` in the head (one or two ``), both from the same renderer so `srcset`/`sizes`/`media` are byte-for-byte equal. Fail-open. (Changed after the ASF golden files: the preload is a region pair, not a single marker, so no separate marker provider is needed.) | +| `HeroPictureRenderer` | Pure: one place that produces the ``/`` attributes and the preload attributes from a `PublicHeroDto`; golden-tested. | +| `HeroDataContributor` (`ICmsDataBlockContributor`) | Adds the key `hero` (the `PublicHeroDto`, or null) to the data block. | +| `HeroTexts` + `Texts/nl.json`, `en.json` | Backend texts (validation messages) per `docs/translation-files.md`. | + +### Data model (sketch, detailed in Functional Design) + +| Entity | Fields | +|---|---| +| `Hero` | `Id`, `Language` (default `nl`; unique per language so a language can be added later without migrating rows), `Title` (text with line breaks), `Tagline`, `Lead`, `Display` (`single`/`slideshow`), `Button1Label/Target`, `Button2Label/Target`, `StartsAt`, `EndsAt`, `IsActive`, `UpdatedAt`, `UpdatedBy` | +| `HeroSlide` | `Id` (GUID, stable), `HeroId`, `ImageId`, `Alt`, `Decorative`, `SortOrder`, `IsActive` | +| `HeroImage` | `Id`, `OriginalKey` (store key), `Sha256`, `SourceFormat`, `Width`, `Height`, `Bytes`, `Focus` (general, default centre: `X`, `Y`, `Zoom`), optional `WideFocus` and `TallFocus` (`X`, `Y`, `Zoom`, nullable), `VariantSetHash`, `VariantsJson` (list of `{ratio, width, type, key, bytes}`), `CreatedAt` | + +## C2. `SlpModularCms.Core.Media` (New, general media service in Core) + +| Component | Purpose and responsibilities | +|---|---| +| `IMediaStore` | The storage interface: `PutAsync(key, stream, contentType)`, `OpenReadAsync(key)`, `DeleteAsync(key)`, `DeletePrefixAsync(prefix)`, `ExistsAsync`. Keys are relative paths made by the code, never by a client file name. Behind this interface the store can move from a directory to the database if the hosting demands it (risk R1). | +| `FileSystemMediaStore` | Implementation on a directory (`Media:Directory`) outside the release; atomic writes (temp file then move), path containment check (no `..`, no absolute paths, only a safe character set), no directory listing. | +| `IImageProcessor` | The image library behind an interface: `InspectAsync(stream)` (real format, size, frame count, or a rejection), `RenderAsync(source, RenderRequest)` (decode, apply orientation, crop around focus/zoom to a ratio, resize without upscaling, strip metadata, encode to a format and quality). Implementation chosen in NFR Requirements after a proof on win-x64 and linux-arm64 (candidates ImageSharp, NetVips, Magick.NET, SkiaSharp). | +| `ImageProcessingLimits` / `MediaOptions` | `Media:Directory`, maximum upload bytes (10 MB), maximum pixels, maximum parallel jobs, timeout, accepted input formats, output formats and quality per format. | +| `FocusMath`, `VariantPlanner` | Pure, property-tested: the crop rectangle for a ratio from focus and zoom (always inside the image, as close to the focus as the image allows), and the widths per ratio from the source size (no upscaling, monotonic steps). | +| `MediaPaths` | The address scheme `/media///`; builds and parses addresses, computes the set hash from the content hash and the crop parameters, so a change of focus gives a new address. | +| `MediaEndpoint` | `GET /media/{**path}`: anonymous, same origin; `Cache-Control: public, max-age=31536000, immutable`, `ETag`, `304`, `X-Content-Type-Options: nosniff`, content type from the stored file, `Content-Disposition` not set, rate-limit policy `media-public`; unknown or malformed path = 404 with no detail. Also `HEAD`. | +| `IMediaUploadGuard` | The upload checks in one place (size, real format, pixel and memory bounds, decode timeout, parallelism gate), used by every module that accepts images. | + +## C3. `SlpModularCms.Core.Hosting.Website` (Changed) + +| Component | Change | +|---|---| +| `ICmsDataBlockContributor` (New) | `Key`, `Order`, `GetAsync(context, ct)` returning the value (object) for that key or "no value". | +| `CmsDataBlockTransform` (New, `IHtmlPageTransform`) | Owns the `` marker: asks all contributors (ordered by `Order`) and writes `{"siteUrl": …, : , …}` into the data block. Wants = page contains the marker. Fail-open as every transform. If a contributor throws, the whole block is left as baked: a half-filled block would mislead the site (fail-open for the block as a whole). | +| `OfferingsHtmlTransform` (Changed, module Offerings) | No longer writes the data block; its regions, JSON-LD and prices stay. A new `OfferingsDataContributor` (`Order` 100) supplies `offerings` and `banners`. The output of the block stays byte-identical (key order `siteUrl`, `offerings`, `banners`, then `hero`), so all existing golden files stay green. | +| `HtmlMarkerEditor` | Unchanged API; the preload marker is written through the existing `IIndexHtmlMarkerProvider` (whole-comment replacement). | + +## C4. Frontend admin (New feature folder `frontend/src/features/hero`) + +| Component | Purpose | +|---|---| +| `HeroPage` | The Hero screen in the admin navigation (visible when the Hero module is on, via `/System/capabilities`), shows whether the hero is live (schedule, active slides). | +| `HeroForm` | Title (multi-line), tagline, lead, display, up to two buttons with target validation messages, schedule. | +| `SlideList` | Order (up/down), on/off, alt text or "decorative", remove, add. | +| `ImageUploader` | Upload with progress, shows the accepted formats and the size limit, rejection messages. | +| `FocusEditor` | Own light component: the image with a draggable focus point, a zoom control, live previews of `wide` (3:2) and `tall` (4:5) cut as the host will cut them (same pure maths, shared as a small TypeScript twin of `FocusMath` with the same test vectors), and optional per-ratio overrides with "use the general point" reset. | +| `heroApi`, translations | React Query hooks and `nl/en` texts. | + +## C5. Scripts, docs, CI + +| Component | Purpose | +|---|---| +| `scripts/Seed-Hero.ps1` (+ data) | Seeds the SLP hero and the ASF hero with its 8 photos and the focus estimates of the ASF session, on test only; needs the owner's login like `Seed-Offerings.ps1`. | +| `scripts/smoke-site.sh` (Changed) | Checks the public hero endpoint (200 or 204), a media address answers with the immutable header, and, for a site with markers, no unprocessed hero markers. | +| `docs/hero-module.md` (New) | Contract, addresses, storage and the hosting risk, operation. | +| CI H0 | Done (merged, 0824bfa). | + +## Sites (outside this repository) + +The SLP and ASF websites place the markers and render ``; contract in `site-contract-agreed-with-asf.md`. diff --git a/aidlc-docs/features/hero-module/inception/application-design/services.md b/aidlc-docs/features/hero-module/inception/application-design/services.md new file mode 100644 index 0000000..bc2e6b8 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/services.md @@ -0,0 +1,98 @@ +# Services and orchestration: hero-module + +## Services + +| Service | Responsibility | Collaborators | +|---|---|---| +| `HeroService` (management) | Reads and saves the hero: validates fields (lengths, button targets via `ButtonTargetValidator`, schedule order, slide count and order), writes the hero and slides in one transaction, calls the cache invalidation. | `IHeroRepository`, `ITextCatalog`, `IIndexHtmlCache` | +| `HeroImageService` | The upload pipeline and focus changes (below). Owns the rule that every stored file belongs to exactly one image set. | `IMediaUploadGuard`, `IImageProcessor`, `IMediaStore`, `IHeroImageRepository`, `IIndexHtmlCache` | +| `PublicHeroService` | Builds the public read model from the stored hero: schedule and `IsActive` applied, inactive slides removed, variants that exist listed, the first-slide choice made once here. | `IHeroRepository`, `TimeProvider` | +| Core `MediaEndpoint` | Serves stored variants; no knowledge of the Hero module. | `IMediaStore` | +| Core `CmsDataBlockTransform` | Composes the `#cms-data` block from all contributors. | `ICmsDataBlockContributor` implementations | +| `HeroHtmlTransform` | 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
(offerings, banners, hero)"] + Inj --> T2["HeroHtmlTransform
(region + first slide)"] + Inj --> T3["HeroHtmlTransform
(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. diff --git a/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-dependency.md b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-dependency.md new file mode 100644 index 0000000..faaadee --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-dependency.md @@ -0,0 +1,43 @@ +# Unit dependencies: hero-module + +Rows depend on columns (X = needs it built first; (c) = only a contract, no code dependency). + +| | H1 | H3 | H2 | H4 | H5 | H6 | ASF golden files | SLS input | +|---|---|---|---|---|---|---|---|---| +| **H1** Image pipeline | n/a | | | | | | | | +| **H3** Media store and serving | X (addresses, options) | n/a | | | | | | | +| **H2** Hero module backend | X | X | n/a | | | | (c) JSON shape | | +| **H4** Injection | | | X | n/a | | | X (tests) | (c) title lines | +| **H5** Admin | | | X (API) | | n/a | | | | +| **H6** Delivery | | | X | X | X | n/a | | | + +```mermaid +flowchart LR + H1["H1 Image pipeline"] --> H3["H3 Media store
and serving"] + H1 --> H2["H2 Hero backend"] + H3 --> H2 + H2 --> H4["H4 Injection"] + H2 --> H5["H5 Admin"] + H3 --> H5 + H4 --> T1(["First test deploy"]) + T1 --> H5 + H4 --> H6["H6 Delivery"] + H5 --> H6 + classDef u fill:#FFA726,stroke:#E65100,color:#000; + classDef m fill:#CE93D8,stroke:#6A1B9A,color:#000; + class H1,H2,H3,H4,H5,H6 u; + class T1 m; +``` + +Text alternative: H1 feeds H3 and H2; H3 feeds H2; H2 feeds H4 and H5; the first test deploy follows H4; H5 and H4 feed H6. + +## Shared resources and contracts + +- The Core data block contract (H4) changes how Offerings writes `#cms-data`: its golden files must stay green. +- The public JSON shape (H2) is a contract with the ASF and SLS sessions; the golden files from ASF (13f78c4) drive H4. +- The media address scheme (H1) is used by H2 (data), H3 (endpoint) and H4 (HTML). +- One migration (H2); no change to existing tables. + +## Parallelism + +H2 and H3 can be built in parallel after H1 by different sessions, but the work is done by one session in the order above; the ASF and SLS sessions work on their sides in parallel from the first test deploy. diff --git a/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-story-map.md b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-story-map.md new file mode 100644 index 0000000..12eb273 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work-story-map.md @@ -0,0 +1,42 @@ +# Requirement to unit map: hero-module + +User stories were skipped for this feature (one persona, acceptance criteria in the requirements), so the requirement IDs of `requirements.md` are mapped to units instead. + +| Requirement | H1 | H3 | H2 | H4 | H5 | H6 | +|---|---|---|---|---|---|---| +| FR-01 one hero per site | | | X | | | | +| FR-02 text fields | | | X | | X | | +| FR-03 buttons and target validation | | | X | | X | | +| FR-04 slides | | | X | | X | | +| FR-05 schedule | | | X | | X | | +| FR-06 language-ready model | | | X | | | | +| FR-07 roles and public access | | | X | | | | +| FR-10 upload, real type, formats | X | | X | | X | | +| FR-11 metadata stripped | X | | | | | | +| FR-12 variants, resize and compress | X | | X | | | | +| FR-13 focus and crop per ratio, preview | X | | X | | X | | +| FR-14 own address, hash, immutable | X | X | | | | | +| FR-15 preload equals img | | | | X | | | +| FR-16 no orphans | | X | X | | | | +| FR-17 reuse check | done (SDA: nothing to reuse) | | | | | | +| FR-20 public contract | | | X | | | | +| FR-21 injection into the first HTML | | | | X | | | +| FR-22 only the first slide injected | | | | X | | | +| FR-23 fail-open, cache, ETag | | | | X | | | +| FR-24 schedule and inactive without rebuild | | | X | X | | | +| FR-25 admin screens | | | | | X | | +| FR-30 seed script | | | | | | X | +| FR-31 static texts reviewed | | | | | | X (SLS and ASF sessions) | +| FR-32 `release/*` CI | H0 (done) | | | | | | +| FR-33 backend texts | | | X | | | | +| NFR-01 LCP | | | | X | | X (measure) | +| NFR-02 live | | | X | X | | | +| NFR-03 page weight | X | | | | | X | +| NFR-04 upload safety | X | X | | | | | +| NFR-05 platforms and licence | X | | | | | X | +| NFR-06 storage | | X | | | | X (checklist) | +| NFR-07 accessibility | | | X | X | X | | +| NFR-08 compatibility | | | | X | | X | +| NFR-09 resilience | | | | X | | | + +Every FR and NFR has at least one unit. diff --git a/aidlc-docs/features/hero-module/inception/application-design/unit-of-work.md b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work.md new file mode 100644 index 0000000..dce9f7b --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/unit-of-work.md @@ -0,0 +1,33 @@ +# Units of work: hero-module + +One deployable service (the CMS host); the units are build parts with their own tests. Delivery: **one pull request for H1 to H6**, merged only after Bryan accepts the result on the test hosts (decision 2026-11-16). The first test deploy comes after H1 to H4; H5 follows. + +## Code organisation (brownfield, existing layout) + +| Area | Location | +|---|---| +| Media service | `src/SlpModularCms.Core/Media/` (+ tests in `SlpModularCms.Core.Tests/Media/`) | +| Data block and injection | `src/SlpModularCms.Core/Hosting/Website/` (+ tests in `SlpModularCms.Core.Tests/Hosting/`) | +| Hero module | `src/SlpModularCms.Modules.Hero/` and `src/SlpModularCms.Modules.Hero.Tests/` (new projects, in the solution folders Application/Modules and Tests/Modules, added to `SlpModularCms.Ci.slnf`) | +| Offerings change | `src/SlpModularCms.Modules.Offerings/Services/` | +| Master and sites | `src/SlpModularCms.Api`, `Api.SlpSoftware`, `Api.AndreaSlopFotografie` (module reference, committed defaults, `SiteContractTests`); not `Api.Slave` | +| Admin | `frontend/src/features/hero/` | +| Scripts, docs | `scripts/Seed-Hero.ps1`, `docs/hero-module.md`, `docs/release-checklist-productie.md`, `scripts/smoke-site.sh`, `openapi/slpsoftware.v1.json` | + +## Units + +| Unit | Responsibility | Main artifacts | Per-unit stages | +|---|---|---|---| +| **H0** (done) | `release/*` rule for SLP production | workflow, docs (PR #16, 0824bfa) | none | +| **H1** Image pipeline | Library proof and choice; `IImageProcessor`, `IMediaUploadGuard`, `ImageRejectedException`, pure `FocusMath`, `VariantPlanner`, `MediaPaths`; limits and options | `Core/Media/*`, tests incl. property tests, image fixtures | Functional Design, NFR Requirements (proof), NFR Design, Code Generation | +| **H3** Media store and serving | `IMediaStore`, `FileSystemMediaStore`, `/media/...` endpoint, rate-limit policy, startup check of the directory, options | `Core/Media/*`, host registration | Functional Design, Infrastructure Design (directory outside the release, backup, permissions), Code Generation | +| **H2** Hero module backend | Entities, migration, repositories, `HeroService`, `HeroImageService`, `PublicHeroService`, controllers, `ButtonTargetValidator`, texts, OpenAPI | `Modules.Hero`, tests | Functional Design, Code Generation | +| **H4** Injection | `ICmsDataBlockContributor`, `CmsDataBlockTransform`, Offerings contributor (byte-identical), `HeroHtmlTransform`, `HeroPictureRenderer`, ASF golden files (13f78c4) | `Core/Hosting/Website`, `Modules.Hero`, `Modules.Offerings`, golden files | Functional Design, Code Generation | +| **H5** Admin | Hero screen, slide list, upload, focus editor with previews, TypeScript `focusMath` twin | `frontend/src/features/hero` | Functional Design, Code Generation | +| **H6** Delivery | Seed script (test), docs, smoke test, checklist, LCP measurement, OpenAPI snapshot | scripts, docs | Code Generation, Build and Test | + +NFR Requirements and NFR Design run for H1 and H3 (library, limits, upload safety, storage) and, for the LCP budgets, for H4. Security Baseline and property-based (partial) rules apply as recorded in the requirements. + +## Build order + +1. H1 (library proof first), 2. H3 (needs H1 for addresses), 3. H2, 4. H4, then **first test deploy** and integration with the ASF and SLS sessions, 5. H5, 6. H6. diff --git a/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md b/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md new file mode 100644 index 0000000..72f9ebd --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md @@ -0,0 +1,91 @@ +# Application Design Plan: hero-module + +Vul per vraag de letter in na `[Answer]:`. Bij elke vraag staat mijn aanbeveling; "alle aanbevelingen" mag ook, dan vul ik die in. Het zijn technische keuzes waar ik een besluit van Bryan nodig heb omdat ze kosten, risico of werk voor de websites raken. + +## Wat al vaststaat (uit requirements en contract) + +- Eén module `SlpModularCms.Modules.Hero`; het CMS levert alleen inhoud; crop-model B (host snijdt `wide` 3:2 en `tall` 4:5 rond het focuspunt, focuspunt ook in de data); markers `CMS:HERO-HTML`, `CMS:HERO-PRELOAD` en sleutel `hero` in `#cms-data`; afbeeldingen op `/media/hero//…`, immutable; fail-open. +- Het bestaande blok `#cms-data` wordt nu volledig door `OfferingsHtmlTransform` geschreven (pakketten en banners). Het hero-deel moet in hetzelfde blok komen (afgesproken met ASF). + +## Plan (stappen) + +- [x] 1. Context geanalyseerd (requirements, contract, bestaande `HtmlMarkerInjector`/`IHtmlPageTransform`/`OfferingsHtmlTransform`) +- [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). diff --git a/aidlc-docs/features/hero-module/inception/plans/execution-plan.md b/aidlc-docs/features/hero-module/inception/plans/execution-plan.md new file mode 100644 index 0000000..2d7a72d --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/plans/execution-plan.md @@ -0,0 +1,168 @@ +# Execution Plan: hero-module + +## Detailed Analysis Summary + +### Transformation Scope (Brownfield) +- **Transformation Type**: Single new module plus extensions in Core (media serving, host injection) and the admin frontend; a small CI change. +- **Primary Changes**: New `SlpModularCms.Modules.Hero` (+ Tests); image pipeline (validation, metadata stripping, variants, focus/crop); media serving with content-hash addresses; hero injection markers in the host (`HtmlMarkerEditor` / `HtmlMarkerInjector`, preload in the head, `hero` key in `#cms-data`); admin screens; seed script; release-branch condition on the SLP production jobs. +- **Related Components**: `SlpModularCms.Core` (Hosting/Website, rate limiting, texts), `SlpModularCms.Api` (master composition), `Api.SlpSoftware`, `Api.AndreaSlopFotografie` (module reference and committed defaults, `SiteContractTests`), `frontend/` (admin), `.gitea/workflows/continuous_integration.yaml`, `scripts/`, `openapi/slpsoftware.v1.json`, docs. The websites (SLS, ASF) change on their side. + +### Change Impact Assessment +- **User-facing changes**: Yes. The hero of both websites is rendered from CMS content; the admin gets a Hero screen; the public pages change when the sites adopt the markers. +- **Structural changes**: Yes. A new module, a new media-serving path and new injection parts. +- **Data model changes**: Yes. New tables (hero, slides, images/variants) and an EF migration. +- **API changes**: Yes. New public `GET /api/v1/hero`, new management endpoints, new media route; no change to existing contracts (NFR-08). +- **NFR impact**: Yes. LCP, upload safety (decompression bombs, memory), platform support (win-x64, linux-arm64), storage that survives deploys. + +### Component Relationships +```mermaid +flowchart LR + Admin["Admin frontend
(Hero screen)"] + Hero["Modules.Hero
(new)"] + Core["Core
(media serving, injection, texts)"] + Api["Api (master) and site projects"] + SLS["SLP Software website"] + ASF["ASF website"] + CI["CI workflow"] + Admin --> Hero + Hero --> Core + Api --> Hero + Core --> SLS + Core --> ASF + CI -.-> Api + classDef new fill:#FFA726,stroke:#E65100,stroke-width:2px,color:#000; + classDef exist fill:#BBDEFB,stroke:#1565C0,stroke-width:1px,color:#000; + classDef ext fill:#C8E6C9,stroke:#2E7D32,stroke-width:1px,color:#000; + class Hero new; + class Admin,Core,Api,CI exist; + class SLS,ASF ext; +``` +Text alternative: the admin talks to the new Hero module; the module uses Core for media and injection; the master and site projects reference it; Core serves both websites. + +- **Primary Component**: `SlpModularCms.Modules.Hero` (Major, new). +- **Shared Components**: `SlpModularCms.Core` (Minor: new injection parts and media route), `frontend/` (Minor: new feature folder). +- **Dependent Components**: the two websites (golden files and markers agreed with the ASF and SLS sessions); `Api.*` projects (Configuration-only: module reference). +- **Supporting Components**: CI workflow (Minor: release-branch condition), docs and checklist. + +### Risk Assessment +- **Risk Level**: Medium to High (image processing of untrusted uploads; a native library on several platforms; contract with two sites). +- **Rollback Complexity**: Moderate (the module can be switched off per site; the baked hero stays; one migration). +- **Testing Complexity**: Complex (image fixtures, platform matrix, golden files for injection, LCP measurement on test hosts). + +## Workflow Visualization + +```mermaid +flowchart TD + Start(["User Request"]) + + subgraph INCEPTION["🔵 INCEPTION PHASE"] + WD["Workspace Detection
COMPLETED"] + RE["Reverse Engineering
SKIP"] + RA["Requirements Analysis
COMPLETED"] + US["User Stories
SKIP"] + WP["Workflow Planning
IN PROGRESS"] + AD["Application Design
EXECUTE"] + UG["Units Generation
EXECUTE"] + end + + subgraph CONSTRUCTION["🟢 CONSTRUCTION PHASE"] + FD["Functional Design
EXECUTE"] + NFRA["NFR Requirements
EXECUTE"] + NFRD["NFR Design
EXECUTE"] + ID["Infrastructure Design
CONDITIONAL"] + CG["Code Generation
(Planning + Generation)
EXECUTE"] + BT["Build and Test
EXECUTE"] + end + + Start --> WD + WD --> RA + RA --> WP + WP --> AD + AD --> UG + UG --> FD + FD --> NFRA + NFRA --> NFRD + NFRD --> ID + ID --> CG + CG --> BT + BT --> End(["Complete"]) + + style WD fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style RA fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style WP fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style CG fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style BT fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style AD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style UG fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style FD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style NFRA fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style NFRD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style ID fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style RE fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 + style US fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 + style Start fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000 + style End fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000 + style INCEPTION fill:#BBDEFB,stroke:#1565C0,color:#000 + style CONSTRUCTION fill:#C8E6C9,stroke:#2E7D32,color:#000 + linkStyle default stroke:#333,stroke-width:2px +``` +Text alternative: Inception (detection, requirements done; planning in progress; application design and units to execute; reverse engineering and user stories skipped) leads to construction (design stages per unit, code generation, build and test) and ends without an Operations phase. + +## Phases to Execute + +### 🔵 INCEPTION PHASE +- [x] Workspace Detection (COMPLETED) +- [x] Reverse Engineering (SKIPPED: targeted review; `_shared/` artifacts exist) +- [x] Requirements Analysis (COMPLETED, approved by Bryan 2026-11-16) +- [x] User Stories (SKIPPED) + - **Rationale**: One persona (the site administrator) plus the two websites as consumers; the requirements already carry the acceptance criteria and the contract is agreed with the two site sessions. +- [x] Execution Plan (IN PROGRESS) +- [ ] Application Design - EXECUTE + - **Rationale**: New module and new Core components (image pipeline, media store, injection parts); public JSON shape, marker names and crop/focus model (A3, A4) and the storage decision (A2) are decided here, with the ASF and SLS sessions. +- [ ] Units Generation - EXECUTE + - **Rationale**: Several independent pieces (CI condition, image pipeline, module backend, media serving, injection, admin UI, seed and docs) with a dependency order. + +### 🟢 CONSTRUCTION PHASE +- [ ] Functional Design - EXECUTE (per unit where needed: hero and slide rules, focus/crop model, injection output) + - **Rationale**: New data model and business rules (validation of targets, scheduling, slide selection, variant choice). +- [ ] NFR Requirements - EXECUTE (image pipeline and injection units) + - **Rationale**: Library choice (AVIF, licence, win-x64 and linux-arm64), upload limits, LCP and weight budgets (A1, A6, A7). +- [ ] NFR Design - EXECUTE (image pipeline unit) + - **Rationale**: Decompression-bomb protection, bounded parallelism, timeouts, failure behaviour (SECURITY-05, 11, 15). +- [ ] Infrastructure Design - CONDITIONAL + - **Rationale**: Only if storage is a shared directory (A2); with storage in the database it is skipped. Decided in Application Design. +- [ ] Code Generation - EXECUTE (ALWAYS), per unit, build and tests after every unit +- [ ] Build and Test - EXECUTE (ALWAYS) + - **Rationale**: Full suite, OpenAPI snapshot, golden files with ASF, smoke test extended, LCP measured on both test hosts. + +### 🟡 OPERATIONS PHASE +- SKIP (decided at Requirements Analysis, Q19 = B). The hero points go into `docs/release-checklist-productie.md`. + +## Proposed Units (to be confirmed in Units Generation) + +| Unit | Content | Depends on | +|---|---|---| +| H0 | CI: `release/*` condition on `publish-sls-production` and `deploy-sls-production`, docs | none (can be merged early) | +| H1 | Image pipeline: validation by content, metadata stripping, resize/compress, variants, focus/crop arithmetic (pure, property-tested) | library decision | +| H2 | Hero module backend: entities, migration, admin CRUD, public `GET /hero`, validation, schedule, texts, OpenAPI | H1 for upload | +| H3 | Media storage and serving (hash addresses, immutable cache, nosniff, rate limits) | H1 | +| H4 | Host injection (region marker, head preload, `hero` key in `#cms-data`, cache invalidation, golden files with ASF) | H2, H3 | +| H5 | Admin frontend: hero form, slide list, upload with focus/crop and preview | H2, H3 | +| H6 | Seed script (test), docs, release checklist, smoke test extension | H2 to H5 | + +## Package Change Sequence +1. H0 (independent; can go to master first). +2. H1, then H2 and H3 (parallel after H1). +3. H4 and H5 (parallel after H2 and H3). +4. H6, then Build and Test on the test hosts with the websites' markers. + +## Estimated Timeline +- **Total Stages**: 11 to execute (Application Design, Units Generation, Functional Design, NFR Requirements, NFR Design, Infrastructure Design if needed, Code Generation per unit, Build and Test), 3 skipped or not applicable. +- **Estimated Duration**: roughly 6 to 9 working days of build time across the units, excluding the websites' own work and Bryan's review time. + +## Success Criteria +- **Primary Goal**: The hero of both sites comes from the CMS, is live within about a minute, and the LCP element is in the first HTML without a regression. +- **Key Deliverables**: `SlpModularCms.Modules.Hero`, media serving, host injection with golden files, admin Hero screen, seed script, `release/*` condition, docs and checklist update. +- **Quality Gates**: Security rules compliant (blocking); property tests for the pure functions; full suite green; OpenAPI snapshot updated; smoke tests on both test hosts; LCP measured; no merge or production deploy without Bryan's go. +- **Integration Testing**: Both websites with the markers on the test hosts. +- **Operational Readiness**: Covered by the joint production checklist (no Operations phase). diff --git a/aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md b/aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md new file mode 100644 index 0000000..1310294 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/plans/unit-of-work-plan.md @@ -0,0 +1,71 @@ +# Unit of Work Plan: hero-module + +Vul per vraag de letter in na `[Answer]:` (of "alle aanbevelingen"). Dit is een enkele service (de CMS-host) met één nieuwe module en een uitbreiding van Core; "units" zijn dus bouwonderdelen, geen aparte services. De units H0 tot en met H6 komen uit het uitvoeringsplan en het ontwerp; hieronder staan de keuzes over volgorde en oplevering. + +## Voorstel (uit het ontwerp) + +| Unit | Inhoud | Hangt af van | +|---|---|---| +| H0 | CI: `release/*` voor SLP-productie. **Klaar** (PR #16, 0824bfa) | - | +| H1 | Beeldpijplijn in `Core.Media`: proef met bibliotheken, `IImageProcessor`, uploadwacht, `FocusMath`, `VariantPlanner`, `MediaPaths` | - | +| H3 | Mediaopslag en -serving: `IMediaStore`, `FileSystemMediaStore`, `/media/…`-endpoint, opties, snelheidsbegrenzing | H1 (adressen) | +| H2 | Hero-module backend: tabellen en migratie, beheer-API, publieke `GET /hero`, validatie, planning, teksten, OpenAPI | H1, H3 | +| H4 | Host-injectie: `CmsDataBlockTransform` + `ICmsDataBlockContributor`, Offerings omzetten (byte-identiek), `HeroHtmlTransform` (regio + preload), golden files van ASF | H2 | +| H5 | Admin-frontend: hero-formulier, slides, upload, focus-editor met voorbeeld | H2, H3 | +| H6 | Seed-script, `docs/hero-module.md`, rooktest, productie-checklist, LCP-meting op beide testhosts | H2 tot H5 | + +## Plan (stappen) + +- [x] 1. Eenheden afgeleid uit uitvoeringsplan en ontwerp +- [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. diff --git a/aidlc-docs/features/hero-module/inception/requirements/hero-comparison.md b/aidlc-docs/features/hero-module/inception/requirements/hero-comparison.md new file mode 100644 index 0000000..fd18b3f --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/requirements/hero-comparison.md @@ -0,0 +1,44 @@ +# Hero comparison: SLP Software (SLS) vs Andrea Slop Fotografie (ASF) + +Input for the requirements of `hero-module`. Sources: SLS = `src/features/landing/components/Hero.tsx`, `src/features/landing/data/content.ts` (`heroContent`), `src/prerender/StaticLanding.tsx`, `src/variants/e/Era2026.tsx` (read from the code by the CMS session, 2026-11-16); ASF = `web/src/components/Hero/*`, `web/src/content/heroContent.ts`, `types.ts` (delivered by the ASF session, 2026-11-16). Nothing here is a design decision yet; the decisions of Bryan are at the end. + +## Comparison + +| Aspect | SLS (Tailwind) | ASF (Chakra) | Same / different | Consequence for the CMS content | +|---|---|---|---|---| +| Small label above the title | `eyebrow` ("Web & .NET development"), shown in the code strip below | `tagline` ("Lifestyle fotograaf · Huizen"), a small uppercase label above the title, in the same `h1` | Same idea (short label), different place | One short text field ("tagline"); the site decides where it goes | +| Title | `heading` ("SLP software: websites, apps & meer", screen-reader only) and `displayHeading` (3 lines: "Websites," / "apps" / "& meer."); the era variant joins the lines with a space | `title` ("Andrea Slop"), one string, in the `h1` with the tagline | Different: SLS has a visual line split | One title text; line breaks as a separate optional representation (decision needed) | +| Lead / subtitle | `lead` (long paragraph, about 250 characters) | none | SLS only | Optional "subtitle/lead" text field | +| Code line | `codeLine` ("var website = slp.Bouw(uwIdee);") with blinking caret | none | SLS only, a style element | Not CMS content unless Bryan wants it editable (decision needed) | +| Buttons | Two: "Bekijk pakketten" (anchor `#pakketten`), "Plan een gesprek" (anchor `#contact`). Labels hardcoded in `Hero.tsx`; the era variant takes them from `nl.json` (`era.e2026.ctaPackages/ctaContact`) | One: `cta` `{label "Lees meer", to "/over-mij"}`, an internal route | Same idea (label + target), different count and target kind (page anchor vs site route) | 0..2 buttons, each label + target; the target is free text that the site interprets (anchor, route or address) | +| Images | None | `slides[]`, 8 images of 220 to 440 KB, JPG, one file per slide, no srcset or variants, object-fit cover, 100svh | Different | 0..n slides: the SLS hero has zero | +| Per slide | n/a | `id` (stable), `src`, `alt` (also read by the screen reader as "Photo n of N: alt"). No per-slide label, link or caption | ASF only | Slide: image, alt text, order; stable id | +| Display | Static, no slider | Slider: 6 s per slide, crossfade, slow zoom, pause on mouse hover / keyboard focus / hidden tab / pause button (WCAG 2.2.2), arrows and swipe, wrap-around; one slide = no arrows and no autoplay | Different | Optional "display" value (single / slideshow) that every site renders as it supports; the site keeps the timing and animation | +| Reduced motion | Not relevant (no motion beyond the caret) | `prefers-reduced-motion`: no autoplay, no progress bar, no pause button, no zoom | ASF only | Stays in the site | +| Noscript | The prerendered landing contains the hero text | Slide 1 stays as a static ``; progress bar hidden; arrows and pause need JS | Both readable without JS | The first HTML must contain the hero (LCP) without JS | +| LCP | The text (heading) | The first slide image | **Different** | Host injection per kind: text for SLS; for ASF the first slide `` with `fetchpriority="high"`, `width`/`height`, `srcset` and a matching `` | +| Loading | Everything in one page, text only | Active slide first; next and previous after `onLoad` plus 2 frames; the rest while advancing | ASF only | The host writes only slide 1 into the HTML; the site loads the rest from the data block | +| Prerender | `StaticLanding` renders the `Hero` into `#root` at build time (no hydration; `createRoot` replaces it) | Prerendered with the first slide and a preload link; slides 2 to 8 are empty wrappers | Same pattern (baked HTML, replaced by the app) | Host injection fills the baked hero and puts the full hero in the data block | +| Variants | Five era variants (Era1989 to Era2026) in `variants/e/`; only `Era2026` shows the hero content, it joins `displayHeading` | One layout | SLS only | Same content for every variant; the site renders it. The CMS has no layout choice | +| Where the text is now | `content.ts` (`heroContent`), button labels in `Hero.tsx` and `nl.json` (era) | `heroContent.ts`; aria texts ("Uitgelicht werk", "n van N", "Foto n van N") in the components | Both in code | Title, tagline, lead, buttons and alt texts move to the CMS; the aria texts go to the site's own language file, not the CMS | +| Socials | none in the hero | `HeroSocials` bottom left, from `siteContent.socials` | ASF only | Outside the hero module (site-wide) | +| CMS data today | Packages and banner via markers in `index.html`; the hero is not part of it | Packages and banners via markers and `#cms-data` (`{siteUrl, offerings, banners}`); the hero is not part of it | Same host contract | The data block gets a `hero` key; the baked hero stays the fallback (fail-open) | +| Image address | n/a | Vite import with hashed name in `/assets/` | n/a | CMS media URLs: the preload URL must equal the `img` src exactly; CSP `img-src` must allow the media host (same origin avoids a change) | + +## What is the same (core of the CMS content) + +Title (text), a short tagline, optional lead text, 0..2 buttons (label + target), and a list of 0..n slides (image, alt text, order). The sites differ in presentation, count and kind of buttons, and in whether slides exist. + +## Decisions of Bryan (relayed by SLP Software - SLS - Main, 2026-11-16) + +1. Same approach as packages and forms: the CMS delivers **content only**; every site keeps its own layout and presentation (ASF Chakra, SLS Tailwind). No layouts or sketch choice in the CMS or in the react package. A sketch choice may come later, with a third site. +2. The hero content comes **entirely from the CMS**: texts (title, tagline/subtitle), buttons (label, link) and images (0..n slides with image, alt text and optionally text per slide). Optionally a "display" field (for example single / slideshow) that every site renders according to its own support. +3. The comparison (this file) comes first; the question file is adjusted to what remains. Bryan answers both in one go. +4. The hero LCP (image or text) must be in the first HTML (prerender / host injection), and content is live (NFR-10). + +## Facts from the sites that the design must respect + +- ASF: the order of the slides decides the LCP; the first CMS slide must be in the first HTML with a preload whose URL is exactly the `img` src. +- ASF proposes the data shape `hero {title, tagline, cta{label,url}, slides[{id, imageUrl, width, height, alt, srcset?}]}` and delivers golden files after Bryan approves the requirements. +- ASF aria texts and the 6-second timing stay in the site; they move to the site's language file. +- SLS has no images; its hero has a lead and two buttons. diff --git a/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md b/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md new file mode 100644 index 0000000..c7cdb38 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/requirements/requirement-verification-questions.md @@ -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]: diff --git a/aidlc-docs/features/hero-module/inception/requirements/requirements.md b/aidlc-docs/features/hero-module/inception/requirements/requirements.md new file mode 100644 index 0000000..1b0803b --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/requirements/requirements.md @@ -0,0 +1,152 @@ +# Requirements: Hero module (hero-module) + +- **Feature slug**: hero-module +- **Status**: Draft for approval by Bryan (via SLP Software - SLS - Main); answers of 2026-11-16 processed; SDA reuse question answered (nothing to reuse) +- **Depth**: Standard (comprehensive for the image upload, which is security relevant) +- **Documentation Language**: English; **Conversation Language**: Dutch +- **Inputs**: `hero-comparison.md` (SLS vs ASF), `requirement-verification-questions.md` (19 questions, answered by Bryan 2026-11-16), decisions relayed by SLP Software - SLS - Main, facts from Andrea Slop Fotografie - ASF - Main, NFR-10 of the SLS requirements + +## 1. Intent analysis + +| Item | Value | +|---|---| +| User request | Make the hero of both websites (SLP Software and Andrea Slop Fotografie) manageable from the CMS (texts, buttons, images), immediately visible (NFR-10), with the LCP in the first HTML | +| Request type | New feature (a new module) plus a small CI change | +| Scope | Multiple components: new module `SlpModularCms.Modules.Hero`, Core (host injection, media serving), admin frontend, CI workflow, scripts, docs; the websites change on their side | +| Complexity | Moderate to complex (image processing and upload security, host injection contract with two sites) | +| Reverse engineering | Targeted review only (Offerings banners/packages, `HtmlMarkerEditor`/`HtmlMarkerInjector`, `CmsHost` website modes) | + +## 2. Principles decided by Bryan + +1. **Content only.** Like packages and forms: the CMS delivers content; every site keeps its own layout and presentation (ASF Chakra, SLS Tailwind). No layouts or sketch choice in the CMS or in the react package. A sketch choice may come with a third site. +2. **All hero content from the CMS**: title, tagline, lead, buttons, slides (0..n), plus a "display" field each site renders as it supports. +3. **LCP in the first HTML**: the host injects the hero into the HTML (SLS: text; ASF: first slide `` plus preload); the baked hero stays the fallback when the CMS delivers nothing (fail-open, NFR-10). +4. **Stays in the sites**: screen-reader and control texts ("Photo n of N", "Slideshow paused"), the slider timing and animation, reduced-motion behaviour, socials, the SLS code line. + +## 3. Answers (traceability) + +| Q | Answer | Decision | +|---|---|---| +| 1 | A | One hero per site | +| 2 | One title text with line breaks | Title is one text; a new line in the field is a visual line break. The SLS site derives the screen-reader/SEO text from the lines | +| 3 | Tagline and lead; no code line | The code line stays fixed text in the SLS website | +| 4 | A, with validated target | 0 to 2 buttons: label and target; target is `#anchor`, `/path` or `https://…`, validated by the CMS | +| 5 | A | Field `display`: `single` or `slideshow` | +| 6 | A | Slide: image, required alt text (or explicitly decorative), order, on/off | +| 7 | A + extra | Upload; host keeps the original, reads the size, makes variants for `srcset` (WebP/AVIF); **the administrator can set a focus point and/or crop per image and per use/ratio, with a preview in the admin** | +| 8 | A + extra, 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. diff --git a/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md b/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md new file mode 100644 index 0000000..546661f --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/requirements/site-contract-agreed-with-asf.md @@ -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 `` 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//…`, immutable; the CSP `img-src` does not change. | +| Markers | `…` (title, tagline, button(s), the FIRST slide as ``), `` in the head, key `hero` in `#cms-data` with all slides. Fail-open: no marker, 204 or an error leaves the baked page. | +| Hydration | The region holds neutral HTML (fixed classes, no Chakra classes); React takes over with the same source after hydration; slides 2..n load afterwards. The first slide of the data block must equal the first slide the host wrote into the HTML (same source, same cache rule). | +| Golden files | ASF delivers input JSON, expected HTML region and expected preload, with a README and the commit, in `web/contract/host-injection/hero/` on a new ASF branch `feature/hero-module`. They start once Bryan chose the crop model. An A/B-neutral subset (title, tagline, button, first slide `` without ``) can be delivered earlier. | + +## Crop/focus model: 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 `` 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 | `` | + +- `sizes="100vw"`. Selection is by orientation, not by width, because the hero height comes from the screen (100svh with object-fit cover). The focus point stays as `object-position` for in-between shapes (tablet, narrow window). +- Two preload links: `tall` with `media="(orientation: portrait)"` and `wide` with `media="(orientation: landscape)"`, each with `imagesrcset`, `imagesizes="100vw"`, `fetchpriority="high"`. `srcset`, `sizes` and `media` in the preload must be byte-for-byte equal to those in ``/`` in HERO-HTML (the golden files check this). + +## Source images for the seed + +The 8 ASF photos are already resized exports, not camera originals: all landscape 3:2, 1600x1067 (five), 2048x1362 (two) and 2560x1702 (one). The host must never upscale: for the five 1600-wide photos a variant wider than 1600 does not exist. Bryan may supply better originals (needed for good AVIF variants and a true portrait crop); the focus point per photo is Bryan's choice, set in the CMS after the seed. + +Order, with the current alt texts (path `K:\Development\SlpSoftware\Projects\AndreaSlopFotografie\web\src\assets\hero-N.jpg`): + +| # | File | Size | Alt | +|---|---|---|---| +| 1 | hero-8 | 1600x1067 | Zwangerschapsfoto in de duinen | +| 2 | hero-7 | 1600x1067 | Knusse newbornfoto met de familie | +| 3 | hero-1 | 2560x1702 | Lifestyle fotografie | +| 4 | hero-2 | 1600x1067 | Zwangerschapsshoot in de buitenlucht | +| 5 | hero-3 | 1600x1067 | Newbornshoot van een pasgeboren baby | +| 6 | hero-4 | 2048x1362 | Spontaan portret buiten | +| 7 | hero-5 | 1600x1067 | Natuurlijke lifestylefoto | +| 8 | hero-6 | 2048x1362 | Portret in de natuur | + +Seed values: title "Andrea Slop", tagline "Lifestyle fotograaf · Huizen", button "Lees meer" to `/over-mij`, display `slideshow`. + +## Consequences for the design + +- A `` region needs a stable, deterministic rendering of `srcset`/`sizes`/`media` shared by the HERO-HTML and the preload (one generator, golden-tested). +- Variants are limited by the source size (no upscaling); the public data lists only variants that exist. +- Two preload links (portrait, landscape) are needed when a `tall` ratio exists. +- The first-slide data in `#cms-data` and in the HTML must come from the same computation. + +## Golden files delivered (ASF commit 13f78c4, branch feature/hero-module of the ASF repository) + +Folder `web/contract/host-injection/hero/` (README with all rules, `seed.json`, six inputs: standard, minimal, two-lines, hostile, no-alt, none; per input `NAME.expected.html` and `NAME.expected-preload.html`). The CMS host template must produce exactly these files (Build and Test unit H4). Choices accepted by the CMS session: + +1. Only WebP in the LCP picture and the preload (a preload cannot say "AVIF if supported"); AVIF variants may exist for slides 2..n on the client. +2. Selection by orientation: `` for `tall` plus the `img` for `wide` inside ``; two preloads with `media` portrait and landscape; without `tall` one preload without `media`; without `wide` an `img src` and a preload `href`. +3. Focus as `style="object-position:X% Y%"` on the `img` (no trailing zeros, at most two decimals; no style without a valid focus). `width` and `height` on the `img` are the original image size from the data. +4. The preload is a region pair `…` in the head, like `CMS:HERO-HTML` (this replaces the earlier single-marker idea). +5. A slide without alt (and not decorative), with a foreign or unsafe path or without a size is skipped; no usable slide or no title gives empty regions (the baked hero stays). At most 2 buttons; targets are `#anchor`, `/path` or `https://`. New lines in the title become `
` after escaping. +6. Variant names `/media/hero//wide-1600.webp` and `tall-960.avif`. +7. Seed (first focus estimates by looking at the photos, (x,y) from the top left): hero-8 (0.50,0.55), hero-7 (0.45,0.50), hero-1 (0.55,0.60), hero-2 (0.45,0.45), hero-3 (0.45,0.40), hero-4 (0.45,0.35), hero-5 (0.50,0.55), hero-6 (0.50,0.35). Bryan adjusts them in the admin. + +Not yet built on the ASF side (after this design): hydration and slider from the data block, marker injection in the build, e2e against a stand-in host, the baked fallback from the CMS-driven format. + +## 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): + +`

` + (tagline: `TAGLINE `) + `LINE
LINE

` + (lead: `

LEAD

`, line breaks as `
`) + (buttons: `

LABEL...

`, at most two). An optional per-site setting `Hero:TitlePrefix` (default empty; SLP Software: `"SLP Software: "`) writes `SLP Software: ` (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). diff --git a/aidlc-docs/features/media-library/overview.md b/aidlc-docs/features/media-library/overview.md new file mode 100644 index 0000000..089270f --- /dev/null +++ b/aidlc-docs/features/media-library/overview.md @@ -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//...`) 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//...`) 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. diff --git a/docs/deploy-en-testomgevingen.md b/docs/deploy-en-testomgevingen.md index 4e75b61..cbbda5b 100644 --- a/docs/deploy-en-testomgevingen.md +++ b/docs/deploy-en-testomgevingen.md @@ -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 diff --git a/docs/hero-module.md b/docs/hero-module.md new file mode 100644 index 0000000..02e46c6 --- /dev/null +++ b/docs/hero-module.md @@ -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: `…` (titel, tagline, knoppen, eerste slide als ``) en `…` 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//-.`, 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 (``), 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//shared/media && chmod 700 ~/apps/slpsoftware//shared/media` (voor ASF-test hetzelfde in zijn eigen map). +2. In `shared/env`: `Media__Directory=%h/apps/slpsoftware//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 +./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`. diff --git a/docs/release-checklist-productie.md b/docs/release-checklist-productie.md index 084062a..88d767a 100644 --- a/docs/release-checklist-productie.md +++ b/docs/release-checklist-productie.md @@ -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. diff --git a/frontend/index.html b/frontend/index.html index 58ffefa..0e34ca2 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -5,13 +5,8 @@ SlpModularCms - + +
diff --git a/frontend/public/theme-init.js b/frontend/public/theme-init.js new file mode 100644 index 0000000..6770ee5 --- /dev/null +++ b/frontend/public/theme-init.js @@ -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); +})(); diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index b503cd1..ca75982 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -1,6 +1,6 @@ import { Link } from '@tanstack/react-router'; import { useTranslation } from 'react-i18next'; -import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X } from 'lucide-react'; +import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon } from 'lucide-react'; import type { LucideIcon } from 'lucide-react'; import { cn } from '@/lib/utils'; import { useAuth } from '@/features/auth/context/auth-context'; @@ -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', diff --git a/frontend/src/components/layout/ThemeToggle.test.tsx b/frontend/src/components/layout/ThemeToggle.test.tsx new file mode 100644 index 0000000..1272d1d --- /dev/null +++ b/frontend/src/components/layout/ThemeToggle.test.tsx @@ -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(); + + 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(); + + 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(); + + 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(); + + 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(); + + expect(screen.getByTestId('theme-toggle')).toHaveAccessibleName('Theme: automatic (now dark)'); + }); +}); diff --git a/frontend/src/components/layout/ThemeToggle.tsx b/frontend/src/components/layout/ThemeToggle.tsx index 60041f8..7f8416f 100644 --- a/frontend/src/components/layout/ThemeToggle.tsx +++ b/frontend/src/components/layout/ThemeToggle.tsx @@ -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 ( - + + + + + + {t('theme.title')} + + {MODES.map(({ mode: option, icon: OptionIcon }) => ( + setMode(option)} + aria-current={mode === option ? 'true' : undefined} + data-testid={`theme-option-${option}`} + > + + {t(`theme.mode.${option}`)} + + + ))} + + ); } diff --git a/frontend/src/components/ui/checkbox.test.tsx b/frontend/src/components/ui/checkbox.test.tsx new file mode 100644 index 0000000..f934d29 --- /dev/null +++ b/frontend/src/components/ui/checkbox.test.tsx @@ -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(); + 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(); + 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(); + 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(); + 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 ( +
+ + + + ); + } + let saved: { on: boolean } | null = null; + render( +
{ + 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( + + + + , + ); + 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(); + 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]'); + }); +}); diff --git a/frontend/src/components/ui/checkbox.tsx b/frontend/src/components/ui/checkbox.tsx new file mode 100644 index 0000000..bd5e648 --- /dev/null +++ b/frontend/src/components/ui/checkbox.tsx @@ -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, '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( + ({ className, indeterminate = false, invalid = false, ...props }, forwardedRef) => { + const inner = React.useRef(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 ( + + + + ); + }, +); +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(({ label, id, disabled, ...props }, ref) => { + const generated = React.useId(); + const inputId = id ?? generated; + return ( + + ); +}); +CheckboxField.displayName = 'CheckboxField'; diff --git a/frontend/src/components/ui/radio.tsx b/frontend/src/components/ui/radio.tsx new file mode 100644 index 0000000..c7e7019 --- /dev/null +++ b/frontend/src/components/ui/radio.tsx @@ -0,0 +1,61 @@ +import * as React from 'react'; +import { cn } from '@/lib/utils'; + +export interface RadioProps extends Omit, '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(({ className, invalid = false, ...props }, ref) => ( + + + +)); +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(({ label, id, disabled, ...props }, ref) => { + const generated = React.useId(); + const inputId = id ?? generated; + return ( + + ); +}); +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, 'aria-label'>) { + return ( +
+ {children} +
+ ); +} diff --git a/frontend/src/csp.test.ts b/frontend/src/csp.test.ts new file mode 100644 index 0000000..e05c989 --- /dev/null +++ b/frontend/src/csp.test.ts @@ -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(/]*)>([\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); + }); +}); diff --git a/frontend/src/features/hero/components/CropThumbnail.tsx b/frontend/src/features/hero/components/CropThumbnail.tsx new file mode 100644 index 0000000..7a3aef9 --- /dev/null +++ b/frontend/src/features/hero/components/CropThumbnail.tsx @@ -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 ( + + ); +} + +/** 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}%`, + }; +} diff --git a/frontend/src/features/hero/components/FocusDialog.tsx b/frontend/src/features/hero/components/FocusDialog.tsx new file mode 100644 index 0000000..fdca308 --- /dev/null +++ b/frontend/src/features/hero/components/FocusDialog.tsx @@ -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 ( + { if (!next) onClose(); }}> + + + {t('hero.focus.title')} + + {/* Mounted only while open, so every opening starts from the stored values. */} + {image && } + + + ); +} + +const percent = (fraction: number) => Math.round(fraction * 1000) / 10; + +function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply: (imageId: string, request: HeroFocusRequest) => void; onClose: () => void }) { + const { t } = useTranslation(); + const area = useRef(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('general'); + const [general, setGeneral] = useState(image.focus ?? CENTRE); + const [wide, setWide] = useState(image.wideFocus); + const [tall, setTall] = useState(image.tallFocus); + + const effective = { wide: wide ?? general, tall: tall ?? general }; + const active: FocusDto = target === 'general' ? general : (target === 'wide' ? wide : tall) ?? general; + const editable = target === 'general' || (target === 'wide' ? wide : tall) !== null; + + const update = (next: FocusDto) => { + const clean = normalizeFocus(next); + if (target === 'general') setGeneral(clean); + else if (target === 'wide') setWide(clean); + else setTall(clean); + }; + + const toggleOverride = (checked: boolean) => { + const value = checked ? { ...general } : null; + if (target === 'wide') setWide(value); + if (target === 'tall') setTall(value); + }; + + const moveTo = (event: PointerEvent) => { + const box = area.current?.getBoundingClientRect(); + if (!box || box.width === 0 || box.height === 0 || !editable) return; + update({ ...active, x: (event.clientX - box.left) / box.width, y: (event.clientY - box.top) / box.height }); + }; + + const onKeyDown = (event: KeyboardEvent) => { + if (!editable) return; + const step = event.shiftKey ? 0.05 : 0.01; + const moves: Record = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }; + const move = moves[event.key]; + if (!move) return; + event.preventDefault(); + update({ ...active, x: active.x + move[0], y: active.y + move[1] }); + }; + + const onSave = () => { + 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 ( +
+

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

+

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

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

+ {t('hero.focus.previewPending')} +

+ )} +
+
+
+
+

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

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

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

+
+ {previewUrl && } +
+
+ ); + })} +
+
+ +
+ + +
+
+ ); +} diff --git a/frontend/src/features/hero/components/HeroTabs.tsx b/frontend/src/features/hero/components/HeroTabs.tsx new file mode 100644 index 0000000..86ec1b4 --- /dev/null +++ b/frontend/src/features/hero/components/HeroTabs.tsx @@ -0,0 +1,106 @@ +import { useRef, type KeyboardEvent, type ReactNode } from 'react'; + +export interface HeroTab { + 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 { + label: string; + tabs: HeroTab[]; + 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 id="{idPrefix}-panel-{id}" and aria-labelledby="{idPrefix}-tab-{id}". + */ +export function HeroTabs({ label, tabs, selected, onSelect, idPrefix }: HeroTabsProps) { + const refs = useRef>({}); + + 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 ( +
+ {tabs.map((tab, index) => { + const active = tab.id === selected; + return ( + + ); + })} +
+ ); +} diff --git a/frontend/src/features/hero/components/ProcessingStatus.tsx b/frontend/src/features/hero/components/ProcessingStatus.tsx new file mode 100644 index 0000000..9b0c11d --- /dev/null +++ b/frontend/src/features/hero/components/ProcessingStatus.tsx @@ -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