From 22e077b41baeb188ee132a28d27b7ad84897dbe8 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 13:20:50 +0100 Subject: [PATCH 1/2] Docs: media-library, Requirements Analysis en Application Design op aannames Co-Authored-By: Claude Sonnet 5.5 --- aidlc-docs/active-features.md | 2 +- .../features/media-library/aidlc-state.md | 45 +++++ .../assumptions-and-open-questions.md | 23 +++ aidlc-docs/features/media-library/audit.md | 13 ++ .../application-design/application-design.md | 176 ++++++++++++++++++ .../inception/requirements/requirements.md | 105 +++++++++++ aidlc-docs/features/media-library/overview.md | 2 +- 7 files changed, 364 insertions(+), 2 deletions(-) create mode 100644 aidlc-docs/features/media-library/aidlc-state.md create mode 100644 aidlc-docs/features/media-library/assumptions-and-open-questions.md create mode 100644 aidlc-docs/features/media-library/audit.md create mode 100644 aidlc-docs/features/media-library/inception/application-design/application-design.md create mode 100644 aidlc-docs/features/media-library/inception/requirements/requirements.md diff --git a/aidlc-docs/active-features.md b/aidlc-docs/active-features.md index 54eb947..7baada6 100644 --- a/aidlc-docs/active-features.md +++ b/aidlc-docs/active-features.md @@ -25,4 +25,4 @@ | 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 | +| Feature | [Mediabibliotheek (media-library)](features/media-library/overview.md) | 🟡 Inception: requirements en ontwerp als concept op aannames (2026-11-17; Bryan controleert later; niets gebouwd dat data verhuist) | feature/media-library | Core (Media), Modules.Hero, later gallerij-module, Frontend (admin) | 2026-11-17 | diff --git a/aidlc-docs/features/media-library/aidlc-state.md b/aidlc-docs/features/media-library/aidlc-state.md new file mode 100644 index 0000000..3674c52 --- /dev/null +++ b/aidlc-docs/features/media-library/aidlc-state.md @@ -0,0 +1,45 @@ +# AI-DLC State Tracking + +## Project Information +- **Feature Name**: Media library (one place to manage, keep and reuse photos for all modules) +- **Feature Slug**: media-library +- **Project Type**: Brownfield +- **Start Date**: 2026-11-17 +- **Current Stage**: INCEPTION - Requirements Analysis and Application Design drafted on assumptions (awaiting Bryan's later check); nothing that moves data is built +- **Branch**: feature/media-library (from origin/master e0b3782) + +## Workspace State +- **Existing Code**: Yes (Core/Media, Modules.Hero) +- **Reverse Engineering Needed**: No (artifacts in `_shared/reverse-engineering/`; targeted read of Core/Media and Modules.Hero) +- **Workspace Root**: K:\Development\Projects\SlpModularCms + +## Language Configuration +- **Documentation Language**: English +- **Conversation Language**: User Language (Dutch) +- **Note**: Inherited from the other features. `overview.md` stays Dutch (written by SLS-Main for Bryan). + +## Source Of Truth / Coordination +- Requirements 1 to 7 of Bryan are in `overview.md` (2026-11-17). Bryan is away: no questions to him; every open question has a most probable assumption in `assumptions-and-open-questions.md`; Bryan checks them later. +- Allowed now: requirements, design, and safe, reversible building. **Not allowed without prior alignment (via SLS-Main with Bryan)**: an EF migration that moves existing `HeroImages`, any change of public addresses (`/media/hero//...`), set-hashes or golden files. +- No merge to master, production deploy or production variables without go. + +## Extension Configuration +| Extension | Enabled | Decided At | +|---|---|---| +| Security Baseline | Yes (blocking), as for hero-module | Inherited (upload, delete and file serving are security relevant) | +| Property-Based Testing | Partial (pure functions and round-trips) | Inherited | + +## Operations Configuration +- **Include Operations Phase**: No (points go into docs/release-checklist-productie.md when built) + +## Stage Progress +### INCEPTION PHASE +- [x] Workspace Detection (Feature, brownfield) +- [x] Reverse Engineering (skipped: targeted read) +- [x] Requirements Analysis (inception/requirements/requirements.md; no questions file: assumptions instead) +- [ ] User Stories - SKIP (one persona, acceptance criteria in the requirements) +- [x] Workflow Planning (section 9 of requirements: phases A to D) +- [x] Application Design (inception/application-design/application-design.md, draft) +- [ ] Units Generation (after Bryan's check of the assumptions) +### CONSTRUCTION PHASE +- [ ] Not started. Phase A (safe, reversible) may start after the assumptions are acknowledged; phases B and C move data and need alignment first. diff --git a/aidlc-docs/features/media-library/assumptions-and-open-questions.md b/aidlc-docs/features/media-library/assumptions-and-open-questions.md new file mode 100644 index 0000000..691b1fa --- /dev/null +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -0,0 +1,23 @@ +# Assumptions and deferred questions: media-library + +Kept while Bryan is away (2026-11-17): no questions to him, a most probable assumption per open question instead. Per item: the question, the assumption made, what changes if Bryan chooses differently, and where in code or design. To be put to Bryan by the SLS session; he checks and corrects later. Same form as the Hero list. + +| # | Question | Assumption made | If Bryan chooses differently | Where | +|---|---|---|---|---| +| 1 | Which **uses** (places and ratios) exist? | Hero `wide` (3:2) and `tall` (2:3), ASF shoot-page **mosaic** tiles (a small fixed set of ratios per page, to be listed by the ASF session), **masonry** (natural ratio, no crop), **thumb** (library thumbnails, 1:1 or natural). A use is `(module, place, ratio set)`. | Other ratios only add rows to the use definitions; a free-form ratio per tile would need a ratio editor and more variants per photo. | Application design section 4 (`MediaUseDefinition`) | +| 2 | **Several formats/variants per photo**: who decides the set? | The **use** decides the ratios and widths (as `VariantPlanner` does for Hero); the library never cuts a fixed set per photo. Formats stay WebP and AVIF as today. | A fixed set per photo costs more disk and CPU on the Pi and cuts variants nobody uses. | `VariantPlanner`, application design section 4 | +| 3 | The **7-day automatic clean-up** of unattached Hero images until the library is built. | Switch it off behind a setting (`Media:AutoCleanupUnattached`, default `true` until the library screen exists, then default `false`), so nothing is lost silently once the library can show and delete photos. Retired-file removal (after a replaced set) stays: that is housekeeping of generated files, not a person's photos. | Keep it on until phase C; or switch off now (risk: unused uploads pile up with no screen to remove them). | `HeroMediaCleanup`, `MediaOptions` | +| 4 | **Rights per module**: who may see, use and delete which photos? | One shared library for Owner and Administrator (like Hero and Offerings). No per-module visibility yet. | Per-module visibility needs an owner field on a photo and a filter; the contract has room for it (`ModuleKey` on a use). | `[Authorize(Policy = "AdminOnly")]`, `MediaUse.Module` | +| 5 | **Public addresses**: per module (`/media//...`) or a shared path? | Keep `/media/{area}/{setHash}/{name}`; `area` stays the module (`hero`; a gallery would use `gallery`). The set hash still comes from the original's hash plus the crops of that **use**. A photo used in two modules is two sets (two addresses), cached separately. | A shared path would change addresses and golden files: not allowed without alignment. | `MediaPaths`, `MediaEndpoint` | +| 6 | **Usage register**: do modules report, or does the library keep it centrally? | Modules report: `IMediaUsageProvider` per module answers "where is this photo used" and "detach this photo" from the module's own data. Computed, never copied, so it cannot go stale. The library warns when a module has no provider. | A central register table keeps the answer fast but must be kept in step on every module save (risk of drift); can be added later as a cache. | Application design section 3, `IMediaUsageProvider` | +| 7 | **What counts as "unused"** in the clean-up? | A photo is unused when **no provider** reports a use. A photo used only by an inactive or unpublished slide still counts as used (it is in a slide). | Treating an inactive slide as unused would delete photos a person may want to switch on again; stricter would be safer than looser. | `MediaUsageService` | +| 8 | **Clean-up default period** and slider range. | Default 7 days, slider 1 to 365 days, step 1; "Only unused photos" on. The period is measured from the upload date. | Measured from last use, or another range: a one-line change in the filter. | Clean-up component, `CleanupSelection` | +| 9 | **Storage limit and warning**. | Limit = existing `Media:MaxTotalBytes` (2 GB, decided by Bryan, Hero assumption 12). Warning at 80 percent (amber) and at 100 percent (red, uploads refused with a clear message). Used bytes = originals plus all variants, cached 60 s. | Another threshold or limit: configuration only. | `MediaOptions`, `MediaStorageUsage` | +| 10 | **Delete of a photo that is in use**. | Not possible from Clean-up (those rows are not selectable); possible from the library after a second confirmation that names the uses; the module detaches it first (Hero: the slide loses its image and is unpublished until a new one is chosen, as today). | Block deleting in-use photos completely: the extra confirmation path is removed. | `IMediaUsageProvider.DetachAsync`, library screen | +| 11 | **Shared upload service**: does Hero's upload move into the library? | In phase A Hero keeps its own upload endpoint; the library also lists those photos. In phase B both call one upload service in Core. | Moving Hero upload earlier gives a single path sooner but touches Hero before the data model exists. | `HeroImageService`, `MediaUploadGuard` | +| 12 | **Trash delay** (deleted photos recoverable for a while)? | No trash in phase A: the confirmation naming the count is the safety. A 7-day trash can be added in phase B (a `DeletedAt` and the existing retired-file mechanism). | Trash from the start: reuse `HeroRetiredFile` logic generalised in Core; about 1 day extra. | `HeroRetiredFile`, application design section 5 | +| 13 | **Migration of existing `HeroImages`** (phase C). | Expand then contract: new `MediaAsset` and `MediaUse` tables are filled from `HeroImages` and `HeroSlides` with the **same ids, hashes and set hashes**; Hero reads the library; old columns are dropped in a later release. Needs a back-up and alignment: **not built**. | A one-step move is smaller but cannot be rolled back; or no migration at all and the library keeps reading through Hero (the provider approach) until the gallery module needs own tables. | Requirements section 9, application design section 6 | +| 14 | **Crop per use**: data per use or per photo? | A use owns its crop (focus x, y and zoom per ratio); the photo owns the default focus new uses start from. The set hash of a use is `SetHash(originalSha256, crops of that use)` exactly as today, so existing Hero addresses are unchanged. | Crop per photo only (today's model) cannot serve a mosaic with several tiles of the same photo. | `MediaPaths.SetHash`, `MediaUse` | +| 15 | **Selection range** with shift-click and "select all": across pages or the loaded page? | The loaded list (the clean-up list is loaded fully, the library list incrementally; "select all" says how many are loaded and offers "select all N" for a filtered list). | Strictly the current page: simpler, less useful for a clean-up of hundreds. | Selection component | +| 16 | **Deleting files from the store** when a photo is deleted. | The original and the set directories of that photo are deleted through `IMediaStore` after the database rows; a set shared with another use (same hash) is kept until no use references it. | Soft delete first (see 12). | `IMediaStore.DeleteSetAsync`, `HeroRepository.GetReferencedSetHashesAsync` | +| 17 | **Language of the screen**: nl and en like the rest of the admin. | Yes, `media.*` keys in both files; terms: "Mediabibliotheek", "Opruimen", "Alleen ongebruikte foto's". | Dutch only: remove one file. | `frontend/src/i18n/locales` | diff --git a/aidlc-docs/features/media-library/audit.md b/aidlc-docs/features/media-library/audit.md new file mode 100644 index 0000000..8874345 --- /dev/null +++ b/aidlc-docs/features/media-library/audit.md @@ -0,0 +1,13 @@ +# Audit Log - media-library + +## Workspace Detection (initial request) + +**Timestamp**: 2026-11-17T00:00:00Z + +**User Input**: Cross-session instruction from SLP Software - SLS - Main relaying Bryan: start AI-DLC for `media-library` per `aidlc-docs/features/media-library/overview.md` once Hero and the form controls are on master; Requirements Analysis without questions to Bryan, record the most probable assumption per open question; use the gallery needs (ASF shoot-page mosaic, masonry) and Hero as design sources; design allowed; do not build anything that moves data or touches public addresses/golden files without alignment via SLS-Main. + +**AI Response**: Classified as Feature (new capability). Brownfield. Hero (#17) and admin-form-controls (#19) are on master (4c88ea8), messages-badge (#18) too (e0b3782). Branch `feature/media-library` created from origin/master. Wrote aidlc-state, requirements, assumptions and a draft application design. + +**Context**: Requirements Analysis and Application Design drafted on assumptions. Bryan checks the assumptions later. + +--- diff --git a/aidlc-docs/features/media-library/inception/application-design/application-design.md b/aidlc-docs/features/media-library/inception/application-design/application-design.md new file mode 100644 index 0000000..24fb79e --- /dev/null +++ b/aidlc-docs/features/media-library/inception/application-design/application-design.md @@ -0,0 +1,176 @@ +# Application design (draft on assumptions): media-library + +Status: draft, built on `assumptions-and-open-questions.md`. Nothing here moves data or changes public addresses. + +## 1. Components + +```mermaid +graph TD + UI[Admin: Media library screen] --> API[MediaLibraryController] + UI --> SEL[Selection + BulkActionBar components] + API --> LIB[MediaLibraryService] + LIB --> USE[MediaUsageService] + LIB --> STO[MediaStorageUsage] + LIB --> STORE[IMediaStore] + USE --> PH[Hero IMediaUsageProvider] + USE --> PG[Gallery IMediaUsageProvider, later] + PH --> HERO[(HeroImages / HeroSlides)] + HOST[Public /media endpoint] --> STORE + classDef ui fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + classDef core fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef mod fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + classDef data fill:#fbb6ce,stroke:#b83280,stroke-width:1px,color:#000; + class UI,SEL ui; + class API,LIB,USE,STO,STORE,HOST core; + class PH,PG mod; + class HERO data; +``` + +Text alternative: the admin screen calls the library service in Core, which asks each module's usage provider where a photo is used and reads files and sizes through `IMediaStore`; the public media endpoint is unchanged. + +| Component | Where | Responsibility | +|---|---|---| +| `IMediaUsageProvider` | Core (contract), implemented per module | `ListUsesAsync(photoKey[])`, `DetachAsync(photoKey)`, `ListPhotosAsync(paging)` (phase A read-through) | +| `MediaUsageService` | Core | Fans out to all providers, merges uses, knows which modules have no provider | +| `MediaLibraryService` | Core | Listing (newest first), delete orchestration, clean-up preview | +| `MediaStorageUsage` | Core | Bytes of originals plus variants, cached 60 s, warning level | +| `CleanupSelection` | Core, pure | Given photos, uses, now, days and the unused flag: the preselected set | +| `MediaLibraryController` | Core or new module (see 7) | `GET /api/v1/media`, `GET /api/v1/media/storage`, `POST /api/v1/media/cleanup/preview`, `POST /api/v1/media/delete` | +| Frontend `features/media` | frontend | Screen, `PhotoSelectionList`, `BulkActionBar`, `CleanupDialog`, `StorageMeter`, React Query hooks | + +## 2. Data (target, phase B and later; phase A uses Hero data read-only) + +```mermaid +erDiagram + MediaAsset ||--o{ MediaUse : "is used by" + MediaAsset { + guid Id + string OriginalSha256 + string OriginalKey + int Width + int Height + long Bytes + double DefaultFocusX + double DefaultFocusY + double DefaultZoom + datetime CreatedAt + guid CreatedByUserId + } + MediaUse { + guid Id + guid AssetId + string Module + string Place + string RatioSet + double FocusX + double FocusY + double Zoom + string SetHash + } +``` + +Text alternative: one photo (`MediaAsset`) has many uses (`MediaUse`); each use has its module, place, ratio set, its own crop and the set hash derived from the photo hash plus that crop. + +- `SetHash` of a use is computed by the existing `MediaPaths.SetHash(OriginalSha256, crops)`; for a Hero slide this equals today's value (verified by a test in phase A against current golden data). +- Variants stay files in the store (`/media/{area}/{setHash}/...`); no variants table is needed (the Hero `Variants` list is derived from the planner and the files). +- A use is `Module` + `Place` (for Hero "slide 3", id of the slide), not a free text. + +## 3. Usage contract + +```csharp +public interface IMediaUsageProvider +{ + string Module { get; } // "hero" + Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken ct); + Task> ListPhotosAsync(MediaPaging paging, CancellationToken ct); // phase A read-through + Task DetachAsync(Guid photoId, CancellationToken ct); // before the library deletes the photo + Task DeleteAsync(Guid photoId, CancellationToken ct); // phase A: the module deletes its own photo +} +``` + +A `MediaUse` carries `Module`, `PlaceLabel` (for display, translated by the module, for example "Hero, slide 3"), `PlaceId` and `Active`. In phase A the Hero provider implements all four members over `HeroImages` and `HeroSlides`; from phase B the library owns the photos and `ListPhotosAsync`/`DeleteAsync` fall away. + +## 4. Uses and crops + +```mermaid +flowchart LR + P[Photo + default focus] --> U1[Use: hero wide] + P --> U2[Use: hero tall] + P --> U3[Use: mosaic tile 4:5] + P --> U4[Use: masonry natural] + U1 --> S1[set hash A] + U2 --> S1 + U3 --> S2[set hash B] + U4 --> S3[set hash C] + classDef p fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + classDef u fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef s fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + class P p; + class U1,U2,U3,U4 u; + class S1,S2,S3 s; +``` + +Text alternative: one photo has uses in Hero (wide and tall share one set), a mosaic tile and a masonry gallery; each set has its own hash and address. + +- `MediaUseDefinition` (code, per module): ratio names, ratio values and widths for the variant planner. Hero's `wide` and `tall` exist today; the mosaic's tile ratios and masonry's natural ratio are added by the gallery module. +- A natural-ratio use stores no crop (focus ignored); the planner produces widths only. +- The Hero sets are unchanged: one use per slide carrying the image's `wide` and `tall` crops, one set hash. + +## 5. Delete and clean-up flow + +```mermaid +sequenceDiagram + box rgba(246,224,94,0.4) Admin + participant U as Person + end + box rgba(99,179,237,0.4) Core + participant L as MediaLibraryService + participant S as MediaUsageService + end + box rgba(154,230,180,0.4) Module + participant P as Usage provider + end + U->>L: Clean-up preview (days, only unused) + L->>S: Uses of all photos in the period + S->>P: ListUsesAsync + P-->>S: Uses + L-->>U: Newest first, all selected, bytes to free + U->>L: Confirm selected ids + L->>S: Re-check uses + L->>P: DetachAsync / DeleteAsync + L->>L: Delete files in the store + L-->>U: Result per photo +``` + +Text alternative: the person previews, the service re-checks usage at confirmation time (a photo used since the preview is skipped), the module detaches and deletes, the service removes files and reports per photo. + +- The re-check at confirmation protects against a photo that became used after the preview. +- Bulk delete is limited (100 photos per request), idempotent and reports per photo. + +## 6. Migration outline (phase C, designed only) + +1. Back-up the database and the media directory. +2. Create `MediaAsset` and `MediaUse` (additive migration). No existing table changes. +3. Copy: one asset per `HeroImage` with the **same id, hash, key and set hash**; one use per slide that references it. A verification query compares counts, ids and set hashes and aborts on any difference. +4. Switch Hero reads to the library behind a setting; keep the old columns written for one release (expand), then drop them (contract). +5. Rollback until step 4: delete the new tables (no consumer changed). + +## 7. Module placement (assumed) + +The model and services live in **Core** (`SlpModularCms.Core.Media`, next to the store) so Hero and the gallery module depend on Core only; the controller and the EF tables (phase B) go in a new module `SlpModularCms.Modules.Media` with its own `DbContext` and migrations, like the other modules, and a test project under `Tests/Modules`. Phase A needs no new tables, so the first controller can ship in the Hero-independent Core registration. + +## 8. Frontend + +- `PhotoSelectionList`: virtualised or incremental list of cards (thumbnail, name, size, date, usage chips), with the shared `Checkbox`, shift-click range, select all and clear, `aria-live` count. +- `BulkActionBar`: sticky, shows the count and the actions; actions are data (`{id, label, destructive, run}`) so tags or move can be added. +- `CleanupDialog`: slider (days), `CheckboxField` "Only unused photos" (default on), the same `PhotoSelectionList` preselected, summary of count and bytes, confirm. +- `StorageMeter`: used, limit, warning colour plus text. +- Sidebar entry "Mediabibliotheek" for Owner and Administrator. + +## 9. Test strategy + +- Pure: `CleanupSelection` (age, unused flag, ordering), range selection, set-hash per use equals the Hero value (property tests). +- Service: delete re-check, partial failure, limit of 100, in-use rules, storage warning thresholds. +- Hero provider: uses per slide, detach. +- Regression: golden files and the host-injection tests unchanged; a set made before the library is still served. +- Frontend: selection by mouse and keyboard, announcements, dialog flow, i18n nl and en. diff --git a/aidlc-docs/features/media-library/inception/requirements/requirements.md b/aidlc-docs/features/media-library/inception/requirements/requirements.md new file mode 100644 index 0000000..0ab42a7 --- /dev/null +++ b/aidlc-docs/features/media-library/inception/requirements/requirements.md @@ -0,0 +1,105 @@ +# Requirements: Media library (media-library) + +- **Feature slug**: media-library +- **Status**: Draft on assumptions (Bryan is away; he checks `assumptions-and-open-questions.md` later and corrects where needed) +- **Depth**: Standard (comprehensive for deletion, file serving and the data migration, which are security and data-loss relevant) +- **Documentation Language**: English; **Conversation Language**: Dutch +- **Inputs**: `overview.md` (Bryan's requirements 1 to 7, 2026-11-17), the Hero module as built (`Core/Media`, `Modules.Hero`), `docs/hero-module.md`, the gallery needs of ASF (shoot-page mosaic, masonry) as relayed by SLS-Main. + +## 1. Intent analysis + +| Item | Value | +|---|---| +| User request | One place in the CMS where photos are managed, kept and reused by all modules; nothing is removed automatically; a clean-up tool and bulk actions in the admin | +| Request type | New capability (Core abstraction plus a new admin area), later used by a gallery module | +| Scope | Core (media model and usage register), `Modules.Hero` (becomes a first user), new admin screen, later a gallery module | +| Complexity | Complex: abstraction at the right level, address stability, data migration of existing `HeroImages` | +| Reverse engineering | Targeted read only: `Core/Media` (store, paths, variants, focus), `Modules.Hero` (entity `HeroImage`, `HeroMediaCleanup`, render service) | + +## 2. What exists today (facts the design builds on) + +- `IMediaStore` stores originals and variant sets on disk (`Media__Directory`); public address `/media/{area}/{setHash}/{ratio}-{width}.{ext}` (`MediaPaths`, strict allow-list). `area` is a module name (`hero`). +- The **set hash** is 16 hex characters of SHA-256 over the original's hash and the crops (ratio name plus canonical focus), so a changed focus gives a new address and files are cached for a long time. +- `HeroImage` holds the original (hash, key, size), one general focus and an optional focus per ratio (`wide`, `tall`), the current set hash and its variants. A slide references an image. Uploading the same photo twice gives one image (same hash). +- A background renderer (`HeroRenderService`) cuts variants; an image without a complete set is not published. +- `HeroMediaCleanup` retires uploaded-but-unused images after `Media:RetentionDays` (7) and removes retired files after the same period. This is the automatic clean-up Bryan wants to stop. + +## 3. Principles (from Bryan, 2026-11-17) + +1. **Keep everything.** An upload stays until a person deletes it. +2. **A person decides what goes**: through "Clean up" (a guided, previewed bulk delete) or through bulk actions in the library. +3. **Crop per use, not per photo.** A photo has a default focus; every use (module and place) can carry its own crop. A photo in a masonry gallery needs no crop. +4. **Addresses stay stable.** `/media/hero//...` and the set hashes do not change; ASF, SLS and the golden files keep working. + +## 4. Functional requirements + +| ID | Requirement | Acceptance criteria | +|---|---|---| +| ML-01 | **Library overview.** An admin screen lists all photos of all modules, newest first, with a thumbnail, file name, size, upload date and a usage indicator. | Order is `CreatedAt` descending; paging or incremental loading beyond 100 photos; an empty state; keyboard and screen-reader usable. | +| ML-02 | **Usage indicator.** Per photo: "in use" or "not used", and where (module and place, for example "Hero, slide 3"). | Several uses are all listed; the indicator is computed from the modules' own data, not guessed; a photo used nowhere shows "Not used". | +| ML-03 | **Keep everything.** No automatic removal of any photo or its files. | The Hero step that retires unattached images is switched off once the library owns the retention (see section 8, phase A: behind a setting, default decided in the assumptions); a test proves nothing is removed without a person's action. | +| ML-04 | **Selection component** (own reusable component): checkboxes per photo, select all and clear, a range with shift-click, keyboard operation, a visible count, and a live-region announcement of the count. | Works for mouse, keyboard and screen reader; reused by the library and the clean-up; uses the shared `Checkbox` of the theme. | +| ML-05 | **Bulk actions** on the selection, in the library itself. First action: **Delete**. The action bar is a separate component so more actions (tags, move) can be added without touching the list. | Delete asks for confirmation naming the number of photos and how many are in use; a failure of one photo does not stop the others and is reported per photo. | +| ML-06 | **Delete rules.** A photo that is in use is not deleted unless the person explicitly confirms and the use is detached first. | Default: in-use photos are not selectable for delete in "Clean up" and are marked in the library; deleting an in-use photo from the library shows what will lose its image and requires a second confirmation; the host falls back as it does today for a slide without a set. | +| ML-07 | **"Clean up" button.** Opens the overview of photos that would be cleaned: default everything older than 7 days, with a slider to look more or fewer days back, and a checkbox **Only unused photos**, default on (off = all photos in the period). | The list is newest first; all rows start selected; the person can deselect before confirming; confirming deletes exactly the selected rows; the summary shows the number and the bytes that will be freed. | +| ML-08 | **Clean-up is the same component as the library** (ML-04, ML-05) in a preselected view, not a second implementation. | One list/selection component, two entry points. | +| ML-09 | **Storage usage and limit warning.** The screen shows the used space (originals plus variants), the configured limit, and a warning at a threshold and at the limit. | Used bytes are computed from the store and cached for a short time; the warning level is configurable (assumption: 80 percent); at the limit, uploads give a clear message instead of a failure; the existing `Media:MaxTotalBytes` (2 GB) is the limit. | +| ML-10 | **Upload into the library** (single and multiple), with the same limits and checks as Hero today (type signature, size, megapixels, rate limit). | The Hero upload path and the library share one upload service; the same file is one photo (hash). | +| ML-11 | **Crop per use.** A use (module, place, ratio) can have its own focus and zoom, defaulting to the photo's default focus. Changing a use's crop never affects other uses. | A use owns its crop; the set hash of a use is derived exactly as today from the original's hash plus that use's crops, so addresses stay as they are. | +| ML-12 | **Default focus per photo.** The photo carries the default focus that new uses start from. | Setting it does not change existing uses that have their own crop. | +| ML-13 | **Usage register for modules.** A module reports where it uses photos and can be asked to detach a photo. | Contract in the design (section 3 of the application design); Hero is the first provider; a module without a provider counts as "uses nothing" and the library shows a warning that its uses are unknown (so a photo is not silently deleted). | +| ML-14 | **Public addresses unchanged.** `/media/hero//-.` and every existing set hash stay valid. | Golden files and the host-injection tests stay green without edits; a regression test serves a set created before the library. | +| ML-15 | **Permissions.** Owner and Administrator may use the library (like Hero and Offerings). | `[Authorize(Policy = "AdminOnly")]`; rate limits on upload and bulk delete. | +| ML-16 | **Audit.** Each deletion (single, bulk, clean-up) is logged with user, photo ids and count. | Structured log entry per action; no photo content in the log. | + +## 5. Non-functional requirements + +| ID | Requirement | +|---|---| +| NFR-ML-01 | **Data safety**: a delete is a two-step action (confirm, then act) and the originals can be kept behind a short "trash" delay (assumption 12). No data-moving migration runs without a recent back-up and prior alignment. | +| NFR-ML-02 | **Security** (Security Baseline): the same upload checks as Hero (content signature, size, pixel limit, rate limit), strict address allow-list, no path from user input, authorisation on every endpoint, bulk delete limited in size per request. | +| NFR-ML-03 | **Performance**: the overview loads the first page within 500 ms on the Raspberry Pi test host (thumbnails come from existing variants, never decoding originals in the request); storage usage is cached. | +| NFR-ML-04 | **Accessibility**: WCAG 2.2 AA; selection, range and bulk actions work by keyboard; counts are announced; no information by colour alone; forced-colors safe (shared Checkbox). | +| NFR-ML-05 | **Compatibility**: no change to the public address scheme, set-hash algorithm, `HeroImages` table or golden files in phase A. | +| NFR-ML-06 | **Testability**: selection state, clean-up selection (age and unused filter) and the set-hash derivation per use are pure functions with unit and property tests. | +| NFR-ML-07 | **Operability**: storage limit and warning level configurable (`Media__*`), documented in the release checklist when built. | + +## 6. Design sources + +- **Hero**: general focus plus `wide` and `tall` crops, background rendering, usage by slides, retention logic. It shows what a "use" is today (a slide with a ratio set) and what must keep working. +- **ASF gallery needs**: the shoot-page **mosaic** has several tile ratios per page (so crop per use and several ratios per photo), the **masonry** gallery shows a photo in its own ratio (no crop, only a variant set in the natural ratio). Both are served by "a use decides its ratio set", with a natural-ratio use as a first-class case. +- **Thumbnails** in the library are a use of the library itself (ratio `thumb`), cut once per photo. + +## 7. Out of scope (for now) + +- Tags, albums, search by content, moving photos between modules (the bulk action bar leaves room). +- Replacing a photo's file while keeping its uses (replace-in-place). +- Video or other media types. +- A CDN or database-backed store (`IMediaStore` already allows it; see Hero assumption 20). + +## 8. Constraints and the migration question + +- The existing `HeroImages` table and the Hero admin keep working unchanged in phase A. The library **reads through** the Hero data (a provider that lists `HeroImages` as photos and slides as uses) before any data moves. +- Moving existing photos into a Core table (phases B and C below) is a data migration that needs a back-up and prior alignment; it is designed here and **not built**. +- The automatic retirement of unattached Hero images (7 days) stays until the library can show and delete photos (phase A done); then it is switched off by setting, default per assumption 3. + +## 9. Workflow plan (phases) + +| Phase | Content | Moves data? | Build now? | +|---|---|---|---| +| A. Foundations (safe, reversible) | Usage contract in Core (`IMediaUsageProvider`), Hero provider (read only), library read model over `HeroImages`, storage usage service, selection and bulk-action components (frontend), clean-up selection logic, library screen (list, usage, selection, bulk delete through the Hero service), Hero retention setting | No (delete uses existing Hero delete path) | After Bryan acknowledges the assumptions; pure and read-only parts can start earlier | +| B. Own tables | `MediaAsset` and `MediaUse` tables, upload into the library, default focus | New tables only | Needs alignment | +| C. Migration of Hero | Copy `HeroImages` into `MediaAsset` plus `MediaUse` (one use per slide), keep set hashes and addresses, switch Hero to the library, drop old columns later (expand then contract) | Yes | Needs alignment and a back-up | +| D. Gallery module | First other consumer (mosaic, masonry) | Own data | Separate feature | + +## 10. Traceability to Bryan's requirements + +| Bryan (overview.md) | Here | +|---|---| +| 1 Keep everything | ML-03, principle 1 | +| 2 Clean-up button, slider, only unused | ML-07 | +| 3 Overview newest first, usage indicator | ML-01, ML-02, ML-07 | +| 4 and 6 Bulk actions as own component | ML-04, ML-05, ML-08 | +| 5 Storage and limit warning | ML-09 | +| 7 Crop per use | ML-11, ML-12, design section 4 | +| Boundary: addresses and set hashes | ML-14, NFR-ML-05 | diff --git a/aidlc-docs/features/media-library/overview.md b/aidlc-docs/features/media-library/overview.md index 089270f..c4af5f2 100644 --- a/aidlc-docs/features/media-library/overview.md +++ b/aidlc-docs/features/media-library/overview.md @@ -1,6 +1,6 @@ # 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. +**Status:** Gestart 2026-11-17 (Hero staat op master). Requirements Analysis en Application Design staan als concept op aannames in `inception/` en `assumptions-and-open-questions.md`; Bryan controleert die later. Er is niets gebouwd dat data verhuist of adressen wijzigt. Branch: `feature/media-library`. **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. -- 2.39.5 From 7e2e6a430f793a263c28311ca9a2e4d55f2fcc2e Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 13:47:10 +0100 Subject: [PATCH 2/2] Mediabibliotheek fase A: read-only gebruikscontract, Hero-provider, opruimselectie en selectiecomponenten Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 7 + .../media/components/BulkActionBar.tsx | 62 ++++++++ .../components/PhotoSelectionList.test.tsx | 121 ++++++++++++++++ .../media/components/PhotoSelectionList.tsx | 132 ++++++++++++++++++ .../src/features/media/lib/selection.test.ts | 47 +++++++ frontend/src/features/media/lib/selection.ts | 51 +++++++ frontend/src/i18n/locales/en/translation.json | 16 +++ frontend/src/i18n/locales/nl/translation.json | 16 +++ .../Media/MediaLibraryTests.cs | 91 ++++++++++++ .../Media/Library/CleanupSelection.cs | 30 ++++ .../Media/Library/MediaLibraryService.cs | 32 +++++ .../Media/Library/MediaLibraryTypes.cs | 34 +++++ .../Media/MediaServiceCollectionExtensions.cs | 1 + .../HeroMediaUsageProviderTests.cs | 51 +++++++ src/SlpModularCms.Modules.Hero/HeroModule.cs | 2 + .../Repositories/HeroRepository.cs | 12 ++ .../Services/HeroMediaUsageProvider.cs | 55 ++++++++ 17 files changed, 760 insertions(+) create mode 100644 frontend/src/features/media/components/BulkActionBar.tsx create mode 100644 frontend/src/features/media/components/PhotoSelectionList.test.tsx create mode 100644 frontend/src/features/media/components/PhotoSelectionList.tsx create mode 100644 frontend/src/features/media/lib/selection.test.ts create mode 100644 frontend/src/features/media/lib/selection.ts create mode 100644 src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs create mode 100644 src/SlpModularCms.Core/Media/Library/CleanupSelection.cs create mode 100644 src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs create mode 100644 src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs create mode 100644 src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs create mode 100644 src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs diff --git a/aidlc-docs/features/media-library/assumptions-and-open-questions.md b/aidlc-docs/features/media-library/assumptions-and-open-questions.md index 691b1fa..e4d56f5 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -21,3 +21,10 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 15 | **Selection range** with shift-click and "select all": across pages or the loaded page? | The loaded list (the clean-up list is loaded fully, the library list incrementally; "select all" says how many are loaded and offers "select all N" for a filtered list). | Strictly the current page: simpler, less useful for a clean-up of hundreds. | Selection component | | 16 | **Deleting files from the store** when a photo is deleted. | The original and the set directories of that photo are deleted through `IMediaStore` after the database rows; a set shared with another use (same hash) is kept until no use references it. | Soft delete first (see 12). | `IMediaStore.DeleteSetAsync`, `HeroRepository.GetReferencedSetHashesAsync` | | 17 | **Language of the screen**: nl and en like the rest of the admin. | Yes, `media.*` keys in both files; terms: "Mediabibliotheek", "Opruimen", "Alleen ongebruikte foto's". | Dutch only: remove one file. | `frontend/src/i18n/locales` | +| 18 | **Phase A built (2026-11-17, on assumptions)**: what is in the first step? | Read-only only: the usage contract (`IMediaUsageProvider`, `MediaLibraryService`, pure `CleanupSelection`), the Hero provider and the selection components in the frontend (`PhotoSelectionList`, `BulkActionBar`, selection rules). **No endpoint, no screen, no delete, no migration, no address change yet.** | Wire the screen and endpoints next (list, storage, clean-up preview) and then delete (needs a Hero delete path and Bryan's check of assumptions 3, 7 and 10). | `Core/Media/Library`, `Modules.Hero/Services/HeroMediaUsageProvider.cs`, `frontend/src/features/media` | +| 19 | The **position** of a slide in "Hero, slide 3". | Rank by `SortOrder` within its hero, counting slides that are switched off, 1-based; a slide that is off still counts as a use and is shown "(uit/off)". | Count only active slides, or show the slide's title instead. | `HeroMediaUsageProvider.ListUsesAsync` | +| 20 | The **thumbnail** of a Hero photo in the library. | The smallest published WebP variant of the current set; none yet (a grey "no preview") while the set is not cut. | Use the full-frame preview (`full-*.webp`), which shows the whole picture instead of the wide crop. | `HeroMediaUsageProvider.Thumbnail` | +| 21 | A **name** for a photo. | Photos have no file name today (`HeroImage` does not store it), so the library shows a neutral label (date and size); a name field comes with the library's own tables (phase B). | Store the original file name at upload now (a small Hero migration, additive). | `PhotoItem.name`, phase B | +| 22 | **Select all** and ranges with photos that cannot be selected (in use during a clean-up). | They are skipped by "select all" and by shift-ranges; the header box shows "some" when only part is selected. | Include them but refuse at confirmation. | `PhotoSelectionList`, `selection.ts` | +| 23 | Where does Hero **list all photos** (performance)? | In memory, newest first, as the rest of the Hero repository does (a few dozen photos; the MySQL provider has limits with Guid lists). Paging comes with the screen when the count grows. | Server-side paging by `CreatedAt` (needs an index). | `HeroRepository.GetAllImagesReadOnlyAsync` | +| 24 | **Tile ratios of the ASF mosaic** (assumption 1). | Asked of the ASF session through SLS-Main (2026-11-17); until then the design only names "tiles with a fixed set of ratios per page". | Each answer only adds use definitions. | Application design section 4 | diff --git a/frontend/src/features/media/components/BulkActionBar.tsx b/frontend/src/features/media/components/BulkActionBar.tsx new file mode 100644 index 0000000..f58084d --- /dev/null +++ b/frontend/src/features/media/components/BulkActionBar.tsx @@ -0,0 +1,62 @@ +import type { ReactNode } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Button } from '@/components/ui/button'; + +export interface BulkAction { + id: string; + label: string; + /** A destructive action (delete) is drawn in the warning colour. */ + destructive?: boolean; + disabled?: boolean; + icon?: ReactNode; + run: () => void; +} + +interface BulkActionBarProps { + count: number; + actions: readonly BulkAction[]; + onClear: () => void; + /** Extra text on the bar, for example the bytes the selection takes. */ + summary?: ReactNode; +} + +/** + * The actions on the selected photos. The actions are data, so more of them (tags, move) can be added without touching + * the list. It shows nothing while nothing is selected. + */ +export function BulkActionBar({ count, actions, onClear, summary }: BulkActionBarProps) { + const { t } = useTranslation(); + if (count === 0) return null; + return ( +
+ + {t('media.bulk.selected', { count })} + + {summary && {summary}} +
+ + {actions.map((action) => ( + + ))} +
+
+ ); +} diff --git a/frontend/src/features/media/components/PhotoSelectionList.test.tsx b/frontend/src/features/media/components/PhotoSelectionList.test.tsx new file mode 100644 index 0000000..2c8ce7b --- /dev/null +++ b/frontend/src/features/media/components/PhotoSelectionList.test.tsx @@ -0,0 +1,121 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { useState } from 'react'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import i18n from '@/i18n/config'; +import { emptySelection, type Selection } from '../lib/selection'; +import { BulkActionBar } from './BulkActionBar'; +import { PhotoSelectionList, type PhotoItem } from './PhotoSelectionList'; + +const items: PhotoItem[] = [ + { id: 'p1', name: 'Foto 1', bytes: 2048, createdAt: '2026-11-17T10:00:00Z', uses: [{ module: 'hero', kind: 'slide', position: 3, active: true }] }, + { id: 'p2', name: 'Foto 2', bytes: 500, createdAt: '2026-11-16T10:00:00Z', uses: [] }, + { id: 'p3', name: 'Foto 3', bytes: 1048576, createdAt: '2026-11-15T10:00:00Z', uses: [{ module: 'hero', kind: 'slide', position: 1, active: false }] }, + { id: 'p4', name: 'Foto 4', bytes: 10, createdAt: '2026-11-14T10:00:00Z', uses: [] }, +]; + +function Harness({ disabled }: { disabled?: (item: PhotoItem) => boolean }) { + const [selection, setSelection] = useState(emptySelection); + return ( + <> + + setSelection(emptySelection)} /> + + ); +} + +beforeEach(async () => { + await i18n.changeLanguage('nl'); +}); + +describe('PhotoSelectionList', () => { + it('shows each photo with where it is used, or that it is not used', () => { + render(); + + expect(screen.getByTestId('photo-usage-p1')).toHaveTextContent('Hero, slide 3'); + expect(screen.getByTestId('photo-usage-p2')).toHaveTextContent('Niet gebruikt'); + expect(screen.getByTestId('photo-usage-p3')).toHaveTextContent('Hero, slide 1 (uit)'); + }); + + it('selects a photo with a click and announces the count', async () => { + render(); + + await userEvent.click(screen.getByRole('checkbox', { name: 'Foto 2' })); + + expect(screen.getByRole('checkbox', { name: 'Foto 2' })).toBeChecked(); + expect(screen.getByTestId('photo-selection-status')).toHaveTextContent('1 foto geselecteerd'); + expect(screen.getByTestId('bulk-count')).toHaveTextContent('1 foto geselecteerd'); + }); + + it('selects a range with shift-click', async () => { + render(); + + const user = userEvent.setup(); + + await user.click(screen.getByRole('checkbox', { name: 'Foto 1' })); + await user.keyboard('{Shift>}'); + await user.click(screen.getByRole('checkbox', { name: 'Foto 3' })); + await user.keyboard('{/Shift}'); + + expect(screen.getByRole('checkbox', { name: 'Foto 2' })).toBeChecked(); + expect(screen.getByRole('checkbox', { name: 'Foto 3' })).toBeChecked(); + expect(screen.getByRole('checkbox', { name: 'Foto 4' })).not.toBeChecked(); + }); + + it('works with the keyboard: Space toggles the focused photo', async () => { + render(); + + screen.getByRole('checkbox', { name: 'Foto 4' }).focus(); + await userEvent.keyboard(' '); + + expect(screen.getByRole('checkbox', { name: 'Foto 4' })).toBeChecked(); + }); + + it('select all shows the in-between state for part of the list and clears everything on a second click', async () => { + render(); + const all = screen.getByRole('checkbox', { name: 'Alles selecteren' }) as HTMLInputElement; + + await userEvent.click(screen.getByRole('checkbox', { name: 'Foto 1' })); + expect(all.indeterminate).toBe(true); + + await userEvent.click(all); + expect(screen.getByRole('checkbox', { name: 'Foto 4' })).toBeChecked(); + expect(all).toBeChecked(); + + await userEvent.click(all); + expect(screen.queryByTestId('bulk-action-bar')).not.toBeInTheDocument(); + }); + + it('leaves out photos that cannot be selected, from select all and from ranges', async () => { + render( item.uses.length > 0} />); + + expect(screen.getByRole('checkbox', { name: 'Foto 1' })).toBeDisabled(); + await userEvent.click(screen.getByRole('checkbox', { name: 'Alles selecteren' })); + + expect(screen.getByRole('checkbox', { name: 'Foto 2' })).toBeChecked(); + expect(screen.getByRole('checkbox', { name: 'Foto 4' })).toBeChecked(); + expect(screen.getByRole('checkbox', { name: 'Foto 1' })).not.toBeChecked(); + expect(screen.getByTestId('bulk-count')).toHaveTextContent('2 foto'); + }); + + it('shows a message when there are no photos', () => { + render(); + + expect(screen.getByTestId('photo-list-empty')).toHaveTextContent('Er zijn geen foto'); + }); +}); + +describe('BulkActionBar', () => { + it('shows nothing without a selection, then the count and the actions, and clears the selection', async () => { + render(); + expect(screen.queryByTestId('bulk-action-bar')).not.toBeInTheDocument(); + + await userEvent.click(screen.getByRole('checkbox', { name: 'Foto 1' })); + expect(screen.getByRole('toolbar', { name: 'Acties op de selectie' })).toBeInTheDocument(); + expect(screen.getByTestId('bulk-action-delete')).toHaveTextContent('Verwijderen'); + + await userEvent.click(screen.getByTestId('bulk-clear')); + expect(screen.queryByTestId('bulk-action-bar')).not.toBeInTheDocument(); + expect(screen.getByRole('checkbox', { name: 'Foto 1' })).not.toBeChecked(); + }); +}); diff --git a/frontend/src/features/media/components/PhotoSelectionList.tsx b/frontend/src/features/media/components/PhotoSelectionList.tsx new file mode 100644 index 0000000..cb87ab6 --- /dev/null +++ b/frontend/src/features/media/components/PhotoSelectionList.tsx @@ -0,0 +1,132 @@ +import { useRef } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Checkbox } from '@/components/ui/checkbox'; +import { selectAll, selectRange, stateOf, type Selection } from '../lib/selection'; + +export interface PhotoUse { + /** The module key, for example `hero`; the screen translates it. */ + module: string; + /** The kind of place, for example `slide`. */ + kind: string; + position?: number | null; + active: boolean; +} + +export interface PhotoItem { + id: string; + thumbnailUrl?: string | null; + name: string; + bytes: number; + createdAt: string; + uses: readonly PhotoUse[]; +} + +interface PhotoSelectionListProps { + items: readonly PhotoItem[]; + selection: Selection; + onSelectionChange: (selection: Selection) => void; + /** Photos that cannot be selected (for example in use during a clean-up). */ + isDisabled?: (item: PhotoItem) => boolean; +} + +function formatBytes(bytes: number, language: string) { + const units = ['B', 'KB', 'MB', 'GB']; + let value = bytes; + let unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit++; + } + return `${new Intl.NumberFormat(language, { maximumFractionDigits: unit === 0 ? 0 : 1 }).format(value)} ${units[unit]}`; +} + +/** + * The photos with a checkbox each: click or Space to toggle, shift-click for a range, a "select all" box in the header + * (with the in-between state), and a live announcement of the count. One component for the library and the clean-up. + */ +export function PhotoSelectionList({ items, selection, onSelectionChange, isDisabled }: PhotoSelectionListProps) { + const { t, i18n } = useTranslation(); + const anchor = useRef(null); + const selectable = items.filter((item) => !isDisabled?.(item)); + const selectableIds = selectable.map((item) => item.id); + const state = stateOf(selection, selectableIds); + const dateFormat = new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium', timeStyle: 'short' }); + + const onItemClick = (id: string, checked: boolean, shift: boolean) => { + onSelectionChange(selectRange(selection, selectableIds, shift ? anchor.current : null, id, checked)); + anchor.current = id; + }; + + const usageLabel = (use: PhotoUse) => { + const place = t(`media.use.${use.kind}`, { defaultValue: use.kind }); + const where = use.position ? `${place} ${use.position}` : place; + return `${t(`media.module.${use.module}`, { defaultValue: use.module })}, ${where}${use.active ? '' : ` (${t('media.use.off')})`}`; + }; + + if (items.length === 0) { + return ( +

+ {t('media.list.empty')} +

+ ); + } + + return ( +
+
+ onSelectionChange(state === 'all' ? new Set() : selectAll(selectableIds))} + /> + {t('media.list.selectAll')} + + {t('media.bulk.selected', { count: selection.size })} + +
+
    + {items.map((item) => { + const disabled = isDisabled?.(item) ?? false; + const labelId = `photo-${item.id}-label`; + return ( +
  • + undefined} + onClick={(event) => onItemClick(item.id, event.currentTarget.checked, event.shiftKey)} + /> + {item.thumbnailUrl ? ( + + ) : ( + + {t('media.list.noThumbnail')} + + )} +
    +

    + {item.name} +

    +

    + {dateFormat.format(new Date(item.createdAt))} · {formatBytes(item.bytes, i18n.language)} +

    +

    + {item.uses.length === 0 ? ( + {t('media.use.none')} + ) : ( + {item.uses.map(usageLabel).join('; ')} + )} +

    +
    +
  • + ); + })} +
