From 58f187860404cd1d0a0ec074f587f44ff3bfcdc9 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 14:24:53 +0100 Subject: [PATCH] Media: eis ML-17 (kiezen of uploaden) in requirements, ontwerp en aannamelijst; pure ImagePicker-component Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 3 + .../application-design/application-design.md | 31 +++++ .../inception/requirements/requirements.md | 6 +- .../media/components/ImagePicker.test.tsx | 90 +++++++++++++ .../features/media/components/ImagePicker.tsx | 123 ++++++++++++++++++ .../src/features/media/lib/validateUpload.ts | 11 ++ frontend/src/i18n/locales/en/translation.json | 8 ++ frontend/src/i18n/locales/nl/translation.json | 8 ++ 8 files changed, 278 insertions(+), 2 deletions(-) create mode 100644 frontend/src/features/media/components/ImagePicker.test.tsx create mode 100644 frontend/src/features/media/components/ImagePicker.tsx create mode 100644 frontend/src/features/media/lib/validateUpload.ts 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 d510734..a44c038 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -29,3 +29,6 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 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). | **Answered by the ASF session (2026-11-17, from its code)**: the mosaic shows at most 4 tiles per shoot page, from 2 photos up (layouts for 2, 3, 4). The tile shape is fixed per page by the photo count and order, not chosen per photo: **large** (photo 1) 2x2, desktop about 1:1 (max about 656x632), phone 4:3; **wide** (photo 2 with 3 or 4 photos) 2x1, desktop about 2.2:1 (max about 656x300), phone 3:2; **small** (photos 3 and 4 with 4 photos) 1x1, about 1.04:1 (max about 312x300), phone 1:1. With 2 photos: two large side by side. All object-fit cover (a crop). Widths: large and wide up to about 656 px, small about 312 px; phone half width about 175-300, full width about 350-600; retina variants 480, 640, 960, 1280. **Masonry** (portfolio): natural ratio only, no crop (rounding below half a row of 1/40 of the column width); 1, 2 or 3 columns, column width up to about 427 px; thumb now 800 px wide with the height following the ratio, variants about 480 and 800; the lightbox uses a separate `full`. Used in the design as uses `mosaic-large`, `mosaic-wide`, `mosaic-small` (each with a focus point and a desktop and phone shape) and `masonry` (no crop). | Each answer only adds use definitions. A ratio per photo (not per tile shape) would need a ratio editor. | Application design section 4 | | 25 | **Use definitions in code** (built 2026-11-17, pure data, nothing consumes them yet). | `MediaUseDefinition` (ratios with widths, or natural) and `GalleryUses` for the ASF needs: `mosaic-large` (`tilelarge` 1:1, `tilelargem` 4:3), `mosaic-wide` (`tilewide` 11:5, `tilewidem` 3:2), `mosaic-small` (`tilesmall` 26:25, `tilesmallm` 1:1), `masonry` (`natural`, no crop). Ratio names are letters only (2 to 10) to fit the address allow-list, so a phone shape is a name with an `m` suffix. Widths: large and wide 480, 640, 960, 1280 (retina set from the ASF answer); small 312, 480, 640; masonry 480 and 800. The set hash uses the shared `MediaPaths.SetHash` formula (a test shows it equals the Hero's). Hero's own `wide` (3:2) and `tall` (4:5, not the 2:3 the first design sketch said) stay as built in `VariantPlanner`. | Other widths or ratio values change only the definitions; the ASF `full` (lightbox) variant is not defined yet (it is the full-frame preview ratio). | `Core/Media/Library/MediaUseDefinition.cs` | +| 26 | **Choose or upload everywhere (ML-17)**: how does the Hero upload relate to the library? | Now the Hero keeps its own upload and table; its photos are already in the library list through the provider. When the library owns uploads (phase B) every upload creates exactly one library record (same file = same record by hash). The Hero switches to the shared picker with the phase C migration. Until then the Hero upload flow does not change. | Moving the Hero to the picker earlier (before phase B) would give a single upload path sooner but touches the Hero flow and needs the data model first. | Application design section 10 | +| 27 | **Scope of the shared picker**: single choice or several, and what does it include? | One photo per picker (single choice, radio group). It includes the library photos and one upload button (one file at a time); the Hero's multi-file upload and drag and drop stay on the Hero screen. The picker is pure: the module passes the list and the upload callback. | Several photos at once or drag and drop in the picker: a larger component, added when a module needs it (the gallery will probably need multiple). | `features/media/components/ImagePicker.tsx` | +| 28 | **Uploaded photo not ready yet** in the picker. | It is chosen at once but shows "no preview" until the background renderer has cut its set; an image without a set is not published (as in the Hero today). | Block choosing until it is ready: simpler to explain, slower to work with. | `ImagePicker`, `HeroRenderService` | 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 index fa83759..0df30fa 100644 --- a/aidlc-docs/features/media-library/inception/application-design/application-design.md +++ b/aidlc-docs/features/media-library/inception/application-design/application-design.md @@ -185,3 +185,34 @@ The model and services live in **Core** (`SlpModularCms.Core.Media`, next to the - 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. + +## 10. Choose or upload (ML-17) + +```mermaid +flowchart LR + M[Module screen, for example a hero slide] --> P[ImagePicker] + P -->|choose| L[Library photos] + P -->|upload on the spot| U[Module upload callback] + U --> S[Upload service: guard, limits, store] + S --> R[Background renderer] + S --> L + L --> P + classDef m fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + classDef c fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef s fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + class M m; + class P,L c; + class U,S,R s; +``` + +Text alternative: a module screen uses the picker, which either chooses a library photo or uploads through the module's upload callback; the upload service validates and stores, the renderer cuts variants in the background, and the new photo is in the library and is chosen at once. + +- **Component**: `features/media/components/ImagePicker` (frontend, built as a pure component, not wired anywhere yet). Props: the library photos, the chosen id, `onChange`, an optional `onUpload(file) => Promise`, the upload limit and a short limits text. It is a radio group of thumbnails (arrow keys), plus an upload button; after a successful upload it chooses the new photo. It holds no data and calls nothing by itself, so each module decides what an upload does. +- **Same checks as the Hero**: the quick client checks are one shared function (`validateUpload`: an image, not over the limit); the host repeats and extends them (signature, pixel limit, rate limit, total storage) through the one `IMediaUploadGuard`. A multi-file upload and drag and drop stay module screens' choice (Hero keeps its own). +- **Background processing**: unchanged. An upload stores the original and returns at once; `HeroRenderService` (later a shared renderer) cuts variants. The picker shows a photo without a thumbnail ("no preview") until its set exists, and the library list refreshes while photos are processing. +- **How the Hero upload relates to the library**: + - Now (phase A): the Hero keeps its own upload (`POST /hero/images`) and its `HeroImages` table. Hero photos already appear in the library through the usage provider, so a photo uploaded in the Hero is visible and clean-up-able in the library. The Hero screen does not use the picker yet, and no behaviour changes. + - Phase B: one upload service in Core; **every upload creates exactly one library record** (`MediaAsset`), whichever module's screen it came from; the same file is one record (hash). The Hero's slide then refers to the library photo instead of its own image row. + - Phase C: the existing `HeroImages` are copied as library records with the same ids, hashes and set hashes (design section 6), after which the Hero screen switches to the picker. +- **Other modules** (gallery, mosaic, masonry) use the picker from the start, with their own use definition (`GalleryUses`) deciding the ratios and crops of the chosen photo. +- **Rights and limits**: the same Owner and Administrator rights as the library; the hero upload rate limit (100 per user per hour) applies to the shared upload service. diff --git a/aidlc-docs/features/media-library/inception/requirements/requirements.md b/aidlc-docs/features/media-library/inception/requirements/requirements.md index 0ab42a7..2d91930 100644 --- a/aidlc-docs/features/media-library/inception/requirements/requirements.md +++ b/aidlc-docs/features/media-library/inception/requirements/requirements.md @@ -50,6 +50,7 @@ | 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-17 | **Choose or upload, in every part that needs an image** (new requirement of Bryan, 2026-11-17). In every module that needs an image (Hero, later gallery, mosaic, masonry) the person can upload on the spot, also when the library holds no suitable image yet, and can choose from the existing library photos. An image uploaded on the spot is added to the library automatically and can be chosen everywhere afterwards. | One shared component "choose or upload" (a picker of the library photos plus an upload button) is reused by every module; it applies the same validation, limits and background processing as the Hero upload today; after an upload the new photo is chosen at once; the module keeps its own use (place, crop) of the chosen photo; a photo uploaded in one module is listed and choosable in the others. Until the library owns uploads (phase B) the Hero upload flow stays as it is. | | 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 @@ -87,8 +88,8 @@ | 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 | +| A. Foundations (safe, reversible) | The shared `ImagePicker` component (pure, not wired), 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 (one library record per upload, ML-17), 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 | @@ -101,5 +102,6 @@ | 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 | +| 8 (2026-11-17) Choose or upload in every part that needs an image | ML-17, design section 10 | | 7 Crop per use | ML-11, ML-12, design section 4 | | Boundary: addresses and set hashes | ML-14, NFR-ML-05 | diff --git a/frontend/src/features/media/components/ImagePicker.test.tsx b/frontend/src/features/media/components/ImagePicker.test.tsx new file mode 100644 index 0000000..48f9c8f --- /dev/null +++ b/frontend/src/features/media/components/ImagePicker.test.tsx @@ -0,0 +1,90 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { useState } from 'react'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import i18n from '@/i18n/config'; +import { validateUpload } from '../lib/validateUpload'; +import { ImagePicker } from './ImagePicker'; +import type { PhotoItem } from './PhotoSelectionList'; + +const photo = (id: string, name: string): PhotoItem => ({ id, name, bytes: 1, createdAt: '2026-11-17T10:00:00Z', uses: [], thumbnailUrl: null }); +const items = [photo('a', 'Foto A'), photo('b', 'Foto B')]; +const MB = 1024 * 1024; + +function Harness({ onUpload, initial = null }: { onUpload?: (file: File) => Promise; initial?: string | null }) { + const [value, setValue] = useState(initial); + return ; +} + +const file = (name = 'x.jpg', type = 'image/jpeg', size = 1000) => new File([new Uint8Array(size)], name, { type }); + +beforeEach(async () => { + await i18n.changeLanguage('nl'); +}); + +describe('validateUpload', () => { + it.each([ + [{ type: 'image/jpeg', size: 100 }, null], + [{ type: '', size: 100 }, null], + [{ type: 'application/pdf', size: 100 }, 'notAnImage'], + [{ type: 'image/png', size: 10 * MB + 1 }, 'tooLarge'], + [{ type: 'image/png', size: 10 * MB }, null], + ])('%j gives %s', (f, expected) => expect(validateUpload(f, 10 * MB)).toBe(expected)); +}); + +describe('ImagePicker', () => { + it('chooses a library photo as a radio group, with the arrow keys', async () => { + render(); + + expect(screen.getByRole('radiogroup', { name: 'Afbeelding van slide 1' })).toBeInTheDocument(); + expect(screen.getByRole('radio', { name: 'Foto A' })).toBeChecked(); + screen.getByRole('radio', { name: 'Foto A' }).focus(); + await userEvent.keyboard('{ArrowRight}'); + + expect(screen.getByRole('radio', { name: 'Foto B' })).toBeChecked(); + }); + + it('has no upload button when the module gives no upload', () => { + render(); + + expect(screen.queryByTestId('picker-upload-button')).not.toBeInTheDocument(); + }); + + it('uploads on the spot, then chooses the new photo', async () => { + const upload = vi.fn().mockResolvedValue(photo('c', 'Nieuwe foto')); + render(); + + await userEvent.upload(screen.getByTestId('picker-file'), file()); + + await waitFor(() => expect(upload).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(screen.getByTestId('picker-upload-button')).toHaveTextContent('Afbeelding uploaden')); + expect(screen.queryByTestId('picker-problem')).not.toBeInTheDocument(); + }); + + it('refuses what the host would refuse, without calling the upload', async () => { + const upload = vi.fn(); + render(); + + await userEvent.upload(screen.getByTestId('picker-file'), file('x.pdf', 'application/pdf'), { applyAccept: false }); + expect(screen.getByTestId('picker-problem')).toHaveTextContent('geen afbeelding'); + + await userEvent.upload(screen.getByTestId('picker-file'), file('big.jpg', 'image/jpeg', 10 * MB + 1)); + expect(screen.getByTestId('picker-problem')).toHaveTextContent('maximaal 10 MB'); + expect(upload).not.toHaveBeenCalled(); + }); + + it('shows a message when the upload fails and keeps the current choice', async () => { + render( Promise.reject(new Error('nope'))} initial="b" />); + + await userEvent.upload(screen.getByTestId('picker-file'), file()); + + expect(await screen.findByTestId('picker-problem')).toHaveTextContent('niet gelukt'); + expect(screen.getByRole('radio', { name: 'Foto B' })).toBeChecked(); + }); + + it('says so when the library is empty', () => { + render(); + + expect(screen.getByTestId('picker-empty')).toHaveTextContent('nog geen foto'); + }); +}); diff --git a/frontend/src/features/media/components/ImagePicker.tsx b/frontend/src/features/media/components/ImagePicker.tsx new file mode 100644 index 0000000..47ef627 --- /dev/null +++ b/frontend/src/features/media/components/ImagePicker.tsx @@ -0,0 +1,123 @@ +import { useId, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { ImagePlus } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { cn } from '@/lib/utils'; +import { validateUpload } from '../lib/validateUpload'; +import type { PhotoItem } from './PhotoSelectionList'; + +interface ImagePickerProps { + /** The photos of the library to choose from, newest first. */ + items: readonly PhotoItem[]; + /** The id of the chosen photo, or null. */ + value: string | null; + onChange: (id: string) => void; + /** + * Uploads one file and answers with the photo as the library lists it. The module decides how (the hero uses its own + * upload and background processing); the picker only shows the state and chooses the result. Without it there is no + * upload button. + */ + onUpload?: (file: File) => Promise; + /** The largest file the host accepts, in bytes. */ + maxUploadBytes: number; + /** A short line about formats and limits, shown under the buttons. */ + limitsText?: string; + /** Accessible name of the group (what the image is for, for example "Image of slide 2"). */ + label: string; +} + +/** + * "Choose an image or upload one": the photos of the library as a group of radio buttons (arrow keys move and choose) + * and an upload button that adds the new photo to the library and chooses it at once. One component for every module that + * needs an image. It holds no data of its own and calls nothing by itself: the module passes the list and the upload. + */ +export function ImagePicker({ items, value, onChange, onUpload, maxUploadBytes, limitsText, label }: ImagePickerProps) { + const { t } = useTranslation(); + const groupName = useId(); + const fileInput = useRef(null); + const [uploading, setUploading] = useState(false); + const [problem, setProblem] = useState(null); + + const upload = async (file: File | undefined) => { + if (!file || !onUpload || uploading) return; + const refused = validateUpload(file, maxUploadBytes); + if (refused) { + setProblem(refused === 'tooLarge' ? t('media.picker.tooLarge', { max: Math.round(maxUploadBytes / (1024 * 1024)) }) : t('media.picker.notAnImage')); + return; + } + setProblem(null); + setUploading(true); + try { + const photo = await onUpload(file); + onChange(photo.id); + } catch { + setProblem(t('media.picker.failed')); + } finally { + setUploading(false); + if (fileInput.current) fileInput.current.value = ''; + } + }; + + return ( +
+ {onUpload && ( +
+ void upload(event.target.files?.[0])} + /> + + {limitsText &&

{limitsText}

} +
+ )} + {problem && ( +

+ {problem} +

+ )} + {items.length === 0 ? ( +

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

+ ) : ( +
+ {items.map((item) => ( + + ))} +
+ )} +
+ ); +} diff --git a/frontend/src/features/media/lib/validateUpload.ts b/frontend/src/features/media/lib/validateUpload.ts new file mode 100644 index 0000000..1666025 --- /dev/null +++ b/frontend/src/features/media/lib/validateUpload.ts @@ -0,0 +1,11 @@ +export type UploadProblem = 'notAnImage' | 'tooLarge'; + +/** + * The quick checks before a file is sent (the same two the hero upload makes): it must be an image and not over the + * limit. The host checks everything again (signature, pixels, rate); this only spares sending a file it will refuse. + */ +export function validateUpload(file: { type: string; size: number }, maxBytes: number): UploadProblem | null { + if (file.type !== '' && !file.type.startsWith('image/')) return 'notAnImage'; + if (file.size > maxBytes) return 'tooLarge'; + return null; +} diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index c6c8b7e..655e684 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -829,6 +829,14 @@ "summary_one": "{{count}} photo ({{size}}) qualifies.", "summary_other": "{{count}} photos ({{size}}) qualify.", "selectedSize": "Selected: {{size}}" + }, + "picker": { + "upload": "Upload an image", + "uploading": "Uploading...", + "empty": "There are no photos in the library yet. Upload one.", + "notAnImage": "This file is not an image.", + "tooLarge": "This file is too large (at most {{max}} MB).", + "failed": "Uploading failed. Try again." } } } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index ee9c693..b1e03f8 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -829,6 +829,14 @@ "summary_one": "{{count}} foto ({{size}}) komt in aanmerking.", "summary_other": "{{count}} foto's ({{size}}) komen in aanmerking.", "selectedSize": "Geselecteerd: {{size}}" + }, + "picker": { + "upload": "Afbeelding uploaden", + "uploading": "Bezig met uploaden...", + "empty": "Er staan nog geen foto's in de bibliotheek. Upload er een.", + "notAnImage": "Dit bestand is geen afbeelding.", + "tooLarge": "Dit bestand is te groot (maximaal {{max}} MB).", + "failed": "Uploaden is niet gelukt. Probeer het opnieuw." } } }