+
+ ); +} diff --git a/frontend/src/features/media/lib/selection.test.ts b/frontend/src/features/media/lib/selection.test.ts new file mode 100644 index 0000000..2a2eebf --- /dev/null +++ b/frontend/src/features/media/lib/selection.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest'; +import { emptySelection, prune, selectAll, selectRange, stateOf, toggle } from './selection'; + +const ids = ['a', 'b', 'c', 'd', 'e']; + +describe('selection rules', () => { + it('toggles one photo on and off without changing the original set', () => { + const one = toggle(emptySelection, 'b'); + expect([...one]).toEqual(['b']); + expect([...toggle(one, 'b')]).toEqual([]); + expect(emptySelection.size).toBe(0); + }); + + it('selects a range from the anchor to the target, in either direction', () => { + expect([...selectRange(emptySelection, ids, 'b', 'd', true)].sort()).toEqual(['b', 'c', 'd']); + expect([...selectRange(emptySelection, ids, 'd', 'b', true)].sort()).toEqual(['b', 'c', 'd']); + }); + + it('clears a range when the target is switched off', () => { + const all = selectAll(ids); + expect([...selectRange(all, ids, 'a', 'c', false)].sort()).toEqual(['d', 'e']); + }); + + it('only changes the target without an anchor or with an anchor that is gone', () => { + expect([...selectRange(emptySelection, ids, null, 'c', true)]).toEqual(['c']); + expect([...selectRange(emptySelection, ids, 'zzz', 'c', true)]).toEqual(['c']); + }); + + it('ignores a target that is not in the list', () => { + const selection = new Set(['a']); + expect(selectRange(selection, ids, 'a', 'nope', true)).toBe(selection); + }); + + it('reports none, some and all', () => { + expect(stateOf(emptySelection, ids)).toBe('none'); + expect(stateOf(new Set(['a']), ids)).toBe('some'); + expect(stateOf(selectAll(ids), ids)).toBe('all'); + expect(stateOf(selectAll(ids), [])).toBe('none'); + }); + + it('drops ids that left the list and keeps the same object when nothing changes', () => { + const selection = new Set(['a', 'x']); + expect([...prune(selection, ids)]).toEqual(['a']); + const clean = new Set(['a']); + expect(prune(clean, ids)).toBe(clean); + }); +}); diff --git a/frontend/src/features/media/lib/selection.ts b/frontend/src/features/media/lib/selection.ts new file mode 100644 index 0000000..342b041 --- /dev/null +++ b/frontend/src/features/media/lib/selection.ts @@ -0,0 +1,51 @@ +/** + * The selection of photos in the library, as pure functions over a set of ids. The list component keeps the state; these + * functions are the rules (toggle, range with shift-click, all, none), so they are easy to test. + */ + +export type Selection = ReadonlySet; + +export const emptySelection: Selection = new Set(); + +export function selectAll(ids: readonly string[]): Selection { + return new Set(ids); +} + +export function toggle(selection: Selection, id: string): Selection { + const next = new Set(selection); + if (!next.delete(id)) next.add(id); + return next; +} + +/** + * Shift-click: every photo between the anchor (the last one clicked) and the target gets the state of the target's new + * value. `ids` is the displayed order. Without a known anchor, or an anchor that is no longer in the list, only the + * target changes. + */ +export function selectRange(selection: Selection, ids: readonly string[], anchor: string | null, target: string, value: boolean): Selection { + const to = ids.indexOf(target); + if (to < 0) return selection; + const from = anchor === null ? -1 : ids.indexOf(anchor); + const [start, end] = from < 0 ? [to, to] : [Math.min(from, to), Math.max(from, to)]; + const next = new Set(selection); + for (const id of ids.slice(start, end + 1)) { + if (value) next.add(id); + else next.delete(id); + } + return next; +} + +/** Drops ids that are no longer in the list (after a delete or a filter change). */ +export function prune(selection: Selection, ids: readonly string[]): Selection { + const visible = new Set(ids); + const next = new Set([...selection].filter((id) => visible.has(id))); + return next.size === selection.size ? selection : next; +} + +export type SelectionState = 'none' | 'some' | 'all'; + +export function stateOf(selection: Selection, ids: readonly string[]): SelectionState { + if (ids.length === 0) return 'none'; + const count = ids.filter((id) => selection.has(id)).length; + return count === 0 ? 'none' : count === ids.length ? 'all' : 'some'; +} diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 438d053..694e495 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -781,5 +781,21 @@ "hasChanges": "unsaved changes", "hasErrors": "has errors" } + }, + "media": { + "module": { "hero": "Hero" }, + "use": { "slide": "slide", "none": "Not used", "off": "off" }, + "list": { + "label": "Photos", + "empty": "There are no photos.", + "selectAll": "Select all", + "noThumbnail": "No preview" + }, + "bulk": { + "label": "Actions on the selection", + "selected_one": "{{count}} photo selected", + "selected_other": "{{count}} photos selected", + "clear": "Clear selection" + } } } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index 24729ed..53725a7 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -781,5 +781,21 @@ "hasChanges": "niet-opgeslagen wijzigingen", "hasErrors": "bevat fouten" } + }, + "media": { + "module": { "hero": "Hero" }, + "use": { "slide": "slide", "none": "Niet gebruikt", "off": "uit" }, + "list": { + "label": "Foto's", + "empty": "Er zijn geen foto's.", + "selectAll": "Alles selecteren", + "noThumbnail": "Geen voorbeeld" + }, + "bulk": { + "label": "Acties op de selectie", + "selected_one": "{{count}} foto geselecteerd", + "selected_other": "{{count}} foto's geselecteerd", + "clear": "Selectie wissen" + } } } diff --git a/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs new file mode 100644 index 0000000..4c8a827 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs @@ -0,0 +1,91 @@ +using FluentAssertions; +using SlpModularCms.Core.Media.Library; +using Xunit; + +namespace SlpModularCms.Core.Tests.Media; + +public class MediaLibraryTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 17, 12, 0, 0, TimeSpan.Zero); + + private static MediaLibraryItem Item(int daysOld, bool used = false, long bytes = 1000, string module = "hero") + { + var photo = new MediaPhoto(module, Guid.NewGuid(), bytes, 1600, 1067, Now.AddDays(-daysOld), null); + IReadOnlyList uses = used ? [new MediaUse(module, photo.Id, "slide", 1, true)] : []; + return new MediaLibraryItem(photo, uses); + } + + [Fact] + public void Cleanup_selects_photos_older_than_the_period_newest_first() + { + var items = new[] { Item(3), Item(10), Item(30), Item(8) }; + + var selected = CleanupSelection.Select(items, Now, 7, onlyUnused: false); + + selected.Select(i => (Now - i.Photo.CreatedAt).Days).Should().Equal(8, 10, 30); + } + + [Fact] + public void Cleanup_only_unused_leaves_out_photos_in_use_but_all_photos_does_not() + { + var used = Item(20, used: true); + var unused = Item(20); + + CleanupSelection.Select([used, unused], Now, 7, onlyUnused: true).Should().ContainSingle().Which.Should().Be(unused); + CleanupSelection.Select([used, unused], Now, 7, onlyUnused: false).Should().HaveCount(2); + } + + [Fact] + public void A_photo_used_only_by_an_inactive_slide_still_counts_as_used() + { + var photo = new MediaPhoto("hero", Guid.NewGuid(), 10, 100, 100, Now.AddDays(-40), null); + var item = new MediaLibraryItem(photo, [new MediaUse("hero", photo.Id, "slide", 2, Active: false)]); + + CleanupSelection.Select([item], Now, 7, onlyUnused: true).Should().BeEmpty(); + } + + [Theory] + [InlineData(-5, 1)] + [InlineData(0, 1)] + [InlineData(7, 7)] + [InlineData(365, 365)] + [InlineData(4000, 365)] + public void The_period_stays_inside_the_slider_range(int days, int expected) => CleanupSelection.ClampDays(days).Should().Be(expected); + + [Fact] + public void A_photo_exactly_at_the_boundary_is_not_selected_yet() + { + var item = Item(7); + + CleanupSelection.Select([item], Now, 7, onlyUnused: false).Should().BeEmpty(); + } + + [Fact] + public void Cleanup_bytes_adds_up_the_originals() => CleanupSelection.Bytes([Item(9, bytes: 100), Item(9, bytes: 250)]).Should().Be(350); + + [Fact] + public async Task The_library_merges_all_modules_newest_first_and_attaches_the_uses() + { + var oldHero = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-5), null); + var newGallery = new MediaPhoto("gallery", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-1), null); + var heroUse = new MediaUse("hero", oldHero.Id, "slide", 3, true); + var library = new MediaLibraryService([new FakeProvider("hero", [oldHero], [heroUse]), new FakeProvider("gallery", [newGallery], [])]); + + var items = await library.ListAsync(CancellationToken.None); + + items.Select(i => i.Photo.Module).Should().Equal("gallery", "hero"); + items[0].InUse.Should().BeFalse(); + items[1].Uses.Should().ContainSingle().Which.Should().Be(heroUse); + library.Modules.Should().Equal("gallery", "hero"); + } + + private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses) : IMediaUsageProvider + { + public string Module => module; + + public Task> ListPhotosAsync(CancellationToken cancellationToken) => Task.FromResult>(photos); + + public Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken cancellationToken) + => Task.FromResult>(uses.Where(u => photoIds.Contains(u.PhotoId)).ToList()); + } +} diff --git a/src/SlpModularCms.Core/Media/Library/CleanupSelection.cs b/src/SlpModularCms.Core/Media/Library/CleanupSelection.cs new file mode 100644 index 0000000..6adb8c7 --- /dev/null +++ b/src/SlpModularCms.Core/Media/Library/CleanupSelection.cs @@ -0,0 +1,30 @@ +namespace SlpModularCms.Core.Media.Library; + +/// +/// The photos a clean-up would preselect: uploaded before the period and, by default, not used anywhere. Pure, so it is +/// easy to test. The period is measured from the upload date (assumption 8 of the media-library list). +/// +public static class CleanupSelection +{ + public const int DefaultDays = 7; + public const int MinDays = 1; + public const int MaxDays = 365; + + /// The days kept inside the slider range. + public static int ClampDays(int days) => Math.Clamp(days, MinDays, MaxDays); + + /// Items uploaded more than days before , newest first; with only those no module uses. + public static IReadOnlyList Select(IEnumerable items, DateTimeOffset now, int days, bool onlyUnused) + { + var cutoff = now.AddDays(-ClampDays(days)); + return items + .Where(item => item.Photo.CreatedAt < cutoff) + .Where(item => !onlyUnused || !item.InUse) + .OrderByDescending(item => item.Photo.CreatedAt) + .ThenBy(item => item.Photo.Id) + .ToList(); + } + + /// The bytes the given items take (originals; the variants are counted by the storage service). + public static long Bytes(IEnumerable items) => items.Sum(item => item.Photo.Bytes); +} diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs new file mode 100644 index 0000000..7c34f13 --- /dev/null +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs @@ -0,0 +1,32 @@ +namespace SlpModularCms.Core.Media.Library; + +/// The library over all modules that report photos: one list, newest first, each photo with its uses. Read-only. +public interface IMediaLibraryService +{ + /// All photos of all modules with their uses, newest first. + Task> ListAsync(CancellationToken cancellationToken); + + /// The modules that report photos (the screen warns about a module that is not in this list). + IReadOnlyList Modules { get; } +} + +public sealed class MediaLibraryService(IEnumerable providers) : IMediaLibraryService +{ + private readonly IMediaUsageProvider[] _providers = providers.ToArray(); + + public IReadOnlyList Modules => _providers.Select(p => p.Module).OrderBy(m => m, StringComparer.Ordinal).ToList(); + + public async Task> ListAsync(CancellationToken cancellationToken) + { + var items = new List(); + foreach (var provider in _providers) + { + var photos = await provider.ListPhotosAsync(cancellationToken); + var uses = await provider.ListUsesAsync(photos.Select(p => p.Id).ToList(), cancellationToken); + var byPhoto = uses.ToLookup(u => u.PhotoId); + items.AddRange(photos.Select(photo => new MediaLibraryItem(photo, byPhoto[photo.Id].ToList()))); + } + + return items.OrderByDescending(i => i.Photo.CreatedAt).ThenBy(i => i.Photo.Id).ToList(); + } +} diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs new file mode 100644 index 0000000..99023b3 --- /dev/null +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs @@ -0,0 +1,34 @@ +namespace SlpModularCms.Core.Media.Library; + +/// A photo as the library shows it. The module that owns it fills it; the library only reads. +/// The module key (for example hero); with it names the photo. +/// A public address of a small variant, or null while no variant exists yet. +public sealed record MediaPhoto(string Module, Guid Id, long Bytes, int Width, int Height, DateTimeOffset CreatedAt, string? ThumbnailUrl); + +/// One place where a photo is used. The library shows it as "module, place kind, position" (for example "Hero, slide 3"). +/// What kind of place (for example slide); the screen translates it. +/// The 1-based position inside the place, or null when it has none. +/// False when the place is switched off (still a use: the photo is kept). +public sealed record MediaUse(string Module, Guid PhotoId, string PlaceKind, int? Position, bool Active); + +/// A photo with everything that uses it. +public sealed record MediaLibraryItem(MediaPhoto Photo, IReadOnlyList Uses) +{ + public bool InUse => Uses.Count > 0; +} + +/// +/// What a module tells the media library. Read-only: the library never changes a module's data through this contract +/// (deleting and detaching come in a later step). The answers are computed from the module's own data, never copied. +/// +public interface IMediaUsageProvider +{ + /// The module key, lower case, equal to its media area when it has one. + string Module { get; } + + /// The photos of this module, newest first. + Task> ListPhotosAsync(CancellationToken cancellationToken); + + /// Where the given photos are used (only photos of this module). + Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken cancellationToken); +} diff --git a/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs index 6b93cc4..4fdd8bd 100644 --- a/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs @@ -22,6 +22,7 @@ public static class MediaServiceCollectionExtensions services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); + services.TryAddScoped(); if (!services.Any(d => d.ImplementationType == typeof(ImageProcessorSelfTest))) { services.AddHostedService(); diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs new file mode 100644 index 0000000..8d34332 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs @@ -0,0 +1,51 @@ +using FluentAssertions; +using SlpModularCms.Core.Media.Library; +using SlpModularCms.Modules.Hero.Models; +using SlpModularCms.Modules.Hero.Services; +using Xunit; + +namespace SlpModularCms.Modules.Hero.Tests; + +public class HeroMediaUsageProviderTests +{ + [Fact] + public async Task Lists_the_images_newest_first_with_a_thumbnail_and_reports_one_use_per_slide_with_its_position() + { + using var rig = new HeroTestRig(); + var a = await rig.Upload(HeroTestRig.Photo(seed: 1)); + rig.Time.Now = rig.Time.Now.AddMinutes(5); + var b = await rig.Upload(HeroTestRig.Photo(seed: 2)); + rig.Time.Now = rig.Time.Now.AddMinutes(5); + var unused = await rig.Upload(HeroTestRig.Photo(seed: 3)); + await rig.Service.SaveAsync( + new HeroSaveRequest("Titel", null, null, "single", [], + [new HeroSlideRequest(null, Guid.Parse(b.Id), "tweede"), new HeroSlideRequest(null, Guid.Parse(a.Id), "eerste", IsActive: false)]), + HeroTestRig.Admin, CancellationToken.None); + var provider = new HeroMediaUsageProvider(rig.Repository); + + var photos = await provider.ListPhotosAsync(CancellationToken.None); + var uses = await provider.ListUsesAsync(photos.Select(p => p.Id).ToList(), CancellationToken.None); + + provider.Module.Should().Be("hero"); + photos.Select(p => p.Id).Should().Equal(Guid.Parse(unused.Id), Guid.Parse(b.Id), Guid.Parse(a.Id)); + photos.Should().OnlyContain(p => p.ThumbnailUrl != null && p.ThumbnailUrl.StartsWith("/media/hero/")); + uses.Should().HaveCount(2); + uses.Single(u => u.PhotoId == Guid.Parse(b.Id)).Should().Be(new MediaUse("hero", Guid.Parse(b.Id), "slide", 1, true)); + uses.Single(u => u.PhotoId == Guid.Parse(a.Id)).Should().Be(new MediaUse("hero", Guid.Parse(a.Id), "slide", 2, false)); + uses.Should().NotContain(u => u.PhotoId == Guid.Parse(unused.Id)); + } + + [Fact] + public async Task Reading_changes_nothing() + { + using var rig = new HeroTestRig(); + var image = await rig.Upload(HeroTestRig.Photo()); + var provider = new HeroMediaUsageProvider(rig.Repository); + + await provider.ListPhotosAsync(CancellationToken.None); + await provider.ListUsesAsync([Guid.Parse(image.Id)], CancellationToken.None); + + (await rig.Repository.CountImagesAsync(CancellationToken.None)).Should().Be(1); + rig.Db.ChangeTracker.HasChanges().Should().BeFalse(); + } +} diff --git a/src/SlpModularCms.Modules.Hero/HeroModule.cs b/src/SlpModularCms.Modules.Hero/HeroModule.cs index 1850048..939508c 100644 --- a/src/SlpModularCms.Modules.Hero/HeroModule.cs +++ b/src/SlpModularCms.Modules.Hero/HeroModule.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.DependencyInjection; using SlpModularCms.Core.Hosting; using SlpModularCms.Core.Hosting.Website; using SlpModularCms.Core.Media; +using SlpModularCms.Core.Media.Library; using SlpModularCms.Core.Media.Magick; using SlpModularCms.Core.Modules; using SlpModularCms.Core.Texts; @@ -44,6 +45,7 @@ public class HeroModule : IModule services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs index 76f7e1f..2b2126f 100644 --- a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs +++ b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs @@ -22,6 +22,12 @@ public interface IHeroRepository /// Images whose set is missing or does not match their focus, oldest first (tracked). Task CountImagesAsync(CancellationToken cancellationToken); + /// All images, newest first, not tracked (the media library lists them). + Task> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken); + + /// All slides, not tracked (where each image is used). + Task> GetAllSlidesReadOnlyAsync(CancellationToken cancellationToken); + Task> GetImagesNeedingRenderAsync(CancellationToken cancellationToken); /// Images with a complete set made before the full-frame preview existed (tracked). @@ -76,6 +82,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository public Task CountImagesAsync(CancellationToken cancellationToken) => context.HeroImages.CountAsync(cancellationToken); + public async Task> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken) + => (await context.HeroImages.AsNoTracking().ToListAsync(cancellationToken)).OrderByDescending(i => i.CreatedAt).ToList(); + + public async Task> GetAllSlidesReadOnlyAsync(CancellationToken cancellationToken) + => await context.HeroSlides.AsNoTracking().ToListAsync(cancellationToken); + public async Task> GetImagesNeedingRenderAsync(CancellationToken cancellationToken) => (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsRender).OrderBy(i => i.CreatedAt).ToList(); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs new file mode 100644 index 0000000..e386da1 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs @@ -0,0 +1,55 @@ +using SlpModularCms.Core.Media; +using SlpModularCms.Core.Media.Library; +using SlpModularCms.Modules.Hero.Data.Entities; +using SlpModularCms.Modules.Hero.Repositories; + +namespace SlpModularCms.Modules.Hero.Services; + +/// +/// Tells the media library which hero images exist and where they are used (one use per slide, with its position in the +/// hero). Read-only: nothing of the hero changes through this class. +/// +public class HeroMediaUsageProvider(IHeroRepository repository) : IMediaUsageProvider +{ + public const string SlideKind = "slide"; + + public string Module => HeroMapping.Area; + + public async Task> ListPhotosAsync(CancellationToken cancellationToken) + { + var images = await repository.GetAllImagesReadOnlyAsync(cancellationToken); + return images + .Select(i => new MediaPhoto(Module, i.Id, i.Bytes, i.Width, i.Height, i.CreatedAt, Thumbnail(i))) + .ToList(); + } + + public async Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken cancellationToken) + { + var wanted = photoIds.ToHashSet(); + var slides = await repository.GetAllSlidesReadOnlyAsync(cancellationToken); + + // The position of a slide is its place in its hero, in display order (1-based), also for slides that are off. + var uses = new List(); + foreach (var hero in slides.GroupBy(s => s.HeroId)) + { + var ordered = hero.OrderBy(s => s.SortOrder).ThenBy(s => s.Id).ToList(); + for (var index = 0; index < ordered.Count; index++) + { + var slide = ordered[index]; + if (wanted.Contains(slide.ImageId)) + { + uses.Add(new MediaUse(Module, slide.ImageId, SlideKind, index + 1, slide.IsActive)); + } + } + } + + return uses; + } + + /// The smallest published WebP of the set; null while the set is not cut yet. + private static string? Thumbnail(HeroImage image) + { + var pick = HeroMapping.Published(image).Where(v => v.Type == ImageFormat.WebP.MimeType()).OrderBy(v => v.Width).FirstOrDefault(); + return pick is null || string.IsNullOrEmpty(image.SetHash) ? null : MediaPaths.Url(HeroMapping.Area, image.SetHash, pick.FileName); + } +} -- 2.39.5