From caa178a58c00d9daacbe5fcbc7196d8b23f63f23 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 14:12:15 +0100 Subject: [PATCH 01/22] Mediabibliotheek: endpoints (foto's, opslag, opruimvoorbeeld) en scherm; ASF-verhoudingen in ontwerp en aannamelijst Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 2 +- .../application-design/application-design.md | 11 + frontend/src/components/layout/Sidebar.tsx | 10 +- .../media/components/CleanupDialog.tsx | 112 +++++++ .../media/components/PhotoSelectionList.tsx | 12 +- .../media/components/StorageMeter.tsx | 43 +++ frontend/src/features/media/lib/format.ts | 12 + .../src/features/media/lib/toPhotoItem.ts | 15 + frontend/src/features/media/mocks/handlers.ts | 58 ++++ .../media/pages/MediaLibraryPage.test.tsx | 84 +++++ .../features/media/pages/MediaLibraryPage.tsx | 57 ++++ frontend/src/features/media/services/hooks.ts | 32 ++ frontend/src/features/media/services/types.ts | 41 +++ frontend/src/i18n/locales/en/translation.json | 39 ++- frontend/src/i18n/locales/nl/translation.json | 39 ++- frontend/src/mocks/index.ts | 3 +- frontend/src/router.tsx | 13 + openapi/slpsoftware.v1.json | 304 ++++++++++++++++++ .../Media/MediaLibraryControllerTests.cs | 87 +++++ .../Media/MediaStorageUsageTests.cs | 49 +++ .../Hosting/ServiceCollectionExtensions.cs | 2 + .../Media/Library/MediaLibraryController.cs | 63 ++++ .../Media/Library/MediaStorageUsage.cs | 72 +++++ .../Media/MediaServiceCollectionExtensions.cs | 2 +- 24 files changed, 1141 insertions(+), 21 deletions(-) create mode 100644 frontend/src/features/media/components/CleanupDialog.tsx create mode 100644 frontend/src/features/media/components/StorageMeter.tsx create mode 100644 frontend/src/features/media/lib/format.ts create mode 100644 frontend/src/features/media/lib/toPhotoItem.ts create mode 100644 frontend/src/features/media/mocks/handlers.ts create mode 100644 frontend/src/features/media/pages/MediaLibraryPage.test.tsx create mode 100644 frontend/src/features/media/pages/MediaLibraryPage.tsx create mode 100644 frontend/src/features/media/services/hooks.ts create mode 100644 frontend/src/features/media/services/types.ts create mode 100644 src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs create mode 100644 src/SlpModularCms.Core.Tests/Media/MediaStorageUsageTests.cs create mode 100644 src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs create mode 100644 src/SlpModularCms.Core/Media/Library/MediaStorageUsage.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 e4d56f5..2c0070a 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -27,4 +27,4 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 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 | +| 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 | 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 24fb79e..fa83759 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 @@ -114,6 +114,17 @@ Text alternative: one photo has uses in Hero (wide and tall share one set), a mo - `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. +- **Use definitions from the ASF site (2026-11-17, see assumption 24)**: + +| Use | Ratio (desktop / phone) | Widths | Crop | +|---|---|---|---| +| `hero-wide`, `hero-tall` | 3:2 / 2:3 (as built) | as built | focus per use | +| `mosaic-large` (photo 1) | about 1:1 / 4:3 | up to 656, retina 480, 640, 960, 1280 | focus point | +| `mosaic-wide` (photo 2 of 3 or 4) | about 2.2:1 / 3:2 | up to 656, same retina set | focus point | +| `mosaic-small` (photos 3 and 4 of 4) | about 1.04:1 / 1:1 | up to 312, retina set | focus point | +| `masonry` | natural | about 480 and 800 (thumb), plus `full` for the lightbox | none | + +The mosaic tile shape is fixed per page by the number and order of the photos, so a use is `(page, tile role)`; a photo can have a different crop in each role. Phone shapes differ from desktop shapes, so a mosaic use carries two ratios (desktop and phone), like Hero's `wide` and `tall`. - 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 diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index ca75982..e5c84c4 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -1,6 +1,6 @@ import { Link } from '@tanstack/react-router'; import { useTranslation } from 'react-i18next'; -import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon } from 'lucide-react'; +import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon, Images } from 'lucide-react'; import type { LucideIcon } from 'lucide-react'; import { cn } from '@/lib/utils'; import { useAuth } from '@/features/auth/context/auth-context'; @@ -38,6 +38,14 @@ const NAV_ITEMS: NavItem[] = [ roles: ['Owner', 'Administrator'], requiredModule: 'Hero', }, + { + to: '/media', + labelKey: 'nav.media', + icon: Images, + testId: 'nav-media', + roles: ['Owner', 'Administrator'], + requiredModule: 'Hero', + }, { to: '/offerings', labelKey: 'nav.offerings', diff --git a/frontend/src/features/media/components/CleanupDialog.tsx b/frontend/src/features/media/components/CleanupDialog.tsx new file mode 100644 index 0000000..11b4974 --- /dev/null +++ b/frontend/src/features/media/components/CleanupDialog.tsx @@ -0,0 +1,112 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { CheckboxField } from '@/components/ui/checkbox'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { Label } from '@/components/ui/label'; +import { formatBytes } from '../lib/format'; +import { selectAll, type Selection } from '../lib/selection'; +import { toPhotoItem } from '../lib/toPhotoItem'; +import { useCleanupPreview } from '../services/hooks'; +import { BulkActionBar } from './BulkActionBar'; +import { PhotoSelectionList } from './PhotoSelectionList'; + +const DEFAULT_DAYS = 7; +const MIN_DAYS = 1; +const MAX_DAYS = 365; + +/** + * "Clean up": the photos older than the chosen number of days (by default 7), by default only the unused ones, newest + * first and all selected so single photos can be taken out. This step is a PREVIEW: nothing is deleted yet (deleting + * comes after the assumptions have been checked). + */ +export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) { + const { t, i18n } = useTranslation(); + const [days, setDays] = useState(DEFAULT_DAYS); + const [debouncedDays, setDebouncedDays] = useState(DEFAULT_DAYS); + const [onlyUnused, setOnlyUnused] = useState(true); + // Everything starts selected: the person only takes photos OUT. A new period or filter starts again with all in. + const [excluded, setExcluded] = useState>(new Set()); + const timer = useRef | undefined>(undefined); + const preview = useCleanupPreview(debouncedDays, onlyUnused, open); + + useEffect(() => () => clearTimeout(timer.current), []); + + const changeDays = (value: number) => { + setDays(value); + clearTimeout(timer.current); + timer.current = setTimeout(() => { + setDebouncedDays(value); + setExcluded(new Set()); + }, 300); + }; + + const photos = preview.data?.photos; + const ids = useMemo(() => (photos ?? []).map((p) => p.id), [photos]); + const selection = useMemo(() => selectAll(ids.filter((id) => !excluded.has(id))), [ids, excluded]); + const setSelection = (next: Selection) => setExcluded(new Set(ids.filter((id) => !next.has(id)))); + + const items = useMemo(() => (photos ?? []).map((p) => toPhotoItem(p, t)), [photos, t]); + const selectedBytes = (photos ?? []).filter((p) => selection.has(p.id)).reduce((sum, p) => sum + p.bytes, 0); + + return ( + + + + {t('media.cleanup.title')} + {t('media.cleanup.description')} + + +
+
+ + changeDays(Number(event.target.value))} + className="w-full accent-primary" + data-testid="cleanup-days" + /> +
+ { + setOnlyUnused(event.target.checked); + setExcluded(new Set()); + }} + label={t('media.cleanup.onlyUnused')} + data-testid="cleanup-only-unused" + /> + +

+ {t('media.cleanup.previewNote')} +

+ + {preview.isError && ( +

+ {t('media.error')} +

+ )} + {preview.isPending &&

{t('media.loading')}

} + {preview.data && ( + <> +

+ {t('media.cleanup.summary', { count: preview.data.count, size: formatBytes(preview.data.bytes, i18n.language) })} +

+ + setSelection(new Set())} + summary={t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) })} + /> + + )} +
+
+
+ ); +} diff --git a/frontend/src/features/media/components/PhotoSelectionList.tsx b/frontend/src/features/media/components/PhotoSelectionList.tsx index cb87ab6..d9f7a46 100644 --- a/frontend/src/features/media/components/PhotoSelectionList.tsx +++ b/frontend/src/features/media/components/PhotoSelectionList.tsx @@ -1,6 +1,7 @@ import { useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { Checkbox } from '@/components/ui/checkbox'; +import { formatBytes } from '../lib/format'; import { selectAll, selectRange, stateOf, type Selection } from '../lib/selection'; export interface PhotoUse { @@ -29,17 +30,6 @@ interface PhotoSelectionListProps { 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. diff --git a/frontend/src/features/media/components/StorageMeter.tsx b/frontend/src/features/media/components/StorageMeter.tsx new file mode 100644 index 0000000..a9509b8 --- /dev/null +++ b/frontend/src/features/media/components/StorageMeter.tsx @@ -0,0 +1,43 @@ +import { useTranslation } from 'react-i18next'; +import { cn } from '@/lib/utils'; +import { formatBytes } from '../lib/format'; +import type { MediaStorageDto } from '../services/types'; + +/** Used space against the limit, with a warning at 80 percent and a clear message at the limit (colour plus text). */ +export function StorageMeter({ storage }: { storage: MediaStorageDto }) { + const { t, i18n } = useTranslation(); + const hasLimit = storage.limitBytes > 0; + const percent = hasLimit ? Math.min(100, Math.round((storage.usedBytes / storage.limitBytes) * 100)) : 0; + const used = formatBytes(storage.usedBytes, i18n.language); + + return ( +
+

+ {t('media.storage.title')} +

+

+ {hasLimit ? t('media.storage.usedOf', { used, limit: formatBytes(storage.limitBytes, i18n.language), percent }) : t('media.storage.used', { used })} +

+ {hasLimit && ( +
+
+
+ )} + {storage.level !== 'ok' && ( +

+ {storage.level === 'full' ? t('media.storage.full') : t('media.storage.warning', { percent: storage.warningPercent })} +

+ )} +
+ ); +} diff --git a/frontend/src/features/media/lib/format.ts b/frontend/src/features/media/lib/format.ts new file mode 100644 index 0000000..095d155 --- /dev/null +++ b/frontend/src/features/media/lib/format.ts @@ -0,0 +1,12 @@ +const UNITS = ['B', 'KB', 'MB', 'GB', 'TB']; + +/** A size in bytes as a short, localised text (1,5 MB). */ +export function formatBytes(bytes: number, language: string): string { + let value = Math.max(0, 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]}`; +} diff --git a/frontend/src/features/media/lib/toPhotoItem.ts b/frontend/src/features/media/lib/toPhotoItem.ts new file mode 100644 index 0000000..8607e91 --- /dev/null +++ b/frontend/src/features/media/lib/toPhotoItem.ts @@ -0,0 +1,15 @@ +import type { TFunction } from 'i18next'; +import type { PhotoItem } from '../components/PhotoSelectionList'; +import type { MediaPhotoDto } from '../services/types'; + +/** The list shows a neutral name (the size of the photo): photos do not store a file name yet (assumption 21). */ +export function toPhotoItem(photo: MediaPhotoDto, t: TFunction): PhotoItem { + return { + id: photo.id, + thumbnailUrl: photo.thumbnailUrl, + name: t('media.list.photoName', { width: photo.width, height: photo.height }), + bytes: photo.bytes, + createdAt: photo.createdAt, + uses: photo.uses, + }; +} diff --git a/frontend/src/features/media/mocks/handlers.ts b/frontend/src/features/media/mocks/handlers.ts new file mode 100644 index 0000000..4db340b --- /dev/null +++ b/frontend/src/features/media/mocks/handlers.ts @@ -0,0 +1,58 @@ +import { http, HttpResponse } from 'msw'; +import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPhotoDto, MediaStorageDto } from '@/features/media/services/types'; + +const daysAgo = (days: number) => new Date(Date.now() - days * 86_400_000).toISOString(); + +export const seedPhotos = (): MediaPhotoDto[] => [ + { + id: 'hero:11111111-1111-1111-1111-111111111111', + module: 'hero', + bytes: 2_400_000, + width: 3000, + height: 2000, + createdAt: daysAgo(1), + thumbnailUrl: '/media/hero/0123456789abcdef/wide-480.webp', + uses: [{ module: 'hero', kind: 'slide', position: 1, active: true }], + }, + { + id: 'hero:22222222-2222-2222-2222-222222222222', + module: 'hero', + bytes: 1_800_000, + width: 2400, + height: 1600, + createdAt: daysAgo(12), + thumbnailUrl: null, + uses: [], + }, + { + id: 'hero:33333333-3333-3333-3333-333333333333', + module: 'hero', + bytes: 900_000, + width: 1600, + height: 1067, + createdAt: daysAgo(30), + thumbnailUrl: null, + uses: [{ module: 'hero', kind: 'slide', position: 2, active: false }], + }, +]; + +export const seedStorage = (): MediaStorageDto => ({ usedBytes: 100_000_000, limitBytes: 2_147_483_648, level: 'ok', warningPercent: 80 }); + +export const mediaHandlers = [ + http.get('*/media-library/photos', () => HttpResponse.json({ photos: seedPhotos(), modules: ['hero'] } satisfies MediaLibraryDto)), + http.get('*/media-library/storage', () => HttpResponse.json(seedStorage())), + http.get('*/media-library/cleanup-preview', ({ request }) => { + const url = new URL(request.url); + const days = Number(url.searchParams.get('days') ?? 7); + const onlyUnused = url.searchParams.get('onlyUnused') !== 'false'; + const cutoff = Date.now() - days * 86_400_000; + const photos = seedPhotos().filter((p) => new Date(p.createdAt).getTime() < cutoff && (!onlyUnused || p.uses.length === 0)); + return HttpResponse.json({ + days, + onlyUnused, + count: photos.length, + bytes: photos.reduce((sum, p) => sum + p.bytes, 0), + photos, + } satisfies MediaCleanupPreviewDto); + }), +]; diff --git a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx new file mode 100644 index 0000000..b8a4ffb --- /dev/null +++ b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx @@ -0,0 +1,84 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { http, HttpResponse } from 'msw'; +import { screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import i18n from '@/i18n/config'; +import { server } from '@/mocks/server'; +import { renderWithProviders } from '@/test/utils'; +import { seedStorage } from '../mocks/handlers'; +import { MediaLibraryPage } from './MediaLibraryPage'; + +beforeEach(async () => { + await i18n.changeLanguage('nl'); +}); + +describe('MediaLibraryPage', () => { + it('lists the photos newest first with where each is used, and the storage', async () => { + renderWithProviders(); + + const list = await screen.findByTestId('photo-selection-list'); + const rows = within(list).getAllByRole('listitem'); + expect(rows).toHaveLength(3); + expect(within(rows[0]!).getByText('Hero, slide 1')).toBeInTheDocument(); + expect(within(rows[1]!).getByText('Niet gebruikt')).toBeInTheDocument(); + expect(within(rows[2]!).getByText('Hero, slide 2 (uit)')).toBeInTheDocument(); + expect(await screen.findByTestId('storage-text')).toHaveTextContent('van'); + expect(screen.queryByTestId('storage-warning')).not.toBeInTheDocument(); + }); + + it('warns when the storage is nearly full and says so when it is full', async () => { + server.use(http.get('*/media-library/storage', () => HttpResponse.json({ ...seedStorage(), usedBytes: 1_800_000_000, level: 'warning' }))); + const { unmount } = renderWithProviders(); + expect(await screen.findByTestId('storage-warning')).toHaveTextContent('80%'); + unmount(); + + server.use(http.get('*/media-library/storage', () => HttpResponse.json({ ...seedStorage(), usedBytes: 2_147_483_648, level: 'full' }))); + renderWithProviders(); + expect(await screen.findByTestId('storage-warning')).toHaveTextContent('vol'); + }); + + it('selects photos and shows the bulk bar without any delete action yet', async () => { + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getAllByRole('checkbox', { name: /Foto 3000/ })[0]!); + + expect(await screen.findByTestId('bulk-count')).toHaveTextContent('1 foto geselecteerd'); + expect(screen.queryByTestId('bulk-action-delete')).not.toBeInTheDocument(); + }); + + it('opens the clean-up: older than 7 days, only unused, all selected, newest first, and nothing is deleted', async () => { + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getByTestId('cleanup-open')); + + const dialog = await screen.findByTestId('cleanup-dialog'); + expect(within(dialog).getByTestId('cleanup-only-unused')).toBeChecked(); + expect(await within(dialog).findByTestId('cleanup-summary')).toHaveTextContent('1 foto'); + expect(within(dialog).getByTestId('cleanup-preview-note')).toHaveTextContent('nog niets verwijderd'); + const boxes = within(dialog).getAllByRole('checkbox', { name: /Foto/ }); + expect(boxes).toHaveLength(1); + await waitFor(() => expect(boxes[0]).toBeChecked()); + }); + + it('includes photos in use when "only unused" is switched off', async () => { + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + await userEvent.click(screen.getByTestId('cleanup-open')); + const dialog = await screen.findByTestId('cleanup-dialog'); + await within(dialog).findByTestId('cleanup-summary'); + + await userEvent.click(within(dialog).getByTestId('cleanup-only-unused')); + + await waitFor(() => expect(within(dialog).getByTestId('cleanup-summary')).toHaveTextContent('2 foto')); + expect(within(dialog).getAllByRole('checkbox', { name: /Foto/ })).toHaveLength(2); + }); + + it('shows an error when the library cannot be loaded', async () => { + server.use(http.get('*/media-library/photos', () => new HttpResponse(null, { status: 500 }))); + renderWithProviders(); + + expect(await screen.findByTestId('media-error')).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/features/media/pages/MediaLibraryPage.tsx b/frontend/src/features/media/pages/MediaLibraryPage.tsx new file mode 100644 index 0000000..d2b574f --- /dev/null +++ b/frontend/src/features/media/pages/MediaLibraryPage.tsx @@ -0,0 +1,57 @@ +import { useMemo, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Eraser } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { BulkActionBar } from '../components/BulkActionBar'; +import { CleanupDialog } from '../components/CleanupDialog'; +import { PhotoSelectionList } from '../components/PhotoSelectionList'; +import { StorageMeter } from '../components/StorageMeter'; +import { emptySelection, prune, type Selection } from '../lib/selection'; +import { toPhotoItem } from '../lib/toPhotoItem'; +import { useMediaPhotos, useMediaStorage } from '../services/hooks'; + +/** + * The media library: every photo of every module, newest first, with where it is used; the storage against its limit; + * the "Clean up" preview. Selecting works already (bulk actions come with deleting, after the assumptions are checked). + */ +export function MediaLibraryPage() { + const { t } = useTranslation(); + const photos = useMediaPhotos(); + const storage = useMediaStorage(); + const [chosen, setSelection] = useState(emptySelection); + const [cleanupOpen, setCleanupOpen] = useState(false); + + const items = useMemo(() => (photos.data?.photos ?? []).map((p) => toPhotoItem(p, t)), [photos.data, t]); + // Photos that left the list (after a reload) drop out of the selection. + const selection = useMemo(() => prune(chosen, items.map((i) => i.id)), [chosen, items]); + + return ( +
+
+

{t('media.page.title')}

+ +
+ + {storage.data && } + + {photos.isError && ( +

+ {t('media.error')} +

+ )} + {photos.isPending &&

{t('media.loading')}

} + {photos.data && photos.data.modules.length === 0 && ( +

+ {t('media.page.noModules')} +

+ )} + {photos.data && } + setSelection(emptySelection)} /> + + +
+ ); +} diff --git a/frontend/src/features/media/services/hooks.ts b/frontend/src/features/media/services/hooks.ts new file mode 100644 index 0000000..fa7e09c --- /dev/null +++ b/frontend/src/features/media/services/hooks.ts @@ -0,0 +1,32 @@ +import { keepPreviousData, useQuery } from '@tanstack/react-query'; +import { api } from '@/lib/api-client'; +import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaStorageDto } from './types'; + +export const MEDIA_KEY = ['media-library']; + +/** All photos of all modules, newest first, with where each is used. */ +export function useMediaPhotos() { + return useQuery({ + queryKey: [...MEDIA_KEY, 'photos'], + queryFn: () => api.get('/api/v1/media-library/photos'), + }); +} + +/** The space the media directory takes against its limit. */ +export function useMediaStorage() { + return useQuery({ + queryKey: [...MEDIA_KEY, 'storage'], + queryFn: () => api.get('/api/v1/media-library/storage'), + staleTime: 30_000, + }); +} + +/** What a clean-up with these settings would select. A preview: nothing is deleted. */ +export function useCleanupPreview(days: number, onlyUnused: boolean, enabled: boolean) { + return useQuery({ + queryKey: [...MEDIA_KEY, 'cleanup-preview', days, onlyUnused], + queryFn: () => api.get(`/api/v1/media-library/cleanup-preview?days=${days}&onlyUnused=${onlyUnused}`), + enabled, + placeholderData: keepPreviousData, + }); +} diff --git a/frontend/src/features/media/services/types.ts b/frontend/src/features/media/services/types.ts new file mode 100644 index 0000000..c577e5c --- /dev/null +++ b/frontend/src/features/media/services/types.ts @@ -0,0 +1,41 @@ +export interface MediaUseDto { + module: string; + kind: string; + position: number | null; + active: boolean; +} + +export interface MediaPhotoDto { + /** `module:guid`, unique over all modules. */ + id: string; + module: string; + bytes: number; + width: number; + height: number; + createdAt: string; + thumbnailUrl: string | null; + uses: MediaUseDto[]; +} + +export interface MediaLibraryDto { + photos: MediaPhotoDto[]; + modules: string[]; +} + +export type MediaStorageLevel = 'ok' | 'warning' | 'full'; + +export interface MediaStorageDto { + usedBytes: number; + /** 0 means no limit. */ + limitBytes: number; + level: MediaStorageLevel; + warningPercent: number; +} + +export interface MediaCleanupPreviewDto { + days: number; + onlyUnused: boolean; + count: number; + bytes: number; + photos: MediaPhotoDto[]; +} diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 694e495..c6c8b7e 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -17,6 +17,7 @@ "openMenu": "Open navigation", "closeMenu": "Close navigation", "hero": "Hero", + "media": "Media library", "unreadMessages_one": "{{count}} new message", "unreadMessages_other": "{{count}} new messages" }, @@ -783,19 +784,51 @@ } }, "media": { - "module": { "hero": "Hero" }, - "use": { "slide": "slide", "none": "Not used", "off": "off" }, + "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" + "noThumbnail": "No preview", + "photoName": "Photo {{width}} × {{height}}" }, "bulk": { "label": "Actions on the selection", "selected_one": "{{count}} photo selected", "selected_other": "{{count}} photos selected", "clear": "Clear selection" + }, + "loading": "Loading...", + "error": "The media library could not be loaded.", + "page": { + "title": "Media library", + "noModules": "No module reports photos yet." + }, + "storage": { + "title": "Storage", + "used": "{{used}} used", + "usedOf": "{{used}} of {{limit}} used ({{percent}}%)", + "warning": "Storage is more than {{percent}}% full. Clean up photos before the limit is reached.", + "full": "Storage is full. No more photos can be uploaded until there is room." + }, + "cleanup": { + "open": "Clean up", + "title": "Clean up", + "description": "Photos older than the number of days below, newest first. Take out the photos you want to keep.", + "days_one": "Older than {{count}} day", + "days_other": "Older than {{count}} days", + "onlyUnused": "Only unused photos", + "previewNote": "This is a preview: nothing is deleted yet.", + "summary_one": "{{count}} photo ({{size}}) qualifies.", + "summary_other": "{{count}} photos ({{size}}) qualify.", + "selectedSize": "Selected: {{size}}" } } } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index 53725a7..ee9c693 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -17,6 +17,7 @@ "openMenu": "Navigatie openen", "closeMenu": "Navigatie sluiten", "hero": "Hero", + "media": "Mediabibliotheek", "unreadMessages_one": "{{count}} nieuw bericht", "unreadMessages_other": "{{count}} nieuwe berichten" }, @@ -783,19 +784,51 @@ } }, "media": { - "module": { "hero": "Hero" }, - "use": { "slide": "slide", "none": "Niet gebruikt", "off": "uit" }, + "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" + "noThumbnail": "Geen voorbeeld", + "photoName": "Foto {{width}} × {{height}}" }, "bulk": { "label": "Acties op de selectie", "selected_one": "{{count}} foto geselecteerd", "selected_other": "{{count}} foto's geselecteerd", "clear": "Selectie wissen" + }, + "loading": "Laden...", + "error": "De mediabibliotheek kon niet worden geladen.", + "page": { + "title": "Mediabibliotheek", + "noModules": "Er is nog geen module die foto's meldt." + }, + "storage": { + "title": "Opslag", + "used": "{{used}} in gebruik", + "usedOf": "{{used}} van {{limit}} in gebruik ({{percent}}%)", + "warning": "De opslag is voor meer dan {{percent}}% vol. Ruim foto's op voordat de limiet bereikt is.", + "full": "De opslag is vol. Er kunnen geen foto's meer worden geüpload tot er ruimte is." + }, + "cleanup": { + "open": "Opruimen", + "title": "Opruimen", + "description": "Foto's die ouder zijn dan het aantal dagen hieronder, nieuwste eerst. Haal foto's uit de selectie die je wilt houden.", + "days_one": "Ouder dan {{count}} dag", + "days_other": "Ouder dan {{count}} dagen", + "onlyUnused": "Alleen ongebruikte foto's", + "previewNote": "Dit is een voorbeeld: er wordt nog niets verwijderd.", + "summary_one": "{{count}} foto ({{size}}) komt in aanmerking.", + "summary_other": "{{count}} foto's ({{size}}) komen in aanmerking.", + "selectedSize": "Geselecteerd: {{size}}" } } } diff --git a/frontend/src/mocks/index.ts b/frontend/src/mocks/index.ts index 717edf6..fd565d6 100644 --- a/frontend/src/mocks/index.ts +++ b/frontend/src/mocks/index.ts @@ -8,9 +8,10 @@ import { systemHandlers } from '@/features/system/mocks/handlers'; import { offeringsHandlers } from '@/features/offerings/mocks/handlers'; import { contactHandlers } from '@/features/contact/mocks/handlers'; import { heroHandlers } from '@/features/hero/mocks/handlers'; +import { mediaHandlers } from '@/features/media/mocks/handlers'; /** All default MSW handlers, composed from feature folders (Q3-B). */ -export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers, ...heroHandlers]; +export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers, ...heroHandlers, ...mediaHandlers]; export { authHandlers } from '@/features/auth/mocks/handlers'; export { userHandlers } from '@/features/users/mocks/handlers'; diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx index d4be45f..1c43541 100644 --- a/frontend/src/router.tsx +++ b/frontend/src/router.tsx @@ -245,6 +245,18 @@ const heroRoute = createRoute({ ), }); +const mediaRoute = createRoute({ + getParentRoute: () => authenticatedRoute, + path: '/media', + component: () => ( + + + {lazyPage(() => import('@/features/media/pages/MediaLibraryPage'), 'MediaLibraryPage')()} + + + ), +}); + const offeringsRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/offerings', @@ -333,6 +345,7 @@ export const routeTree = rootRoute.addChildren([ usersRoute, cmsRoute, heroRoute, + mediaRoute, offeringsRoute, offeringsNewRoute, offeringsEditRoute, diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index 843d434..252268b 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -1060,6 +1060,200 @@ ], "type": "object" }, + "MediaCleanupPreviewDto": { + "properties": { + "bytes": { + "format": "int64", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "count": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "days": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "onlyUnused": { + "type": "boolean" + }, + "photos": { + "items": { + "$ref": "#/components/schemas/MediaPhotoDto" + }, + "type": "array" + } + }, + "required": [ + "days", + "onlyUnused", + "count", + "bytes", + "photos" + ], + "type": "object" + }, + "MediaLibraryDto": { + "properties": { + "modules": { + "items": { + "type": "string" + }, + "type": "array" + }, + "photos": { + "items": { + "$ref": "#/components/schemas/MediaPhotoDto" + }, + "type": "array" + } + }, + "required": [ + "photos", + "modules" + ], + "type": "object" + }, + "MediaPhotoDto": { + "properties": { + "bytes": { + "format": "int64", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "createdAt": { + "format": "date-time", + "type": "string" + }, + "height": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "id": { + "type": "string" + }, + "module": { + "type": "string" + }, + "thumbnailUrl": { + "type": [ + "null", + "string" + ] + }, + "uses": { + "items": { + "$ref": "#/components/schemas/MediaUseDto" + }, + "type": "array" + }, + "width": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + } + }, + "required": [ + "id", + "module", + "bytes", + "width", + "height", + "createdAt", + "thumbnailUrl", + "uses" + ], + "type": "object" + }, + "MediaStorageDto": { + "properties": { + "level": { + "type": "string" + }, + "limitBytes": { + "format": "int64", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "usedBytes": { + "format": "int64", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "warningPercent": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + } + }, + "required": [ + "usedBytes", + "limitBytes", + "level", + "warningPercent" + ], + "type": "object" + }, + "MediaUseDto": { + "properties": { + "active": { + "type": "boolean" + }, + "kind": { + "type": "string" + }, + "module": { + "type": "string" + }, + "position": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ] + } + }, + "required": [ + "module", + "kind", + "position", + "active" + ], + "type": "object" + }, "OfferingBannerRequest": { "properties": { "endsAt": { @@ -3252,6 +3446,116 @@ ] } }, + "/api/v1/media-library/cleanup-preview": { + "get": { + "parameters": [ + { + "in": "query", + "name": "days", + "schema": { + "default": 7, + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + } + }, + { + "in": "query", + "name": "onlyUnused", + "schema": { + "default": true, + "type": "boolean" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MediaCleanupPreviewDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/MediaCleanupPreviewDto" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/MediaCleanupPreviewDto" + } + } + }, + "description": "OK" + } + }, + "tags": [ + "MediaLibrary" + ] + } + }, + "/api/v1/media-library/photos": { + "get": { + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MediaLibraryDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/MediaLibraryDto" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/MediaLibraryDto" + } + } + }, + "description": "OK" + } + }, + "tags": [ + "MediaLibrary" + ] + } + }, + "/api/v1/media-library/storage": { + "get": { + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MediaStorageDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/MediaStorageDto" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/MediaStorageDto" + } + } + }, + "description": "OK" + } + }, + "tags": [ + "MediaLibrary" + ] + } + }, "/api/v1/offerings": { "get": { "responses": { diff --git a/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs new file mode 100644 index 0000000..fc44359 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs @@ -0,0 +1,87 @@ +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using SlpModularCms.Core.Media.Library; +using Xunit; + +namespace SlpModularCms.Core.Tests.Media; + +public class MediaLibraryControllerTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 17, 12, 0, 0, TimeSpan.Zero); + + private sealed class Clock : TimeProvider + { + public override DateTimeOffset GetUtcNow() => Now; + } + + private static MediaLibraryItem Item(int daysOld, bool used) + { + var photo = new MediaPhoto("hero", Guid.NewGuid(), 1000, 1600, 1067, Now.AddDays(-daysOld), "/media/hero/0123456789abcdef/wide-480.webp"); + return new MediaLibraryItem(photo, used ? [new MediaUse("hero", photo.Id, "slide", 2, true)] : []); + } + + private static MediaLibraryController Controller(params MediaLibraryItem[] items) + { + var library = Substitute.For(); + library.ListAsync(Arg.Any()).Returns(items.OrderByDescending(i => i.Photo.CreatedAt).ToList()); + library.Modules.Returns(["hero"]); + return new MediaLibraryController(library, new Clock()); + } + + [Fact] + public void Only_administrators_may_use_it() + { + typeof(MediaLibraryController).GetCustomAttributes(typeof(AuthorizeAttribute), true) + .Cast().Should().ContainSingle(a => a.Policy == "AdminOnly"); + } + + [Fact] + public async Task Photos_lists_each_photo_with_its_uses_and_a_module_prefixed_id() + { + var used = Item(2, used: true); + var result = (OkObjectResult)await Controller(used, Item(9, used: false)).Photos(CancellationToken.None); + + var dto = result.Value.Should().BeOfType().Subject; + dto.Photos.Should().HaveCount(2); + dto.Photos[0].Id.Should().Be($"hero:{used.Photo.Id}"); + dto.Photos[0].Uses.Should().ContainSingle().Which.Should().Be(new MediaUseDto("hero", "slide", 2, true)); + dto.Modules.Should().Equal("hero"); + } + + [Fact] + public async Task The_cleanup_preview_selects_old_unused_photos_and_deletes_nothing() + { + var oldUnused = Item(20, used: false); + var controller = Controller(Item(3, used: false), Item(20, used: true), oldUnused); + + var preview = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(7, true, CancellationToken.None)).Value!; + + preview.Count.Should().Be(1); + preview.Photos.Single().Id.Should().Be($"hero:{oldUnused.Photo.Id}"); + preview.Bytes.Should().Be(1000); + preview.OnlyUnused.Should().BeTrue(); + } + + [Fact] + public async Task The_cleanup_preview_can_include_photos_in_use_and_keeps_the_period_in_range() + { + var controller = Controller(Item(20, used: true), Item(20, used: false)); + + var preview = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(99999, false, CancellationToken.None)).Value!; + + preview.Days.Should().Be(365); + preview.Count.Should().Be(0); + var shorter = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(7, false, CancellationToken.None)).Value!; + shorter.Count.Should().Be(2); + } + + [Fact] + public async Task Storage_without_a_media_store_reports_zero_and_ok() + { + var result = (MediaStorageDto)((OkObjectResult)await Controller().Storage(CancellationToken.None)).Value!; + + result.Should().Be(new MediaStorageDto(0, 0, "ok", 80)); + } +} diff --git a/src/SlpModularCms.Core.Tests/Media/MediaStorageUsageTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaStorageUsageTests.cs new file mode 100644 index 0000000..6ad3496 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Media/MediaStorageUsageTests.cs @@ -0,0 +1,49 @@ +using FluentAssertions; +using Microsoft.Extensions.Options; +using NSubstitute; +using SlpModularCms.Core.Media; +using SlpModularCms.Core.Media.Library; +using Xunit; + +namespace SlpModularCms.Core.Tests.Media; + +public class MediaStorageUsageTests +{ + private sealed class Clock(DateTimeOffset now) : TimeProvider + { + public DateTimeOffset Now { get; set; } = now; + + public override DateTimeOffset GetUtcNow() => Now; + } + + [Theory] + [InlineData(0, 100, MediaStorageLevel.Ok)] + [InlineData(79, 100, MediaStorageLevel.Ok)] + [InlineData(80, 100, MediaStorageLevel.Warning)] + [InlineData(99, 100, MediaStorageLevel.Warning)] + [InlineData(100, 100, MediaStorageLevel.Full)] + [InlineData(500, 100, MediaStorageLevel.Full)] + [InlineData(500, 0, MediaStorageLevel.Ok)] + public void The_level_follows_the_share_of_the_limit(long used, long limit, MediaStorageLevel expected) + => MediaStorageUsage.LevelFor(used, limit).Should().Be(expected); + + [Fact] + public async Task The_measurement_is_kept_for_a_minute_and_then_taken_again() + { + var store = Substitute.For(); + store.GetTotalBytesAsync(Arg.Any()).Returns(850L, 900L); + var clock = new Clock(new DateTimeOffset(2026, 11, 17, 12, 0, 0, TimeSpan.Zero)); + var usage = new MediaStorageUsage(store, Options.Create(new MediaOptions { MaxTotalBytes = 1000 }), clock); + + var first = await usage.GetAsync(CancellationToken.None); + clock.Now = clock.Now.AddSeconds(30); + var cached = await usage.GetAsync(CancellationToken.None); + clock.Now = clock.Now.AddSeconds(31); + var later = await usage.GetAsync(CancellationToken.None); + + first.Should().Be(new MediaStorageInfo(850, 1000, MediaStorageLevel.Warning)); + cached.Should().BeSameAs(first); + later.UsedBytes.Should().Be(900); + await store.Received(2).GetTotalBytesAsync(Arg.Any()); + } +} diff --git a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs index 79a14b8..c199a95 100644 --- a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs @@ -85,6 +85,8 @@ public static class ServiceCollectionExtensions services.AddOptions() .Configure>((o, reset) => o.TokenLifespan = TimeSpan.FromMinutes(reset.Value.TokenLifetimeMinutes)); services.TryAddSingleton(TimeProvider.System); + // The media library reads from the usage providers of whichever modules are loaded (none is fine). + services.TryAddScoped(); services.TryAddSingleton(sp => new ResetCooldown(sp.GetRequiredService(), TimeSpan.FromMinutes(sp.GetRequiredService>().Value.CooldownMinutes))); services.AddScoped(); diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs new file mode 100644 index 0000000..0d22b3f --- /dev/null +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs @@ -0,0 +1,63 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace SlpModularCms.Core.Media.Library; + +public sealed record MediaUseDto(string Module, string Kind, int? Position, bool Active); + +public sealed record MediaPhotoDto(string Id, string Module, long Bytes, int Width, int Height, DateTimeOffset CreatedAt, string? ThumbnailUrl, IReadOnlyList Uses); + +public sealed record MediaLibraryDto(IReadOnlyList Photos, IReadOnlyList Modules); + +public sealed record MediaStorageDto(long UsedBytes, long LimitBytes, string Level, int WarningPercent); + +/// What a clean-up with these settings would select. A preview only: nothing is deleted. +public sealed record MediaCleanupPreviewDto(int Days, bool OnlyUnused, int Count, long Bytes, IReadOnlyList Photos); + +/// +/// The media library for administrators: the photos of all modules with where they are used, the storage against its +/// limit, and a preview of the clean-up. Read-only: deleting comes after the assumptions are checked. +/// +[ApiController] +[Route("media-library")] +[Authorize(Policy = "AdminOnly")] +public class MediaLibraryController(IMediaLibraryService library, TimeProvider time, MediaStorageUsage? storage = null) : ControllerBase +{ + [HttpGet("photos")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Photos(CancellationToken cancellationToken) + { + var items = await library.ListAsync(cancellationToken); + return Ok(new MediaLibraryDto(items.Select(ToDto).ToList(), library.Modules)); + } + + [HttpGet("storage")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Storage(CancellationToken cancellationToken) + { + // A host without media has nothing stored: zero used, no limit. + var info = storage is null ? new MediaStorageInfo(0, 0, MediaStorageLevel.Ok) : await storage.GetAsync(cancellationToken); + return Ok(new MediaStorageDto(info.UsedBytes, info.LimitBytes, info.Level.ToString().ToLowerInvariant(), MediaStorageUsage.WarningPercent)); + } + + [HttpGet("cleanup-preview")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task CleanupPreview([FromQuery] int days = CleanupSelection.DefaultDays, [FromQuery] bool onlyUnused = true, CancellationToken cancellationToken = default) + { + var clamped = CleanupSelection.ClampDays(days); + var selected = CleanupSelection.Select(await library.ListAsync(cancellationToken), time.GetUtcNow(), clamped, onlyUnused); + return Ok(new MediaCleanupPreviewDto(clamped, onlyUnused, selected.Count, CleanupSelection.Bytes(selected), selected.Select(ToDto).ToList())); + } + + private static MediaPhotoDto ToDto(MediaLibraryItem item) + => new( + $"{item.Photo.Module}:{item.Photo.Id}", + item.Photo.Module, + item.Photo.Bytes, + item.Photo.Width, + item.Photo.Height, + item.Photo.CreatedAt, + item.Photo.ThumbnailUrl, + item.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList()); +} diff --git a/src/SlpModularCms.Core/Media/Library/MediaStorageUsage.cs b/src/SlpModularCms.Core/Media/Library/MediaStorageUsage.cs new file mode 100644 index 0000000..c0d2d6b --- /dev/null +++ b/src/SlpModularCms.Core/Media/Library/MediaStorageUsage.cs @@ -0,0 +1,72 @@ +using Microsoft.Extensions.Options; + +namespace SlpModularCms.Core.Media.Library; + +public enum MediaStorageLevel +{ + Ok, + Warning, + Full, +} + +/// Everything in the media directory (originals and variants). +/// The safety limit; 0 means no limit. +public sealed record MediaStorageInfo(long UsedBytes, long LimitBytes, MediaStorageLevel Level); + +/// +/// The space the media directory takes against its limit (Media:MaxTotalBytes). Measuring walks the directory, so +/// the answer is kept for a minute (assumption 9 of the media-library list: warning at 80 percent, full at 100). +/// +public sealed class MediaStorageUsage(IMediaStore store, IOptions options, TimeProvider? time = null) +{ + public const int WarningPercent = 80; + private static readonly TimeSpan CacheFor = TimeSpan.FromSeconds(60); + private readonly TimeProvider _time = time ?? TimeProvider.System; + private readonly SemaphoreSlim _gate = new(1, 1); + private MediaStorageInfo? _cached; + private DateTimeOffset _measuredAt; + + public static MediaStorageLevel LevelFor(long used, long limit) + { + if (limit <= 0) + { + return MediaStorageLevel.Ok; + } + + if (used >= limit) + { + return MediaStorageLevel.Full; + } + + return used * 100 >= limit * WarningPercent ? MediaStorageLevel.Warning : MediaStorageLevel.Ok; + } + + public async Task GetAsync(CancellationToken cancellationToken) + { + var now = _time.GetUtcNow(); + if (_cached is { } fresh && now - _measuredAt < CacheFor) + { + return fresh; + } + + await _gate.WaitAsync(cancellationToken); + try + { + now = _time.GetUtcNow(); + if (_cached is { } again && now - _measuredAt < CacheFor) + { + return again; + } + + var used = await store.GetTotalBytesAsync(cancellationToken); + var limit = Math.Max(0, options.Value.MaxTotalBytes); + _cached = new MediaStorageInfo(used, limit, LevelFor(used, limit)); + _measuredAt = now; + return _cached; + } + finally + { + _gate.Release(); + } + } +} diff --git a/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs index 4fdd8bd..02a12e1 100644 --- a/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs @@ -22,7 +22,7 @@ public static class MediaServiceCollectionExtensions services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddScoped(); + services.TryAddSingleton(); if (!services.Any(d => d.ImplementationType == typeof(ImageProcessorSelfTest))) { services.AddHostedService(); -- 2.39.5 From a71db84632e1f10cc4392e95571079e1ed58c6c0 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 14:17:28 +0100 Subject: [PATCH 02/22] Media: instelling Media:AutoCleanupUnattached (standaard true) om ongebruikte uploads te bewaren Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 2 +- docs/hero-module.md | 2 +- .../Media/ImageProcessing.cs | 8 +++++ .../HeroServiceTests.cs | 31 +++++++++++++++++++ .../Services/HeroMediaCleanup.cs | 6 +++- 5 files changed, 46 insertions(+), 3 deletions(-) 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 2c0070a..586e891 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -6,7 +6,7 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu |---|---|---|---|---| | 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` | +| 3 | The **7-day automatic clean-up** of unattached Hero images until the library is built. | **Built (2026-11-17, safe: default unchanged)**: the setting `Media:AutoCleanupUnattached` exists, default `true` (today's behaviour); set `Media__AutoCleanupUnattached=false` per host to keep every upload. Plan: switch it off (default `false`) once the library screen and delete are accepted by Bryan. 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` | diff --git a/docs/hero-module.md b/docs/hero-module.md index 02e46c6..b40ae1c 100644 --- a/docs/hero-module.md +++ b/docs/hero-module.md @@ -26,7 +26,7 @@ De admin toont alleen een badge Live of Niet live. | Instelling | Betekenis | |---|---| | `Media__Directory` | De map voor de afbeeldingen, **buiten de release** en buiten de webroot. Zonder deze instelling (of als de map niet beschrijfbaar is) staan uploads uit; bestaande bestanden en de publieke hero blijven werken. Niet in een committed appsettings-bestand. | -| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. | +| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7), `Media__AutoCleanupUnattached` (standaard `true`; `false` bewaart ongebruikte uploads tot iemand ze verwijdert, voor de mediabibliotheek) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. | | `Hero__TextOnlyRegion` | `true` voor een site waarvan de hero geen afbeeldingen heeft (SLP Software; staat in de committed instellingen van die site): een hero zonder slides wordt dan als tekst (titelregels, lead, knoppen) in de eerste HTML geschreven. Uit (standaard, ook voor ASF): een hero zonder slides laat de pagina ongemoeid. | | `Hero__TitlePrefix` | Merktekst die in de tekst-only-regio als eerste, visueel te verbergen deel van de h1 wordt geschreven (``), zodat crawlers en schermlezers de volledige titel lezen. SLP Software: `"SLP Software: "` (committed instelling); leeg (standaard, ook ASF) schrijft niets. De site verbergt de klasse zelf visueel. | | `Media__RenderSetTimeoutSeconds` (600), `Media__StripTimeoutSeconds` (60) | De tijd die het knippen van alle varianten van één foto in de achtergrond mag duren, en het verwijderen van metadata bij een upload. Ruim gekozen: een grote foto op een Raspberry Pi kost minuten. | diff --git a/src/SlpModularCms.Core/Media/ImageProcessing.cs b/src/SlpModularCms.Core/Media/ImageProcessing.cs index 3687d34..97bf299 100644 --- a/src/SlpModularCms.Core/Media/ImageProcessing.cs +++ b/src/SlpModularCms.Core/Media/ImageProcessing.cs @@ -65,6 +65,14 @@ public sealed class MediaOptions public long MaxTotalBytes { get; set; } = 2L * 1024 * 1024 * 1024; public int RetentionDays { get; set; } = 7; + + /// + /// Whether photos that were uploaded but never used are removed automatically after . + /// The media library keeps everything until a person removes it, so set this to false (Media__AutoCleanupUnattached=false) + /// once the library can show and delete photos. Retired files of photos a person removed stay housekeeping either way. + /// Default true keeps today's behaviour (assumption 3 of the media-library list). + /// + public bool AutoCleanupUnattached { get; set; } = true; } /// diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs index 63ac04f..ddf15ba 100644 --- a/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs @@ -412,6 +412,37 @@ public class HeroMediaCleanupTests again.Variants.Should().OnlyContain(v => v.Url.Contains(set)); } + [Fact] + public async Task AnImageNobodyUsed_IsKept_WhenAutomaticCleanupIsOff() + { + using var rig = new HeroTestRig(); + rig.Media.AutoCleanupUnattached = false; + await rig.Upload(HeroTestRig.Photo()); + + rig.Time.Now = rig.Time.Now.AddDays(400); + await rig.Cleanup.RunOnceAsync(CancellationToken.None); + rig.Time.Now = rig.Time.Now.AddDays(400); + await rig.Cleanup.RunOnceAsync(CancellationToken.None); + + rig.Db.HeroImages.Should().HaveCount(1); + (await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().HaveCount(1); + rig.Db.HeroRetiredFiles.Should().BeEmpty(); + } + + [Fact] + public async Task APhotoAPersonRemoved_StillLeavesAfterTheRetentionTime_WhenAutomaticCleanupIsOff() + { + using var rig = new HeroTestRig(); + rig.Media.AutoCleanupUnattached = false; + var (set, original) = await RetireAnImage(rig); + + rig.Time.Now = rig.Time.Now.AddDays(8); + await rig.Cleanup.RunOnceAsync(CancellationToken.None); + + (await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().NotContain(s => s.SetHash == set); + (await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse(); + } + [Fact] public async Task AnImageNobodyUsed_IsRetiredAndRemoved_AfterTheRetentionTime() { diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs index 943c0f1..0fe2e7d 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs @@ -29,7 +29,11 @@ public class HeroMediaCleanup( var removed = 0; // 1. Images that were uploaded but never used by a slide: retire them (their files go on a later run). - foreach (var image in await repository.GetUnattachedImagesCreatedBeforeAsync(cutoff, cancellationToken)) + // Skipped when the media library keeps every upload until a person removes it (Media:AutoCleanupUnattached = false). + var unattached = options.Value.AutoCleanupUnattached + ? await repository.GetUnattachedImagesCreatedBeforeAsync(cutoff, cancellationToken) + : []; + foreach (var image in unattached) { repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = image.SetHash, RetiredAt = cutoff.AddSeconds(-1) }); repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = cutoff.AddSeconds(-1) }); -- 2.39.5 From 1e89d8f3d77ceef815e24d0bd0a36e62f0f92275 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 14:18:51 +0100 Subject: [PATCH 03/22] Media: gebruiksdefinities (mozaiek groot/breed/klein, masonry) als pure code met tests Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 1 + .../Media/MediaUseDefinitionTests.cs | 72 +++++++++++++++++++ .../Media/Library/MediaUseDefinition.cs | 72 +++++++++++++++++++ 3 files changed, 145 insertions(+) create mode 100644 src/SlpModularCms.Core.Tests/Media/MediaUseDefinitionTests.cs create mode 100644 src/SlpModularCms.Core/Media/Library/MediaUseDefinition.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 586e891..d510734 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -28,3 +28,4 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 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). | **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` | diff --git a/src/SlpModularCms.Core.Tests/Media/MediaUseDefinitionTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaUseDefinitionTests.cs new file mode 100644 index 0000000..1d3d15e --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Media/MediaUseDefinitionTests.cs @@ -0,0 +1,72 @@ +using FluentAssertions; +using SlpModularCms.Core.Media; +using SlpModularCms.Core.Media.Library; +using Xunit; + +namespace SlpModularCms.Core.Tests.Media; + +public class MediaUseDefinitionTests +{ + private const string Sha = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + [Fact] + public void Every_ratio_name_and_width_fits_the_media_address_scheme() + { + foreach (var use in GalleryUses.All) + { + var plans = use.PlansFor(4000, 3000); + var specs = VariantPlanner.Plan(4000, 3000, plans, new HashSet { ImageFormat.WebP }); + specs.Should().NotBeEmpty(use.Key); + foreach (var spec in specs) + { + var name = MediaPaths.FileName(spec.Ratio.Name, spec.Width, spec.Format); + MediaPaths.TryParse($"{use.Module}/{use.SetHash(Sha)}/{name}", out _).Should().BeTrue($"{use.Key}: {name}"); + } + } + } + + [Fact] + public void The_keys_are_unique() => GalleryUses.All.Select(u => u.Key).Should().OnlyHaveUniqueItems(); + + [Fact] + public void A_mosaic_use_has_a_desktop_and_a_phone_shape_and_a_masonry_use_has_none_of_its_own() + { + GalleryUses.MosaicLarge.Ratios.Select(r => r.Name).Should().Equal("tilelarge", "tilelargem"); + GalleryUses.Masonry.Natural.Should().BeTrue(); + GalleryUses.Masonry.PlansFor(3000, 2000).Should().ContainSingle().Which.Ratio.Should().Be(new Ratio("natural", 3000, 2000)); + } + + [Fact] + public void A_natural_use_keeps_the_photos_own_shape_without_a_crop() + { + var spec = VariantPlanner.Plan(3000, 2000, GalleryUses.Masonry.PlansFor(3000, 2000), new HashSet { ImageFormat.WebP }) + .Single(s => s.Width == 800); + + (spec.Crop.Width, spec.Crop.Height).Should().Be((3000, 2000)); + spec.Height.Should().Be(533); + } + + [Fact] + public void The_crop_of_a_use_changes_its_set_hash_but_not_the_set_hash_of_another_use() + { + var focus = new Dictionary { ["tilelarge"] = new(0.2, 0.3, 1.5) }; + + GalleryUses.MosaicLarge.SetHash(Sha, focus).Should().NotBe(GalleryUses.MosaicLarge.SetHash(Sha)); + GalleryUses.MosaicWide.SetHash(Sha, focus).Should().Be(GalleryUses.MosaicWide.SetHash(Sha)); + GalleryUses.MosaicLarge.SetHash(Sha, focus).Should().Be(GalleryUses.MosaicLarge.SetHash(Sha, focus)); + } + + [Fact] + public void A_natural_use_does_not_depend_on_a_crop() + => GalleryUses.Masonry.SetHash(Sha, new Dictionary { ["natural"] = new(0.1, 0.1, 2) }).Should().Be(GalleryUses.Masonry.SetHash(Sha)); + + [Fact] + public void The_set_hash_formula_is_the_one_the_hero_uses_today() + { + // Same inputs through the shared function the hero calls: the library does not invent a second scheme. + var hero = new MediaUseDefinition("hero", "hero", [new("wide", 3, 2, [640]), new("tall", 4, 5, [480])]); + var focus = new Dictionary { ["wide"] = new(0.3, 0.4, 1.2) }; + + hero.SetHash(Sha, focus).Should().Be(MediaPaths.SetHash(Sha, [("wide", new FocusSetting(0.3, 0.4, 1.2)), ("tall", FocusSetting.Centre)])); + } +} diff --git a/src/SlpModularCms.Core/Media/Library/MediaUseDefinition.cs b/src/SlpModularCms.Core/Media/Library/MediaUseDefinition.cs new file mode 100644 index 0000000..976a695 --- /dev/null +++ b/src/SlpModularCms.Core/Media/Library/MediaUseDefinition.cs @@ -0,0 +1,72 @@ +namespace SlpModularCms.Core.Media.Library; + +/// One ratio of a use: its name (part of the file name), its shape and the widths cut for it. +public sealed record UseRatio(string Name, int Numerator, int Denominator, IReadOnlyList Widths); + +/// +/// What a USE of a photo needs (a place on a page, not the photo itself): the ratios with their widths, or the natural +/// shape of the photo without a crop. A photo can have several uses; each use has its own crop (focus per ratio) and so +/// its own set. Pure data, no behaviour that moves anything. +/// +/// For example mosaic-large; unique. +/// The module whose pages show it (also its media area). +/// Empty for a natural-ratio use. +/// The photo is shown in its own shape: no crop, one ratio taken from the photo itself. +public sealed record MediaUseDefinition(string Key, string Module, IReadOnlyList Ratios, bool Natural = false) +{ + public const string NaturalRatioName = "natural"; + + /// The ratio plans for a photo, given the focus per ratio name (centre when none is given). + public IReadOnlyList PlansFor(int sourceWidth, int sourceHeight, IReadOnlyDictionary? focus = null) + { + if (Natural) + { + var widths = Ratios.Count > 0 ? Ratios[0].Widths : []; + return [new RatioPlan(new Ratio(NaturalRatioName, sourceWidth, sourceHeight), FocusSetting.Centre, widths)]; + } + + return Ratios + .Select(r => new RatioPlan(new Ratio(r.Name, r.Numerator, r.Denominator), focus is not null && focus.TryGetValue(r.Name, out var f) ? f : FocusSetting.Centre, r.Widths)) + .ToList(); + } + + /// + /// The set hash of this use for a photo: the existing formula over the photo's hash and the crops of this use, so a + /// photo gets the same address for the same use and crops, and another use never shares a set by accident. + /// A natural-ratio use has no crop, so its set depends on the photo alone (and the use key). + /// + public string SetHash(string originalSha256, IReadOnlyDictionary? focus = null) + { + var crops = Natural + ? [(NaturalRatioName, FocusSetting.Centre)] + : Ratios.Select(r => (r.Name, focus is not null && focus.TryGetValue(r.Name, out var f) ? f : FocusSetting.Centre)).ToList(); + return MediaPaths.SetHash(originalSha256, crops); + } +} + +/// +/// The uses of the gallery that the Andrea Slop Fotografie site needs (answer of the ASF session, 2026-11-17): the +/// mosaic tiles (a shape fixed per page by the number and order of the photos, a desktop and a phone shape each) and the +/// masonry portfolio (natural shape). Ratio names are letters only, 2 to 10 long, so they fit the address allow-list. +/// +public static class GalleryUses +{ + public const string Module = "gallery"; + + private static readonly int[] Large = [480, 640, 960, 1280]; + private static readonly int[] Small = [312, 480, 640]; + + /// Photo 1 of 2 to 4: about 1:1 on desktop (max about 656 wide), 4:3 on a phone. + public static readonly MediaUseDefinition MosaicLarge = new("mosaic-large", Module, [new("tilelarge", 1, 1, Large), new("tilelargem", 4, 3, Large)]); + + /// Photo 2 of 3 or 4: about 2.2:1 on desktop, 3:2 on a phone. + public static readonly MediaUseDefinition MosaicWide = new("mosaic-wide", Module, [new("tilewide", 11, 5, Large), new("tilewidem", 3, 2, Large)]); + + /// Photos 3 and 4 of 4: about 1.04:1 on desktop (max about 312 wide), 1:1 on a phone. + public static readonly MediaUseDefinition MosaicSmall = new("mosaic-small", Module, [new("tilesmall", 26, 25, Small), new("tilesmallm", 1, 1, Small)]); + + /// The portfolio: the photo's own shape, no crop; thumbnail widths about 480 and 800. + public static readonly MediaUseDefinition Masonry = new("masonry", Module, [new(MediaUseDefinition.NaturalRatioName, 1, 1, [480, 800])], Natural: true); + + public static IReadOnlyList All { get; } = [MosaicLarge, MosaicWide, MosaicSmall, Masonry]; +} -- 2.39.5 From 58f187860404cd1d0a0ec074f587f44ff3bfcdc9 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 14:24:53 +0100 Subject: [PATCH 04/22] 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." } } } -- 2.39.5 From 6b3a2879087795df0d0a343ed6655e3bb5a55781 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 14:26:55 +0100 Subject: [PATCH 05/22] OpenAPI-snapshot: door de host gegenereerd (tag MediaLibrary) Co-Authored-By: Claude Sonnet 5.5 --- openapi/slpsoftware.v1.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index 252268b..92e0827 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -3957,6 +3957,9 @@ { "name": "SlpModularCms.Api" }, + { + "name": "MediaLibrary" + }, { "name": "System" }, -- 2.39.5 From 7263a9a39a51b2614186576a96b301d571c578c3 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 15:08:05 +0100 Subject: [PATCH 06/22] Mediabibliotheek: prullenbak, delete met tweede bevestiging, laatste gebruik, bestandsnaam (backend) Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 38 ++- openapi/slpsoftware.v1.json | 255 +++++++++++++++++ .../Media/MediaLibraryTests.cs | 106 +++++++- .../Media/ImageProcessing.cs | 3 + .../Media/Library/CleanupSelection.cs | 9 +- .../Media/Library/MediaLibraryController.cs | 83 +++++- .../Media/Library/MediaLibraryService.cs | 133 ++++++++- .../Media/Library/MediaLibraryTypes.cs | 33 ++- .../HeroMediaUsageProviderTests.cs | 151 +++++++++- .../Controllers/HeroControllers.cs | 2 +- .../Data/Entities/HeroEntities.cs | 9 + .../Data/HeroDbContext.cs | 1 + ...7140509_AddMediaLibraryColumns.Designer.cs | 257 ++++++++++++++++++ .../20261117140509_AddMediaLibraryColumns.cs | 50 ++++ .../Migrations/HeroDbContextModelSnapshot.cs | 10 + .../Repositories/HeroRepository.cs | 36 ++- .../Services/HeroImageService.cs | 89 +++++- .../Services/HeroMediaCleanup.cs | 9 + .../Services/HeroMediaUsageProvider.cs | 32 ++- .../Services/HeroService.cs | 7 + 20 files changed, 1271 insertions(+), 42 deletions(-) create mode 100644 src/SlpModularCms.Modules.Hero/Migrations/20261117140509_AddMediaLibraryColumns.Designer.cs create mode 100644 src/SlpModularCms.Modules.Hero/Migrations/20261117140509_AddMediaLibraryColumns.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 a44c038..4e6fa63 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -6,17 +6,17 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu |---|---|---|---|---| | 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. | **Built (2026-11-17, safe: default unchanged)**: the setting `Media:AutoCleanupUnattached` exists, default `true` (today's behaviour); set `Media__AutoCleanupUnattached=false` per host to keep every upload. Plan: switch it off (default `false`) once the library screen and delete are accepted by Bryan. 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` | +| 3 | The **7-day automatic clean-up** of unattached Hero images until the library is built. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | **Built (2026-11-17, safe: default unchanged)**: the setting `Media:AutoCleanupUnattached` exists, default `true` (today's behaviour); set `Media__AutoCleanupUnattached=false` per host to keep every upload. Plan: switch it off (default `false`) once the library screen and delete are accepted by Bryan. 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? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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` | +| 7 | **What counts as "unused"** in the clean-up? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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 | +| 10 | **Delete of a photo that is in use**. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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 | +| 12 | **Trash delay** (deleted photos recoverable for a while)? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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). **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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` | @@ -24,7 +24,7 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 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 | +| 21 | A **name** for a photo. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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). | **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 | @@ -32,3 +32,25 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 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` | + +## Decisions of the second round (Bryan, 2026-11-17, via SLP Software - SLS - Main) + +| # | Decision | Consequence in design and code | +|---|---|---| +| 3 | The automatic removal of unused Hero uploads is switched off once Bryan has approved the screen (PR #22). | `Media:AutoCleanupUnattached` keeps its default `true`; it becomes `false` only at or after his approval of PR #22. | +| 4 | One shared library for Owner and Administrator, no rights per module. | As designed (`AdminOnly`). | +| 7 | A photo used only by a switched-off slide counts as **used**. | As designed (`HeroMediaUsageProvider` reports it as a use with `Active = false`). | +| 8 | The clean-up period counts from the **last use**, not the upload date. | Each photo gets "unused since" (the moment it was last detached from a slide; the upload date when it was never used). Details in assumption 29. | +| 10 | Deleting a photo that is in use is possible after a **second confirmation that names the places**. | Delete refuses an in-use photo unless the request says it was confirmed twice; the module detaches it (Hero: the slides using it are removed). Assumption 30. | +| 12 | There is a **trash**: recoverable for 7 days (`DeletedAt` plus the existing retired-file mechanism). | Delete means "to the trash"; the files go 7 days later. A trash view lists them with Restore. Assumption 31. | +| 13 | The migration of `HeroImages` to the library's own tables may be built next (expand then contract, same ids, hashes and addresses). | Conditions: document a back-up and rollback plan first; roll out only to TEST, never production; tell SLS-Main before deploying to test. Assumption 32. | +| 21 | The original file name is stored at every upload from now on (additive); existing photos keep the neutral label. | `OriginalFileName` on the Hero image (additive migration); the library shows it. | + +### New assumptions from these decisions + +| # | Question | Assumption made | If Bryan chooses differently | Where | +|---|---|---|---|---| +| 29 | **Reference date of the clean-up** (decision 8). | For a photo that is not in use: the moment it was last detached from a slide (`LastUsedAt`), else its upload date. For a photo that is in use right now (clean-up with "Only unused photos" off): its upload date, since "last used" is "now" and nothing would ever be old enough. The period slider keeps its range (1 to 365 days, default 7). | "Last used" for a photo in use = the last save that kept it, so with the filter off only photos left alone for the whole period are offered. | `HeroImage.LastUsedAt`, `HeroService.SaveAsync`, `CleanupSelection` | +| 30 | **Detaching a used photo when it is deleted** (decision 10). | In the Hero the slides that use the photo are removed from the hero (a slide cannot exist without an image); the second confirmation names them ("Hero, slide 3"). The hero then has fewer slides and stays published as long as it has a title. | Keep the slide and mark it "image missing" until a new image is chosen: needs a nullable slide image and a changed public contract. | `HeroMediaUsageProvider.TrashAsync` | +| 31 | **Trash mechanics** (decision 12). | `DeletedAt` on the Hero image: a trashed photo is hidden from the Hero (slides, upload by hash, renderer) and shown in the library trash; Restore clears it. After 7 days the cleanup turns it into retired files (removed immediately) and removes the row. Uploading the same file again restores it. The trash period is `Media:TrashDays` (7). | Another period: the setting; no trash: delete straight to retired files. | `HeroImage.DeletedAt`, `HeroMediaCleanup`, `MediaOptions.TrashDays` | +| 32 | **Migration of `HeroImages`** (decision 13): the plan and the safeguards. | Designed in `inception/application-design/migration-plan.md` (back-up, rollback, verification, test-only rollout). The additive columns of this round (`OriginalFileName`, `DeletedAt`, `LastUsedAt`) are copied with the rest. Not run anywhere until SLS-Main has been told and agrees to the test deploy. | n/a | `migration-plan.md` | diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index 92e0827..7c3ca79 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -1140,6 +1140,13 @@ "format": "date-time", "type": "string" }, + "deletedAt": { + "format": "date-time", + "type": [ + "null", + "string" + ] + }, "height": { "format": "int32", "pattern": "^-?(?:0|[1-9]\\d*)$", @@ -1154,12 +1161,25 @@ "module": { "type": "string" }, + "originalFileName": { + "type": [ + "null", + "string" + ] + }, "thumbnailUrl": { "type": [ "null", "string" ] }, + "unusedSince": { + "format": "date-time", + "type": [ + "null", + "string" + ] + }, "uses": { "items": { "$ref": "#/components/schemas/MediaUseDto" @@ -1187,6 +1207,20 @@ ], "type": "object" }, + "MediaRestoreRequest": { + "properties": { + "ids": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "ids" + ], + "type": "object" + }, "MediaStorageDto": { "properties": { "level": { @@ -1225,6 +1259,38 @@ ], "type": "object" }, + "MediaTrashRequest": { + "properties": { + "confirmedInUse": { + "default": false, + "type": "boolean" + }, + "ids": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "ids" + ], + "type": "object" + }, + "MediaTrashResponse": { + "properties": { + "results": { + "items": { + "$ref": "#/components/schemas/MediaUseResultDto" + }, + "type": "array" + } + }, + "required": [ + "results" + ], + "type": "object" + }, "MediaUseDto": { "properties": { "active": { @@ -1254,6 +1320,28 @@ ], "type": "object" }, + "MediaUseResultDto": { + "properties": { + "id": { + "type": "string" + }, + "status": { + "type": "string" + }, + "uses": { + "items": { + "$ref": "#/components/schemas/MediaUseDto" + }, + "type": "array" + } + }, + "required": [ + "id", + "status", + "uses" + ], + "type": "object" + }, "OfferingBannerRequest": { "properties": { "endsAt": { @@ -3498,6 +3586,75 @@ ] } }, + "/api/v1/media-library/delete": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/MediaTrashRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/MediaTrashRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/MediaTrashRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MediaTrashResponse" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/MediaTrashResponse" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/MediaTrashResponse" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Bad Request" + } + }, + "tags": [ + "MediaLibrary" + ] + } + }, "/api/v1/media-library/photos": { "get": { "responses": { @@ -3527,6 +3684,75 @@ ] } }, + "/api/v1/media-library/restore": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/MediaRestoreRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/MediaRestoreRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/MediaRestoreRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MediaTrashResponse" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/MediaTrashResponse" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/MediaTrashResponse" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Bad Request" + } + }, + "tags": [ + "MediaLibrary" + ] + } + }, "/api/v1/media-library/storage": { "get": { "responses": { @@ -3556,6 +3782,35 @@ ] } }, + "/api/v1/media-library/trash": { + "get": { + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MediaLibraryDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/MediaLibraryDto" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/MediaLibraryDto" + } + } + }, + "description": "OK" + } + }, + "tags": [ + "MediaLibrary" + ] + } + }, "/api/v1/offerings": { "get": { "responses": { diff --git a/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs index 4c8a827..3353bce 100644 --- a/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs +++ b/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs @@ -79,10 +79,114 @@ public class MediaLibraryTests library.Modules.Should().Equal("gallery", "hero"); } - private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses) : IMediaUsageProvider + [Fact] + public async Task Trash_refuses_a_photo_in_use_until_the_person_confirmed_and_then_names_the_places() + { + var photo = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-40), null); + var use = new MediaUse("hero", photo.Id, "slide", 3, true); + var provider = new FakeProvider("hero", [photo], [use]); + var library = new MediaLibraryService([provider]); + + var refused = await library.TrashAsync([$"hero:{photo.Id}"], confirmedInUse: false, Guid.Empty, CancellationToken.None); + var done = await library.TrashAsync([$"hero:{photo.Id}"], confirmedInUse: true, Guid.Empty, CancellationToken.None); + + refused.Should().ContainSingle().Which.Status.Should().Be("inUse"); + refused.Single().Uses.Should().Equal(use); + provider.Trashed.Should().Equal(photo.Id); + done.Single().Status.Should().Be("trashed"); + done.Single().Uses.Should().Equal(use); + } + + [Fact] + public async Task Trash_reports_every_photo_on_its_own_and_one_failure_does_not_stop_the_others() + { + var ok = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null); + var broken = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null); + var provider = new FakeProvider("hero", [ok, broken], []) { FailFor = broken.Id }; + var library = new MediaLibraryService([provider]); + + var results = await library.TrashAsync([$"hero:{broken.Id}", $"hero:{ok.Id}", "hero:not-a-guid", $"other:{Guid.NewGuid()}", $"hero:{Guid.NewGuid()}"], false, Guid.Empty, CancellationToken.None); + + results.Select(r => r.Status).Should().Equal("failed", "trashed", "notFound", "notFound", "notFound"); + provider.Trashed.Should().Equal(ok.Id); + } + + [Fact] + public async Task Trash_and_restore_accept_at_most_100_photos_and_a_photo_once() + { + var provider = new FakeProvider("hero", [], []); + var library = new MediaLibraryService([provider]); + var tooMany = Enumerable.Range(0, 101).Select(_ => $"hero:{Guid.NewGuid()}").ToList(); + + await FluentActions.Awaiting(() => library.TrashAsync(tooMany, false, Guid.Empty, CancellationToken.None)).Should().ThrowAsync(); + await FluentActions.Awaiting(() => library.RestoreAsync(tooMany, Guid.Empty, CancellationToken.None)).Should().ThrowAsync(); + var id = $"hero:{Guid.NewGuid()}"; + (await library.TrashAsync([id, id], false, Guid.Empty, CancellationToken.None)).Should().ContainSingle(); + } + + [Fact] + public async Task Restore_gives_the_photo_back_and_lists_the_trash_most_recent_first() + { + var older = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-9), null, DeletedAt: Now.AddDays(-3)); + var newer = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-9), null, DeletedAt: Now.AddDays(-1)); + var provider = new FakeProvider("hero", [], [], trash: [older, newer]); + var library = new MediaLibraryService([provider]); + + (await library.ListTrashAsync(CancellationToken.None)).Select(i => i.Photo.Id).Should().Equal(newer.Id, older.Id); + (await library.RestoreAsync([$"hero:{older.Id}"], Guid.Empty, CancellationToken.None)).Single().Status.Should().Be("restored"); + } + + [Fact] + public void The_clean_up_counts_from_the_last_use_and_falls_back_to_the_upload_date() + { + var detachedRecently = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-100), null, UnusedSince: Now.AddDays(-2)); + var detachedLongAgo = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-100), null, UnusedSince: Now.AddDays(-30)); + var neverUsed = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-20), null); + var items = new[] { detachedRecently, detachedLongAgo, neverUsed }.Select(p => new MediaLibraryItem(p, [])).ToList(); + + var selected = CleanupSelection.Select(items, Now, 7, onlyUnused: true); + + selected.Select(i => i.Photo.Id).Should().BeEquivalentTo([detachedLongAgo.Id, neverUsed.Id]); + } + + [Fact] + public void A_photo_in_use_counts_from_its_upload_date() + { + var photo = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-20), null, UnusedSince: Now.AddDays(-1)); + var item = new MediaLibraryItem(photo, [new MediaUse("hero", photo.Id, "slide", 1, true)]); + + CleanupSelection.ReferenceDate(item).Should().Be(photo.CreatedAt); + CleanupSelection.Select([item], Now, 7, onlyUnused: false).Should().ContainSingle(); + } + + private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses, MediaPhoto[]? trash = null) : IMediaUsageProvider { public string Module => module; + public List Trashed { get; } = []; + + public Guid? FailFor { get; init; } + + public Task> ListTrashAsync(CancellationToken cancellationToken) => Task.FromResult>(trash ?? []); + + public Task TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken) + { + if (photoId == FailFor) + { + throw new InvalidOperationException("boom"); + } + + if (photos.All(p => p.Id != photoId)) + { + return Task.FromResult(null); + } + + Trashed.Add(photoId); + return Task.FromResult(uses.Count(u => u.PhotoId == photoId)); + } + + public Task RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken) => Task.FromResult(trash?.Any(p => p.Id == photoId) == true); + public Task> ListPhotosAsync(CancellationToken cancellationToken) => Task.FromResult>(photos); public Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken cancellationToken) diff --git a/src/SlpModularCms.Core/Media/ImageProcessing.cs b/src/SlpModularCms.Core/Media/ImageProcessing.cs index 97bf299..0c6c5b8 100644 --- a/src/SlpModularCms.Core/Media/ImageProcessing.cs +++ b/src/SlpModularCms.Core/Media/ImageProcessing.cs @@ -73,6 +73,9 @@ public sealed class MediaOptions /// Default true keeps today's behaviour (assumption 3 of the media-library list). ///
public bool AutoCleanupUnattached { get; set; } = true; + + /// How long a photo stays recoverable in the trash before its files are removed. + public int TrashDays { get; set; } = 7; } /// diff --git a/src/SlpModularCms.Core/Media/Library/CleanupSelection.cs b/src/SlpModularCms.Core/Media/Library/CleanupSelection.cs index 6adb8c7..cb55219 100644 --- a/src/SlpModularCms.Core/Media/Library/CleanupSelection.cs +++ b/src/SlpModularCms.Core/Media/Library/CleanupSelection.cs @@ -2,7 +2,8 @@ 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). +/// easy to test. The period counts from the LAST USE (decision 8): for a photo that is not in use the moment it was last +/// detached, else its upload date; for a photo in use right now its upload date (assumption 29). /// public static class CleanupSelection { @@ -18,13 +19,17 @@ public static class CleanupSelection { var cutoff = now.AddDays(-ClampDays(days)); return items - .Where(item => item.Photo.CreatedAt < cutoff) + .Where(item => ReferenceDate(item) < cutoff) .Where(item => !onlyUnused || !item.InUse) .OrderByDescending(item => item.Photo.CreatedAt) .ThenBy(item => item.Photo.Id) .ToList(); } + /// The date the period counts from. + public static DateTimeOffset ReferenceDate(MediaLibraryItem item) + => item.InUse ? item.Photo.CreatedAt : item.Photo.UnusedSince ?? item.Photo.CreatedAt; + /// 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/MediaLibraryController.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs index 0d22b3f..491b58b 100644 --- a/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs @@ -1,3 +1,4 @@ +using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -6,18 +7,40 @@ namespace SlpModularCms.Core.Media.Library; public sealed record MediaUseDto(string Module, string Kind, int? Position, bool Active); -public sealed record MediaPhotoDto(string Id, string Module, long Bytes, int Width, int Height, DateTimeOffset CreatedAt, string? ThumbnailUrl, IReadOnlyList Uses); +public sealed record MediaPhotoDto( + string Id, + string Module, + long Bytes, + int Width, + int Height, + DateTimeOffset CreatedAt, + string? ThumbnailUrl, + IReadOnlyList Uses, + string? OriginalFileName = null, + DateTimeOffset? UnusedSince = null, + DateTimeOffset? DeletedAt = null); public sealed record MediaLibraryDto(IReadOnlyList Photos, IReadOnlyList Modules); public sealed record MediaStorageDto(long UsedBytes, long LimitBytes, string Level, int WarningPercent); -/// What a clean-up with these settings would select. A preview only: nothing is deleted. +/// What a clean-up with these settings would select. A preview: nothing is deleted until the person confirms. public sealed record MediaCleanupPreviewDto(int Days, bool OnlyUnused, int Count, long Bytes, IReadOnlyList Photos); +/// Photo ids as listed (module:guid), at most 100. +/// True when the person confirmed a second time, knowing where the photos in use are used. +public sealed record MediaTrashRequest(IReadOnlyList Ids, bool ConfirmedInUse = false); + +public sealed record MediaRestoreRequest(IReadOnlyList Ids); + +public sealed record MediaUseResultDto(string Id, string Status, IReadOnlyList Uses); + +public sealed record MediaTrashResponse(IReadOnlyList Results); + /// /// The media library for administrators: the photos of all modules with where they are used, the storage against its -/// limit, and a preview of the clean-up. Read-only: deleting comes after the assumptions are checked. +/// limit, the clean-up preview, and moving photos to the trash and back. Deleting is always "to the trash": the files go +/// after the trash period. /// [ApiController] [Route("media-library")] @@ -32,6 +55,14 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t return Ok(new MediaLibraryDto(items.Select(ToDto).ToList(), library.Modules)); } + [HttpGet("trash")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Trash(CancellationToken cancellationToken) + { + var items = await library.ListTrashAsync(cancellationToken); + return Ok(new MediaLibraryDto(items.Select(ToDto).ToList(), library.Modules)); + } + [HttpGet("storage")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task Storage(CancellationToken cancellationToken) @@ -50,6 +81,47 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t return Ok(new MediaCleanupPreviewDto(clamped, onlyUnused, selected.Count, CleanupSelection.Bytes(selected), selected.Select(ToDto).ToList())); } + /// Moves photos to the trash. A photo in use is refused (status inUse) unless confirmedInUse is true. + [HttpPost("delete")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Delete([FromBody] MediaTrashRequest request, CancellationToken cancellationToken) + { + if (!ValidIds(request.Ids)) + { + return BadRequest(); + } + + var results = await library.TrashAsync(request.Ids, request.ConfirmedInUse, CallerId(), cancellationToken); + return Ok(new MediaTrashResponse(results.Select(ToDto).ToList())); + } + + [HttpPost("restore")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Restore([FromBody] MediaRestoreRequest request, CancellationToken cancellationToken) + { + if (!ValidIds(request.Ids)) + { + return BadRequest(); + } + + var results = await library.RestoreAsync(request.Ids, CallerId(), cancellationToken); + return Ok(new MediaTrashResponse(results.Select(ToDto).ToList())); + } + + private static bool ValidIds(IReadOnlyList? ids) + => ids is { Count: > 0 and <= MediaLibraryService.MaxIdsPerRequest } && ids.All(id => !string.IsNullOrWhiteSpace(id) && id.Length <= 80); + + private Guid CallerId() + { + var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"); + return Guid.TryParse(claim, out var id) ? id : Guid.Empty; + } + + private static MediaUseResultDto ToDto(MediaTrashResult result) + => new(result.Id, result.Status, result.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList()); + private static MediaPhotoDto ToDto(MediaLibraryItem item) => new( $"{item.Photo.Module}:{item.Photo.Id}", @@ -59,5 +131,8 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t item.Photo.Height, item.Photo.CreatedAt, item.Photo.ThumbnailUrl, - item.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList()); + item.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList(), + item.Photo.OriginalFileName, + item.Photo.UnusedSince, + item.Photo.DeletedAt); } diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs index 7c34f13..0938646 100644 --- a/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs @@ -1,17 +1,39 @@ +using Microsoft.Extensions.Logging; + namespace SlpModularCms.Core.Media.Library; -/// The library over all modules that report photos: one list, newest first, each photo with its uses. Read-only. +/// The result for one photo of a trash or restore request. +/// The photo id as the caller sent it (module:guid). +/// trashed, restored, inUse (not done: it is used and the caller did not confirm), notFound or failed. +/// Where the photo was used when it was refused or trashed. +public sealed record MediaTrashResult(string Id, string Status, IReadOnlyList Uses); + +/// The library over all modules that report photos: one list, newest first, each photo with its uses. public interface IMediaLibraryService { /// All photos of all modules with their uses, newest first. Task> ListAsync(CancellationToken cancellationToken); + /// The photos in the trash, most recently trashed first. + Task> ListTrashAsync(CancellationToken cancellationToken); + /// The modules that report photos (the screen warns about a module that is not in this list). IReadOnlyList Modules { get; } + + /// + /// Moves photos to the trash. The usage is checked again here, at the moment of deleting: a photo that is in use is + /// only trashed when says the person confirmed it knowing where it is used. + /// + Task> TrashAsync(IReadOnlyCollection ids, bool confirmedInUse, Guid callerId, CancellationToken cancellationToken); + + Task> RestoreAsync(IReadOnlyCollection ids, Guid callerId, CancellationToken cancellationToken); } -public sealed class MediaLibraryService(IEnumerable providers) : IMediaLibraryService +public sealed class MediaLibraryService(IEnumerable providers, ILogger? logger = null) : IMediaLibraryService { + /// The most photos one trash or restore request may name. + public const int MaxIdsPerRequest = 100; + private readonly IMediaUsageProvider[] _providers = providers.ToArray(); public IReadOnlyList Modules => _providers.Select(p => p.Module).OrderBy(m => m, StringComparer.Ordinal).ToList(); @@ -29,4 +51,111 @@ public sealed class MediaLibraryService(IEnumerable provide return items.OrderByDescending(i => i.Photo.CreatedAt).ThenBy(i => i.Photo.Id).ToList(); } + + public async Task> ListTrashAsync(CancellationToken cancellationToken) + { + var items = new List(); + foreach (var provider in _providers) + { + items.AddRange((await provider.ListTrashAsync(cancellationToken)).Select(photo => new MediaLibraryItem(photo, []))); + } + + return items.OrderByDescending(i => i.Photo.DeletedAt).ThenBy(i => i.Photo.Id).ToList(); + } + + public async Task> TrashAsync(IReadOnlyCollection ids, bool confirmedInUse, Guid callerId, CancellationToken cancellationToken) + { + EnsureWithinLimit(ids); + var results = new List(); + foreach (var id in ids.Distinct(StringComparer.Ordinal)) + { + if (!TryResolve(id, out var provider, out var photoId)) + { + results.Add(new MediaTrashResult(id, "notFound", [])); + continue; + } + + try + { + var uses = await provider.ListUsesAsync([photoId], cancellationToken); + if (uses.Count > 0 && !confirmedInUse) + { + results.Add(new MediaTrashResult(id, "inUse", uses)); + continue; + } + + var detached = await provider.TrashAsync(photoId, callerId, cancellationToken); + results.Add(new MediaTrashResult(id, detached is null ? "notFound" : "trashed", uses)); + if (detached is not null) + { + logger?.LogInformation("Media {Photo} moved to the trash by user {UserId} ({Uses} uses removed)", id, callerId, detached); + } + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + // One photo failing never stops the others; the caller sees it per photo. + logger?.LogWarning(exception, "Moving media {Photo} to the trash failed", id); + results.Add(new MediaTrashResult(id, "failed", [])); + } + } + + return results; + } + + public async Task> RestoreAsync(IReadOnlyCollection ids, Guid callerId, CancellationToken cancellationToken) + { + EnsureWithinLimit(ids); + var results = new List(); + foreach (var id in ids.Distinct(StringComparer.Ordinal)) + { + if (!TryResolve(id, out var provider, out var photoId)) + { + results.Add(new MediaTrashResult(id, "notFound", [])); + continue; + } + + try + { + var restored = await provider.RestoreAsync(photoId, callerId, cancellationToken); + results.Add(new MediaTrashResult(id, restored ? "restored" : "notFound", [])); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger?.LogWarning(exception, "Restoring media {Photo} failed", id); + results.Add(new MediaTrashResult(id, "failed", [])); + } + } + + return results; + } + + private static void EnsureWithinLimit(IReadOnlyCollection ids) + { + if (ids.Count > MaxIdsPerRequest) + { + throw new ArgumentOutOfRangeException(nameof(ids), $"At most {MaxIdsPerRequest} photos per request."); + } + } + + /// Splits module:guid and finds the provider of that module. + private bool TryResolve(string id, out IMediaUsageProvider provider, out Guid photoId) + { + provider = null!; + photoId = Guid.Empty; + var colon = id.IndexOf(':'); + if (colon <= 0 || !Guid.TryParse(id.AsSpan(colon + 1), out photoId)) + { + return false; + } + + var module = id[..colon]; + var found = _providers.FirstOrDefault(p => string.Equals(p.Module, module, StringComparison.Ordinal)); + if (found is null) + { + return false; + } + + provider = found; + return true; + } } diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs index 99023b3..6d303c2 100644 --- a/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs @@ -3,7 +3,20 @@ 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); +/// The file name as uploaded, or null for photos uploaded before it was stored. +/// The moment the photo was last detached from where it was used; null when it was never used. +/// When the photo was moved to the trash; null for a photo in the library. +public sealed record MediaPhoto( + string Module, + Guid Id, + long Bytes, + int Width, + int Height, + DateTimeOffset CreatedAt, + string? ThumbnailUrl, + string? OriginalFileName = null, + DateTimeOffset? UnusedSince = null, + DateTimeOffset? DeletedAt = null); /// 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. @@ -18,17 +31,29 @@ public sealed record MediaLibraryItem(MediaPhoto Photo, IReadOnlyList } /// -/// 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. +/// What a module tells the media library and does for it. The answers are computed from the module's own data, never copied. +/// Deleting always means "to the trash" (recoverable for a while); the module removes the files later itself. /// 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. + /// The photos of this module that are not in the trash, newest first. Task> ListPhotosAsync(CancellationToken cancellationToken); + /// The photos of this module in the trash, most recently trashed first. + Task> ListTrashAsync(CancellationToken cancellationToken); + /// Where the given photos are used (only photos of this module). Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken cancellationToken); + + /// + /// Moves a photo to the trash after detaching it from where it is used. Returns how many places lost it, or null when + /// there is no such photo outside the trash. + /// + Task TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken); + + /// Takes a photo out of the trash. False when it is not in the trash. + Task RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken); } diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs index 8d34332..6d38ce1 100644 --- a/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs @@ -8,6 +8,12 @@ namespace SlpModularCms.Modules.Hero.Tests; public class HeroMediaUsageProviderTests { + private static HeroMediaUsageProvider Provider(HeroTestRig rig) => new(rig.Repository, rig.Images); + + private static Task NoSlides() => Task.FromResult(Save([])); + + private static HeroSaveRequest Save(params HeroSlideRequest[] slides) => new("Titel", null, null, "single", [], slides); + [Fact] public async Task Lists_the_images_newest_first_with_a_thumbnail_and_reports_one_use_per_slide_with_its_position() { @@ -18,10 +24,9 @@ public class HeroMediaUsageProviderTests 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)]), + Save(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 provider = Provider(rig); var photos = await provider.ListPhotosAsync(CancellationToken.None); var uses = await provider.ListUsesAsync(photos.Select(p => p.Id).ToList(), CancellationToken.None); @@ -40,12 +45,150 @@ public class HeroMediaUsageProviderTests { using var rig = new HeroTestRig(); var image = await rig.Upload(HeroTestRig.Photo()); - var provider = new HeroMediaUsageProvider(rig.Repository); + var provider = Provider(rig); await provider.ListPhotosAsync(CancellationToken.None); await provider.ListUsesAsync([Guid.Parse(image.Id)], CancellationToken.None); + await provider.ListTrashAsync(CancellationToken.None); (await rig.Repository.CountImagesAsync(CancellationToken.None)).Should().Be(1); rig.Db.ChangeTracker.HasChanges().Should().BeFalse(); } + + [Fact] + public async Task An_upload_remembers_the_cleaned_original_file_name() + { + using var rig = new HeroTestRig(); + var bytes = HeroTestRig.Photo(); + + await rig.Images.UploadAsync(new MemoryStream(bytes), bytes.Length, HeroTestRig.Admin, CancellationToken.None, "C:\\fotos\\zomer\u0007 2026.jpg"); + + (await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().OriginalFileName.Should().Be("zomer 2026.jpg"); + } + + [Theory] + [InlineData(null, null)] + [InlineData(" ", null)] + [InlineData("../../etc/passwd", "passwd")] + [InlineData("a/b\\c.jpg", "c.jpg")] + public void File_names_are_cleaned_for_display_only(string? input, string? expected) => HeroFileNames.Clean(input).Should().Be(expected); + + [Fact] + public void A_very_long_file_name_is_cut() => HeroFileNames.Clean(new string('a', 500))!.Length.Should().Be(HeroFileNames.MaxLength); + + [Fact] + public async Task Trashing_a_photo_in_use_removes_its_slides_hides_it_and_remembers_the_last_use() + { + using var rig = new HeroTestRig(); + var a = await rig.Upload(HeroTestRig.Photo(seed: 1)); + var b = await rig.Upload(HeroTestRig.Photo(seed: 2)); + await rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "een"), new HeroSlideRequest(null, Guid.Parse(b.Id), "twee")), HeroTestRig.Admin, CancellationToken.None); + var provider = Provider(rig); + rig.Time.Now = rig.Time.Now.AddDays(3); + + var removed = await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None); + + removed.Should().Be(1); + (await provider.ListPhotosAsync(CancellationToken.None)).Select(p => p.Id).Should().Equal(Guid.Parse(b.Id)); + var trashed = (await provider.ListTrashAsync(CancellationToken.None)).Single(); + trashed.Id.Should().Be(Guid.Parse(a.Id)); + trashed.DeletedAt.Should().Be(rig.Time.Now); + trashed.UnusedSince.Should().Be(rig.Time.Now); + (await rig.Service.GetAsync(CancellationToken.None)).Slides.Should().ContainSingle().Which.Image.Id.Should().Be(b.Id); + } + + [Fact] + public async Task A_trashed_photo_cannot_be_put_in_a_slide_and_is_not_cut_in_the_background() + { + using var rig = new HeroTestRig(); + var a = await rig.UploadWithoutRendering(HeroTestRig.Photo()); + var provider = Provider(rig); + await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None); + + var save = () => rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "foto")), HeroTestRig.Admin, CancellationToken.None); + + await save.Should().ThrowAsync(); + (await rig.RenderPending()).Should().Be(0); + } + + [Fact] + public async Task Trashing_an_unknown_or_already_trashed_photo_gives_null() + { + using var rig = new HeroTestRig(); + var a = await rig.Upload(HeroTestRig.Photo()); + var provider = Provider(rig); + + (await provider.TrashAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None)).Should().BeNull(); + await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None); + (await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().BeNull(); + } + + [Fact] + public async Task Restoring_brings_the_photo_back_without_its_slides() + { + using var rig = new HeroTestRig(); + var a = await rig.Upload(HeroTestRig.Photo()); + await rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "foto")), HeroTestRig.Admin, CancellationToken.None); + var provider = Provider(rig); + await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None); + + (await provider.RestoreAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().BeTrue(); + (await provider.RestoreAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().BeFalse(); + + (await provider.ListPhotosAsync(CancellationToken.None)).Should().ContainSingle(); + (await provider.ListTrashAsync(CancellationToken.None)).Should().BeEmpty(); + (await provider.ListUsesAsync([Guid.Parse(a.Id)], CancellationToken.None)).Should().BeEmpty(); + } + + [Fact] + public async Task Uploading_the_same_photo_again_brings_it_back_from_the_trash() + { + using var rig = new HeroTestRig(); + var bytes = HeroTestRig.Photo(); + var first = await rig.Upload(bytes); + var provider = Provider(rig); + await provider.TrashAsync(Guid.Parse(first.Id), HeroTestRig.Admin, CancellationToken.None); + + var again = await rig.Upload(bytes); + + again.Id.Should().Be(first.Id); + (await provider.ListTrashAsync(CancellationToken.None)).Should().BeEmpty(); + (await provider.ListPhotosAsync(CancellationToken.None)).Should().ContainSingle(); + } + + [Fact] + public async Task Saving_the_hero_without_a_slide_remembers_when_its_photo_was_last_used() + { + using var rig = new HeroTestRig(); + var a = await rig.Upload(HeroTestRig.Photo()); + await rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "foto")), HeroTestRig.Admin, CancellationToken.None); + (await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().UnusedSince.Should().BeNull(); + + rig.Time.Now = rig.Time.Now.AddDays(2); + await rig.Service.SaveAsync(Save(), HeroTestRig.Admin, CancellationToken.None); + + (await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().UnusedSince.Should().Be(rig.Time.Now); + } + + [Fact] + public async Task A_trashed_photo_is_emptied_from_the_trash_after_the_trash_period_and_its_files_go() + { + using var rig = new HeroTestRig(); + var a = await rig.Upload(HeroTestRig.Photo()); + var row = rig.Db.HeroImages.Single(); + var (set, original) = (row.SetHash, row.OriginalKey); + await Provider(rig).TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None); + + rig.Time.Now = rig.Time.Now.AddDays(6); + await rig.Cleanup.RunOnceAsync(CancellationToken.None); + rig.Db.HeroImages.Should().HaveCount(1); + (await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeTrue(); + + rig.Time.Now = rig.Time.Now.AddDays(2); + await rig.Cleanup.RunOnceAsync(CancellationToken.None); + + rig.Db.HeroImages.Should().BeEmpty(); + (await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().NotContain(s => s.SetHash == set); + (await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse(); + } } diff --git a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs index c3ee9d3..9c727e2 100644 --- a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs +++ b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs @@ -82,7 +82,7 @@ public class HeroImagesController(IHeroImageService service, IOptionsThe file name as uploaded (for display only, cleaned; never used as a path). Null for photos uploaded before it was stored. + public string? OriginalFileName { get; set; } + + /// The moment the photo was last detached from a slide; null while it was never used. The clean-up counts from here (decision 8). + public DateTimeOffset? LastUsedAt { get; set; } + + /// Set when the photo was moved to the trash; its files stay for Media:TrashDays and it is hidden from the hero. + public DateTimeOffset? DeletedAt { get; set; } + public FocusSetting General => new FocusSetting(FocusX, FocusY, Zoom).Normalize(); public FocusSetting FocusFor(string ratio) => ratio switch diff --git a/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs b/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs index b54b803..8bc1846 100644 --- a/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs +++ b/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs @@ -60,6 +60,7 @@ public class HeroDbContext(DbContextOptions options) : DbContext( entity.Property(e => e.SetHash).IsRequired().HasMaxLength(16); entity.Property(e => e.CreatedAt).IsRequired(); entity.Property(e => e.CreatedByUserId).IsRequired(); + entity.Property(e => e.OriginalFileName).HasMaxLength(200); entity.Ignore(e => e.General); // The variants of the current set: a small list that is always replaced as a whole. diff --git a/src/SlpModularCms.Modules.Hero/Migrations/20261117140509_AddMediaLibraryColumns.Designer.cs b/src/SlpModularCms.Modules.Hero/Migrations/20261117140509_AddMediaLibraryColumns.Designer.cs new file mode 100644 index 0000000..9217d07 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Migrations/20261117140509_AddMediaLibraryColumns.Designer.cs @@ -0,0 +1,257 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Hero.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Hero.Migrations +{ + [DbContext(typeof(HeroDbContext))] + [Migration("20261117140509_AddMediaLibraryColumns")] + partial class AddMediaLibraryColumns + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Button1Label") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Button1Target") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("Button2Label") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Button2Target") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("Display") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("Lead") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("Tagline") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("Language") + .IsUnique(); + + b.ToTable("Heroes", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroImage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CreatedByUserId") + .HasColumnType("char(36)"); + + b.Property("DeletedAt") + .HasColumnType("datetime"); + + b.Property("FocusX") + .HasColumnType("double"); + + b.Property("FocusY") + .HasColumnType("double"); + + b.Property("Height") + .HasColumnType("int"); + + b.Property("LastUsedAt") + .HasColumnType("datetime"); + + b.Property("OriginalFileName") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("OriginalKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("OriginalSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("SetHash") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("SourceFormat") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("TallFocusX") + .HasColumnType("double"); + + b.Property("TallFocusY") + .HasColumnType("double"); + + b.Property("TallZoom") + .HasColumnType("double"); + + b.Property("Variants") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("WideFocusX") + .HasColumnType("double"); + + b.Property("WideFocusY") + .HasColumnType("double"); + + b.Property("WideZoom") + .HasColumnType("double"); + + b.Property("Width") + .HasColumnType("int"); + + b.Property("Zoom") + .HasColumnType("double"); + + b.HasKey("Id"); + + b.HasIndex("OriginalSha256") + .IsUnique(); + + b.ToTable("HeroImages", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroRetiredFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("RetiredAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.ToTable("HeroRetiredFiles", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Alt") + .IsRequired() + .HasMaxLength(600) + .HasColumnType("varchar(600)"); + + b.Property("Decorative") + .HasColumnType("tinyint(1)"); + + b.Property("HeroId") + .HasColumnType("char(36)"); + + b.Property("ImageId") + .HasColumnType("char(36)"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ImageId"); + + b.HasIndex("HeroId", "SortOrder"); + + b.ToTable("HeroSlides", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b => + { + b.HasOne("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", null) + .WithMany("Slides") + .HasForeignKey("HeroId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SlpModularCms.Modules.Hero.Data.Entities.HeroImage", "Image") + .WithMany() + .HasForeignKey("ImageId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Image"); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", b => + { + b.Navigation("Slides"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Hero/Migrations/20261117140509_AddMediaLibraryColumns.cs b/src/SlpModularCms.Modules.Hero/Migrations/20261117140509_AddMediaLibraryColumns.cs new file mode 100644 index 0000000..64b40c6 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Migrations/20261117140509_AddMediaLibraryColumns.cs @@ -0,0 +1,50 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Hero.Migrations +{ + /// + public partial class AddMediaLibraryColumns : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "DeletedAt", + table: "HeroImages", + type: "datetime", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastUsedAt", + table: "HeroImages", + type: "datetime", + nullable: true); + + migrationBuilder.AddColumn( + name: "OriginalFileName", + table: "HeroImages", + type: "varchar(200)", + maxLength: 200, + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "DeletedAt", + table: "HeroImages"); + + migrationBuilder.DropColumn( + name: "LastUsedAt", + table: "HeroImages"); + + migrationBuilder.DropColumn( + name: "OriginalFileName", + table: "HeroImages"); + } + } +} diff --git a/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs index 0894cdb..822eb07 100644 --- a/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs +++ b/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs @@ -93,6 +93,9 @@ namespace SlpModularCms.Modules.Hero.Migrations b.Property("CreatedByUserId") .HasColumnType("char(36)"); + b.Property("DeletedAt") + .HasColumnType("datetime"); + b.Property("FocusX") .HasColumnType("double"); @@ -102,6 +105,13 @@ namespace SlpModularCms.Modules.Hero.Migrations b.Property("Height") .HasColumnType("int"); + b.Property("LastUsedAt") + .HasColumnType("datetime"); + + b.Property("OriginalFileName") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + b.Property("OriginalKey") .IsRequired() .HasMaxLength(200) diff --git a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs index 2b2126f..231c964 100644 --- a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs +++ b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs @@ -22,6 +22,18 @@ public interface IHeroRepository /// Images whose set is missing or does not match their focus, oldest first (tracked). Task CountImagesAsync(CancellationToken cancellationToken); + /// An image whether or not it is in the trash, tracked (restore, trash). + Task GetImageIncludingTrashedAsync(Guid id, CancellationToken cancellationToken); + + /// The photos in the trash, most recently trashed first, not tracked. + Task> GetTrashedImagesReadOnlyAsync(CancellationToken cancellationToken); + + /// Photos that were trashed before the cutoff, tracked (the trash is emptied for them). + Task> GetTrashedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken); + + /// The slides that use an image, tracked (they are removed when the image goes to the trash). + Task> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken); + /// All images, newest first, not tracked (the media library lists them). Task> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken); @@ -70,32 +82,44 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository public void RemoveSlide(HeroSlide slide) => context.HeroSlides.Remove(slide); public Task GetImageAsync(Guid id, CancellationToken cancellationToken) + => context.HeroImages.FirstOrDefaultAsync(i => i.Id == id && i.DeletedAt == null, cancellationToken); + + public Task GetImageIncludingTrashedAsync(Guid id, CancellationToken cancellationToken) => context.HeroImages.FirstOrDefaultAsync(i => i.Id == id, cancellationToken); + public async Task> GetTrashedImagesReadOnlyAsync(CancellationToken cancellationToken) + => (await context.HeroImages.AsNoTracking().Where(i => i.DeletedAt != null).ToListAsync(cancellationToken)).OrderByDescending(i => i.DeletedAt).ToList(); + + public async Task> GetTrashedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken) + => (await context.HeroImages.Where(i => i.DeletedAt != null).ToListAsync(cancellationToken)).Where(i => i.DeletedAt < cutoff).ToList(); + + public async Task> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken) + => await context.HeroSlides.Where(s => s.ImageId == imageId).ToListAsync(cancellationToken); + public async Task> GetImagesAsync(IReadOnlyCollection ids, CancellationToken cancellationToken) { // The MySQL provider cannot map a Guid list parameter in an IN clause; there are only a few dozen images, so they // are read and filtered here. var wanted = ids.ToHashSet(); - return (await context.HeroImages.ToListAsync(cancellationToken)).Where(i => wanted.Contains(i.Id)).ToList(); + return (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(i => wanted.Contains(i.Id)).ToList(); } 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(); + => (await context.HeroImages.AsNoTracking().Where(i => i.DeletedAt == null).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(); + => (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(HeroMapping.NeedsRender).OrderBy(i => i.CreatedAt).ToList(); public async Task> GetImagesNeedingPreviewAsync(CancellationToken cancellationToken) - => (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsPreview).OrderBy(i => i.CreatedAt).ToList(); + => (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(HeroMapping.NeedsPreview).OrderBy(i => i.CreatedAt).ToList(); public Task GetImageFreshAsync(Guid id, CancellationToken cancellationToken) - => context.HeroImages.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id, cancellationToken); + => context.HeroImages.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id && i.DeletedAt == null, cancellationToken); public Task GetImageBySha256Async(string sha256, CancellationToken cancellationToken) => context.HeroImages.FirstOrDefaultAsync(i => i.OriginalSha256 == sha256, cancellationToken); @@ -110,7 +134,7 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository public async Task> GetUnattachedImagesCreatedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken) { var used = context.HeroSlides.Select(s => s.ImageId); - var candidates = await context.HeroImages.Where(i => !used.Contains(i.Id)).ToListAsync(cancellationToken); + var candidates = await context.HeroImages.Where(i => !used.Contains(i.Id) && i.DeletedAt == null).ToListAsync(cancellationToken); return candidates.Where(i => i.CreatedAt < cutoff).ToList(); } diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs index d2482ac..3759993 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs @@ -31,7 +31,7 @@ public interface IHeroImageService /// image. Until its set exists the image has no variants and is not published. /// /// The upload is refused; see the code. - Task UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken); + Task UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken, string? originalFileName = null); /// How many images exist, how many wait for their variants and how many only lack the full-frame preview (for the log). Task<(int Total, int NeedRender, int NeedPreview)> GetRenderBacklogAsync(CancellationToken cancellationToken); @@ -67,6 +67,16 @@ public interface IHeroImageService /// Removes an image nothing uses; its files go after the retention time. Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); + + /// + /// Moves an image to the trash: the slides that use it are removed from the hero (and remember the moment as its last use), + /// it disappears from the hero and its files stay for the trash period. Returns how many slides were removed. + /// + /// There is no such image outside the trash. + Task TrashAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); + + /// Takes an image out of the trash again. False when it is not in the trash. + Task RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); } public class HeroImageService( @@ -83,7 +93,7 @@ public class HeroImageService( { private readonly TimeProvider _time = time ?? TimeProvider.System; - public async Task UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken) + public async Task UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken, string? originalFileName = null) { using var admitted = await guard.AdmitAsync(upload, declaredLength, cancellationToken); var sha = Convert.ToHexStringLower(SHA256.HashData(admitted.Bytes)); @@ -91,8 +101,18 @@ public class HeroImageService( // The same photo again is the same image. When its files are gone (a lost or restored media directory) the upload // repairs them from the file that was just sent. var existing = await repository.GetImageBySha256Async(sha, cancellationToken); + var fileName = HeroFileNames.Clean(originalFileName); + + // The same photo uploaded again also brings it back from the trash. + if (existing is not null) + { + existing.DeletedAt = null; + existing.OriginalFileName ??= fileName; + } + if (existing is not null && await FilesExistAsync(existing, cancellationToken)) { + await repository.SaveChangesAsync(cancellationToken); // The same photo again also gives up the failed state: the renderer tries it again when it is still pending. signal?.Reset(existing.Id); signal?.Notify(); @@ -118,6 +138,7 @@ public class HeroImageService( Bytes = original.Length, CreatedAt = _time.GetUtcNow(), CreatedByUserId = callerId, + OriginalFileName = fileName, }; // The files first, the row last: an aborted request leaves at most an original nobody refers to (the clean-up @@ -323,6 +344,47 @@ public class HeroImageService( logger.LogInformation("Hero image {ImageId} removed by user {UserId}", imageId, callerId); } + public async Task TrashAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken) + { + var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException(); + var now = _time.GetUtcNow(); + + // A slide cannot exist without its image, so the slides that use it go with it; the moment counts as its last use. + var slides = await repository.GetSlidesOfImageAsync(imageId, cancellationToken); + foreach (var slide in slides) + { + repository.RemoveSlide(slide); + } + + if (slides.Count > 0) + { + image.LastUsedAt = now; + } + + image.DeletedAt = now; + await repository.SaveChangesAsync(cancellationToken); + indexCache?.Invalidate(); + + logger.LogInformation("Hero image {ImageId} moved to the trash by user {UserId} ({Slides} slides removed)", imageId, callerId, slides.Count); + return slides.Count; + } + + public async Task RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken) + { + var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken); + if (image is null || image.DeletedAt is null) + { + return false; + } + + image.DeletedAt = null; + await repository.SaveChangesAsync(cancellationToken); + signal?.Notify(); + + logger.LogInformation("Hero image {ImageId} restored from the trash by user {UserId}", imageId, callerId); + return true; + } + private static void Apply(FocusDto? value, Action<(double?, double?, double?)> assign) { if (value is null) @@ -378,3 +440,26 @@ public class HeroImageService( } } } + +/// The file name of an upload as it is shown in the library: cleaned, for display only, never part of a path. +public static class HeroFileNames +{ + public const int MaxLength = 200; + + public static string? Clean(string? name) + { + if (string.IsNullOrWhiteSpace(name)) + { + return null; + } + + var last = name[(name.LastIndexOfAny(['/', '\\']) + 1)..]; + var cleaned = new string(last.Where(c => !char.IsControl(c)).ToArray()).Trim(); + if (cleaned.Length > MaxLength) + { + cleaned = cleaned[..MaxLength]; + } + + return cleaned.Length == 0 ? null : cleaned; + } +} diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs index 0fe2e7d..024c6f6 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroMediaCleanup.cs @@ -40,6 +40,15 @@ public class HeroMediaCleanup( repository.RemoveImage(image); } + // 1b. Photos that have been in the trash for the trash period: their files go now (they are retired, immediately due). + var trashCutoff = now.AddDays(-Math.Max(0, options.Value.TrashDays)); + foreach (var image in await repository.GetTrashedBeforeAsync(trashCutoff, cancellationToken)) + { + repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = image.SetHash, RetiredAt = cutoff.AddSeconds(-1) }); + repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = cutoff.AddSeconds(-1) }); + repository.RemoveImage(image); + } + await repository.SaveChangesAsync(cancellationToken); // 2. Retired files whose retention has passed, unless an image uses them again. diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs index e386da1..5c088e2 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs @@ -7,21 +7,19 @@ 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. +/// hero), and moves them to the trash and back for it. The files are removed by after the trash period. /// -public class HeroMediaUsageProvider(IHeroRepository repository) : IMediaUsageProvider +public class HeroMediaUsageProvider(IHeroRepository repository, IHeroImageService images) : 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(); - } + => (await repository.GetAllImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList(); + + public async Task> ListTrashAsync(CancellationToken cancellationToken) + => (await repository.GetTrashedImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList(); public async Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken cancellationToken) { @@ -46,6 +44,24 @@ public class HeroMediaUsageProvider(IHeroRepository repository) : IMediaUsagePro return uses; } + public async Task TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken) + { + try + { + return await images.TrashAsync(photoId, callerId, cancellationToken); + } + catch (HeroImageNotFoundException) + { + return null; + } + } + + public Task RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken) + => images.RestoreAsync(photoId, callerId, cancellationToken); + + private MediaPhoto ToPhoto(HeroImage i) + => new(Module, i.Id, i.Bytes, i.Width, i.Height, i.CreatedAt, Thumbnail(i), i.OriginalFileName, i.LastUsedAt, i.DeletedAt); + /// The smallest published WebP of the set; null while the set is not cut yet. private static string? Thumbnail(HeroImage image) { diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroService.cs index 98b4752..162b691 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroService.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroService.cs @@ -121,8 +121,15 @@ public class HeroService( slide.SortOrder = i; } + // A photo that no slide uses any more remembers when it was last used (the media library counts from there). + var stillUsed = slideRequests.Select(r => r.ImageId).ToHashSet(); foreach (var removed in hero.Slides.Where(s => !keep.Contains(s.Id)).ToList()) { + if (removed.Image is { } detached && !stillUsed.Contains(detached.Id)) + { + detached.LastUsedAt = now; + } + hero.Slides.Remove(removed); if (!created) { -- 2.39.5 From a01bcd33c47f537d2d77518774665a97a332e88a Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 15:18:15 +0100 Subject: [PATCH 07/22] Mediabibliotheek: verwijderen naar prullenbak in de UI, terugzetten, opruimen bevestigen, migratieplan, besluiten van Bryan in de docs Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 35 +++--- .../application-design/application-design.md | 26 ++++ .../application-design/migration-plan.md | 73 ++++++++++++ .../inception/requirements/requirements.md | 15 ++- docs/hero-module.md | 2 +- .../media/components/CleanupDialog.tsx | 24 +++- .../media/components/DeleteDialog.tsx | 111 +++++++++++++++++ .../media/components/PhotoSelectionList.tsx | 21 ++-- .../src/features/media/lib/toPhotoItem.ts | 6 +- frontend/src/features/media/lib/usageLabel.ts | 15 +++ frontend/src/features/media/mocks/handlers.ts | 33 +++++- .../media/pages/MediaLibraryPage.test.tsx | 112 +++++++++++++++++- .../features/media/pages/MediaLibraryPage.tsx | 61 ++++++++-- frontend/src/features/media/services/hooks.ts | 31 ++++- frontend/src/features/media/services/types.ts | 23 ++++ frontend/src/i18n/locales/en/translation.json | 36 +++++- frontend/src/i18n/locales/nl/translation.json | 36 +++++- 17 files changed, 604 insertions(+), 56 deletions(-) create mode 100644 aidlc-docs/features/media-library/inception/application-design/migration-plan.md create mode 100644 frontend/src/features/media/components/DeleteDialog.tsx create mode 100644 frontend/src/features/media/lib/usageLabel.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 4e6fa63..6e4b948 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -4,34 +4,34 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | # | 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 | +| 1 | Which **uses** (places and ratios) exist? **[Confirmed by Bryan "as designed", 2026-11-17]** | 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? **[Confirmed by Bryan "as designed", 2026-11-17]** | 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. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | **Built (2026-11-17, safe: default unchanged)**: the setting `Media:AutoCleanupUnattached` exists, default `true` (today's behaviour); set `Media__AutoCleanupUnattached=false` per host to keep every upload. Plan: switch it off (default `false`) once the library screen and delete are accepted by Bryan. 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? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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` | +| 5 | **Public addresses**: per module (`/media//...`) or a shared path? **[Confirmed by Bryan "as designed", 2026-11-17]** | 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? **[Confirmed by Bryan "as designed", 2026-11-17]** | 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? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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` | +| 9 | **Storage limit and warning**. **[Confirmed by Bryan "as designed", 2026-11-17]** | 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**. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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` | +| 11 | **Shared upload service**: does Hero's upload move into the library? **[Confirmed by Bryan "as designed", 2026-11-17]** | 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)? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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). **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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` | +| 14 | **Crop per use**: data per use or per photo? **[Confirmed by Bryan "as designed", 2026-11-17]** | 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? **[Confirmed by Bryan "as designed", 2026-11-17]** | 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. **[Confirmed by Bryan "as designed", 2026-11-17]** | 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` | +| 19 | The **position** of a slide in "Hero, slide 3". **[Confirmed by Bryan "as designed", 2026-11-17]** | 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. **[Confirmed by Bryan "as designed", 2026-11-17]** | 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. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | 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). | **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` | +| 26 | **Choose or upload everywhere (ML-17)**: how does the Hero upload relate to the library? **[Confirmed by Bryan "as designed", 2026-11-17]** | 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? **[Confirmed by Bryan "as designed", 2026-11-17]** | 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. **[Confirmed by Bryan "as designed", 2026-11-17]** | 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` | ## Decisions of the second round (Bryan, 2026-11-17, via SLP Software - SLS - Main) @@ -54,3 +54,10 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 30 | **Detaching a used photo when it is deleted** (decision 10). | In the Hero the slides that use the photo are removed from the hero (a slide cannot exist without an image); the second confirmation names them ("Hero, slide 3"). The hero then has fewer slides and stays published as long as it has a title. | Keep the slide and mark it "image missing" until a new image is chosen: needs a nullable slide image and a changed public contract. | `HeroMediaUsageProvider.TrashAsync` | | 31 | **Trash mechanics** (decision 12). | `DeletedAt` on the Hero image: a trashed photo is hidden from the Hero (slides, upload by hash, renderer) and shown in the library trash; Restore clears it. After 7 days the cleanup turns it into retired files (removed immediately) and removes the row. Uploading the same file again restores it. The trash period is `Media:TrashDays` (7). | Another period: the setting; no trash: delete straight to retired files. | `HeroImage.DeletedAt`, `HeroMediaCleanup`, `MediaOptions.TrashDays` | | 32 | **Migration of `HeroImages`** (decision 13): the plan and the safeguards. | Designed in `inception/application-design/migration-plan.md` (back-up, rollback, verification, test-only rollout). The additive columns of this round (`OriginalFileName`, `DeletedAt`, `LastUsedAt`) are copied with the rest. Not run anywhere until SLS-Main has been told and agrees to the test deploy. | n/a | `migration-plan.md` | + +### Status of the assumptions (2026-11-17) + +- **Decided by Bryan** (second round, table above): 3, 4, 7, 8, 10, 12, 13, 21. +- **Confirmed by Bryan "as designed"**: 1, 2, 5, 6, 9, 11, 14, 15, 16, 19, 20, 26, 27, 28. +- **Still assumptions** (not put to him separately): 17 (language), 18 (what phase A contained, now overtaken), 22 (selectability), 23 (performance), 24 (ASF data), 25 (use definitions); and the older rows 18 to 25 above. Assumptions 29 to 32 follow from his decisions. +- Assumption 12 now reads: there IS a trash (decision 12), the earlier "no trash in phase A" no longer applies. Assumption 10: deleting a used photo is possible after a second confirmation (built). Assumption 21: the original file name is stored from now on (built). 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 0df30fa..cc190e8 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 @@ -216,3 +216,29 @@ Text alternative: a module screen uses the picker, which either chooses a librar - 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. + +## 11. Delete, trash and last use (built 2026-11-17, decisions 8, 10, 12, 21) + +```mermaid +flowchart LR + L[Library or Clean-up] -->|delete ids| C[MediaLibraryService] + C -->|uses again| P[Usage provider] + P -->|none, or confirmed twice| T[Module trash: detach and DeletedAt] + T --> TR[(Trash 7 days)] + TR -->|restore| P + TR -->|after the period| R[Retired files, removed with the sets] + classDef a fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + classDef b fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef c fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + class L a; + class C,P b; + class T,TR,R c; +``` + +Text alternative: delete goes through the library service, which checks the usage again and asks the module to trash the photo; the trash keeps it for the trash period and can restore it; afterwards its files are retired and removed. + +- API: `POST media-library/delete {ids, confirmedInUse}` and `POST media-library/restore {ids}` (at most 100 ids), `GET media-library/trash`; the answer lists a status per photo (`trashed`, `inUse`, `notFound`, `failed`). +- Hero: `HeroImages.DeletedAt`, `LastUsedAt`, `OriginalFileName` (additive migration `AddMediaLibraryColumns`); a trashed image is left out of every Hero lookup, the renderer and slide validation; slides using it are removed when it is trashed; `HeroMediaCleanup` empties the trash after `Media:TrashDays`. +- Last use: `LastUsedAt` is set when a hero save detaches the photo from its last slide, and when it is trashed while in use. The clean-up counts from there (assumption 29). +- Frontend: `DeleteDialog` (first and second confirmation), trash view with Restore, the clean-up dialog now confirms into the same delete flow. +- The migration to own tables is planned in `migration-plan.md` (not built). diff --git a/aidlc-docs/features/media-library/inception/application-design/migration-plan.md b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md new file mode 100644 index 0000000..78329b5 --- /dev/null +++ b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md @@ -0,0 +1,73 @@ +# Migration plan: HeroImages to the library's own tables (decision 13) + +Status: plan, not built, not run anywhere. Decided by Bryan 2026-11-17 (via SLP Software - SLS - Main): it may be built in the next step, **only after this plan with its back-up and rollback exists**, **rolled out to TEST only (never production)**, and **SLS-Main is told before anything is deployed to test**. + +## Goal + +Give every photo one library record that does not depend on the Hero: `MediaAsset` (the photo) and `MediaUse` (where it is used), with **the same ids, hashes, set hashes and public addresses** as today. Nothing in `/media/hero//...` changes, so ASF, SLS and the golden files stay as they are. + +## Why expand then contract + +| Phase | What | Reversible? | +|---|---|---| +| 0 Back-up | Back-up of the database and a listing of the media directory (below). | n/a | +| 1 Expand | New tables `MediaAssets` and `MediaUses`, filled by copying `HeroImages` and `HeroSlides`. The Hero keeps reading and writing its own tables; the library reads the new tables behind a setting. | Yes: drop the two new tables, nothing else changed. | +| 2 Switch | Hero reads photos from the library tables (setting on). New uploads write both (dual write) so the old tables stay complete. | Yes: switch the setting off; the old tables are complete. | +| 3 Contract (a later release, after acceptance) | The Hero stops writing its own image columns; they are dropped in a separate migration. | Only from the back-up of that moment. Not part of the first rollout. | + +Files are never moved or renamed: the migration changes rows only, so the media directory is the same before and after. + +## Mapping + +| `HeroImages` column | `MediaAssets` column | Note | +|---|---|---| +| `Id` | `Id` | Same id, so references keep working. | +| `OriginalSha256`, `OriginalKey`, `SourceFormat`, `Width`, `Height`, `Bytes` | same | | +| `FocusX`, `FocusY`, `Zoom` | `DefaultFocusX`, `DefaultFocusY`, `DefaultZoom` | The photo's default focus. | +| `WideFocus*`, `TallFocus*` | `MediaUses` rows (one per slide use, ratios `wide` and `tall`) | The per-use crop; for a photo without a slide the default focus is enough. | +| `SetHash`, `Variants` | `MediaUses.SetHash` (per use) | Unchanged values; computed by the existing formula. | +| `CreatedAt`, `CreatedByUserId` | same | | +| `OriginalFileName`, `LastUsedAt`, `DeletedAt` | same | Added in the media-library step (additive columns of the Hero). | + +| `HeroSlides` | `MediaUses` | +|---|---| +| `Id`, `ImageId` | `Id`, `AssetId` (module `hero`, place kind `slide`, place id = slide id) | + +## Back-up (before phase 1, every environment) + +1. **Database**: a full dump of the Hero database (and of the CMS database if it is one), written to a dated file outside the deploy directory, for example `mysqldump --single-transaction > hero-before-media-migration-YYYYMMDD.sql`. Keep it until the contract phase is accepted. +2. **Media directory**: nothing is moved, but a listing with sizes and hashes is saved (`find -type f -exec sha256sum {} +` to a text file) so the directory can be compared afterwards. On the Raspberry Pi a copy of the directory is also a quick option (`cp -a`), if there is room. +3. **Row counts** noted: `HeroImages`, `HeroSlides`, `HeroRetiredFiles`. + +## Verification (right after phase 1, every environment) + +The migration job compares and **aborts** (rolls its transaction back) on any difference: + +- number of `MediaAssets` = number of `HeroImages` (all rows, also those in the trash); +- every `HeroImages.Id`, `OriginalSha256` and `SetHash` has an identical `MediaAssets`/`MediaUses` counterpart; +- number of `MediaUses` of module `hero` = number of `HeroSlides`; +- a sample of ten public addresses (`/media/hero//`) is requested before and after and gives the same bytes (checked by the smoke test). + +## Rollback + +| When | How | +|---|---| +| The verification fails | The migration runs in one transaction and rolls back by itself; nothing is left. | +| After phase 1, before the switch | Drop `MediaUses` and `MediaAssets` (the EF `Down` migration). The Hero never read them. | +| After the switch | Switch the setting back (`Media:Library:ReadFromLibrary=false`); the old tables are complete because of the dual write. Then drop the new tables if wanted. | +| After the contract phase (later) | Restore the database dump taken before that migration and the media listing check. | + +## Roll-out rules (from Bryan) + +1. **Test only.** No production variables, no production deploy, no release branch. +2. **Tell SLS-Main before deploying to test** (they run the deploy and the smoke test). +3. Back-up first (above), on the test host too. +4. Deploy with the setting **off**, check the verification result in the log, then switch it on, then the smoke test (hero markers, `/theme-init.js`, a sample of media addresses), then Bryan checks the admin. + +## What is built first (next step, when this plan is accepted) + +1. A new module `SlpModularCms.Modules.Media` with its own `DbContext`, the tables `MediaAssets` and `MediaUses` and an additive EF migration (no existing table touched), with tests. +2. The copy-and-verify job (idempotent, safe to run twice) behind a setting; unit and in-memory tests, and a test against MariaDB. +3. The library reading from the new tables behind `Media:Library:ReadFromLibrary` (default off). + +Nothing in steps 1 to 3 runs without the setting, so a deploy of that code alone changes no data except the new, empty tables. diff --git a/aidlc-docs/features/media-library/inception/requirements/requirements.md b/aidlc-docs/features/media-library/inception/requirements/requirements.md index 2d91930..6632683 100644 --- a/aidlc-docs/features/media-library/inception/requirements/requirements.md +++ b/aidlc-docs/features/media-library/inception/requirements/requirements.md @@ -39,9 +39,9 @@ | 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-05 | **Bulk actions** on the selection, in the library itself. First action: **Delete** (to the trash, ML-18). 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** (decision 10). A photo that is in use can be deleted after a **second confirmation that names the places**; the module detaches it first (Hero: its slides are removed). | The first confirmation says how many photos and how many are in use; the second names the places per photo; the server refuses a photo in use unless the request carries the confirmation and checks the usage again at that moment; one photo failing does not stop the others and is reported per photo. | +| ML-07 | **"Clean up" button.** Opens the overview of photos that would be cleaned: default everything not used for more than 7 days (counted from the LAST USE, decision 8), 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). | @@ -105,3 +105,12 @@ | 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 | + +## 11. Added by decisions of 2026-11-17 + +| ID | Requirement | Acceptance criteria | +|---|---|---| +| ML-18 | **Trash** (decision 12). Delete means "to the trash": recoverable for 7 days (`Media:TrashDays`); a trash view lists the photos with Restore; after the period the files are removed by the existing retired-file mechanism. Uploading the same file again brings it back. | A trashed photo is hidden from the hero and from the renderer; restore returns it (without its old slides); the clean-up of the trash is idempotent; a photo is never removed while it is referenced. | +| ML-19 | **Original file name** is stored at every upload (additive) and shown in the library; photos from before keep a neutral label. | The name is cleaned (no path, no control characters, at most 200 characters) and never used as a path. | +| ML-20 | **Last use** per photo: the moment it was last detached from a slide (or trashed); the clean-up period counts from there, from the upload date for a photo that was never used. | See assumption 29. | +| ML-21 | **Migration of the Hero photos** to the library's own tables, expand then contract, same ids, hashes and addresses; documented back-up and rollback first; test only; SLS-Main is told before a test deploy. | See `migration-plan.md`. | diff --git a/docs/hero-module.md b/docs/hero-module.md index b40ae1c..a5fca83 100644 --- a/docs/hero-module.md +++ b/docs/hero-module.md @@ -26,7 +26,7 @@ De admin toont alleen een badge Live of Niet live. | Instelling | Betekenis | |---|---| | `Media__Directory` | De map voor de afbeeldingen, **buiten de release** en buiten de webroot. Zonder deze instelling (of als de map niet beschrijfbaar is) staan uploads uit; bestaande bestanden en de publieke hero blijven werken. Niet in een committed appsettings-bestand. | -| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7), `Media__AutoCleanupUnattached` (standaard `true`; `false` bewaart ongebruikte uploads tot iemand ze verwijdert, voor de mediabibliotheek) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. | +| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7), `Media__TrashDays` (standaard 7: bewaartijd van foto's in de prullenbak van de mediabibliotheek), `Media__AutoCleanupUnattached` (standaard `true`; `false` bewaart ongebruikte uploads tot iemand ze verwijdert, voor de mediabibliotheek) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. | | `Hero__TextOnlyRegion` | `true` voor een site waarvan de hero geen afbeeldingen heeft (SLP Software; staat in de committed instellingen van die site): een hero zonder slides wordt dan als tekst (titelregels, lead, knoppen) in de eerste HTML geschreven. Uit (standaard, ook voor ASF): een hero zonder slides laat de pagina ongemoeid. | | `Hero__TitlePrefix` | Merktekst die in de tekst-only-regio als eerste, visueel te verbergen deel van de h1 wordt geschreven (``), zodat crawlers en schermlezers de volledige titel lezen. SLP Software: `"SLP Software: "` (committed instelling); leeg (standaard, ook ASF) schrijft niets. De site verbergt de klasse zelf visueel. | | `Media__RenderSetTimeoutSeconds` (600), `Media__StripTimeoutSeconds` (60) | De tijd die het knippen van alle varianten van één foto in de achtergrond mag duren, en het verwijderen van metadata bij een upload. Ruim gekozen: een grote foto op een Raspberry Pi kost minuten. | diff --git a/frontend/src/features/media/components/CleanupDialog.tsx b/frontend/src/features/media/components/CleanupDialog.tsx index 11b4974..11851ee 100644 --- a/frontend/src/features/media/components/CleanupDialog.tsx +++ b/frontend/src/features/media/components/CleanupDialog.tsx @@ -1,5 +1,6 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; +import { Button } from '@/components/ui/button'; import { CheckboxField } from '@/components/ui/checkbox'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Label } from '@/components/ui/label'; @@ -8,6 +9,7 @@ import { selectAll, type Selection } from '../lib/selection'; import { toPhotoItem } from '../lib/toPhotoItem'; import { useCleanupPreview } from '../services/hooks'; import { BulkActionBar } from './BulkActionBar'; +import { DeleteDialog } from './DeleteDialog'; import { PhotoSelectionList } from './PhotoSelectionList'; const DEFAULT_DAYS = 7; @@ -16,8 +18,8 @@ const MAX_DAYS = 365; /** * "Clean up": the photos older than the chosen number of days (by default 7), by default only the unused ones, newest - * first and all selected so single photos can be taken out. This step is a PREVIEW: nothing is deleted yet (deleting - * comes after the assumptions have been checked). + * first and all selected so single photos can be taken out. Confirming moves exactly the selected photos to the trash + * (a photo in use asks for a second confirmation naming the places). */ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) { const { t, i18n } = useTranslation(); @@ -26,6 +28,7 @@ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenCha const [onlyUnused, setOnlyUnused] = useState(true); // Everything starts selected: the person only takes photos OUT. A new period or filter starts again with all in. const [excluded, setExcluded] = useState>(new Set()); + const [deleting, setDeleting] = useState(false); const timer = useRef | undefined>(undefined); const preview = useCleanupPreview(debouncedDays, onlyUnused, open); @@ -46,6 +49,7 @@ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenCha const setSelection = (next: Selection) => setExcluded(new Set(ids.filter((id) => !next.has(id)))); const items = useMemo(() => (photos ?? []).map((p) => toPhotoItem(p, t)), [photos, t]); + const selectedItems = useMemo(() => items.filter((item) => selection.has(item.id)), [items, selection]); const selectedBytes = (photos ?? []).filter((p) => selection.has(p.id)).reduce((sum, p) => sum + p.bytes, 0); return ( @@ -82,7 +86,7 @@ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenCha />

- {t('media.cleanup.previewNote')} + {t('media.cleanup.trashNote')}

{preview.isError && ( @@ -103,9 +107,23 @@ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenCha onClear={() => setSelection(new Set())} summary={t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) })} /> +
+ +
)} + { + setExcluded(new Set()); + onOpenChange(false); + }} + /> ); diff --git a/frontend/src/features/media/components/DeleteDialog.tsx b/frontend/src/features/media/components/DeleteDialog.tsx new file mode 100644 index 0000000..33bcccf --- /dev/null +++ b/frontend/src/features/media/components/DeleteDialog.tsx @@ -0,0 +1,111 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { usageLabel } from '../lib/usageLabel'; +import { useTrashPhotos } from '../services/hooks'; +import type { PhotoItem } from './PhotoSelectionList'; + +interface DeleteDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + items: readonly PhotoItem[]; + /** Called with the ids that were moved to the trash. */ + onDone?: (trashedIds: string[]) => void; +} + +/** + * Deleting means "to the trash" (recoverable for a while). A photo that is in use needs a SECOND confirmation that names + * the places that lose it (decision 10). A photo that went wrong is reported; the others are done. + */ +export function DeleteDialog({ open, onOpenChange, items, onDone }: DeleteDialogProps) { + return ( + + {open && onOpenChange(false)} onDone={onDone} />} + + ); +} + +function DeleteDialogBody({ items, onClose, onDone }: { items: readonly PhotoItem[]; onClose: () => void; onDone?: (trashedIds: string[]) => void }) { + const { t } = useTranslation(); + const trash = useTrashPhotos(); + const [step, setStep] = useState<'first' | 'second'>('first'); + const [failed, setFailed] = useState(0); + const inUse = items.filter((item) => item.uses.length > 0); + + const submit = () => { + trash.mutate( + { ids: items.map((i) => i.id), confirmedInUse: inUse.length > 0 }, + { + onSuccess: ({ results }) => { + const trashed = results.filter((r) => r.status === 'trashed').map((r) => r.id); + onDone?.(trashed); + const problems = results.length - trashed.length; + if (problems === 0) onClose(); + else setFailed(problems); + }, + }, + ); + }; + + const onConfirm = () => { + if (inUse.length > 0 && step === 'first') setStep('second'); + else submit(); + }; + + if (failed > 0) { + return ( + <> + + {t('media.delete.title')} + + {t('media.delete.partial', { count: failed })} + + + + + + + ); + } + + return ( + <> + + {step === 'first' ? t('media.delete.title') : t('media.delete.secondTitle')} + + {step === 'first' ? t('media.delete.confirm', { count: items.length }) : t('media.delete.secondText', { count: inUse.length })} + + + {step === 'first' && inUse.length > 0 && ( +

+ {t('media.delete.inUseCount', { count: inUse.length })} +

+ )} + {step === 'second' && ( +
    + {inUse.map((item) => ( +
  • + {item.name}: {item.uses.map((use) => usageLabel(t, use)).join('; ')} +
  • + ))} +
+ )} + {trash.isError && ( +

+ {t('media.error')} +

+ )} + + + + + + ); +} diff --git a/frontend/src/features/media/components/PhotoSelectionList.tsx b/frontend/src/features/media/components/PhotoSelectionList.tsx index d9f7a46..f7b4e79 100644 --- a/frontend/src/features/media/components/PhotoSelectionList.tsx +++ b/frontend/src/features/media/components/PhotoSelectionList.tsx @@ -2,6 +2,7 @@ import { useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { Checkbox } from '@/components/ui/checkbox'; import { formatBytes } from '../lib/format'; +import { usageLabel } from '../lib/usageLabel'; import { selectAll, selectRange, stateOf, type Selection } from '../lib/selection'; export interface PhotoUse { @@ -20,6 +21,10 @@ export interface PhotoItem { bytes: number; createdAt: string; uses: readonly PhotoUse[]; + /** When the photo was last detached from where it was used (null: never used). */ + unusedSince?: string | null; + /** When the photo went to the trash (only in the trash view). */ + deletedAt?: string | null; } interface PhotoSelectionListProps { @@ -47,12 +52,6 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa 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 (

@@ -106,10 +105,14 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa {dateFormat.format(new Date(item.createdAt))} · {formatBytes(item.bytes, i18n.language)}

- {item.uses.length === 0 ? ( - {t('media.use.none')} + {item.deletedAt ? ( + {t('media.trash.since', { date: dateFormat.format(new Date(item.deletedAt)) })} + ) : item.uses.length === 0 ? ( + + {item.unusedSince ? t('media.use.noneSince', { date: dateFormat.format(new Date(item.unusedSince)) }) : t('media.use.none')} + ) : ( - {item.uses.map(usageLabel).join('; ')} + {item.uses.map((use) => usageLabel(t, use)).join('; ')} )}

diff --git a/frontend/src/features/media/lib/toPhotoItem.ts b/frontend/src/features/media/lib/toPhotoItem.ts index 8607e91..10aa98d 100644 --- a/frontend/src/features/media/lib/toPhotoItem.ts +++ b/frontend/src/features/media/lib/toPhotoItem.ts @@ -2,14 +2,16 @@ import type { TFunction } from 'i18next'; import type { PhotoItem } from '../components/PhotoSelectionList'; import type { MediaPhotoDto } from '../services/types'; -/** The list shows a neutral name (the size of the photo): photos do not store a file name yet (assumption 21). */ +/** The list shows the original file name; photos uploaded before it was stored get a neutral label (the size, assumption 21). */ export function toPhotoItem(photo: MediaPhotoDto, t: TFunction): PhotoItem { return { id: photo.id, thumbnailUrl: photo.thumbnailUrl, - name: t('media.list.photoName', { width: photo.width, height: photo.height }), + name: photo.originalFileName ?? t('media.list.photoName', { width: photo.width, height: photo.height }), bytes: photo.bytes, createdAt: photo.createdAt, uses: photo.uses, + unusedSince: photo.unusedSince, + deletedAt: photo.deletedAt, }; } diff --git a/frontend/src/features/media/lib/usageLabel.ts b/frontend/src/features/media/lib/usageLabel.ts new file mode 100644 index 0000000..2b1d98c --- /dev/null +++ b/frontend/src/features/media/lib/usageLabel.ts @@ -0,0 +1,15 @@ +import type { TFunction } from 'i18next'; + +export interface UsePlace { + module: string; + kind: string; + position?: number | null; + active: boolean; +} + +/** "Hero, slide 3" (with "(uit)" for a switched-off place). */ +export function usageLabel(t: TFunction, use: UsePlace): string { + 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')})`}`; +} diff --git a/frontend/src/features/media/mocks/handlers.ts b/frontend/src/features/media/mocks/handlers.ts index 4db340b..8463631 100644 --- a/frontend/src/features/media/mocks/handlers.ts +++ b/frontend/src/features/media/mocks/handlers.ts @@ -1,5 +1,5 @@ import { http, HttpResponse } from 'msw'; -import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPhotoDto, MediaStorageDto } from '@/features/media/services/types'; +import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPhotoDto, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from '@/features/media/services/types'; const daysAgo = (days: number) => new Date(Date.now() - days * 86_400_000).toISOString(); @@ -13,6 +13,9 @@ export const seedPhotos = (): MediaPhotoDto[] => [ createdAt: daysAgo(1), thumbnailUrl: '/media/hero/0123456789abcdef/wide-480.webp', uses: [{ module: 'hero', kind: 'slide', position: 1, active: true }], + originalFileName: 'zomer.jpg', + unusedSince: null, + deletedAt: null, }, { id: 'hero:22222222-2222-2222-2222-222222222222', @@ -23,6 +26,9 @@ export const seedPhotos = (): MediaPhotoDto[] => [ createdAt: daysAgo(12), thumbnailUrl: null, uses: [], + originalFileName: null, + unusedSince: null, + deletedAt: null, }, { id: 'hero:33333333-3333-3333-3333-333333333333', @@ -33,12 +39,37 @@ export const seedPhotos = (): MediaPhotoDto[] => [ createdAt: daysAgo(30), thumbnailUrl: null, uses: [{ module: 'hero', kind: 'slide', position: 2, active: false }], + originalFileName: null, + unusedSince: null, + deletedAt: null, }, ]; export const seedStorage = (): MediaStorageDto => ({ usedBytes: 100_000_000, limitBytes: 2_147_483_648, level: 'ok', warningPercent: 80 }); +/** Stateless mocks of trash and restore: a photo in use is refused without the second confirmation. */ +export const mediaTrashHandlers = [ + http.get('*/media-library/trash', () => HttpResponse.json({ photos: [], modules: ['hero'] } satisfies MediaLibraryDto)), + http.post('*/media-library/delete', async ({ request }) => { + const body = (await request.json()) as MediaTrashRequest; + const photos = seedPhotos(); + return HttpResponse.json({ + results: body.ids.map((id) => { + const photo = photos.find((p) => p.id === id); + if (!photo) return { id, status: 'notFound', uses: [] }; + if (photo.uses.length > 0 && !body.confirmedInUse) return { id, status: 'inUse', uses: photo.uses }; + return { id, status: 'trashed', uses: photo.uses }; + }), + } satisfies MediaTrashResponse); + }), + http.post('*/media-library/restore', async ({ request }) => { + const body = (await request.json()) as { ids: string[] }; + return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'restored', uses: [] })) } satisfies MediaTrashResponse); + }), +]; + export const mediaHandlers = [ + ...mediaTrashHandlers, http.get('*/media-library/photos', () => HttpResponse.json({ photos: seedPhotos(), modules: ['hero'] } satisfies MediaLibraryDto)), http.get('*/media-library/storage', () => HttpResponse.json(seedStorage())), http.get('*/media-library/cleanup-preview', ({ request }) => { diff --git a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx index b8a4ffb..90544cf 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx @@ -5,7 +5,7 @@ import userEvent from '@testing-library/user-event'; import i18n from '@/i18n/config'; import { server } from '@/mocks/server'; import { renderWithProviders } from '@/test/utils'; -import { seedStorage } from '../mocks/handlers'; +import { seedPhotos, seedStorage } from '../mocks/handlers'; import { MediaLibraryPage } from './MediaLibraryPage'; beforeEach(async () => { @@ -37,14 +37,14 @@ describe('MediaLibraryPage', () => { expect(await screen.findByTestId('storage-warning')).toHaveTextContent('vol'); }); - it('selects photos and shows the bulk bar without any delete action yet', async () => { + it('selects photos and shows the bulk bar with the delete action', async () => { renderWithProviders(); await screen.findByTestId('photo-selection-list'); - await userEvent.click(screen.getAllByRole('checkbox', { name: /Foto 3000/ })[0]!); + await userEvent.click(screen.getByRole('checkbox', { name: 'zomer.jpg' })); expect(await screen.findByTestId('bulk-count')).toHaveTextContent('1 foto geselecteerd'); - expect(screen.queryByTestId('bulk-action-delete')).not.toBeInTheDocument(); + expect(screen.getByTestId('bulk-action-delete')).toHaveTextContent('Naar prullenbak'); }); it('opens the clean-up: older than 7 days, only unused, all selected, newest first, and nothing is deleted', async () => { @@ -56,7 +56,7 @@ describe('MediaLibraryPage', () => { const dialog = await screen.findByTestId('cleanup-dialog'); expect(within(dialog).getByTestId('cleanup-only-unused')).toBeChecked(); expect(await within(dialog).findByTestId('cleanup-summary')).toHaveTextContent('1 foto'); - expect(within(dialog).getByTestId('cleanup-preview-note')).toHaveTextContent('nog niets verwijderd'); + expect(within(dialog).getByTestId('cleanup-preview-note')).toHaveTextContent('prullenbak'); const boxes = within(dialog).getAllByRole('checkbox', { name: /Foto/ }); expect(boxes).toHaveLength(1); await waitFor(() => expect(boxes[0]).toBeChecked()); @@ -75,6 +75,108 @@ describe('MediaLibraryPage', () => { expect(within(dialog).getAllByRole('checkbox', { name: /Foto/ })).toHaveLength(2); }); + it('moves an unused photo to the trash after one confirmation', async () => { + let body: { ids: string[]; confirmedInUse: boolean } | null = null; + server.use( + http.post('*/media-library/delete', async ({ request }) => { + body = (await request.json()) as { ids: string[]; confirmedInUse: boolean }; + return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) }); + }), + ); + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222')); + await userEvent.click(screen.getByTestId('bulk-action-delete')); + expect(await screen.findByTestId('delete-text')).toHaveTextContent('prullenbak'); + await userEvent.click(screen.getByTestId('delete-confirm')); + + await waitFor(() => expect(screen.queryByTestId('delete-dialog')).not.toBeInTheDocument()); + expect(body).toEqual({ ids: ['hero:22222222-2222-2222-2222-222222222222'], confirmedInUse: false }); + }); + + it('asks a second confirmation that names the places for a photo in use', async () => { + let body: { ids: string[]; confirmedInUse: boolean } | null = null; + server.use( + http.post('*/media-library/delete', async ({ request }) => { + body = (await request.json()) as { ids: string[]; confirmedInUse: boolean }; + return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) }); + }), + ); + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getByTestId('photo-select-hero:11111111-1111-1111-1111-111111111111')); + await userEvent.click(screen.getByTestId('bulk-action-delete')); + expect(await screen.findByTestId('delete-inuse-count')).toHaveTextContent('1 foto wordt nog gebruikt'); + await userEvent.click(screen.getByTestId('delete-confirm')); + + expect(await screen.findByTestId('delete-places')).toHaveTextContent('Hero, slide 1'); + expect(body).toBeNull(); + await userEvent.click(screen.getByTestId('delete-confirm')); + + await waitFor(() => expect(body).toEqual({ ids: ['hero:11111111-1111-1111-1111-111111111111'], confirmedInUse: true })); + }); + + it('reports photos that could not be deleted', async () => { + server.use( + http.post('*/media-library/delete', async ({ request }) => { + const { ids } = (await request.json()) as { ids: string[] }; + return HttpResponse.json({ results: ids.map((id, i) => ({ id, status: i === 0 ? 'failed' : 'trashed', uses: [] })) }); + }), + ); + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222')); + await userEvent.click(screen.getByTestId('photo-select-hero:33333333-3333-3333-3333-333333333333')); + await userEvent.click(screen.getByTestId('bulk-action-delete')); + await userEvent.click(screen.getByTestId('delete-confirm')); + await userEvent.click(await screen.findByTestId('delete-confirm')); + + expect(await screen.findByTestId('delete-partial')).toHaveTextContent('1 foto kon niet worden verwijderd'); + }); + + it('shows the trash and restores a photo', async () => { + let restored: string[] = []; + server.use( + http.get('*/media-library/trash', () => HttpResponse.json({ photos: [{ ...seedPhotos()[1]!, deletedAt: new Date().toISOString() }], modules: ['hero'] })), + http.post('*/media-library/restore', async ({ request }) => { + restored = ((await request.json()) as { ids: string[] }).ids; + return HttpResponse.json({ results: restored.map((id) => ({ id, status: 'restored', uses: [] })) }); + }), + ); + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getByTestId('view-trash')); + expect(await screen.findByTestId('trash-note')).toBeInTheDocument(); + await userEvent.click(await screen.findByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222')); + await userEvent.click(screen.getByTestId('bulk-action-restore')); + + await waitFor(() => expect(restored).toEqual(['hero:22222222-2222-2222-2222-222222222222'])); + }); + + it('confirming the clean-up moves exactly the selected photos to the trash', async () => { + let body: { ids: string[]; confirmedInUse: boolean } | null = null; + server.use( + http.post('*/media-library/delete', async ({ request }) => { + body = (await request.json()) as { ids: string[]; confirmedInUse: boolean }; + return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) }); + }), + ); + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + await userEvent.click(screen.getByTestId('cleanup-open')); + const dialog = await screen.findByTestId('cleanup-dialog'); + await within(dialog).findByTestId('cleanup-summary'); + + await userEvent.click(within(dialog).getByTestId('cleanup-confirm')); + await userEvent.click(await screen.findByTestId('delete-confirm')); + + await waitFor(() => expect(body).toEqual({ ids: ['hero:22222222-2222-2222-2222-222222222222'], confirmedInUse: false })); + }); + it('shows an error when the library cannot be loaded', async () => { server.use(http.get('*/media-library/photos', () => new HttpResponse(null, { status: 500 }))); renderWithProviders(); diff --git a/frontend/src/features/media/pages/MediaLibraryPage.tsx b/frontend/src/features/media/pages/MediaLibraryPage.tsx index d2b574f..8662caa 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.tsx @@ -1,29 +1,56 @@ import { useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Eraser } from 'lucide-react'; +import { Eraser, RotateCcw, Trash2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { BulkActionBar } from '../components/BulkActionBar'; import { CleanupDialog } from '../components/CleanupDialog'; +import { DeleteDialog } from '../components/DeleteDialog'; import { PhotoSelectionList } from '../components/PhotoSelectionList'; import { StorageMeter } from '../components/StorageMeter'; import { emptySelection, prune, type Selection } from '../lib/selection'; import { toPhotoItem } from '../lib/toPhotoItem'; -import { useMediaPhotos, useMediaStorage } from '../services/hooks'; +import { useMediaPhotos, useMediaStorage, useMediaTrash, useRestorePhotos } from '../services/hooks'; + +type View = 'library' | 'trash'; /** * The media library: every photo of every module, newest first, with where it is used; the storage against its limit; - * the "Clean up" preview. Selecting works already (bulk actions come with deleting, after the assumptions are checked). + * the "Clean up" tool; bulk delete (to the trash); and the trash with restore. */ export function MediaLibraryPage() { const { t } = useTranslation(); + const [view, setView] = useState('library'); const photos = useMediaPhotos(); + const trash = useMediaTrash(view === 'trash'); const storage = useMediaStorage(); + const restore = useRestorePhotos(); const [chosen, setSelection] = useState(emptySelection); const [cleanupOpen, setCleanupOpen] = useState(false); + const [deleting, setDeleting] = useState(false); - const items = useMemo(() => (photos.data?.photos ?? []).map((p) => toPhotoItem(p, t)), [photos.data, t]); - // Photos that left the list (after a reload) drop out of the selection. + const source = view === 'library' ? photos : trash; + const items = useMemo(() => (source.data?.photos ?? []).map((p) => toPhotoItem(p, t)), [source.data, t]); + // Photos that left the list (after a reload or a move) drop out of the selection. const selection = useMemo(() => prune(chosen, items.map((i) => i.id)), [chosen, items]); + const selectedItems = items.filter((item) => selection.has(item.id)); + + const switchView = (next: View) => { + setView(next); + setSelection(emptySelection); + }; + + const actions = + view === 'library' + ? [{ id: 'delete', label: t('media.delete.action'), destructive: true, icon:
) : ( - {item.uses.map((use) => usageLabel(t, use)).join('; ')} + + {item.uses.map((use, index) => { + const label = usageLabel(t, use); + const href = usageHref(use); + return ( + + {index > 0 && '; '} + {href ? ( + + {label} + + ) : ( + label + )} + + ); + })} + )}

diff --git a/frontend/src/features/media/lib/usageLabel.ts b/frontend/src/features/media/lib/usageLabel.ts index 2b1d98c..d2e32c2 100644 --- a/frontend/src/features/media/lib/usageLabel.ts +++ b/frontend/src/features/media/lib/usageLabel.ts @@ -13,3 +13,8 @@ export function usageLabel(t: TFunction, use: UsePlace): string { const where = use.position ? `${place} ${use.position}` : place; return `${t(`media.module.${use.module}`, { defaultValue: use.module })}, ${where}${use.active ? '' : ` (${t('media.use.off')})`}`; } + +/** Where the admin screen of the module that uses the photo lives (null when there is none). */ +export function usageHref(use: Pick): string | null { + return use.module === 'hero' ? '/hero' : null; +} diff --git a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx index 90544cf..8951820 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx @@ -177,6 +177,20 @@ describe('MediaLibraryPage', () => { await waitFor(() => expect(body).toEqual({ ids: ['hero:22222222-2222-2222-2222-222222222222'], confirmedInUse: false })); }); + it('filters the library on used and unused photos and links a use to its module', async () => { + renderWithProviders(); + const list = await screen.findByTestId('photo-selection-list'); + expect(within(list).getAllByRole('listitem')).toHaveLength(3); + + await userEvent.click(screen.getByTestId('filter-unused')); + expect(within(screen.getByTestId('photo-selection-list')).getAllByRole('listitem')).toHaveLength(1); + + await userEvent.click(screen.getByTestId('filter-used')); + const used = within(screen.getByTestId('photo-selection-list')).getAllByRole('listitem'); + expect(used).toHaveLength(2); + expect(within(used[0]!).getByRole('link', { name: 'Hero, slide 1' })).toHaveAttribute('href', '/hero'); + }); + it('shows an error when the library cannot be loaded', async () => { server.use(http.get('*/media-library/photos', () => new HttpResponse(null, { status: 500 }))); renderWithProviders(); diff --git a/frontend/src/features/media/pages/MediaLibraryPage.tsx b/frontend/src/features/media/pages/MediaLibraryPage.tsx index 8662caa..7ff88e7 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.tsx @@ -12,6 +12,7 @@ import { toPhotoItem } from '../lib/toPhotoItem'; import { useMediaPhotos, useMediaStorage, useMediaTrash, useRestorePhotos } from '../services/hooks'; type View = 'library' | 'trash'; +type UseFilter = 'all' | 'used' | 'unused'; /** * The media library: every photo of every module, newest first, with where it is used; the storage against its limit; @@ -27,9 +28,16 @@ export function MediaLibraryPage() { const [chosen, setSelection] = useState(emptySelection); const [cleanupOpen, setCleanupOpen] = useState(false); const [deleting, setDeleting] = useState(false); + const [filter, setFilter] = useState('all'); const source = view === 'library' ? photos : trash; - const items = useMemo(() => (source.data?.photos ?? []).map((p) => toPhotoItem(p, t)), [source.data, t]); + const items = useMemo( + () => + (source.data?.photos ?? []) + .filter((p) => view === 'trash' || filter === 'all' || (filter === 'used') === p.uses.length > 0) + .map((p) => toPhotoItem(p, t)), + [source.data, t, view, filter], + ); // Photos that left the list (after a reload or a move) drop out of the selection. const selection = useMemo(() => prune(chosen, items.map((i) => i.id)), [chosen, items]); const selectedItems = items.filter((item) => selection.has(item.id)); @@ -72,6 +80,16 @@ export function MediaLibraryPage() { ))} + {view === 'library' && ( +
+ {(['all', 'used', 'unused'] as const).map((value) => ( + + ))} +
+ )} + {view === 'trash' && (

{t('media.trash.note')} diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 68fe6c5..7514f16 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -867,6 +867,12 @@ "close": "Close", "partial_one": "{{count}} photo could not be deleted. The rest went to the trash.", "partial_other": "{{count}} photos could not be deleted. The rest went to the trash." + }, + "filter": { + "label": "Filter", + "all": "All photos", + "used": "Used", + "unused": "Unused" } } } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index d6c8049..29f047e 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -867,6 +867,12 @@ "close": "Sluiten", "partial_one": "{{count}} foto kon niet worden verwijderd. De rest is naar de prullenbak.", "partial_other": "{{count}} foto's konden niet worden verwijderd. De rest is naar de prullenbak." + }, + "filter": { + "label": "Filter", + "all": "Alle foto's", + "used": "Gebruikt", + "unused": "Ongebruikt" } } } -- 2.39.5 From fc9417f7529c4c402fc08d2406e3ac63cff4617a Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 15:27:18 +0100 Subject: [PATCH 09/22] Hero: opslaanbalk echt tegen de onderrand van het scherm (sticky meet vanaf de contentrand), meer ruimte rond Opslaan Co-Authored-By: Claude Sonnet 5.5 --- .../src/features/hero/pages/HeroPage.test.tsx | 15 +++++++++++++++ frontend/src/features/hero/pages/HeroPage.tsx | 18 +++++++++++------- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/frontend/src/features/hero/pages/HeroPage.test.tsx b/frontend/src/features/hero/pages/HeroPage.test.tsx index 710f339..645f0d8 100644 --- a/frontend/src/features/hero/pages/HeroPage.test.tsx +++ b/frontend/src/features/hero/pages/HeroPage.test.tsx @@ -1170,4 +1170,19 @@ describe('Tabs Content and Images', () => { expect(bar).toHaveClass('-mx-6', 'bg-background', 'border-t'); expect(bar.className).not.toMatch(/bg-background\//); }); + + it('sticks flush with the bottom of the viewport: undoes the padding of the scrolling area, no bottom margin, and the page cancels the padding below it', async () => { + await openPage(); + + const bar = screen.getByTestId('hero-save-bar'); + //

has p-6 and a sticky box measures from the content edge, so -bottom-6 (measured in Chrome) puts it on the screen edge. + expect(bar).toHaveClass('sticky', '-bottom-6'); + expect(bar.className).not.toMatch(/(^|\s)-?mb-/); + expect(bar.className).not.toMatch(/(^|\s)(translate|bottom-)/); + expect(screen.getByTestId('hero-page')).toHaveClass('-mb-6'); + // Room around the button: more padding above and below than before. + expect(bar).toHaveClass('pt-4', 'gap-4'); + expect(bar.style.paddingBottom).toContain('1rem'); + expect(screen.getByTestId('hero-form').className).not.toMatch(/pb-/); + }); }); diff --git a/frontend/src/features/hero/pages/HeroPage.tsx b/frontend/src/features/hero/pages/HeroPage.tsx index b81943a..285f4b9 100644 --- a/frontend/src/features/hero/pages/HeroPage.tsx +++ b/frontend/src/features/hero/pages/HeroPage.tsx @@ -99,7 +99,7 @@ export function HeroPage() { const { data: hero, isLoading, isError, refetch } = useHero(); return ( -
+

{t('hero.title')}

{hero && ( @@ -386,7 +386,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { const heroErrors = errors; return ( -
void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8 pb-4" noValidate data-testid="hero-form"> + void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8" noValidate data-testid="hero-form"> images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} /> setServerError(null)} /> @@ -585,11 +585,15 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
- {/* Full width of the content area (no gap at the sides or below), opaque, with a clear top edge and a shadow; the - bottom padding keeps clear of the home bar of a phone. */} + {/* Flush with the bottom of the viewport and the full width of the content area, fully opaque so nothing shows + through or below it, with a clear top edge and a shadow. A sticky box measures its offset from the CONTENT + edge of the scrolling area (
has p-6), so "bottom: 0" would stop 24px above the screen edge and let + content show below the bar (measured in Chrome); -bottom-6 undoes that padding. The page root cancels the same + padding (-mb-6), so at the end of the page the bar is still at the very bottom and the last content is never + hidden behind it. The bottom padding clears the home bar of a phone. */}
@@ -605,7 +609,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { disabled={save.isPending || !hasUnsaved} aria-disabled={save.isPending || !hasUnsaved} aria-busy={save.isPending} - className={hasUnsaved && !save.isPending ? 'ring-2 ring-primary ring-offset-2' : undefined} + className={`min-w-28 ${hasUnsaved && !save.isPending ? 'ring-2 ring-primary ring-offset-2' : ''}`} data-testid="hero-save" > {save.isPending ? ( -- 2.39.5 From 150c156fd731d89e7a7fab0871d636cec7e55d34 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 15:38:40 +0100 Subject: [PATCH 10/22] Mediabibliotheek: module Media met eigen tabellen en geverifieerde kopie van de Hero-foto's (fase 1 van de migratie, standaard uit) Co-Authored-By: Claude Sonnet 5.5 --- SlpModularCms.Ci.slnf | 2 + SlpModularCms.sln | 32 +++ .../assumptions-and-open-questions.md | 2 + .../application-design/migration-plan.md | 26 ++- ...ModularCms.Api.AndreaSlopFotografie.csproj | 1 + .../SlpModularCms.Api.SlpSoftware.csproj | 1 + .../SiteContractTests.cs | 6 +- .../SlpModularCms.Api.csproj | 1 + .../Media/Library/MediaMigrationTypes.cs | 45 ++++ .../HeroMediaMigrationSourceTests.cs | 56 +++++ src/SlpModularCms.Modules.Hero/HeroModule.cs | 1 + .../Repositories/HeroRepository.cs | 6 + .../Services/HeroMediaMigrationSource.cs | 63 ++++++ .../MediaLibraryCopierTests.cs | 115 ++++++++++ .../MediaLibraryMariaDbTests.cs | 113 ++++++++++ .../SlpModularCms.Modules.Media.Tests.csproj | 34 +++ .../Data/Entities/MediaEntities.cs | 59 +++++ .../Data/MediaDbContext.cs | 40 ++++ .../MediaLibraryOptions.cs | 13 ++ .../MediaModule.cs | 72 +++++++ .../20261117143138_InitialCreate.Designer.cs | 154 +++++++++++++ .../20261117143138_InitialCreate.cs | 96 +++++++++ .../Migrations/MediaDbContextModelSnapshot.cs | 151 +++++++++++++ .../Services/MediaLibraryCopier.cs | 204 ++++++++++++++++++ .../SlpModularCms.Modules.Media.csproj | 19 ++ 25 files changed, 1304 insertions(+), 8 deletions(-) create mode 100644 src/SlpModularCms.Core/Media/Library/MediaMigrationTypes.cs create mode 100644 src/SlpModularCms.Modules.Hero.Tests/HeroMediaMigrationSourceTests.cs create mode 100644 src/SlpModularCms.Modules.Hero/Services/HeroMediaMigrationSource.cs create mode 100644 src/SlpModularCms.Modules.Media.Tests/MediaLibraryCopierTests.cs create mode 100644 src/SlpModularCms.Modules.Media.Tests/MediaLibraryMariaDbTests.cs create mode 100644 src/SlpModularCms.Modules.Media.Tests/SlpModularCms.Modules.Media.Tests.csproj create mode 100644 src/SlpModularCms.Modules.Media/Data/Entities/MediaEntities.cs create mode 100644 src/SlpModularCms.Modules.Media/Data/MediaDbContext.cs create mode 100644 src/SlpModularCms.Modules.Media/MediaLibraryOptions.cs create mode 100644 src/SlpModularCms.Modules.Media/MediaModule.cs create mode 100644 src/SlpModularCms.Modules.Media/Migrations/20261117143138_InitialCreate.Designer.cs create mode 100644 src/SlpModularCms.Modules.Media/Migrations/20261117143138_InitialCreate.cs create mode 100644 src/SlpModularCms.Modules.Media/Migrations/MediaDbContextModelSnapshot.cs create mode 100644 src/SlpModularCms.Modules.Media/Services/MediaLibraryCopier.cs create mode 100644 src/SlpModularCms.Modules.Media/SlpModularCms.Modules.Media.csproj diff --git a/SlpModularCms.Ci.slnf b/SlpModularCms.Ci.slnf index 1265755..ac3ee04 100644 --- a/SlpModularCms.Ci.slnf +++ b/SlpModularCms.Ci.slnf @@ -17,6 +17,8 @@ "src\\SlpModularCms.Modules.Offerings.Tests\\SlpModularCms.Modules.Offerings.Tests.csproj", "src\\SlpModularCms.Modules.Hero\\SlpModularCms.Modules.Hero.csproj", "src\\SlpModularCms.Modules.Hero.Tests\\SlpModularCms.Modules.Hero.Tests.csproj", + "src\\SlpModularCms.Modules.Media\\SlpModularCms.Modules.Media.csproj", + "src\\SlpModularCms.Modules.Media.Tests\\SlpModularCms.Modules.Media.Tests.csproj", "src\\SlpModularCms.Modules.Contact\\SlpModularCms.Modules.Contact.csproj", "src\\SlpModularCms.Modules.Contact.Tests\\SlpModularCms.Modules.Contact.Tests.csproj" ] diff --git a/SlpModularCms.sln b/SlpModularCms.sln index 836c7b3..e1ed2e1 100644 --- a/SlpModularCms.sln +++ b/SlpModularCms.sln @@ -50,6 +50,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Hero" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Hero.Tests", "src\SlpModularCms.Modules.Hero.Tests\SlpModularCms.Modules.Hero.Tests.csproj", "{838B2DA6-8B01-4C83-A696-D910AB2BC5D9}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Media", "src\SlpModularCms.Modules.Media\SlpModularCms.Modules.Media.csproj", "{729ABD96-ADEB-4352-8030-2F6074B977F0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Media.Tests", "src\SlpModularCms.Modules.Media.Tests\SlpModularCms.Modules.Media.Tests.csproj", "{E697D4E1-FA8D-468C-BC31-81520715E246}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -300,6 +306,30 @@ Global {838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x64.Build.0 = Release|Any CPU {838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x86.ActiveCfg = Release|Any CPU {838B2DA6-8B01-4C83-A696-D910AB2BC5D9}.Release|x86.Build.0 = Release|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|x64.ActiveCfg = Debug|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|x64.Build.0 = Debug|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|x86.ActiveCfg = Debug|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|x86.Build.0 = Debug|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|Any CPU.Build.0 = Release|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|x64.ActiveCfg = Release|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|x64.Build.0 = Release|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|x86.ActiveCfg = Release|Any CPU + {729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|x86.Build.0 = Release|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|x64.ActiveCfg = Debug|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|x64.Build.0 = Debug|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|x86.ActiveCfg = Debug|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|x86.Build.0 = Debug|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Release|Any CPU.Build.0 = Release|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Release|x64.ActiveCfg = Release|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Release|x64.Build.0 = Release|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Release|x86.ActiveCfg = Release|Any CPU + {E697D4E1-FA8D-468C-BC31-81520715E246}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -327,5 +357,7 @@ Global {9EAC8A27-8DB0-4E3B-B144-280882828DE8} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {4A7E3360-C7D0-4ADF-BC98-79AA912A8867} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} {838B2DA6-8B01-4C83-A696-D910AB2BC5D9} = {77DF6642-7863-4D67-BAEE-217EC2D99894} + {729ABD96-ADEB-4352-8030-2F6074B977F0} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} + {E697D4E1-FA8D-468C-BC31-81520715E246} = {77DF6642-7863-4D67-BAEE-217EC2D99894} EndGlobalSection EndGlobal 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 6e4b948..0d1d04c 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -61,3 +61,5 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu - **Confirmed by Bryan "as designed"**: 1, 2, 5, 6, 9, 11, 14, 15, 16, 19, 20, 26, 27, 28. - **Still assumptions** (not put to him separately): 17 (language), 18 (what phase A contained, now overtaken), 22 (selectability), 23 (performance), 24 (ASF data), 25 (use definitions); and the older rows 18 to 25 above. Assumptions 29 to 32 follow from his decisions. - Assumption 12 now reads: there IS a trash (decision 12), the earlier "no trash in phase A" no longer applies. Assumption 10: deleting a used photo is possible after a second confirmation (built). Assumption 21: the original file name is stored from now on (built). +| 33 | **Where the copy runs and what it copies** (built 2026-11-17). | A new module `Modules.Media` owns the tables (`MediaAssets`, `MediaUses`); modules offer their data through `IMediaMigrationSource` so the library module does not depend on the Hero. The copy is a verified mirror in one transaction behind `Media:Library:CopyOnStartup` (default false). The use of a hero slide carries both crops (`wide`, `tall`) of its photo as JSON; its set hash is the photo's current set hash. | A copy job triggered from the admin instead of start-up: easier to time, needs an endpoint and a button. | `Modules.Media/Services/MediaLibraryCopier.cs`, `HeroMediaMigrationSource` | +| 34 | **Naming**: entity `MediaAssetUse` (table `MediaUses`), because `MediaUse` already names the read model in Core. | As built. | Rename the table or the record: a small migration. | `Modules.Media/Data` | diff --git a/aidlc-docs/features/media-library/inception/application-design/migration-plan.md b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md index 78329b5..b4bc899 100644 --- a/aidlc-docs/features/media-library/inception/application-design/migration-plan.md +++ b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md @@ -64,10 +64,26 @@ The migration job compares and **aborts** (rolls its transaction back) on any di 3. Back-up first (above), on the test host too. 4. Deploy with the setting **off**, check the verification result in the log, then switch it on, then the smoke test (hero markers, `/theme-init.js`, a sample of media addresses), then Bryan checks the admin. -## What is built first (next step, when this plan is accepted) +## Status (2026-11-17): phase 1 (expand) is built, behind a setting that is OFF -1. A new module `SlpModularCms.Modules.Media` with its own `DbContext`, the tables `MediaAssets` and `MediaUses` and an additive EF migration (no existing table touched), with tests. -2. The copy-and-verify job (idempotent, safe to run twice) behind a setting; unit and in-memory tests, and a test against MariaDB. -3. The library reading from the new tables behind `Media:Library:ReadFromLibrary` (default off). +Built on `feature/media-library-screen`, not yet deployed anywhere: -Nothing in steps 1 to 3 runs without the setting, so a deploy of that code alone changes no data except the new, empty tables. +- New module `SlpModularCms.Modules.Media` (own `MediaDbContext`, tables `MediaAssets` and `MediaUses`, additive migration `InitialCreate`; no existing table is touched). It is referenced by the three hosts, so a deploy of this code creates the two empty tables at start-up and nothing else. +- `IMediaMigrationSource` (Core) and `HeroMediaMigrationSource` (Hero, read-only): the hero's photos (also those in the trash) and slides with their own ids, hashes and set hashes. +- `MediaLibraryCopier`: copies and **verifies** (counts, ids, hash, key, size, set hash) in one transaction; any difference or error rolls the whole copy back and nothing is left. It MIRRORS the source, so running it again gives the same result; rows of other modules are not touched. +- The copy runs only when `Media__Library__CopyOnStartup=true` (default **false**) and a failure is logged, never fatal. +- Tested in memory and against a real MariaDB (migration, copy twice, rollback on a failing copy). + +Nothing reads from the new tables yet (phase 2, the switch, is not built). The library screen still reads the hero through the usage provider. + +### Roll-out on TEST (needs SLS-Main to be told first) + +1. Back-up (database dump and media listing) as above. +2. Deploy the branch with `Media__Library__CopyOnStartup` unset: the two empty tables appear; check the log for the Media migration. +3. Set `Media__Library__CopyOnStartup=true` and restart: the log says `Media library copy verified: N photos and M uses from hero` (or the error and the rollback). +4. Rollback at any point: set it back to false (the tables stay, unused) or drop `MediaUses` and `MediaAssets`. +5. Never on production. + +### Still to build (phases 2 and 3) + +The switch (`Media:Library:ReadFromLibrary`, dual write of new uploads, library reading from the new tables) and the contract phase. They need Bryan's acceptance of the copy on test first. diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj b/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj index 8302f79..623fce0 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj +++ b/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj @@ -31,6 +31,7 @@ + diff --git a/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj b/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj index 53a41cd..b31dd5f 100644 --- a/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj +++ b/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj @@ -25,6 +25,7 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/src/SlpModularCms.Modules.Media/Data/Entities/MediaEntities.cs b/src/SlpModularCms.Modules.Media/Data/Entities/MediaEntities.cs new file mode 100644 index 0000000..b99fd79 --- /dev/null +++ b/src/SlpModularCms.Modules.Media/Data/Entities/MediaEntities.cs @@ -0,0 +1,59 @@ +namespace SlpModularCms.Modules.Media.Data.Entities; + +/// +/// A photo in the library: the original (never served), its default focus and when it was last used or trashed. The ids, +/// hashes and keys are the ones the owning module already uses, so public addresses stay as they are. +/// +public class MediaAsset +{ + public Guid Id { get; set; } + + /// The module that uploaded it (for example hero); the library is shared, this only says where it came from. + public string Module { get; set; } = string.Empty; + + /// SHA-256 of the file as uploaded (hex); the same photo uploaded twice is one record. + public string OriginalSha256 { get; set; } = string.Empty; + + public string OriginalKey { get; set; } = string.Empty; + public string SourceFormat { get; set; } = string.Empty; + public int Width { get; set; } + public int Height { get; set; } + public long Bytes { get; set; } + + public double DefaultFocusX { get; set; } = 0.5; + public double DefaultFocusY { get; set; } = 0.5; + public double DefaultZoom { get; set; } = 1.0; + + public DateTimeOffset CreatedAt { get; set; } + public Guid CreatedByUserId { get; set; } + public string? OriginalFileName { get; set; } + public DateTimeOffset? LastUsedAt { get; set; } + public DateTimeOffset? DeletedAt { get; set; } + + public List Uses { get; set; } = []; +} + +/// +/// One place where a photo is used, with its own crops. The set hash is computed by the module with the existing formula +/// over the photo's hash and these crops. +/// +public class MediaAssetUse +{ + public Guid Id { get; set; } + public Guid AssetId { get; set; } + public MediaAsset? Asset { get; set; } + + public string Module { get; set; } = string.Empty; + + /// For example slide. + public string PlaceKind { get; set; } = string.Empty; + + /// The 1-based position in the place (display order). + public int Position { get; set; } + + public bool Active { get; set; } = true; + public string SetHash { get; set; } = string.Empty; + + /// The crops of this use as JSON: [{ratio, x, y, zoom}]. Empty for a natural-ratio use. + public string Crops { get; set; } = "[]"; +} diff --git a/src/SlpModularCms.Modules.Media/Data/MediaDbContext.cs b/src/SlpModularCms.Modules.Media/Data/MediaDbContext.cs new file mode 100644 index 0000000..3f85b1d --- /dev/null +++ b/src/SlpModularCms.Modules.Media/Data/MediaDbContext.cs @@ -0,0 +1,40 @@ +using Microsoft.EntityFrameworkCore; +using SlpModularCms.Modules.Media.Data.Entities; + +namespace SlpModularCms.Modules.Media.Data; + +public class MediaDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet MediaAssets => Set(); + public DbSet MediaUses => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(entity => + { + entity.ToTable("MediaAssets"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Module).IsRequired().HasMaxLength(20); + entity.Property(e => e.OriginalSha256).IsRequired().HasMaxLength(64); + entity.HasIndex(e => e.OriginalSha256).IsUnique(); + entity.Property(e => e.OriginalKey).IsRequired().HasMaxLength(200); + entity.Property(e => e.SourceFormat).IsRequired().HasMaxLength(10); + entity.Property(e => e.OriginalFileName).HasMaxLength(200); + entity.HasIndex(e => e.CreatedAt); + entity.HasMany(e => e.Uses).WithOne(u => u.Asset).HasForeignKey(u => u.AssetId).OnDelete(DeleteBehavior.Cascade); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("MediaUses"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Module).IsRequired().HasMaxLength(20); + entity.Property(e => e.PlaceKind).IsRequired().HasMaxLength(20); + entity.Property(e => e.SetHash).IsRequired().HasMaxLength(16); + entity.Property(e => e.Crops).IsRequired().HasColumnType("longtext"); + entity.HasIndex(e => e.AssetId); + }); + } +} diff --git a/src/SlpModularCms.Modules.Media/MediaLibraryOptions.cs b/src/SlpModularCms.Modules.Media/MediaLibraryOptions.cs new file mode 100644 index 0000000..8e2a65a --- /dev/null +++ b/src/SlpModularCms.Modules.Media/MediaLibraryOptions.cs @@ -0,0 +1,13 @@ +namespace SlpModularCms.Modules.Media; + +/// Settings of the library's own tables (Media:Library:*). Everything is off by default: a deploy of the code alone only adds the empty tables. +public class MediaLibraryOptions +{ + public const string SectionName = "Media:Library"; + + /// + /// Copy the photos and uses of the modules into the library's tables once at start-up and verify the copy + /// (Media__Library__CopyOnStartup=true). Safe to repeat: the copy mirrors the source. Never touches the modules' own data. + /// + public bool CopyOnStartup { get; set; } +} diff --git a/src/SlpModularCms.Modules.Media/MediaModule.cs b/src/SlpModularCms.Modules.Media/MediaModule.cs new file mode 100644 index 0000000..76625e6 --- /dev/null +++ b/src/SlpModularCms.Modules.Media/MediaModule.cs @@ -0,0 +1,72 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Builder; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Modules; +using SlpModularCms.Modules.Media.Data; +using SlpModularCms.Modules.Media.Services; + +namespace SlpModularCms.Modules.Media; + +/// +/// The library's own tables (photos and where they are used). Phase 1 of the migration plan: only the tables, and a copy +/// of the modules' photos behind Media:Library:CopyOnStartup (off by default). Nothing reads from these tables yet. +/// +[ExcludeFromCodeCoverage] +public class MediaModule : IModule +{ + public string Name => "Media"; + public string Version => "1.0.0"; + + public void RegisterServices(IServiceCollection services) + { + services.AddDbContext((serviceProvider, options) => + { + var config = serviceProvider.GetRequiredService(); + options.UseMySQL(config.GetConnectionString("DefaultConnection")!); + options.ReplaceService(); + }); + + services.AddOptions().Configure((options, configuration) => + configuration.GetSection(MediaLibraryOptions.SectionName).Bind(options)); + services.AddScoped(); + services.AddHostedService(); + } + + public void UseModule(IApplicationBuilder app) + { + using var scope = app.ApplicationServices.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Database.Migrate(); + } +} + +/// Runs the verified copy once at start-up when Media:Library:CopyOnStartup is on; a failure is logged and never stops the host. +public sealed class MediaLibraryCopyService(IServiceScopeFactory scopes, IOptions options, ILogger logger) : IHostedService +{ + public async Task StartAsync(CancellationToken cancellationToken) + { + if (!options.Value.CopyOnStartup) + { + return; + } + + try + { + using var scope = scopes.CreateScope(); + await scope.ServiceProvider.GetRequiredService().CopyAsync(cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError(exception, "The media library copy failed and was rolled back; the modules' own data is untouched."); + } + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/src/SlpModularCms.Modules.Media/Migrations/20261117143138_InitialCreate.Designer.cs b/src/SlpModularCms.Modules.Media/Migrations/20261117143138_InitialCreate.Designer.cs new file mode 100644 index 0000000..902c72b --- /dev/null +++ b/src/SlpModularCms.Modules.Media/Migrations/20261117143138_InitialCreate.Designer.cs @@ -0,0 +1,154 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Media.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Media.Migrations +{ + [DbContext(typeof(MediaDbContext))] + [Migration("20261117143138_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAsset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CreatedByUserId") + .HasColumnType("char(36)"); + + b.Property("DefaultFocusX") + .HasColumnType("double"); + + b.Property("DefaultFocusY") + .HasColumnType("double"); + + b.Property("DefaultZoom") + .HasColumnType("double"); + + b.Property("DeletedAt") + .HasColumnType("datetime"); + + b.Property("Height") + .HasColumnType("int"); + + b.Property("LastUsedAt") + .HasColumnType("datetime"); + + b.Property("Module") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("OriginalFileName") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("OriginalKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("OriginalSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("SourceFormat") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("Width") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("OriginalSha256") + .IsUnique(); + + b.ToTable("MediaAssets", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAssetUse", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Active") + .HasColumnType("tinyint(1)"); + + b.Property("AssetId") + .HasColumnType("char(36)"); + + b.Property("Crops") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Module") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("PlaceKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Position") + .HasColumnType("int"); + + b.Property("SetHash") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Id"); + + b.HasIndex("AssetId"); + + b.ToTable("MediaUses", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAssetUse", b => + { + b.HasOne("SlpModularCms.Modules.Media.Data.Entities.MediaAsset", "Asset") + .WithMany("Uses") + .HasForeignKey("AssetId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Asset"); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAsset", b => + { + b.Navigation("Uses"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Media/Migrations/20261117143138_InitialCreate.cs b/src/SlpModularCms.Modules.Media/Migrations/20261117143138_InitialCreate.cs new file mode 100644 index 0000000..1881e9c --- /dev/null +++ b/src/SlpModularCms.Modules.Media/Migrations/20261117143138_InitialCreate.cs @@ -0,0 +1,96 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Media.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterDatabase() + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "MediaAssets", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + Module = table.Column(type: "varchar(20)", maxLength: 20, nullable: false), + OriginalSha256 = table.Column(type: "varchar(64)", maxLength: 64, nullable: false), + OriginalKey = table.Column(type: "varchar(200)", maxLength: 200, nullable: false), + SourceFormat = table.Column(type: "varchar(10)", maxLength: 10, nullable: false), + Width = table.Column(type: "int", nullable: false), + Height = table.Column(type: "int", nullable: false), + Bytes = table.Column(type: "bigint", nullable: false), + DefaultFocusX = table.Column(type: "double", nullable: false), + DefaultFocusY = table.Column(type: "double", nullable: false), + DefaultZoom = table.Column(type: "double", nullable: false), + CreatedAt = table.Column(type: "datetime", nullable: false), + CreatedByUserId = table.Column(type: "char(36)", nullable: false), + OriginalFileName = table.Column(type: "varchar(200)", maxLength: 200, nullable: true), + LastUsedAt = table.Column(type: "datetime", nullable: true), + DeletedAt = table.Column(type: "datetime", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_MediaAssets", x => x.Id); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "MediaUses", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + AssetId = table.Column(type: "char(36)", nullable: false), + Module = table.Column(type: "varchar(20)", maxLength: 20, nullable: false), + PlaceKind = table.Column(type: "varchar(20)", maxLength: 20, nullable: false), + Position = table.Column(type: "int", nullable: false), + Active = table.Column(type: "tinyint(1)", nullable: false), + SetHash = table.Column(type: "varchar(16)", maxLength: 16, nullable: false), + Crops = table.Column(type: "longtext", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MediaUses", x => x.Id); + table.ForeignKey( + name: "FK_MediaUses_MediaAssets_AssetId", + column: x => x.AssetId, + principalTable: "MediaAssets", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_MediaAssets_CreatedAt", + table: "MediaAssets", + column: "CreatedAt"); + + migrationBuilder.CreateIndex( + name: "IX_MediaAssets_OriginalSha256", + table: "MediaAssets", + column: "OriginalSha256", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MediaUses_AssetId", + table: "MediaUses", + column: "AssetId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MediaUses"); + + migrationBuilder.DropTable( + name: "MediaAssets"); + } + } +} diff --git a/src/SlpModularCms.Modules.Media/Migrations/MediaDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Media/Migrations/MediaDbContextModelSnapshot.cs new file mode 100644 index 0000000..1d7f5b3 --- /dev/null +++ b/src/SlpModularCms.Modules.Media/Migrations/MediaDbContextModelSnapshot.cs @@ -0,0 +1,151 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Media.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Media.Migrations +{ + [DbContext(typeof(MediaDbContext))] + partial class MediaDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAsset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CreatedByUserId") + .HasColumnType("char(36)"); + + b.Property("DefaultFocusX") + .HasColumnType("double"); + + b.Property("DefaultFocusY") + .HasColumnType("double"); + + b.Property("DefaultZoom") + .HasColumnType("double"); + + b.Property("DeletedAt") + .HasColumnType("datetime"); + + b.Property("Height") + .HasColumnType("int"); + + b.Property("LastUsedAt") + .HasColumnType("datetime"); + + b.Property("Module") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("OriginalFileName") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("OriginalKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("OriginalSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("SourceFormat") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("Width") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("OriginalSha256") + .IsUnique(); + + b.ToTable("MediaAssets", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAssetUse", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Active") + .HasColumnType("tinyint(1)"); + + b.Property("AssetId") + .HasColumnType("char(36)"); + + b.Property("Crops") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Module") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("PlaceKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Position") + .HasColumnType("int"); + + b.Property("SetHash") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Id"); + + b.HasIndex("AssetId"); + + b.ToTable("MediaUses", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAssetUse", b => + { + b.HasOne("SlpModularCms.Modules.Media.Data.Entities.MediaAsset", "Asset") + .WithMany("Uses") + .HasForeignKey("AssetId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Asset"); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAsset", b => + { + b.Navigation("Uses"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Media/Services/MediaLibraryCopier.cs b/src/SlpModularCms.Modules.Media/Services/MediaLibraryCopier.cs new file mode 100644 index 0000000..0856f74 --- /dev/null +++ b/src/SlpModularCms.Modules.Media/Services/MediaLibraryCopier.cs @@ -0,0 +1,204 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using SlpModularCms.Core.Media.Library; +using SlpModularCms.Modules.Media.Data; +using SlpModularCms.Modules.Media.Data.Entities; + +namespace SlpModularCms.Modules.Media.Services; + +/// What a copy did and what the verification found. +public sealed record MediaCopyReport(int Assets, int Uses, IReadOnlyList Differences) +{ + public bool Verified => Differences.Count == 0; +} + +public sealed class MediaCopyVerificationException(MediaCopyReport report) + : Exception($"The copy of the media library does not match its source: {string.Join("; ", report.Differences.Take(5))}") +{ + public MediaCopyReport Report { get; } = report; +} + +/// +/// Copies the photos and uses of every module () into the library's own tables and +/// verifies the copy against the source (migration plan, decision 13). The copy MIRRORS the source: re-running it gives +/// the same result, rows of a module that no longer exist at the source are removed from the copy. The modules' own data +/// is never changed. A difference after copying rolls the whole copy back and raises . +/// +public sealed class MediaLibraryCopier(MediaDbContext db, IEnumerable sources, ILogger logger) +{ + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + public async Task CopyAsync(CancellationToken cancellationToken) + { + var assets = new List(); + var uses = new List(); + var modules = new List(); + foreach (var source in sources) + { + modules.Add(source.Module); + assets.AddRange(await source.ListAssetsAsync(cancellationToken)); + uses.AddRange(await source.ListUsesAsync(cancellationToken)); + } + + var transaction = db.Database.IsRelational() ? await db.Database.BeginTransactionAsync(cancellationToken) : null; + try + { + await MirrorAsync(assets, uses, modules, cancellationToken); + await db.SaveChangesAsync(cancellationToken); + + var report = await VerifyAsync(assets, uses, modules, cancellationToken); + if (!report.Verified) + { + throw new MediaCopyVerificationException(report); + } + + if (transaction is not null) + { + await transaction.CommitAsync(cancellationToken); + } + + logger.LogInformation("Media library copy verified: {Assets} photos and {Uses} uses from {Modules}.", report.Assets, report.Uses, string.Join(", ", modules)); + return report; + } + catch + { + if (transaction is not null) + { + await transaction.RollbackAsync(CancellationToken.None); + } + + db.ChangeTracker.Clear(); + throw; + } + finally + { + if (transaction is not null) + { + await transaction.DisposeAsync(); + } + } + } + + private async Task MirrorAsync(IReadOnlyList assets, IReadOnlyList uses, IReadOnlyList modules, CancellationToken cancellationToken) + { + var existingAssets = new Dictionary(); + var existingUses = new Dictionary(); + foreach (var module in modules) + { + // One equality query per module: the MySQL provider cannot translate a list parameter in an IN clause. + foreach (var asset in await db.MediaAssets.Where(a => a.Module == module).ToListAsync(cancellationToken)) + { + existingAssets[asset.Id] = asset; + } + + foreach (var use in await db.MediaUses.Where(u => u.Module == module).ToListAsync(cancellationToken)) + { + existingUses[use.Id] = use; + } + } + + foreach (var snapshot in assets) + { + if (!existingAssets.Remove(snapshot.Id, out var row)) + { + row = new MediaAsset { Id = snapshot.Id }; + db.MediaAssets.Add(row); + } + + row.Module = snapshot.Module; + row.OriginalSha256 = snapshot.OriginalSha256; + row.OriginalKey = snapshot.OriginalKey; + row.SourceFormat = snapshot.SourceFormat; + row.Width = snapshot.Width; + row.Height = snapshot.Height; + row.Bytes = snapshot.Bytes; + row.DefaultFocusX = snapshot.FocusX; + row.DefaultFocusY = snapshot.FocusY; + row.DefaultZoom = snapshot.Zoom; + row.CreatedAt = snapshot.CreatedAt; + row.CreatedByUserId = snapshot.CreatedByUserId; + row.OriginalFileName = snapshot.OriginalFileName; + row.LastUsedAt = snapshot.LastUsedAt; + row.DeletedAt = snapshot.DeletedAt; + } + + // Uses reference their asset; the crops of a use are the crops of its photo (the hero's wide and tall). + var cropsByAsset = assets.ToDictionary(a => a.Id, a => JsonSerializer.Serialize(a.Crops, Json)); + foreach (var snapshot in uses) + { + if (!existingUses.Remove(snapshot.Id, out var row)) + { + row = new MediaAssetUse { Id = snapshot.Id }; + db.MediaUses.Add(row); + } + + row.AssetId = snapshot.AssetId; + row.Module = snapshot.Module; + row.PlaceKind = snapshot.PlaceKind; + row.Position = snapshot.Position; + row.Active = snapshot.Active; + row.SetHash = snapshot.SetHash; + row.Crops = cropsByAsset.TryGetValue(snapshot.AssetId, out var crops) ? crops : "[]"; + } + + // What is left no longer exists at the source. + db.MediaUses.RemoveRange(existingUses.Values); + db.MediaAssets.RemoveRange(existingAssets.Values); + } + + private async Task VerifyAsync(IReadOnlyList assets, IReadOnlyList uses, IReadOnlyList modules, CancellationToken cancellationToken) + { + var differences = new List(); + var copiedAssets = new Dictionary(); + var copiedUses = new Dictionary(); + foreach (var module in modules) + { + foreach (var asset in await db.MediaAssets.AsNoTracking().Where(a => a.Module == module).ToListAsync(cancellationToken)) + { + copiedAssets[asset.Id] = asset; + } + + foreach (var use in await db.MediaUses.AsNoTracking().Where(u => u.Module == module).ToListAsync(cancellationToken)) + { + copiedUses[use.Id] = use; + } + } + + if (copiedAssets.Count != assets.Count) + { + differences.Add($"photos: source {assets.Count}, copy {copiedAssets.Count}"); + } + + if (copiedUses.Count != uses.Count) + { + differences.Add($"uses: source {uses.Count}, copy {copiedUses.Count}"); + } + + foreach (var asset in assets) + { + if (!copiedAssets.TryGetValue(asset.Id, out var copy)) + { + differences.Add($"photo {asset.Id} is missing in the copy"); + } + else if (copy.OriginalSha256 != asset.OriginalSha256 || copy.OriginalKey != asset.OriginalKey || copy.Bytes != asset.Bytes) + { + differences.Add($"photo {asset.Id}: hash, key or size differs"); + } + } + + foreach (var use in uses) + { + if (!copiedUses.TryGetValue(use.Id, out var copy)) + { + differences.Add($"use {use.Id} is missing in the copy"); + } + else if (copy.SetHash != use.SetHash || copy.AssetId != use.AssetId) + { + differences.Add($"use {use.Id}: set hash or photo differs"); + } + } + + return new MediaCopyReport(copiedAssets.Count, copiedUses.Count, differences); + } +} diff --git a/src/SlpModularCms.Modules.Media/SlpModularCms.Modules.Media.csproj b/src/SlpModularCms.Modules.Media/SlpModularCms.Modules.Media.csproj new file mode 100644 index 0000000..3d21af3 --- /dev/null +++ b/src/SlpModularCms.Modules.Media/SlpModularCms.Modules.Media.csproj @@ -0,0 +1,19 @@ + + + + net10.0 + enable + enable + + + + + <_Parameter1>SlpModularCms.Modules.Media.Tests + + + + + + + + -- 2.39.5 From 4ae1789575df3230aea419dbf8797773186b705f Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 15:39:52 +0100 Subject: [PATCH 11/22] Docs: controlestappen rond de kopie op test en aanname over deploy zonder dump Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 1 + .../application-design/migration-plan.md | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+) 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 0d1d04c..9b94c85 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -63,3 +63,4 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu - Assumption 12 now reads: there IS a trash (decision 12), the earlier "no trash in phase A" no longer applies. Assumption 10: deleting a used photo is possible after a second confirmation (built). Assumption 21: the original file name is stored from now on (built). | 33 | **Where the copy runs and what it copies** (built 2026-11-17). | A new module `Modules.Media` owns the tables (`MediaAssets`, `MediaUses`); modules offer their data through `IMediaMigrationSource` so the library module does not depend on the Hero. The copy is a verified mirror in one transaction behind `Media:Library:CopyOnStartup` (default false). The use of a hero slide carries both crops (`wide`, `tall`) of its photo as JSON; its set hash is the photo's current set hash. | A copy job triggered from the admin instead of start-up: easier to time, needs an endpoint and a button. | `Modules.Media/Services/MediaLibraryCopier.cs`, `HeroMediaMigrationSource` | | 34 | **Naming**: entity `MediaAssetUse` (table `MediaUses`), because `MediaUse` already names the read model in Core. | As built. | Rename the table or the record: a small migration. | `Modules.Media/Data` | +| 35 | **Test deploy without a separate database dump** (decided on assumption by SLS-Main, 2026-11-17, Bryan away). | The Raspberry Pi test host cannot be dumped by SLS-Main; the test data can be rebuilt with the seed scripts and both database changes of the branch (`AddMediaLibraryColumns`, the empty Media tables) are additive, so the test deploy goes ahead without a dump. The copy stays OFF until Bryan agrees. | Take a dump on the Pi before the deploy (and certainly before the copy is switched on). | `migration-plan.md`, section "Test host" | diff --git a/aidlc-docs/features/media-library/inception/application-design/migration-plan.md b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md index b4bc899..bf74941 100644 --- a/aidlc-docs/features/media-library/inception/application-design/migration-plan.md +++ b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md @@ -87,3 +87,23 @@ Nothing reads from the new tables yet (phase 2, the switch, is not built). The l ### Still to build (phases 2 and 3) The switch (`Media:Library:ReadFromLibrary`, dual write of new uploads, library reading from the new tables) and the contract phase. They need Bryan's acceptance of the copy on test first. + +## Test host: what to check around the copy (prepared 2026-11-17; the copy is NOT switched on yet) + +**Deploy without the copy (decided on assumption by SLS-Main, Bryan away):** the test deploy of the branch carries two additive database changes, the Hero migration `AddMediaLibraryColumns` (three nullable columns) and the empty tables of the Media module. No separate database dump is taken on the Raspberry Pi (SLS-Main cannot make one); the assumption is that the test data can be rebuilt with the seed scripts and that both changes are additive. Bryan checks this assumption later. + +After that deploy, check in the log: + +- `Applying migration '..._AddMediaLibraryColumns'` and `Applying migration '..._InitialCreate'` (Media) appear once, no error; +- the Hero admin still opens, a photo can be uploaded and a slide saved (smoke test), and `/media/hero//...` addresses still answer; +- `Media__Library__CopyOnStartup` is NOT set: no line `Media library copy verified` appears. + +**To switch the copy on (only after Bryan's agreement):** + +1. Make a database dump first if it can be done, and note the number of rows: `SELECT COUNT(*) FROM HeroImages; SELECT COUNT(*) FROM HeroSlides;`. +2. Set the environment variable `Media__Library__CopyOnStartup=true` on the test host and restart the application. +3. The log must say `Media library copy verified: N photos and M uses from hero.` with N equal to the `HeroImages` count and M equal to the `HeroSlides` count. An error line `The media library copy failed and was rolled back` means nothing was copied. +4. Check: `SELECT COUNT(*) FROM MediaAssets; SELECT COUNT(*) FROM MediaUses;` equals the same counts; the library screen still shows the same photos (it still reads the hero). +5. Switch it off again (remove the variable, restart) when done: the copy can be repeated at any time; it is a mirror. + +**Rollback:** remove the variable (the tables stay, unused), or drop the tables with the EF `Down` migration of the Media module; the Hero's own tables are never changed by the copy. -- 2.39.5 From 8ad071da1ceabc54486279d3be9a2d1f66116a3a Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 16:38:28 +0100 Subject: [PATCH 12/22] Mediabibliotheek: gebruik-link via de router (blijft onder /admin) en opent de Hero op het tabblad Afbeeldingen Co-Authored-By: Claude Sonnet 5.5 --- .../media/components/PhotoSelectionList.tsx | 17 ++---- frontend/src/features/media/lib/usageLabel.ts | 19 +++++- .../media/pages/MediaLibraryPage.test.tsx | 59 +++++++++++++------ .../features/media/pages/MediaLibraryPage.tsx | 20 ++++++- 4 files changed, 82 insertions(+), 33 deletions(-) diff --git a/frontend/src/features/media/components/PhotoSelectionList.tsx b/frontend/src/features/media/components/PhotoSelectionList.tsx index 3454204..32c2613 100644 --- a/frontend/src/features/media/components/PhotoSelectionList.tsx +++ b/frontend/src/features/media/components/PhotoSelectionList.tsx @@ -1,8 +1,8 @@ -import { useRef } from 'react'; +import { useRef, type ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; import { Checkbox } from '@/components/ui/checkbox'; import { formatBytes } from '../lib/format'; -import { usageHref, usageLabel } from '../lib/usageLabel'; +import { usageLabel } from '../lib/usageLabel'; import { selectAll, selectRange, stateOf, type Selection } from '../lib/selection'; export interface PhotoUse { @@ -33,13 +33,15 @@ interface PhotoSelectionListProps { onSelectionChange: (selection: Selection) => void; /** Photos that cannot be selected (for example in use during a clean-up). */ isDisabled?: (item: PhotoItem) => boolean; + /** How a use is shown (the page makes it a router link to the module). Default: the plain label. */ + renderUse?: (use: PhotoUse, label: string) => ReactNode; } /** * 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) { +export function PhotoSelectionList({ items, selection, onSelectionChange, isDisabled, renderUse }: PhotoSelectionListProps) { const { t, i18n } = useTranslation(); const anchor = useRef(null); const selectable = items.filter((item) => !isDisabled?.(item)); @@ -115,17 +117,10 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa {item.uses.map((use, index) => { const label = usageLabel(t, use); - const href = usageHref(use); return ( {index > 0 && '; '} - {href ? ( - - {label} - - ) : ( - label - )} + {renderUse ? renderUse(use, label) : label} ); })} diff --git a/frontend/src/features/media/lib/usageLabel.ts b/frontend/src/features/media/lib/usageLabel.ts index d2e32c2..68a6982 100644 --- a/frontend/src/features/media/lib/usageLabel.ts +++ b/frontend/src/features/media/lib/usageLabel.ts @@ -14,7 +14,22 @@ export function usageLabel(t: TFunction, use: UsePlace): string { return `${t(`media.module.${use.module}`, { defaultValue: use.module })}, ${where}${use.active ? '' : ` (${t('media.use.off')})`}`; } -/** Where the admin screen of the module that uses the photo lives (null when there is none). */ -export function usageHref(use: Pick): string | null { +/** + * The admin route of the module that uses the photo (null when there is none). It is a ROUTER path: the router adds the + * base path of the admin app (/admin) when it makes the link, so it never goes outside the admin. + */ +export function usageTarget(use: Pick): '/hero' | null { return use.module === 'hero' ? '/hero' : null; } + +/** + * The hero screen opens on the tab it was left on; a use is a slide, so the link leaves it on the images tab. + * (Storage can be blocked: then the screen simply opens on its own default.) + */ +export function rememberHeroImagesTab(): void { + try { + window.sessionStorage.setItem('cms-hero-tab', 'images'); + } catch { + // Not available: nothing to remember. + } +} diff --git a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx index 8951820..48cf39a 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx @@ -5,16 +5,30 @@ import userEvent from '@testing-library/user-event'; import i18n from '@/i18n/config'; import { server } from '@/mocks/server'; import { renderWithProviders } from '@/test/utils'; +import { createMemoryHistory, createRootRoute, createRoute, createRouter, RouterProvider } from '@tanstack/react-router'; import { seedPhotos, seedStorage } from '../mocks/handlers'; import { MediaLibraryPage } from './MediaLibraryPage'; +/** The page inside a router with the same base path as the real admin app (/admin), and a stub hero route to land on. */ +function renderPage() { + const root = createRootRoute(); + const media = createRoute({ getParentRoute: () => root, path: '/media', component: MediaLibraryPage }); + const hero = createRoute({ getParentRoute: () => root, path: '/hero', component: () =>

hero

}); + const router = createRouter({ + routeTree: root.addChildren([media, hero]), + basepath: '/admin', + history: createMemoryHistory({ initialEntries: ['/admin/media'] }), + }); + return renderWithProviders(); +} + beforeEach(async () => { await i18n.changeLanguage('nl'); }); describe('MediaLibraryPage', () => { it('lists the photos newest first with where each is used, and the storage', async () => { - renderWithProviders(); + renderPage(); const list = await screen.findByTestId('photo-selection-list'); const rows = within(list).getAllByRole('listitem'); @@ -28,17 +42,17 @@ describe('MediaLibraryPage', () => { it('warns when the storage is nearly full and says so when it is full', async () => { server.use(http.get('*/media-library/storage', () => HttpResponse.json({ ...seedStorage(), usedBytes: 1_800_000_000, level: 'warning' }))); - const { unmount } = renderWithProviders(); + const { unmount } = renderPage(); expect(await screen.findByTestId('storage-warning')).toHaveTextContent('80%'); unmount(); server.use(http.get('*/media-library/storage', () => HttpResponse.json({ ...seedStorage(), usedBytes: 2_147_483_648, level: 'full' }))); - renderWithProviders(); + renderPage(); expect(await screen.findByTestId('storage-warning')).toHaveTextContent('vol'); }); it('selects photos and shows the bulk bar with the delete action', async () => { - renderWithProviders(); + renderPage(); await screen.findByTestId('photo-selection-list'); await userEvent.click(screen.getByRole('checkbox', { name: 'zomer.jpg' })); @@ -48,7 +62,7 @@ describe('MediaLibraryPage', () => { }); it('opens the clean-up: older than 7 days, only unused, all selected, newest first, and nothing is deleted', async () => { - renderWithProviders(); + renderPage(); await screen.findByTestId('photo-selection-list'); await userEvent.click(screen.getByTestId('cleanup-open')); @@ -63,7 +77,7 @@ describe('MediaLibraryPage', () => { }); it('includes photos in use when "only unused" is switched off', async () => { - renderWithProviders(); + renderPage(); await screen.findByTestId('photo-selection-list'); await userEvent.click(screen.getByTestId('cleanup-open')); const dialog = await screen.findByTestId('cleanup-dialog'); @@ -83,7 +97,7 @@ describe('MediaLibraryPage', () => { return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) }); }), ); - renderWithProviders(); + renderPage(); await screen.findByTestId('photo-selection-list'); await userEvent.click(screen.getByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222')); @@ -103,7 +117,7 @@ describe('MediaLibraryPage', () => { return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) }); }), ); - renderWithProviders(); + renderPage(); await screen.findByTestId('photo-selection-list'); await userEvent.click(screen.getByTestId('photo-select-hero:11111111-1111-1111-1111-111111111111')); @@ -125,7 +139,7 @@ describe('MediaLibraryPage', () => { return HttpResponse.json({ results: ids.map((id, i) => ({ id, status: i === 0 ? 'failed' : 'trashed', uses: [] })) }); }), ); - renderWithProviders(); + renderPage(); await screen.findByTestId('photo-selection-list'); await userEvent.click(screen.getByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222')); @@ -146,7 +160,7 @@ describe('MediaLibraryPage', () => { return HttpResponse.json({ results: restored.map((id) => ({ id, status: 'restored', uses: [] })) }); }), ); - renderWithProviders(); + renderPage(); await screen.findByTestId('photo-selection-list'); await userEvent.click(screen.getByTestId('view-trash')); @@ -165,7 +179,7 @@ describe('MediaLibraryPage', () => { return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) }); }), ); - renderWithProviders(); + renderPage(); await screen.findByTestId('photo-selection-list'); await userEvent.click(screen.getByTestId('cleanup-open')); const dialog = await screen.findByTestId('cleanup-dialog'); @@ -177,8 +191,8 @@ describe('MediaLibraryPage', () => { await waitFor(() => expect(body).toEqual({ ids: ['hero:22222222-2222-2222-2222-222222222222'], confirmedInUse: false })); }); - it('filters the library on used and unused photos and links a use to its module', async () => { - renderWithProviders(); + it('filters the library on used and unused photos', async () => { + renderPage(); const list = await screen.findByTestId('photo-selection-list'); expect(within(list).getAllByRole('listitem')).toHaveLength(3); @@ -186,14 +200,25 @@ describe('MediaLibraryPage', () => { expect(within(screen.getByTestId('photo-selection-list')).getAllByRole('listitem')).toHaveLength(1); await userEvent.click(screen.getByTestId('filter-used')); - const used = within(screen.getByTestId('photo-selection-list')).getAllByRole('listitem'); - expect(used).toHaveLength(2); - expect(within(used[0]!).getByRole('link', { name: 'Hero, slide 1' })).toHaveAttribute('href', '/hero'); + expect(within(screen.getByTestId('photo-selection-list')).getAllByRole('listitem')).toHaveLength(2); + }); + + it('links a use to the hero under the admin base path (/admin/hero, not /hero) and opens its images tab', async () => { + window.sessionStorage.removeItem('cms-hero-tab'); + renderPage(); + const list = await screen.findByTestId('photo-selection-list'); + const link = within(within(list).getAllByRole('listitem')[0]!).getByRole('link', { name: 'Hero, slide 1' }); + + expect(link).toHaveAttribute('href', '/admin/hero'); + + await userEvent.click(link); + expect(await screen.findByTestId('hero-stub')).toBeInTheDocument(); + expect(window.sessionStorage.getItem('cms-hero-tab')).toBe('images'); }); it('shows an error when the library cannot be loaded', async () => { server.use(http.get('*/media-library/photos', () => new HttpResponse(null, { status: 500 }))); - renderWithProviders(); + renderPage(); expect(await screen.findByTestId('media-error')).toBeInTheDocument(); }); diff --git a/frontend/src/features/media/pages/MediaLibraryPage.tsx b/frontend/src/features/media/pages/MediaLibraryPage.tsx index 7ff88e7..a8ce2d8 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.tsx @@ -1,16 +1,30 @@ -import { useMemo, useState } from 'react'; +import { useMemo, useState, type ReactNode } from 'react'; +import { Link } from '@tanstack/react-router'; import { useTranslation } from 'react-i18next'; import { Eraser, RotateCcw, Trash2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { BulkActionBar } from '../components/BulkActionBar'; import { CleanupDialog } from '../components/CleanupDialog'; import { DeleteDialog } from '../components/DeleteDialog'; -import { PhotoSelectionList } from '../components/PhotoSelectionList'; +import { PhotoSelectionList, type PhotoUse } from '../components/PhotoSelectionList'; import { StorageMeter } from '../components/StorageMeter'; import { emptySelection, prune, type Selection } from '../lib/selection'; +import { rememberHeroImagesTab, usageTarget } from '../lib/usageLabel'; import { toPhotoItem } from '../lib/toPhotoItem'; import { useMediaPhotos, useMediaStorage, useMediaTrash, useRestorePhotos } from '../services/hooks'; +/** A use becomes a link to the screen of its module, made by the router (so it stays under the admin base path). */ +function renderUse(use: PhotoUse, label: string): ReactNode { + const target = usageTarget(use); + return target ? ( + + {label} + + ) : ( + label + ); +} + type View = 'library' | 'trash'; type UseFilter = 'all' | 'used' | 'unused'; @@ -106,7 +120,7 @@ export function MediaLibraryPage() { {t('media.page.noModules')}

)} - {source.data && } + {source.data && } setSelection(emptySelection)} /> -- 2.39.5 From 1384cafa7ba33d7d82bf82ebb5f3051bb59dd5ec Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 16:58:23 +0100 Subject: [PATCH 13/22] WIP: bulkbalk boven de lijst, definitief verwijderen en prullenbak legen, uitsnede direct zonder opslaan, teller per batch --- .../hero/components/ProcessingStatus.tsx | 47 ++++-- frontend/src/features/hero/mocks/handlers.ts | 18 ++- .../src/features/hero/pages/HeroPage.test.tsx | 151 +++++++++++------- frontend/src/features/hero/pages/HeroPage.tsx | 59 ++++--- frontend/src/features/hero/services/hooks.ts | 17 +- frontend/src/features/hero/services/types.ts | 2 +- .../media/components/BulkActionBar.tsx | 16 +- .../media/components/CleanupDialog.tsx | 16 +- .../components/PhotoSelectionList.test.tsx | 28 +++- .../media/components/PhotoSelectionList.tsx | 11 +- .../features/media/components/PurgeDialog.tsx | 95 +++++++++++ frontend/src/features/media/mocks/handlers.ts | 9 ++ .../features/media/pages/MediaLibraryPage.tsx | 30 +++- frontend/src/features/media/services/hooks.ts | 11 +- frontend/src/features/media/services/types.ts | 8 +- frontend/src/i18n/locales/en/translation.json | 17 +- frontend/src/i18n/locales/nl/translation.json | 17 +- .../Media/MediaLibraryControllerTests.cs | 19 +++ .../Media/MediaLibraryTests.cs | 63 ++++++++ .../Media/Library/MediaLibraryController.cs | 28 +++- .../Media/Library/MediaLibraryService.cs | 58 +++++++ .../Media/Library/MediaLibraryTypes.cs | 19 +++ .../HeroMediaUsageProviderTests.cs | 75 +++++++++ .../HeroSetFocusTests.cs | 45 ++++++ .../Controllers/HeroControllers.cs | 14 ++ .../Repositories/HeroRepository.cs | 9 ++ .../Services/HeroImageService.cs | 65 ++++++++ .../Services/HeroMediaUsageProvider.cs | 3 + 28 files changed, 816 insertions(+), 134 deletions(-) create mode 100644 frontend/src/features/media/components/PurgeDialog.tsx create mode 100644 src/SlpModularCms.Modules.Hero.Tests/HeroSetFocusTests.cs diff --git a/frontend/src/features/hero/components/ProcessingStatus.tsx b/frontend/src/features/hero/components/ProcessingStatus.tsx index 9b0c11d..7ac85d2 100644 --- a/frontend/src/features/hero/components/ProcessingStatus.tsx +++ b/frontend/src/features/hero/components/ProcessingStatus.tsx @@ -112,25 +112,44 @@ export function PhotoPlaceholder({ failed, testId, step }: { failed: boolean; te } /** - * The photo of a slide whose crop is being made again (a changed focus point): the old picture stays visible underneath, - * with the same calm shimmer and a short text, so it is clear that the change is not on the website yet. + * The photo of a slide whose crop is being made again (a new crop): the old picture stays visible underneath, with one + * short, readable line ("Wordt verwerkt…"), a progress bar from 0 to 100 percent and the percentage. No spinner, so it also + * works without motion. A new crop needs no save: it goes live by itself when the new variants are complete. */ export function RecutThumbnail({ src, failed, testId, step }: { src: string; failed: boolean; testId: string; step?: { done: number; total: number } | null }) { const { t } = useTranslation(); + const percent = step && step.total > 0 ? Math.min(100, Math.round((step.done / step.total) * 100)) : 0; return ( -
+
- - {failed ? null : } - {failed ? t('hero.slides.failed') : t('hero.slides.recut')} - {!failed && step ? {step.done}/{step.total} : null} - +
+ {failed ? ( + {t('hero.slides.failed')} + ) : ( + <> +
+ {t('hero.slides.processing')} + {percent}% +
+
+
+
+ + )} +
); } diff --git a/frontend/src/features/hero/mocks/handlers.ts b/frontend/src/features/hero/mocks/handlers.ts index 582e79f..74db8d7 100644 --- a/frontend/src/features/hero/mocks/handlers.ts +++ b/frontend/src/features/hero/mocks/handlers.ts @@ -1,6 +1,6 @@ import { http, HttpResponse } from 'msw'; import { API_BASE } from '@/features/auth/mocks/fixtures'; -import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types'; +import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types'; const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({ id, @@ -57,6 +57,7 @@ export const resetMockHero = (): void => { uploads = 0; uploadFailure = null; retried = []; + focusRequests = []; recutting = new Set(); }; @@ -79,6 +80,10 @@ export const getRetriedImages = (): string[] => retried; export const getSavedHeroRequests = (): HeroSaveRequest[] => saved; +let focusRequests: { imageId: string; body: HeroFocusRequest }[] = []; +/** The crops sent at once with PUT hero/images/{id}/focus (no save of the hero involved). */ +export const getFocusRequests = (): { imageId: string; body: HeroFocusRequest }[] => focusRequests; + export const failNextUpload = (failure: { status: number; error: string; message: string } | null): void => { uploadFailure = failure; }; @@ -118,6 +123,17 @@ export const heroHandlers = [ return HttpResponse.json(hero); }), + http.put(`${API_BASE}/api/v1/hero/images/:id/focus`, async ({ params, request }) => { + const id = String(params.id); + const body = (await request.json()) as HeroFocusRequest; + focusRequests.push({ imageId: id, body }); + const current = images[id] ?? hero.slides.find((s) => s.imageId === id)?.image ?? seedImage(id); + images[id] = { ...current, focus: body.focus, wideFocus: body.wide ?? null, tallFocus: body.tall ?? null, processing: true }; + recutting.add(id); + hero = { ...hero, slides: hero.slides.map((s) => (s.imageId === id ? { ...s, image: images[id] } : s)) }; + return HttpResponse.json(images[id]); + }), + http.get(`${API_BASE}/api/v1/hero/images/limits`, () => HttpResponse.json({ formats: ['JPEG', 'PNG', 'GIF', 'BMP', 'TIFF', 'WebP', 'AVIF'], maxUploadBytes: 10 * 1024 * 1024, maxMegapixels: 64 }), ), diff --git a/frontend/src/features/hero/pages/HeroPage.test.tsx b/frontend/src/features/hero/pages/HeroPage.test.tsx index 645f0d8..7a76294 100644 --- a/frontend/src/features/hero/pages/HeroPage.test.tsx +++ b/frontend/src/features/hero/pages/HeroPage.test.tsx @@ -5,7 +5,8 @@ import { http, HttpResponse } from 'msw'; import { server } from '@/mocks/server'; import { API_BASE } from '@/features/auth/mocks/fixtures'; import { renderApp, mockAuthenticated } from '@/test/utils'; -import { emptyHero, failNextUpload, finishMockRecut, getRetriedImages, getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers'; +import { emptyHero, failNextUpload, finishMockRecut, getRetriedImages, getFocusRequests, + getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers'; import { _resetSetupStatusCache } from '@/router'; const T = { timeout: 10000 }; @@ -42,16 +43,16 @@ describe('Hero page', () => { expect(screen.queryByTestId('hero-slide-0-focus')).not.toBeInTheDocument(); }); - it('shows how many photos are ready, with an accessible progress bar, and hides it when all are ready', async () => { + it('counts only the photos that are being prepared, not the finished ones, with an accessible progress bar, and hides it when all are ready', async () => { const waiting = (n: number) => ({ ...slide(n), image: { ...slide(n).image, variants: [], src: '', processing: true } }); setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), waiting(2), waiting(3)] }); await openPage(); - expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/1 van 3|1 of 3/); - const bar = screen.getByRole('progressbar'); - expect(bar).toHaveAttribute('aria-valuenow', '1'); - expect(bar).toHaveAttribute('aria-valuemax', '3'); + expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/0 van 2|0 of 2/); + const bar = screen.getByRole('progressbar', { name: /verwerkt|processed|Verwerking|Processing/i }); + expect(bar).toHaveAttribute('aria-valuenow', '0'); + expect(bar).toHaveAttribute('aria-valuemax', '2'); }); it('keeps unsaved edits when the background refresh brings a finished photo', async () => { @@ -294,7 +295,7 @@ describe('Focus dialog', () => { expect(screen.getByTestId('focus-y')).toHaveValue(55); }); - it('keeps a change locally until the hero is saved, then sends it with the save', async () => { + it('applies a new crop at once, without saving the hero, and the photo shows it is being processed', async () => { await open(); fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '30' } }); @@ -306,42 +307,28 @@ describe('Focus dialog', () => { await userEvent.click(screen.getByTestId('focus-save')); await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument()); + await waitFor(() => expect(getFocusRequests()).toHaveLength(1)); + expect(getFocusRequests()[0]).toEqual({ + imageId: '10000000-0000-0000-0000-000000000001', + body: { focus: { x: 0.3, y: 0.5, zoom: 1 }, wide: null, tall: { x: 0.8, y: 0.5, zoom: 2 } }, + }); expect(getSavedHeroRequests()).toHaveLength(0); - expect(screen.getByTestId('hero-slide-0-focus-pending')).toBeInTheDocument(); - - // Reopening shows the pending values. - await userEvent.click(screen.getByTestId('hero-slide-0-focus')); - expect(screen.getByTestId('focus-x')).toHaveValue(30); - await userEvent.click(screen.getByTestId('focus-target-tall')); - expect(screen.getByTestId('focus-override-tall')).toBeChecked(); - expect(screen.getByTestId('focus-x')).toHaveValue(80); - expect(screen.getByTestId('focus-zoom')).toHaveValue('2'); - await userEvent.click(screen.getByTestId('focus-cancel')); - - await userEvent.click(screen.getByTestId('hero-save')); - - await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); - expect(getSavedHeroRequests()[0].imageFocus).toEqual([ - { - imageId: '10000000-0000-0000-0000-000000000001', - focus: { x: 0.3, y: 0.5, zoom: 1 }, - wide: null, - tall: { x: 0.8, y: 0.5, zoom: 2 }, - }, - ]); - await waitFor(() => expect(screen.queryByTestId('hero-slide-0-focus-pending')).not.toBeInTheDocument()); + expect(await screen.findByTestId('hero-slide-0-recut', {}, T)).toBeInTheDocument(); + expect(screen.queryByTestId('hero-slide-0-focus-pending')).not.toBeInTheDocument(); + expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument(); + expect(screen.getByTestId('hero-save')).toBeDisabled(); }); - it('sends no focus edits when nothing was changed', async () => { + it('sends no crop with the save: the hero save carries only the content', async () => { await open(); await userEvent.click(screen.getByTestId('focus-cancel')); - // Something else changed, so there is something to save; the cancelled focus is not part of it. await userEvent.type(screen.getByTestId('hero-tagline'), 'x'); await userEvent.click(screen.getByTestId('hero-save')); await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); - expect(getSavedHeroRequests()[0].imageFocus).toEqual([]); + expect(getSavedHeroRequests()[0].imageFocus).toBeUndefined(); + expect(getFocusRequests()).toHaveLength(0); }); it('goes back to the general point when the own setting is switched off', async () => { @@ -731,7 +718,7 @@ describe('Progress of a photo that is being prepared', () => { await openPage(); - expect(await screen.findByTestId('hero-processing-current', {}, T)).toHaveTextContent(/foto 2 van 3.*stap 7 van 16|photo 2 of 3.*step 7 of 16/); + expect(await screen.findByTestId('hero-processing-current', {}, T)).toHaveTextContent(/foto 1 van 2.*stap 7 van 16|photo 1 of 2.*step 7 of 16/); expect(screen.getByTestId('hero-slide-1-processing-step')).toHaveTextContent('7/16'); expect(screen.queryByTestId('hero-slide-2-processing-step')).not.toBeInTheDocument(); }); @@ -743,28 +730,42 @@ describe('A changed focus point makes a new crop in the background', () => { resetMockHero(); }); - it('shows that the new crop is not live yet (old picture underneath), counts it in the total, and clears it when done', async () => { + it('shows the new crop as processing right away (old picture underneath, text and a 0-100% bar, no spinner), outside the upload counter, and clears it when done', async () => { setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] }); await openPage(); await userEvent.click(screen.getByTestId('hero-slide-0-focus')); fireEvent.change(await screen.findByTestId('focus-x', {}, T), { target: { value: '25' } }); await userEvent.click(screen.getByTestId('focus-save')); - await userEvent.click(screen.getByTestId('hero-save')); const recut = await screen.findByTestId('hero-slide-0-recut', {}, T); - expect(recut).toHaveClass('hero-shimmer'); expect(recut.querySelector('img')).not.toBeNull(); - expect(recut).toHaveTextContent(/Nieuwe uitsnede|new crop/); - expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/1 van 2|1 of 2/); + expect(screen.getByTestId('hero-slide-0-recut-text')).toHaveTextContent(/^(Wordt verwerkt…|Processing…)$/); + const bar = screen.getByTestId('hero-slide-0-recut-bar'); + expect(bar).toHaveAttribute('aria-valuemin', '0'); + expect(bar).toHaveAttribute('aria-valuemax', '100'); + expect(bar).toHaveAttribute('aria-valuenow', '0'); + expect(screen.getByTestId('hero-slide-0-recut-percent')).toHaveTextContent('0%'); + expect(recut.querySelector('.animate-spin')).toBeNull(); + expect(screen.queryByTestId('hero-processing-count')).not.toBeInTheDocument(); expect(screen.queryByTestId('hero-slide-1-recut')).not.toBeInTheDocument(); // The server finishes the new crop; the page asks again by itself. finishMockRecut(); await waitFor(() => expect(screen.queryByTestId('hero-slide-0-recut')).not.toBeInTheDocument(), { timeout: 12000 }); - expect(screen.queryByTestId('hero-processing')).not.toBeInTheDocument(); expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled(); }, 25000); + it('shows the step of a new crop as a percentage on the bar', async () => { + const busy = { ...slide(1), image: { ...slide(1).image, processing: true, renderDone: 4, renderTotal: 16 } }; + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [busy] }); + + await openPage(); + + const recut = await screen.findByTestId('hero-slide-0-recut', {}, T); + expect(screen.getByTestId('hero-slide-0-recut-bar')).toHaveAttribute('aria-valuenow', '25'); + expect(screen.getByTestId('hero-slide-0-recut-percent')).toHaveTextContent('25%'); + }); + it('shows a failed new crop with the retry', async () => { const failed = { ...slide(1), image: { ...slide(1).image, processing: true, failed: true } }; setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [failed] }); @@ -915,6 +916,43 @@ describe('Each photo shows by itself when its processing is finished', () => { expect(screen.queryByText(/stond al|already/i)).not.toBeInTheDocument(); }); + it('counts only the newly uploaded photos, not the whole hero: one new photo next to eight finished ones is 0 of 1', async () => { + const id = '70000000-0000-0000-0000-000000000021'; + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [1, 2, 3, 4, 5, 6, 7, 8].map((n) => slide(n)) }); + server.use( + http.post(`${API_BASE}/api/v1/hero/images`, () => HttpResponse.json(cutting(id), { status: 201 })), + http.get(`${API_BASE}/api/v1/hero/images/${id}`, () => HttpResponse.json(cutting(id))), + ); + await openPage(); + + await userEvent.upload(screen.getByTestId('hero-upload'), jpg('nieuw.jpg')); + + expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/^(0 van 1|0 of 1)/); + expect(screen.getByTestId('hero-processing-bar')).toHaveAttribute('aria-valuemax', '1'); + }); + + it('counts a batch of uploads as that batch only (0 of x), and the next upload starts a new count', async () => { + const ids = ['70000000-0000-0000-0000-000000000031', '70000000-0000-0000-0000-000000000032', '70000000-0000-0000-0000-000000000033']; + let n = 0; + const finished = new Set(); + server.use( + http.post(`${API_BASE}/api/v1/hero/images`, () => HttpResponse.json(cutting(ids[n++]), { status: 201 })), + ...ids.map((id) => http.get(`${API_BASE}/api/v1/hero/images/${id}`, () => HttpResponse.json(finished.has(id) ? ready(id) : cutting(id)))), + ); + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] }); + await openPage(); + + await userEvent.upload(screen.getByTestId('hero-upload'), [jpg('a.jpg'), jpg('b.jpg')]); + expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/^(0 van 2|0 of 2)/); + + finished.add(ids[0]); + finished.add(ids[1]); + await waitFor(() => expect(screen.queryByTestId('hero-processing')).not.toBeInTheDocument(), { timeout: 12000 }); + + await userEvent.upload(screen.getByTestId('hero-upload'), jpg('c.jpg')); + expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/^(0 van 1|0 of 1)/); + }, 40000); + it('finishes photo by photo: the first one can be worked on while the second is still busy, and the total at the top follows', async () => { const ids = ['70000000-0000-0000-0000-000000000011', '70000000-0000-0000-0000-000000000012']; let n = 0; @@ -961,47 +999,39 @@ describe('The picture of a slide is the way to adjust its crop', () => { expect(await screen.findByTestId('focus-dialog', {}, T)).toBeInTheDocument(); }); - it('shows the new crop on the thumbnail right after Apply, with the not-saved note, and drops it when the change is undone', async () => { + it('starts processing the photo right after Apply, with no unsaved note', async () => { setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] }); await openPage(); - expect(screen.queryByTestId('hero-slide-0-focus-local')).not.toBeInTheDocument(); await userEvent.click(screen.getByTestId('hero-slide-0-focus')); fireEvent.change(await screen.findByTestId('focus-x', {}, T), { target: { value: '10' } }); await userEvent.click(screen.getByTestId('focus-save')); await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument()); - const local = await screen.findByTestId('hero-slide-0-focus-local', {}, T); - expect(local.getAttribute('src')).toContain('full-1280.webp'); - expect(local.style.left).toMatch(/^-?\d/); - expect(screen.getByTestId('hero-slide-0-focus-pending')).toHaveTextContent(/Focus gewijzigd, nog niet opgeslagen|Focus changed, not saved yet/); + expect(await screen.findByTestId('hero-slide-0-recut', {}, T)).toBeInTheDocument(); + expect(screen.queryByTestId('hero-slide-0-focus-pending')).not.toBeInTheDocument(); + expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument(); }); - it('follows the whole chain: Apply, Save sends the focus, the new crop is made (animation), then it is finished', async () => { + it('follows the whole chain: Apply sends the crop at once, the new crop is made (bar), then it is finished, and the hero never needed saving', async () => { setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] }); await openPage(); await userEvent.click(screen.getByTestId('hero-slide-1-focus')); fireEvent.change(await screen.findByTestId('focus-y', {}, T), { target: { value: '20' } }); await userEvent.click(screen.getByTestId('focus-save')); - await screen.findByTestId('hero-slide-1-focus-pending', {}, T); - await userEvent.click(screen.getByTestId('hero-save')); - - await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); - expect(getSavedHeroRequests()[0].imageFocus).toEqual([ - expect.objectContaining({ imageId: '10000000-0000-0000-0000-000000000002', focus: { x: 0.5, y: 0.2, zoom: 1 } }), - ]); - // Saved: the note of the unsaved change is gone and the new crop is being made, with the animation, on that photo only. + await waitFor(() => expect(getFocusRequests()).toHaveLength(1)); + expect(getFocusRequests()[0].body.focus).toEqual({ x: 0.5, y: 0.2, zoom: 1 }); const recut = await screen.findByTestId('hero-slide-1-recut', {}, T); - expect(recut).toHaveClass('hero-shimmer'); - expect(recut).toHaveTextContent(/Nieuwe uitsnede wordt gemaakt|Making the new crop/); - expect(screen.queryByTestId('hero-slide-1-focus-pending')).not.toBeInTheDocument(); + expect(within(recut).getByTestId('hero-slide-1-recut-bar')).toHaveAttribute('role', 'progressbar'); expect(screen.queryByTestId('hero-slide-0-recut')).not.toBeInTheDocument(); + expect(getSavedHeroRequests()).toHaveLength(0); finishMockRecut(); expect(await screen.findByTestId('hero-slide-1-done-text', {}, { timeout: 12000 })).toHaveTextContent(/Verwerking afgerond|Processing finished/); expect(screen.queryByTestId('hero-slide-1-recut')).not.toBeInTheDocument(); expect(screen.getByTestId('hero-slide-1-focus').tagName).toBe('BUTTON'); + expect(screen.getByTestId('hero-save')).toBeDisabled(); }, 30000); }); @@ -1042,7 +1072,7 @@ describe('The Save button', () => { expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument(); }); - it('is greyed out again when a change is undone, and active for a focus change that is applied', async () => { + it('is greyed out again when a change is undone, and stays greyed out for a crop (it needs no save)', async () => { setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] }); await openPage(); const save = screen.getByTestId('hero-save'); @@ -1056,7 +1086,8 @@ describe('The Save button', () => { fireEvent.change(await screen.findByTestId('focus-x', {}, T), { target: { value: '15' } }); await userEvent.click(screen.getByTestId('focus-save')); - await waitFor(() => expect(save).toBeEnabled()); + await waitFor(() => expect(getFocusRequests()).toHaveLength(1)); + expect(save).toBeDisabled(); }); it('stays active when saving failed, so it can be tried again', async () => { diff --git a/frontend/src/features/hero/pages/HeroPage.tsx b/frontend/src/features/hero/pages/HeroPage.tsx index 285f4b9..4a0d2a1 100644 --- a/frontend/src/features/hero/pages/HeroPage.tsx +++ b/frontend/src/features/hero/pages/HeroPage.tsx @@ -24,7 +24,7 @@ import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard'; import { UploadProgress, type UploadItem } from '../components/UploadProgress'; import { mediaUrl } from '../lib/media'; import { heroFormSchema, type HeroFormData } from '../schemas/hero'; -import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks'; +import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useSetHeroImageFocus, useUploadHeroImage } from '../services/hooks'; import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from '../services/types'; const textareaClass = @@ -42,7 +42,7 @@ function toForm(hero: HeroAdminDto): HeroFormData { }; } -function toRequest(values: HeroFormData, focusEdits: Record): HeroSaveRequest { +function toRequest(values: HeroFormData): HeroSaveRequest { return { title: values.title, tagline: values.tagline || null, @@ -50,7 +50,6 @@ function toRequest(values: HeroFormData, focusEdits: Record b.label !== '' && b.target !== ''), slides: values.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.decorative ? null : s.alt, decorative: s.decorative, isActive: s.isActive })), - imageFocus: Object.entries(focusEdits).map(([imageId, edit]) => ({ imageId, ...edit })), }; } @@ -146,8 +145,12 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { const limits = useHeroUploadLimits().data; const [localImages, setLocalImages] = useState>({}); const [focusImageId, setFocusImageId] = useState(null); - // Changed focus points are kept here until the hero is saved: they are sent with the save and dropped when the page is left. - const [focusEdits, setFocusEdits] = useState>({}); + // A new crop is applied at once (no save needed): the server cuts the new variants in the background. + const setImageFocus = useSetHeroImageFocus(); + // The photos of the current upload batch, for the counter "x of y processed": only the photos uploaded together, not + // every photo of the hero. A new batch starts when the previous one is finished. + const [batch, setBatch] = useState([]); + const [recutIds, setRecutIds] = useState([]); const fileInput = useRef(null); const { @@ -241,20 +244,19 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { } }, [images, slides.fields]); - // A focus change counts as unsaved only while it differs from what is saved (applying the old point again is no change). - const samePoint = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null); - const hasPendingFocus = Object.entries(focusEdits).some(([imageId, edit]) => { - const saved = images[imageId]; - return !saved || !samePoint(saved.focus, edit.focus) || !samePoint(saved.wideFocus, edit.wide) || !samePoint(saved.tallFocus, edit.tall); - }); // The form is compared with the last saved state (react-hook-form keeps it), so a change that is undone no longer counts. // Photos still being prepared on the server and the background refresh are not changes of the administrator. - const hasUnsaved = isDirty || hasPendingFocus; + const hasUnsaved = isDirty; const contentChanged = Object.keys(dirtyFields).some((key) => key !== 'slides'); - const imagesChanged = Boolean(dirtyFields.slides?.some?.(Boolean)) || hasPendingFocus; + const imagesChanged = Boolean(dirtyFields.slides?.some?.(Boolean)); const contentInvalid = Object.keys(errors).some((key) => key !== 'slides'); const imagesInvalid = Boolean(errors.slides); const busyCount = slides.fields.filter((f) => images[f.imageId]?.processing).length; + // The counter above the form covers the current upload batch only. After a reload (no batch known) it covers the photos that + // are still being prepared. A new crop is shown on its own photo, not in this counter. + const statusImages = (batch.length > 0 ? batch.map((id) => images[id]) : slides.fields.map((f) => images[f.imageId]).filter((i) => i?.processing && !recutIds.includes(i.id))).filter( + (image): image is HeroImageDto => image !== undefined, + ); useEffect(() => { if (!hasUnsaved) return undefined; const warn = (event: BeforeUnloadEvent) => { @@ -264,10 +266,19 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { return () => window.removeEventListener('beforeunload', warn); }, [hasUnsaved]); - // The image as the dialog shows it: the saved one with a not yet saved change of its focus applied. - const withPendingFocus = (image: HeroImageDto | null): HeroImageDto | null => { - const edit = image ? focusEdits[image.id] : undefined; - return image && edit ? { ...image, focus: edit.focus, wideFocus: edit.wide, tallFocus: edit.tall } : image; + // A new crop goes to the server at once; the page then shows the photo as processing until the new variants are ready. + const applyFocus = (imageId: string, request: HeroFocusRequest) => { + setServerError(null); + setImageFocus.mutate( + { imageId, request }, + { + onSuccess: (image) => { + setLocalImages((current) => ({ ...current, [image.id]: image })); + setRecutIds((current) => [...new Set([...current, image.id])]); + }, + onError: (error) => setServerError(serverMessage(error, t('errors.generic'), t('errors.network'))), + }, + ); }; // Up to this many files go to the host at the same time; the variants are cut in the background, so an upload itself @@ -290,11 +301,15 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { const results: (HeroImageDto | 'failed' | undefined)[] = new Array(files.length).fill(undefined); let flushed = 0; let cursor = 0; + let inBatch = batch.some((id) => images[id]?.processing); const flush = () => { while (flushed < files.length && results[flushed] !== undefined) { const result = results[flushed]; if (result && result !== 'failed') { setLocalImages((current) => ({ ...current, [result.id]: result })); + const joins = inBatch; + setBatch((current) => (joins ? [...current, result.id] : [result.id])); + inBatch = true; // Ready at once (the same photo was already in the CMS): the same note as after a photo that took a while. if (!result.processing) markDone(result.id); slides.append({ id: null, imageId: result.id, alt: '', decorative: false, isActive: true }, { shouldFocus: false }); @@ -356,8 +371,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { const onSubmit = async (values: HeroFormData) => { setServerError(null); try { - const savedHero = await save.mutateAsync(toRequest(values, focusEdits)); - setFocusEdits({}); + const savedHero = await save.mutateAsync(toRequest(values)); // What was just saved is the new starting point: nothing is unsaved any more. reset(toForm(savedHero)); toast.success(t('hero.savedToast')); @@ -387,7 +401,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { return ( void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8" noValidate data-testid="hero-form"> - images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} /> + setServerError(null)} /> setFocusImageId(field.imageId)} testId={`hero-slide-${index}-focus`} /> @@ -624,8 +637,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
setFocusEdits((current) => ({ ...current, [imageId]: edit }))} + image={focusImageId ? images[focusImageId] ?? null : null} + onApply={applyFocus} onClose={() => setFocusImageId(null)} /> diff --git a/frontend/src/features/hero/services/hooks.ts b/frontend/src/features/hero/services/hooks.ts index 2a8faf5..34cf3ba 100644 --- a/frontend/src/features/hero/services/hooks.ts +++ b/frontend/src/features/hero/services/hooks.ts @@ -1,6 +1,6 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { api } from '@/lib/api-client'; -import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroUploadLimits } from './types'; +import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest, HeroUploadLimits } from './types'; export const HERO_KEY = ['hero']; @@ -68,3 +68,18 @@ export const heroImageQuery = (imageId: string) => ({ refetchInterval: (query: { state: { data?: HeroImageDto } }) => (query.state.data?.processing ? 5000 : false), refetchIntervalInBackground: true, }); + +/** + * A new crop for an image, applied at once without saving the hero (Bryan, 2026-11-17): the server cuts the new variants + * in the background and the image switches to them when they are complete. The answer is the image, now processing. + */ +export function useSetHeroImageFocus() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: ({ imageId, request }) => api.put(`/api/v1/hero/images/${imageId}/focus`, request), + onSuccess: (image) => { + queryClient.setQueryData(['hero', 'image', image.id], image); + return queryClient.invalidateQueries({ queryKey: HERO_KEY }); + }, + }); +} diff --git a/frontend/src/features/hero/services/types.ts b/frontend/src/features/hero/services/types.ts index d032d6e..d573e04 100644 --- a/frontend/src/features/hero/services/types.ts +++ b/frontend/src/features/hero/services/types.ts @@ -80,7 +80,7 @@ export interface HeroSaveRequest { buttons: HeroButtonDto[]; slides: HeroSlideRequest[]; /** Changed focus points of images; they take effect with this save. */ - imageFocus: HeroImageFocusRequest[]; + imageFocus?: HeroImageFocusRequest[]; } export interface HeroImageFocusRequest extends HeroFocusRequest { diff --git a/frontend/src/features/media/components/BulkActionBar.tsx b/frontend/src/features/media/components/BulkActionBar.tsx index f58084d..96ab255 100644 --- a/frontend/src/features/media/components/BulkActionBar.tsx +++ b/frontend/src/features/media/components/BulkActionBar.tsx @@ -12,28 +12,24 @@ export interface BulkAction { run: () => void; } -interface BulkActionBarProps { +export interface BulkActionBarProps { count: number; actions: readonly BulkAction[]; onClear: () => void; - /** Extra text on the bar, for example the bytes the selection takes. */ + /** Extra text next to the count, 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. + * The actions on the selected photos: the count, a way to clear the selection and the actions. It sits in the header of + * the photo list (see PhotoSelectionList), which is the one shared place for it. 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 })} diff --git a/frontend/src/features/media/components/CleanupDialog.tsx b/frontend/src/features/media/components/CleanupDialog.tsx index 11851ee..6449d59 100644 --- a/frontend/src/features/media/components/CleanupDialog.tsx +++ b/frontend/src/features/media/components/CleanupDialog.tsx @@ -8,7 +8,6 @@ import { formatBytes } from '../lib/format'; import { selectAll, type Selection } from '../lib/selection'; import { toPhotoItem } from '../lib/toPhotoItem'; import { useCleanupPreview } from '../services/hooks'; -import { BulkActionBar } from './BulkActionBar'; import { DeleteDialog } from './DeleteDialog'; import { PhotoSelectionList } from './PhotoSelectionList'; @@ -100,12 +99,15 @@ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenCha

{t('media.cleanup.summary', { count: preview.data.count, size: formatBytes(preview.data.bytes, i18n.language) })}

- - setSelection(new Set())} - summary={t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) })} + setSelection(new Set()), + summary: t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) }), + }} />
+ + + ); + } + + return ( + <> + + {all ? t('media.purge.emptyTitle') : t('media.purge.title')} + + {all ? t('media.purge.confirmAll', { count, size: formatBytes(bytes, i18n.language) }) : t('media.purge.confirm', { count })} + + +

+ {t('media.purge.irreversible')} +

+ {purge.isError && ( +

+ {t('media.error')} +

+ )} + + + + + + ); +} diff --git a/frontend/src/features/media/mocks/handlers.ts b/frontend/src/features/media/mocks/handlers.ts index 8463631..f56cd28 100644 --- a/frontend/src/features/media/mocks/handlers.ts +++ b/frontend/src/features/media/mocks/handlers.ts @@ -68,7 +68,16 @@ export const mediaTrashHandlers = [ }), ]; +export const mediaPurgeHandlers = [ + http.post('*/media-library/purge', async ({ request }) => { + const body = (await request.json()) as { ids?: string[]; all?: boolean }; + const ids = body.all ? ['hero:all'] : (body.ids ?? []); + return HttpResponse.json({ results: ids.map((id) => ({ id, status: 'purged', uses: [] })) } satisfies MediaTrashResponse); + }), +]; + export const mediaHandlers = [ + ...mediaPurgeHandlers, ...mediaTrashHandlers, http.get('*/media-library/photos', () => HttpResponse.json({ photos: seedPhotos(), modules: ['hero'] } satisfies MediaLibraryDto)), http.get('*/media-library/storage', () => HttpResponse.json(seedStorage())), diff --git a/frontend/src/features/media/pages/MediaLibraryPage.tsx b/frontend/src/features/media/pages/MediaLibraryPage.tsx index a8ce2d8..1727c5f 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.tsx @@ -1,11 +1,11 @@ import { useMemo, useState, type ReactNode } from 'react'; import { Link } from '@tanstack/react-router'; import { useTranslation } from 'react-i18next'; -import { Eraser, RotateCcw, Trash2 } from 'lucide-react'; +import { Eraser, RotateCcw, Trash2, XCircle } from 'lucide-react'; import { Button } from '@/components/ui/button'; -import { BulkActionBar } from '../components/BulkActionBar'; import { CleanupDialog } from '../components/CleanupDialog'; import { DeleteDialog } from '../components/DeleteDialog'; +import { PurgeDialog } from '../components/PurgeDialog'; import { PhotoSelectionList, type PhotoUse } from '../components/PhotoSelectionList'; import { StorageMeter } from '../components/StorageMeter'; import { emptySelection, prune, type Selection } from '../lib/selection'; @@ -42,6 +42,7 @@ export function MediaLibraryPage() { const [chosen, setSelection] = useState(emptySelection); const [cleanupOpen, setCleanupOpen] = useState(false); const [deleting, setDeleting] = useState(false); + const [purging, setPurging] = useState<'selected' | 'all' | null>(null); const [filter, setFilter] = useState('all'); const source = view === 'library' ? photos : trash; @@ -55,6 +56,7 @@ export function MediaLibraryPage() { // Photos that left the list (after a reload or a move) drop out of the selection. const selection = useMemo(() => prune(chosen, items.map((i) => i.id)), [chosen, items]); const selectedItems = items.filter((item) => selection.has(item.id)); + const trashBytes = (trash.data?.photos ?? []).reduce((sum, p) => sum + p.bytes, 0); const switchView = (next: View) => { setView(next); @@ -72,6 +74,7 @@ export function MediaLibraryPage() { icon:
); diff --git a/frontend/src/features/media/services/hooks.ts b/frontend/src/features/media/services/hooks.ts index 92338d4..86a15a0 100644 --- a/frontend/src/features/media/services/hooks.ts +++ b/frontend/src/features/media/services/hooks.ts @@ -1,6 +1,6 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { api } from '@/lib/api-client'; -import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from './types'; +import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPurgeRequest, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from './types'; export const MEDIA_KEY = ['media-library']; @@ -57,3 +57,12 @@ export function useRestorePhotos() { onSuccess: () => queryClient.invalidateQueries({ queryKey: MEDIA_KEY }), }); } + +/** Removes photos from the trash for good (not reversible); `all` empties the whole trash. */ +export function usePurgePhotos() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (body) => api.post('/api/v1/media-library/purge', body), + onSuccess: () => queryClient.invalidateQueries({ queryKey: MEDIA_KEY }), + }); +} diff --git a/frontend/src/features/media/services/types.ts b/frontend/src/features/media/services/types.ts index 0934c2a..12b9177 100644 --- a/frontend/src/features/media/services/types.ts +++ b/frontend/src/features/media/services/types.ts @@ -45,7 +45,7 @@ export interface MediaCleanupPreviewDto { photos: MediaPhotoDto[]; } -export type MediaTrashStatus = 'trashed' | 'restored' | 'inUse' | 'notFound' | 'failed'; +export type MediaTrashStatus = 'trashed' | 'restored' | 'purged' | 'inUse' | 'notInTrash' | 'notFound' | 'failed'; export interface MediaTrashResultDto { id: string; @@ -62,3 +62,9 @@ export interface MediaTrashRequest { /** True when the person confirmed a second time, knowing where the photos in use are used. */ confirmedInUse: boolean; } + +export interface MediaPurgeRequest { + ids?: string[]; + /** Empty the whole trash (the server lists it and removes everything in batches). */ + all?: boolean; +} diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 7514f16..b4f2c11 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -849,7 +849,7 @@ "trash": { "since": "In the trash since {{date}}", "restore": "Restore", - "note": "Photos in the trash are removed for good after 7 days (default). Restore them while you can." + "note": "Photos in the trash are removed for good after 7 days (default). Restore them while you can, or delete them for good now." }, "delete": { "action": "Move to trash", @@ -873,6 +873,21 @@ "all": "All photos", "used": "Used", "unused": "Unused" + }, + "purge": { + "action": "Delete for good", + "title": "Delete for good", + "emptyTitle": "Empty the trash", + "emptyButton": "Empty the trash", + "emptyConfirm": "Empty the trash", + "confirmButton": "Delete for good", + "confirm_one": "This photo is deleted for good, with its files.", + "confirm_other": "These {{count}} photos are deleted for good, with their files.", + "confirmAll_one": "The trash is emptied: {{count}} photo ({{size}}) is deleted for good.", + "confirmAll_other": "The trash is emptied: {{count}} photos ({{size}}) are deleted for good.", + "irreversible": "This cannot be undone.", + "partial_one": "{{count}} photo could not be deleted. The rest was deleted for good.", + "partial_other": "{{count}} photos could not be deleted. The rest was deleted for good." } } } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index 29f047e..b278a09 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -849,7 +849,7 @@ "trash": { "since": "In de prullenbak sinds {{date}}", "restore": "Terugzetten", - "note": "Foto's in de prullenbak worden na 7 dagen definitief verwijderd (standaard). Zet ze terug zolang het kan." + "note": "Foto's in de prullenbak worden na 7 dagen definitief verwijderd (standaard). Zet ze terug zolang het kan, of verwijder ze nu definitief." }, "delete": { "action": "Naar prullenbak", @@ -873,6 +873,21 @@ "all": "Alle foto's", "used": "Gebruikt", "unused": "Ongebruikt" + }, + "purge": { + "action": "Definitief verwijderen", + "title": "Definitief verwijderen", + "emptyTitle": "Prullenbak legen", + "emptyButton": "Prullenbak legen", + "emptyConfirm": "Prullenbak legen", + "confirmButton": "Definitief verwijderen", + "confirm_one": "Deze foto wordt definitief verwijderd, met zijn bestanden.", + "confirm_other": "Deze {{count}} foto's worden definitief verwijderd, met hun bestanden.", + "confirmAll_one": "De prullenbak wordt geleegd: {{count}} foto ({{size}}) wordt definitief verwijderd.", + "confirmAll_other": "De prullenbak wordt geleegd: {{count}} foto's ({{size}}) worden definitief verwijderd.", + "irreversible": "Dit kan niet ongedaan worden gemaakt.", + "partial_one": "{{count}} foto kon niet worden verwijderd. De rest is definitief verwijderd.", + "partial_other": "{{count}} foto's konden niet worden verwijderd. De rest is definitief verwijderd." } } } diff --git a/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs index fc44359..161cf50 100644 --- a/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs +++ b/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs @@ -77,6 +77,25 @@ public class MediaLibraryControllerTests shorter.Count.Should().Be(2); } + [Fact] + public async Task Purge_names_the_ids_or_empties_the_whole_trash_and_refuses_an_empty_or_oversized_request() + { + var library = Substitute.For(); + library.PurgeAsync(Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(ci => ci.Arg>().Select(id => new MediaTrashResult(id, "purged", [])).ToList()); + library.PurgeAllAsync(Arg.Any(), Arg.Any()).Returns([new MediaTrashResult("hero:a", "purged", []), new MediaTrashResult("hero:b", "purged", [])]); + var controller = new MediaLibraryController(library, new Clock()); + + var some = (MediaTrashResponse)((OkObjectResult)await controller.Purge(new MediaPurgeRequest(["hero:x"]), CancellationToken.None)).Value!; + var all = (MediaTrashResponse)((OkObjectResult)await controller.Purge(new MediaPurgeRequest(null, All: true), CancellationToken.None)).Value!; + + some.Results.Should().ContainSingle().Which.Status.Should().Be("purged"); + all.Results.Should().HaveCount(2); + (await controller.Purge(new MediaPurgeRequest([]), CancellationToken.None)).Should().BeOfType(); + (await controller.Purge(new MediaPurgeRequest(null), CancellationToken.None)).Should().BeOfType(); + (await controller.Purge(new MediaPurgeRequest(Enumerable.Range(0, 101).Select(i => $"hero:{i}").ToList()), CancellationToken.None)).Should().BeOfType(); + } + [Fact] public async Task Storage_without_a_media_store_reports_zero_and_ok() { diff --git a/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs index 3353bce..09b416c 100644 --- a/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs +++ b/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs @@ -159,10 +159,73 @@ public class MediaLibraryTests CleanupSelection.Select([item], Now, 7, onlyUnused: false).Should().ContainSingle(); } + [Fact] + public async Task Purge_reports_per_photo_and_only_removes_what_the_module_accepts() + { + var inTrash = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now); + var notTrashed = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null); + var used = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now); + var broken = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now); + var provider = new FakeProvider("hero", [notTrashed], [], trash: [inTrash, used, broken]) { InUsePurge = used.Id, FailFor = broken.Id }; + var library = new MediaLibraryService([provider]); + + var results = await library.PurgeAsync([$"hero:{inTrash.Id}", $"hero:{notTrashed.Id}", $"hero:{used.Id}", $"hero:{broken.Id}", "nope", $"gallery:{Guid.NewGuid()}"], Guid.Empty, CancellationToken.None); + + results.Select(r => r.Status).Should().Equal("purged", "notInTrash", "inUse", "failed", "notFound", "notFound"); + provider.Purged.Should().Equal(inTrash.Id); + } + + [Fact] + public async Task Purge_all_empties_the_whole_trash_in_batches_of_100() + { + var trash = Enumerable.Range(0, 250).Select(_ => new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now)).ToArray(); + var provider = new FakeProvider("hero", [], [], trash: trash); + var library = new MediaLibraryService([provider]); + + var results = await library.PurgeAllAsync(Guid.Empty, CancellationToken.None); + + results.Should().HaveCount(250).And.OnlyContain(r => r.Status == "purged"); + provider.Purged.Should().HaveCount(250); + } + + [Fact] + public async Task Purge_accepts_at_most_100_photos_in_one_request() + { + var library = new MediaLibraryService([new FakeProvider("hero", [], [])]); + var tooMany = Enumerable.Range(0, 101).Select(_ => $"hero:{Guid.NewGuid()}").ToList(); + + await FluentActions.Awaiting(() => library.PurgeAsync(tooMany, Guid.Empty, CancellationToken.None)).Should().ThrowAsync(); + } + private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses, MediaPhoto[]? trash = null) : IMediaUsageProvider { public string Module => module; + public List Purged { get; } = []; + + public Guid? InUsePurge { get; init; } + + public Task PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken) + { + if (photoId == FailFor) + { + throw new InvalidOperationException("boom"); + } + + if (photoId == InUsePurge) + { + return Task.FromResult(MediaPurgeOutcome.InUse); + } + + if (trash?.Any(p => p.Id == photoId) != true) + { + return Task.FromResult(MediaPurgeOutcome.NotInTrash); + } + + Purged.Add(photoId); + return Task.FromResult(MediaPurgeOutcome.Purged); + } + public List Trashed { get; } = []; public Guid? FailFor { get; init; } diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs index 491b58b..6b01c28 100644 --- a/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs @@ -33,6 +33,10 @@ public sealed record MediaTrashRequest(IReadOnlyList Ids, bool Confirmed public sealed record MediaRestoreRequest(IReadOnlyList Ids); +/// Photos in the trash to remove for good (at most 100). Ignored when is true. +/// Remove everything that is in the trash (the trash is emptied, in batches on the server). +public sealed record MediaPurgeRequest(IReadOnlyList? Ids = null, bool All = false); + public sealed record MediaUseResultDto(string Id, string Status, IReadOnlyList Uses); public sealed record MediaTrashResponse(IReadOnlyList Results); @@ -110,12 +114,34 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t return Ok(new MediaTrashResponse(results.Select(ToDto).ToList())); } + /// Removes photos from the trash for good: not reversible. Only photos in the trash that are used nowhere. + [HttpPost("purge")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Purge([FromBody] MediaPurgeRequest request, CancellationToken cancellationToken) + { + if (request.All) + { + var all = await library.PurgeAllAsync(CallerId(), cancellationToken); + return Ok(new MediaTrashResponse(all.Select(ToDto).ToList())); + } + + if (!ValidIds(request.Ids)) + { + return BadRequest(); + } + + var results = await library.PurgeAsync(request.Ids!, CallerId(), cancellationToken); + return Ok(new MediaTrashResponse(results.Select(ToDto).ToList())); + } + private static bool ValidIds(IReadOnlyList? ids) => ids is { Count: > 0 and <= MediaLibraryService.MaxIdsPerRequest } && ids.All(id => !string.IsNullOrWhiteSpace(id) && id.Length <= 80); private Guid CallerId() { - var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"); + var user = HttpContext?.User; + var claim = user?.FindFirstValue(ClaimTypes.NameIdentifier) ?? user?.FindFirstValue("sub"); return Guid.TryParse(claim, out var id) ? id : Guid.Empty; } diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs index 0938646..7b446c9 100644 --- a/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs @@ -27,6 +27,15 @@ public interface IMediaLibraryService Task> TrashAsync(IReadOnlyCollection ids, bool confirmedInUse, Guid callerId, CancellationToken cancellationToken); Task> RestoreAsync(IReadOnlyCollection ids, Guid callerId, CancellationToken cancellationToken); + + /// + /// Removes photos from the trash for good. Each photo is checked again by its module: only a photo that is in the trash + /// and used nowhere is removed (statuses purged, notInTrash, inUse, notFound, failed). + /// + Task> PurgeAsync(IReadOnlyCollection ids, Guid callerId, CancellationToken cancellationToken); + + /// Removes everything that is in the trash for good, in batches of . + Task> PurgeAllAsync(Guid callerId, CancellationToken cancellationToken); } public sealed class MediaLibraryService(IEnumerable providers, ILogger? logger = null) : IMediaLibraryService @@ -129,6 +138,55 @@ public sealed class MediaLibraryService(IEnumerable provide return results; } + public async Task> PurgeAsync(IReadOnlyCollection ids, Guid callerId, CancellationToken cancellationToken) + { + EnsureWithinLimit(ids); + var results = new List(); + foreach (var id in ids.Distinct(StringComparer.Ordinal)) + { + if (!TryResolve(id, out var provider, out var photoId)) + { + results.Add(new MediaTrashResult(id, "notFound", [])); + continue; + } + + try + { + var outcome = await provider.PurgeAsync(photoId, callerId, cancellationToken); + var status = outcome switch + { + MediaPurgeOutcome.Purged => "purged", + MediaPurgeOutcome.InUse => "inUse", + _ => "notInTrash", + }; + results.Add(new MediaTrashResult(id, status, [])); + if (outcome == MediaPurgeOutcome.Purged) + { + logger?.LogInformation("Media {Photo} removed for good by user {UserId}", id, callerId); + } + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger?.LogWarning(exception, "Removing media {Photo} for good failed", id); + results.Add(new MediaTrashResult(id, "failed", [])); + } + } + + return results; + } + + public async Task> PurgeAllAsync(Guid callerId, CancellationToken cancellationToken) + { + var ids = (await ListTrashAsync(cancellationToken)).Select(i => $"{i.Photo.Module}:{i.Photo.Id}").ToList(); + var results = new List(); + foreach (var batch in ids.Chunk(MaxIdsPerRequest)) + { + results.AddRange(await PurgeAsync(batch, callerId, cancellationToken)); + } + + return results; + } + private static void EnsureWithinLimit(IReadOnlyCollection ids) { if (ids.Count > MaxIdsPerRequest) diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs index 6d303c2..fcdbb0c 100644 --- a/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs @@ -56,4 +56,23 @@ public interface IMediaUsageProvider /// Takes a photo out of the trash. False when it is not in the trash. Task RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken); + + /// + /// Removes a photo FOR GOOD: its original and its cut sets (a set another photo still shares stays). Only a photo that is + /// in the trash and used nowhere; the module checks this again itself. + /// + Task PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken); +} + +/// What happened to a photo that was to be removed for good. +public enum MediaPurgeOutcome +{ + /// Removed: the files and the record are gone. + Purged, + + /// There is no such photo in the trash (not trashed, or already gone). Nothing was changed. + NotInTrash, + + /// The photo is used somewhere after all. Nothing was changed. + InUse, } diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs index 6d38ce1..3d005d3 100644 --- a/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs @@ -170,6 +170,81 @@ public class HeroMediaUsageProviderTests (await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().UnusedSince.Should().Be(rig.Time.Now); } + [Fact] + public async Task Purging_removes_a_photo_in_the_trash_for_good_with_its_original_and_set() + { + using var rig = new HeroTestRig(); + var a = await rig.Upload(HeroTestRig.Photo(seed: 1)); + var keep = await rig.Upload(HeroTestRig.Photo(seed: 2)); + var rowA = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(a.Id)); + var (set, original) = (rowA.SetHash, rowA.OriginalKey); + var keepRow = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(keep.Id)); + var provider = Provider(rig); + await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None); + + var outcome = await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None); + + outcome.Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.Purged); + rig.Db.HeroImages.Select(i => i.Id).Should().Equal(Guid.Parse(keep.Id)); + (await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().NotContain(s => s.SetHash == set).And.Contain(s => s.SetHash == keepRow.SetHash); + (await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse(); + (await rig.Store.ExistsAsync(keepRow.OriginalKey, CancellationToken.None)).Should().BeTrue(); + } + + [Fact] + public async Task Purging_refuses_a_photo_that_is_not_in_the_trash_and_changes_nothing() + { + using var rig = new HeroTestRig(); + var a = await rig.Upload(HeroTestRig.Photo()); + var original = rig.Db.HeroImages.Single().OriginalKey; + var provider = Provider(rig); + + (await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.NotInTrash); + (await provider.PurgeAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.NotInTrash); + + rig.Db.HeroImages.Should().HaveCount(1); + (await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeTrue(); + } + + [Fact] + public async Task Purging_refuses_a_photo_that_a_slide_uses_after_all() + { + using var rig = new HeroTestRig(); + var a = await rig.Upload(HeroTestRig.Photo()); + await rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "foto")), HeroTestRig.Admin, CancellationToken.None); + var provider = Provider(rig); + await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None); + // A slide that still points at the trashed photo (a race or an old row): the purge must notice. + var hero = rig.Db.Heroes.Single(); + rig.Db.HeroSlides.Add(new Data.Entities.HeroSlide { Id = Guid.NewGuid(), HeroId = hero.Id, ImageId = Guid.Parse(a.Id), Alt = "x", SortOrder = 9 }); + await rig.Db.SaveChangesAsync(); + + (await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.InUse); + + rig.Db.HeroImages.Should().HaveCount(1); + } + + [Fact] + public async Task Purging_leaves_a_file_another_photo_still_shares() + { + using var rig = new HeroTestRig(); + var a = await rig.Upload(HeroTestRig.Photo(seed: 1)); + var b = await rig.Upload(HeroTestRig.Photo(seed: 2)); + var rowA = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(a.Id)); + var rowB = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(b.Id)); + // Two records that point at the same files (not created by the hero itself, but possible after a restore). + rowB.SetHash = rowA.SetHash; + rowB.OriginalKey = rowA.OriginalKey; + await rig.Db.SaveChangesAsync(); + var provider = Provider(rig); + await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None); + + (await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.Purged); + + (await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().Contain(s => s.SetHash == rowB.SetHash); + (await rig.Store.ExistsAsync(rowB.OriginalKey, CancellationToken.None)).Should().BeTrue(); + } + [Fact] public async Task A_trashed_photo_is_emptied_from_the_trash_after_the_trash_period_and_its_files_go() { diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroSetFocusTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroSetFocusTests.cs new file mode 100644 index 0000000..7e7554c --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroSetFocusTests.cs @@ -0,0 +1,45 @@ +using FluentAssertions; +using SlpModularCms.Modules.Hero.Models; +using SlpModularCms.Modules.Hero.Services; +using Xunit; + +namespace SlpModularCms.Modules.Hero.Tests; + +/// A new crop works at once, without saving the hero (Bryan, 2026-11-17). +public class HeroSetFocusTests +{ + [Fact] + public async Task A_new_crop_starts_processing_at_once_and_goes_live_without_saving_the_hero() + { + using var rig = new HeroTestRig(); + var uploaded = await rig.Upload(HeroTestRig.Photo()); + var id = Guid.Parse(uploaded.Id); + var before = rig.Db.HeroImages.Single(i => i.Id == id).SetHash; + + var answer = await rig.Images.SetFocusAsync(id, new HeroFocusRequest(new FocusDto(0.2, 0.3, 1.5)), HeroTestRig.Admin, CancellationToken.None); + + answer.Should().NotBeNull(); + answer!.Processing.Should().BeTrue("the new variants still have to be cut"); + answer.Focus.Should().Be(new FocusDto(0.2, 0.3, 1.5)); + rig.Db.HeroImages.Single(i => i.Id == id).SetHash.Should().Be(before, "the old set stays live until the new one is complete"); + + (await rig.RenderPending()).Should().Be(1); + + var after = (await rig.Images.GetImageAsync(id, CancellationToken.None))!; + after.Processing.Should().BeFalse(); + rig.Db.HeroImages.Single(i => i.Id == id).SetHash.Should().NotBe(before); + rig.Db.Heroes.Should().BeEmpty("the hero itself was never saved"); + } + + [Fact] + public async Task An_unknown_image_gives_null_and_a_trashed_image_cannot_be_cropped() + { + using var rig = new HeroTestRig(); + var uploaded = await rig.Upload(HeroTestRig.Photo()); + await new HeroMediaUsageProvider(rig.Repository, rig.Images).TrashAsync(Guid.Parse(uploaded.Id), HeroTestRig.Admin, CancellationToken.None); + var request = new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)); + + (await rig.Images.SetFocusAsync(Guid.NewGuid(), request, HeroTestRig.Admin, CancellationToken.None)).Should().BeNull(); + (await rig.Images.SetFocusAsync(Guid.Parse(uploaded.Id), request, HeroTestRig.Admin, CancellationToken.None)).Should().BeNull(); + } +} diff --git a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs index 9c727e2..e1d05f9 100644 --- a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs +++ b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs @@ -105,6 +105,20 @@ public class HeroImagesController(IHeroImageService service, IOptions + /// A new crop for an image, applied at once without saving the hero: the new variants are cut in the background and the + /// image switches to them when they are complete. Answers with the image (processing). + /// + [HttpPut("{id:guid}/focus")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task SetFocus(Guid id, [FromBody] HeroFocusRequest request, CancellationToken cancellationToken) + { + var image = await service.SetFocusAsync(id, request, HeroCaller.Id(User), cancellationToken); + return image is null ? NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) }) : Ok(image); + } + /// The formats and limits an upload has to meet on this host (what the validation uses). [HttpGet("limits")] [ProducesResponseType(StatusCodes.Status200OK)] diff --git a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs index edec1d5..9aa01c1 100644 --- a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs +++ b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs @@ -34,6 +34,9 @@ public interface IHeroRepository /// Photos that were trashed before the cutoff, tracked (the trash is emptied for them). Task> GetTrashedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken); + /// True when an image other than the given one has this set hash or this original key (the files are shared). + Task<(bool SetShared, bool OriginalShared)> FilesSharedWithOthersAsync(Guid imageId, string setHash, string originalKey, CancellationToken cancellationToken); + /// The slides that use an image, tracked (they are removed when the image goes to the trash). Task> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken); @@ -99,6 +102,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository public async Task> GetTrashedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken) => (await context.HeroImages.Where(i => i.DeletedAt != null).ToListAsync(cancellationToken)).Where(i => i.DeletedAt < cutoff).ToList(); + public async Task<(bool SetShared, bool OriginalShared)> FilesSharedWithOthersAsync(Guid imageId, string setHash, string originalKey, CancellationToken cancellationToken) + { + var others = (await context.HeroImages.AsNoTracking().ToListAsync(cancellationToken)).Where(i => i.Id != imageId).ToList(); + return (setHash.Length > 0 && others.Any(i => i.SetHash == setHash), others.Any(i => i.OriginalKey == originalKey)); + } + public async Task> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken) => await context.HeroSlides.Where(s => s.ImageId == imageId).ToListAsync(cancellationToken); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs index 3759993..80eca6d 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SlpModularCms.Core.Hosting.Website; using SlpModularCms.Core.Media; +using SlpModularCms.Core.Media.Library; using SlpModularCms.Modules.Hero.Data.Entities; using SlpModularCms.Modules.Hero.Models; using SlpModularCms.Modules.Hero.Repositories; @@ -46,6 +47,13 @@ public interface IHeroImageService /// The variant the renderer is busy with: (done, total), or null when the image is not being cut right now. (int Done, int Total)? RenderProgress(Guid imageId); + /// + /// Applies a new crop to an image at once, WITHOUT saving the hero (Bryan, 2026-11-17: a new crop must not need another + /// click on Save). The new set is cut in the background and the image switches to it when it is complete, so what is live + /// changes only then. Returns the image as the admin sees it now (processing), or null when there is no such image. + /// + Task SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken); + /// One image as the admin sees it now (including whether it is still being prepared). Null when there is no such image. Task GetImageAsync(Guid imageId, CancellationToken cancellationToken); @@ -77,6 +85,12 @@ public interface IHeroImageService /// Takes an image out of the trash again. False when it is not in the trash. Task RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); + + /// + /// Removes an image that is in the trash FOR GOOD: its original and its set (a file another image shares stays) and the + /// record. Refused when the image is not in the trash or a slide uses it after all. + /// + Task PurgeAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); } public class HeroImageService( @@ -188,6 +202,23 @@ public class HeroImageService( public void NotifyPending() => signal?.Notify(); + public async Task SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken) + { + var image = await repository.GetImageAsync(imageId, cancellationToken); + if (image is null) + { + return null; + } + + ApplyFocus(image, request); + await repository.SaveChangesAsync(cancellationToken); + signal?.Reset(imageId); + signal?.Notify(); + + logger.LogInformation("Hero image {ImageId} got a new crop from user {UserId}; its variants are cut in the background", imageId, callerId); + return await GetImageAsync(imageId, cancellationToken); + } + public async Task GetImageAsync(Guid imageId, CancellationToken cancellationToken) { var image = await repository.GetImageFreshAsync(imageId, cancellationToken); @@ -369,6 +400,40 @@ public class HeroImageService( return slides.Count; } + public async Task PurgeAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken) + { + var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken); + if (image is null || image.DeletedAt is null) + { + return MediaPurgeOutcome.NotInTrash; + } + + if (await repository.ImageInUseAsync(imageId, cancellationToken)) + { + return MediaPurgeOutcome.InUse; + } + + // The row first (nothing refers to it any more), then the files; a file another image still shares stays. + var (setShared, originalShared) = await repository.FilesSharedWithOthersAsync(imageId, image.SetHash, image.OriginalKey, cancellationToken); + var (setHash, originalKey) = (image.SetHash, image.OriginalKey); + repository.RemoveImage(image); + await repository.SaveChangesAsync(cancellationToken); + + if (setHash.Length > 0 && !setShared) + { + await store.DeleteSetAsync(HeroMapping.Area, setHash, cancellationToken); + } + + if (!originalShared) + { + await store.DeleteAsync(originalKey, cancellationToken); + } + + indexCache?.Invalidate(); + logger.LogInformation("Hero image {ImageId} removed for good by user {UserId}", imageId, callerId); + return MediaPurgeOutcome.Purged; + } + public async Task RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken) { var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs index 5c088e2..86f96de 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs @@ -59,6 +59,9 @@ public class HeroMediaUsageProvider(IHeroRepository repository, IHeroImageServic public Task RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken) => images.RestoreAsync(photoId, callerId, cancellationToken); + public Task PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken) + => images.PurgeAsync(photoId, callerId, cancellationToken); + private MediaPhoto ToPhoto(HeroImage i) => new(Module, i.Id, i.Bytes, i.Width, i.Height, i.CreatedAt, Thumbnail(i), i.OriginalFileName, i.LastUsedAt, i.DeletedAt); -- 2.39.5 From e09304c2e9213581fae9fe56a3f6a0f3d351a650 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 17:05:34 +0100 Subject: [PATCH 14/22] Mediabibliotheek en Hero: definitief verwijderen en prullenbak legen, kiezen uit bibliotheek per slide, uitsnede direct zonder opslaan, teller per batch; aannamelijst Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 4 + .../assumptions-and-open-questions.md | 3 + .../hero/components/LibraryPickerDialog.tsx | 70 ++++++ .../src/features/hero/pages/HeroPage.test.tsx | 84 ++++++- frontend/src/features/hero/pages/HeroPage.tsx | 34 ++- .../media/pages/MediaLibraryPage.test.tsx | 73 ++++++ frontend/src/features/media/services/hooks.ts | 3 +- frontend/src/i18n/locales/en/translation.json | 6 + frontend/src/i18n/locales/nl/translation.json | 6 + openapi/slpsoftware.v1.json | 218 ++++++++++++++++++ 10 files changed, 498 insertions(+), 3 deletions(-) create mode 100644 frontend/src/features/hero/components/LibraryPickerDialog.tsx diff --git a/aidlc-docs/features/hero-module/assumptions-and-open-questions.md b/aidlc-docs/features/hero-module/assumptions-and-open-questions.md index b67b3c4..0c84186 100644 --- a/aidlc-docs/features/hero-module/assumptions-and-open-questions.md +++ b/aidlc-docs/features/hero-module/assumptions-and-open-questions.md @@ -46,3 +46,7 @@ Kept while Bryan was away (2026-11-16): no questions to him, a likely assumption | 20 | ASF production hosting (write access, back-up) | Unchanged: Bryan tests with ASF later. | Open. | | HEIC | iPhone HEIC upload | Still to be tested by Bryan with a real iPhone file (the build cannot write HEIC; only the library self-test ran). | Open. | | other | Assumptions 2, 3, 6, 7, 9, 14, 17, 18, 20, 22 to 30 | Stay as documented. | None. | + +## Change of 2026-11-17: a new crop applies at once + +Assumption 1 above (a changed focus only takes effect when the hero is saved) is **replaced by Bryan's later wish**: a new crop must not need another click on Save. The focus dialog now sends the crop at once and the new variants are cut in the background; see assumption 38 of `features/media-library/assumptions-and-open-questions.md`. 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 9b94c85..6e7280c 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -64,3 +64,6 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 33 | **Where the copy runs and what it copies** (built 2026-11-17). | A new module `Modules.Media` owns the tables (`MediaAssets`, `MediaUses`); modules offer their data through `IMediaMigrationSource` so the library module does not depend on the Hero. The copy is a verified mirror in one transaction behind `Media:Library:CopyOnStartup` (default false). The use of a hero slide carries both crops (`wide`, `tall`) of its photo as JSON; its set hash is the photo's current set hash. | A copy job triggered from the admin instead of start-up: easier to time, needs an endpoint and a button. | `Modules.Media/Services/MediaLibraryCopier.cs`, `HeroMediaMigrationSource` | | 34 | **Naming**: entity `MediaAssetUse` (table `MediaUses`), because `MediaUse` already names the read model in Core. | As built. | Rename the table or the record: a small migration. | `Modules.Media/Data` | | 35 | **Test deploy without a separate database dump** (decided on assumption by SLS-Main, 2026-11-17, Bryan away). | The Raspberry Pi test host cannot be dumped by SLS-Main; the test data can be rebuilt with the seed scripts and both database changes of the branch (`AddMediaLibraryColumns`, the empty Media tables) are additive, so the test deploy goes ahead without a dump. The copy stays OFF until Bryan agrees. | Take a dump on the Pi before the deploy (and certainly before the copy is switched on). | `migration-plan.md`, section "Test host" | +| 36 | **Choose from the library in a hero slide** (built 2026-11-17 at Bryan's request, before the migration). | Each slide has "Choose from library" next to its photo: the shared `ImagePicker` lists the library photos of the modules that can be chosen (now the hero's own photos, also those in no slide, never the trash) and a new photo can be uploaded on the spot with the hero's own upload (same checks, limits and background processing). Choosing only sets the slide's existing image id (no data model change). A photo that is already in another slide can be chosen again: it is the same photo, so its **crop is shared by the slides that use it** (the crop belongs to the photo in the hero today; a crop per slide comes with the library's own use records). | A separate crop per slide now would need the use records of phase 2 (or a copy of the photo). | `features/hero/components/LibraryPickerDialog.tsx`, `HeroPage.tsx` | +| 37 | **Removing from the trash for good** (Bryan, 2026-11-17). | `POST media-library/purge {ids}` (at most 100) or `{all:true}` (the server empties the whole trash in batches). Only photos that are in the trash and used nowhere are removed; the module checks it again and answers per photo (`purged`, `notInTrash`, `inUse`, `failed`). The original and the cut set go through `IMediaStore`; a file another photo still shares stays. The UI asks a clear confirmation that says it cannot be undone and names the number (and the size for the whole trash); "Empty the trash" is disabled when the trash is empty. No separate waiting period. | A short undo window for a purge: not built (the trash itself is the undo). | `MediaLibraryService.PurgeAsync`, `HeroImageService.PurgeAsync`, `PurgeDialog` | +| 38 | **A new crop applies at once, without saving the hero** (Bryan, 2026-11-17; replaces Hero assumption 1 of 2026-11-16, which said a focus change only takes effect when the hero is saved). | The focus dialog's Apply sends the crop at once (`PUT hero/images/{id}/focus`); the server cuts the new variants in the background and the photo switches to them when they are complete, so what is live changes only then, without another Save. The photo shows "Wordt verwerkt…", a 0-100% bar and the percentage on itself (no spinner); the upload keeps its own display. The counter "x of y processed" counts the current upload batch only. | Back to applying only on Save: restore the focus edits kept locally in `HeroPage`. | `HeroImageService.SetFocusAsync`, `HeroPage.applyFocus`, `RecutThumbnail` | diff --git a/frontend/src/features/hero/components/LibraryPickerDialog.tsx b/frontend/src/features/hero/components/LibraryPickerDialog.tsx new file mode 100644 index 0000000..ec13359 --- /dev/null +++ b/frontend/src/features/hero/components/LibraryPickerDialog.tsx @@ -0,0 +1,70 @@ +import { useTranslation } from 'react-i18next'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { ImagePicker } from '@/features/media/components/ImagePicker'; +import type { PhotoItem } from '@/features/media/components/PhotoSelectionList'; +import { toPhotoItem } from '@/features/media/lib/toPhotoItem'; +import { useMediaPhotos } from '@/features/media/services/hooks'; +import { useUploadHeroImage } from '../services/hooks'; +import type { HeroImageDto } from '../services/types'; + +interface LibraryPickerDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + /** The hero image the slide has now (a library id is `hero:` plus this). */ + currentImageId: string | null; + /** Which photo was chosen (the hero image id) and, for a photo uploaded here, the image the server answered with. */ + onChoose: (imageId: string, uploaded?: HeroImageDto) => void; + maxUploadBytes: number; + limitsText?: string; + slideNumber: number; +} + +const MODULE = 'hero'; + +/** + * "Choose from the library" for a slide: the photos of the media library that a hero slide can use (now the hero's own + * photos, also those that are in no slide; never the trash), or a new photo uploaded on the spot with the hero's own upload + * (same checks and limits, variants cut in the background). A photo that is already in another slide can be chosen again: + * it is the same photo, so its crop is shared (assumption 36). + */ +export function LibraryPickerDialog({ open, onOpenChange, currentImageId, onChoose, maxUploadBytes, limitsText, slideNumber }: LibraryPickerDialogProps) { + const { t } = useTranslation(); + const library = useMediaPhotos(open); + const upload = useUploadHeroImage(); + const items = (library.data?.photos ?? []).filter((p) => p.module === MODULE).map((p) => toPhotoItem(p, t)); + + const uploadHere = async (file: File): Promise => { + const image = await upload.mutateAsync(file); + onChoose(image.id, image); + return { id: `${MODULE}:${image.id}`, name: file.name, bytes: file.size, createdAt: new Date().toISOString(), uses: [], thumbnailUrl: null }; + }; + + return ( + + + + {t('hero.library.title', { n: slideNumber })} + {t('hero.library.description')} + + {library.isError && ( +

+ {t('media.error')} +

+ )} + {library.isPending ? ( +

{t('media.loading')}

+ ) : ( + onChoose(id.slice(MODULE.length + 1))} + onUpload={uploadHere} + maxUploadBytes={maxUploadBytes} + limitsText={limitsText} + label={t('hero.library.group', { n: slideNumber })} + /> + )} +
+
+ ); +} diff --git a/frontend/src/features/hero/pages/HeroPage.test.tsx b/frontend/src/features/hero/pages/HeroPage.test.tsx index 7a76294..907bcab 100644 --- a/frontend/src/features/hero/pages/HeroPage.test.tsx +++ b/frontend/src/features/hero/pages/HeroPage.test.tsx @@ -761,7 +761,7 @@ describe('A changed focus point makes a new crop in the background', () => { await openPage(); - const recut = await screen.findByTestId('hero-slide-0-recut', {}, T); + await screen.findByTestId('hero-slide-0-recut', {}, T); expect(screen.getByTestId('hero-slide-0-recut-bar')).toHaveAttribute('aria-valuenow', '25'); expect(screen.getByTestId('hero-slide-0-recut-percent')).toHaveTextContent('25%'); }); @@ -1217,3 +1217,85 @@ describe('Tabs Content and Images', () => { expect(screen.getByTestId('hero-form').className).not.toMatch(/pb-/); }); }); + + +describe('Choose a photo from the library for a slide', () => { + beforeEach(() => { + resetMockHero(); + }); + + const libraryPhoto = (n: number, over: Record = {}) => ({ + id: `hero:10000000-0000-0000-0000-00000000000${n}`, + module: 'hero', + bytes: 1000, + width: 1600, + height: 1067, + createdAt: '2026-11-1' + n + 'T10:00:00Z', + thumbnailUrl: `/media/hero/0123456789abcdef/wide-480.webp`, + uses: [], + originalFileName: `foto-${n}.jpg`, + unusedSince: null, + deletedAt: null, + ...over, + }); + + it('lists the library photos (also those in no slide, never the trash) and puts the chosen one in the slide, ready to save', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] }); + server.use( + http.get('*/media-library/photos', () => + HttpResponse.json({ photos: [libraryPhoto(3), libraryPhoto(2), libraryPhoto(1, { uses: [{ module: 'hero', kind: 'slide', position: 1, active: true }] }), libraryPhoto(9, { module: 'gallery', id: 'gallery:x' })], modules: ['hero'] }), + ), + http.get(`${API_BASE}/api/v1/hero/images/10000000-0000-0000-0000-000000000002`, () => HttpResponse.json(slide(2).image)), + ); + await openPage(); + await userEvent.click(screen.getByTestId('hero-slide-0-library')); + + const dialog = await screen.findByTestId('library-picker', {}, T); + const radios = await within(dialog).findAllByRole('radio'); + expect(radios.map((r) => r.getAttribute('aria-label'))).toEqual(['foto-3.jpg', 'foto-2.jpg', 'foto-1.jpg']); + expect(within(dialog).getByRole('radio', { name: 'foto-1.jpg' })).toBeChecked(); + expect(within(dialog).getByTestId('picker-upload-button')).toBeInTheDocument(); + + await userEvent.click(within(dialog).getByRole('radio', { name: 'foto-2.jpg' })); + + await waitFor(() => expect(screen.queryByTestId('library-picker')).not.toBeInTheDocument()); + await waitFor(() => expect(screen.getByTestId('hero-save')).toBeEnabled()); + await userEvent.click(screen.getByTestId('hero-save')); + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + expect(getSavedHeroRequests()[0].slides[0].imageId).toBe('10000000-0000-0000-0000-000000000002'); + }); + + it('lets a photo that is already in another slide be chosen again (same photo, separate slide)', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] }); + server.use( + http.get('*/media-library/photos', () => HttpResponse.json({ photos: [libraryPhoto(2, { uses: [{ module: 'hero', kind: 'slide', position: 2, active: true }] }), libraryPhoto(1)], modules: ['hero'] })), + ); + await openPage(); + await userEvent.click(screen.getByTestId('hero-slide-0-library')); + const dialog = await screen.findByTestId('library-picker', {}, T); + + await userEvent.click(await within(dialog).findByRole('radio', { name: 'foto-2.jpg' })); + + await waitFor(() => expect(screen.queryByTestId('library-picker')).not.toBeInTheDocument()); + await userEvent.click(screen.getByTestId('hero-save')); + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + expect(getSavedHeroRequests()[0].slides.map((x) => x.imageId)).toEqual(['10000000-0000-0000-0000-000000000002', '10000000-0000-0000-0000-000000000002']); + }); + + it('uploads a new photo on the spot with the hero upload and puts it in the slide', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] }); + server.use(http.get('*/media-library/photos', () => HttpResponse.json({ photos: [], modules: ['hero'] }))); + await openPage(); + await userEvent.click(screen.getByTestId('hero-slide-0-library')); + const dialog = await screen.findByTestId('library-picker', {}, T); + expect(await within(dialog).findByTestId('picker-empty')).toBeInTheDocument(); + + await userEvent.upload(within(dialog).getByTestId('picker-file'), new File([new Uint8Array(100)], 'nieuw.jpg', { type: 'image/jpeg' })); + + await waitFor(() => expect(screen.queryByTestId('library-picker')).not.toBeInTheDocument()); + await waitFor(() => expect(screen.getByTestId('hero-save')).toBeEnabled()); + await userEvent.click(screen.getByTestId('hero-save')); + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + expect(getSavedHeroRequests()[0].slides[0].imageId).not.toBe('10000000-0000-0000-0000-000000000001'); + }); +}); diff --git a/frontend/src/features/hero/pages/HeroPage.tsx b/frontend/src/features/hero/pages/HeroPage.tsx index 5ff0716..976d572 100644 --- a/frontend/src/features/hero/pages/HeroPage.tsx +++ b/frontend/src/features/hero/pages/HeroPage.tsx @@ -1,5 +1,5 @@ import { useEffect, useMemo, useRef, useState } from 'react'; -import { useQueries } from '@tanstack/react-query'; +import { useQueries, useQueryClient } from '@tanstack/react-query'; import { useFieldArray, useForm, useWatch } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { useTranslation } from 'react-i18next'; @@ -17,6 +17,7 @@ import { FieldError } from '@/components/ui/FieldError'; import { FormErrorBanner } from '@/components/ui/FormErrorBanner'; import { NetworkError, ProblemDetailsError } from '@/lib/api-client'; import { FocusDialog } from '../components/FocusDialog'; +import { LibraryPickerDialog } from '../components/LibraryPickerDialog'; import { CropThumbnail } from '../components/CropThumbnail'; import { DoneStatus, PhotoPlaceholder, ProcessingStatus, RecutThumbnail, Spinner } from '../components/ProcessingStatus'; import { SlideSwitch } from '../components/SlideSwitch'; @@ -153,6 +154,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { // every photo of the hero. A new batch starts when the previous one is finished. const [batch, setBatch] = useState([]); const [recutIds, setRecutIds] = useState([]); + // The slide (by position) whose photo is being chosen from the library. + const [libraryFor, setLibraryFor] = useState(null); const fileInput = useRef(null); const { @@ -268,6 +271,23 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { return () => window.removeEventListener('beforeunload', warn); }, [hasUnsaved]); + // A photo chosen from the library (or uploaded in the picker) becomes the photo of that slide: only the image id of the + // slide changes (no new data model). The photo is the same photo wherever it is used, so its crop is shared. + const queryClient = useQueryClient(); + const chooseForSlide = async (index: number, imageId: string, uploaded?: HeroImageDto) => { + const current = watchedSlides[index]; + if (!current) return; + try { + const image: HeroImageDto = uploaded ?? ((await queryClient.fetchQuery(heroImageQuery(imageId))) as HeroImageDto); + setLocalImages((cur) => ({ ...cur, [image.id]: image })); + if (uploaded && image.processing) setBatch((cur) => (cur.some((id) => images[id]?.processing) ? [...cur, image.id] : [image.id])); + if (image.id !== current.imageId) slides.update(index, { ...current, imageId: image.id }); + setLibraryFor(null); + } catch (error) { + setServerError(serverMessage(error, t('errors.generic'), t('errors.network'))); + } + }; + // A new crop goes to the server at once; the page then shows the photo as processing until the new variants are ready. const applyFocus = (imageId: string, request: HeroFocusRequest) => { setServerError(null); @@ -551,6 +571,9 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
?
)} +

@@ -632,6 +655,15 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {

+ !open && setLibraryFor(null)} + currentImageId={libraryFor !== null ? (watchedSlides[libraryFor]?.imageId ?? null) : null} + onChoose={(imageId, uploaded) => libraryFor !== null && void chooseForSlide(libraryFor, imageId, uploaded)} + maxUploadBytes={limits?.maxUploadBytes ?? MAX_UPLOAD_BYTES} + limitsText={limits ? t('hero.slides.limits', { formats: limits.formats.join(', '), size: Math.round(limits.maxUploadBytes / (1024 * 1024)), megapixels: limits.maxMegapixels }) : undefined} + slideNumber={(libraryFor ?? 0) + 1} + /> { expect(window.sessionStorage.getItem('cms-hero-tab')).toBe('images'); }); + const trashed = (n: number) => ({ ...seedPhotos()[1]!, id: `hero:2222222${n}-2222-2222-2222-222222222222`, bytes: 1_000_000, deletedAt: new Date().toISOString() }); + + it('removes selected photos from the trash for good after a clear, irreversible confirmation that names the number', async () => { + let body: { ids?: string[]; all?: boolean } | null = null; + server.use( + http.get('*/media-library/trash', () => HttpResponse.json({ photos: [trashed(1), trashed(2)], modules: ['hero'] })), + http.post('*/media-library/purge', async ({ request }) => { + body = (await request.json()) as { ids?: string[]; all?: boolean }; + return HttpResponse.json({ results: (body.ids ?? []).map((id) => ({ id, status: 'purged', uses: [] })) }); + }), + ); + renderPage(); + await screen.findByTestId('photo-selection-list'); + await userEvent.click(screen.getByTestId('view-trash')); + await userEvent.click(await screen.findByTestId('photo-select-hero:22222221-2222-2222-2222-222222222222')); + await userEvent.click(await screen.findByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222')); + + expect(screen.getByTestId('bulk-action-restore')).toBeInTheDocument(); + await userEvent.click(screen.getByTestId('bulk-action-purge')); + + expect(await screen.findByTestId('purge-text')).toHaveTextContent('2 foto'); + expect(screen.getByTestId('purge-warning')).toHaveTextContent('niet ongedaan'); + await userEvent.click(screen.getByTestId('purge-confirm')); + await waitFor(() => expect(body).toEqual({ ids: ['hero:22222221-2222-2222-2222-222222222222', 'hero:22222222-2222-2222-2222-222222222222'] })); + }); + + it('empties the whole trash with one button: the confirmation names the total number and size, and the server is asked for all', async () => { + let body: { ids?: string[]; all?: boolean } | null = null; + server.use( + http.get('*/media-library/trash', () => HttpResponse.json({ photos: [trashed(1), trashed(2), trashed(3)], modules: ['hero'] })), + http.post('*/media-library/purge', async ({ request }) => { + body = (await request.json()) as { ids?: string[]; all?: boolean }; + return HttpResponse.json({ results: [{ id: 'a', status: 'purged', uses: [] }] }); + }), + ); + renderPage(); + await screen.findByTestId('photo-selection-list'); + await userEvent.click(screen.getByTestId('view-trash')); + await waitFor(() => expect(screen.getByTestId('trash-empty')).toBeEnabled()); + + await userEvent.click(screen.getByTestId('trash-empty')); + + expect(await screen.findByTestId('purge-text')).toHaveTextContent(/3 foto's.*2,9 MB|3 foto's \(2,9 MB\)/); + expect(screen.getByTestId('purge-warning')).toHaveTextContent('niet ongedaan'); + await userEvent.click(screen.getByTestId('purge-confirm')); + await waitFor(() => expect(body).toEqual({ all: true })); + }); + + it('disables Empty the trash when the trash is empty', async () => { + server.use(http.get('*/media-library/trash', () => HttpResponse.json({ photos: [], modules: ['hero'] }))); + renderPage(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getByTestId('view-trash')); + + await waitFor(() => expect(screen.getByTestId('trash-empty')).toBeDisabled()); + }); + + it('reports photos that could not be removed for good', async () => { + server.use( + http.get('*/media-library/trash', () => HttpResponse.json({ photos: [trashed(1)], modules: ['hero'] })), + http.post('*/media-library/purge', () => HttpResponse.json({ results: [{ id: 'x', status: 'inUse', uses: [] }] })), + ); + renderPage(); + await screen.findByTestId('photo-selection-list'); + await userEvent.click(screen.getByTestId('view-trash')); + await userEvent.click(await screen.findByTestId('photo-select-hero:22222221-2222-2222-2222-222222222222')); + await userEvent.click(screen.getByTestId('bulk-action-purge')); + await userEvent.click(await screen.findByTestId('purge-confirm')); + + expect(await screen.findByTestId('purge-partial')).toHaveTextContent('1 foto kon niet worden verwijderd'); + }); + it('shows an error when the library cannot be loaded', async () => { server.use(http.get('*/media-library/photos', () => new HttpResponse(null, { status: 500 }))); renderPage(); diff --git a/frontend/src/features/media/services/hooks.ts b/frontend/src/features/media/services/hooks.ts index 86a15a0..055d3d3 100644 --- a/frontend/src/features/media/services/hooks.ts +++ b/frontend/src/features/media/services/hooks.ts @@ -5,8 +5,9 @@ import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPurgeRequest, MediaS export const MEDIA_KEY = ['media-library']; /** All photos of all modules, newest first, with where each is used. */ -export function useMediaPhotos() { +export function useMediaPhotos(enabled = true) { return useQuery({ + enabled, queryKey: [...MEDIA_KEY, 'photos'], queryFn: () => api.get('/api/v1/media-library/photos'), }); diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index b4f2c11..5a35671 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -643,6 +643,12 @@ "label": "Button {{n}}: text", "target": "Button {{n}}: target" }, + "library": { + "choose": "Choose from library", + "title": "Image for slide {{n}}", + "description": "Choose a photo from the media library or upload a new one. A photo that is already in another slide is fine too: it is the same photo, so its crop is shared.", + "group": "Image of slide {{n}}" + }, "slides": { "title": "Images", "add": "Add image", diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index b278a09..64db353 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -643,6 +643,12 @@ "label": "Knop {{n}}: tekst", "target": "Knop {{n}}: doel" }, + "library": { + "choose": "Kies uit bibliotheek", + "title": "Afbeelding voor slide {{n}}", + "description": "Kies een foto uit de mediabibliotheek of upload een nieuwe foto. Een foto die al in een andere slide staat mag ook: het is dezelfde foto, dus de uitsnede is gedeeld.", + "group": "Afbeelding van slide {{n}}" + }, "slides": { "title": "Afbeeldingen", "add": "Afbeelding toevoegen", diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index 7c3ca79..e65cc6b 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -674,6 +674,37 @@ ], "type": "object" }, + "HeroFocusRequest": { + "properties": { + "focus": { + "$ref": "#/components/schemas/FocusDto" + }, + "tall": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/FocusDto" + } + ] + }, + "wide": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/FocusDto" + } + ] + } + }, + "required": [ + "focus" + ], + "type": "object" + }, "HeroImageDto": { "properties": { "failed": { @@ -1207,6 +1238,24 @@ ], "type": "object" }, + "MediaPurgeRequest": { + "properties": { + "all": { + "default": false, + "type": "boolean" + }, + "ids": { + "items": { + "type": "string" + }, + "type": [ + "null", + "array" + ] + } + }, + "type": "object" + }, "MediaRestoreRequest": { "properties": { "ids": { @@ -3491,6 +3540,106 @@ ] } }, + "/api/v1/hero/images/{id}/focus": { + "put": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/HeroFocusRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroFocusRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/HeroFocusRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroImageDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/HeroImageDto" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/HeroImageDto" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Bad Request" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Not Found" + } + }, + "tags": [ + "HeroImages" + ] + } + }, "/api/v1/hero/images/{id}/retry": { "post": { "parameters": [ @@ -3684,6 +3833,75 @@ ] } }, + "/api/v1/media-library/purge": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/MediaPurgeRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/MediaPurgeRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/MediaPurgeRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MediaTrashResponse" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/MediaTrashResponse" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/MediaTrashResponse" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Bad Request" + } + }, + "tags": [ + "MediaLibrary" + ] + } + }, "/api/v1/media-library/restore": { "post": { "requestBody": { -- 2.39.5 From 9bc4153c7066342b50ad676d660a7288734fceb8 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 17:20:09 +0100 Subject: [PATCH 15/22] Mediabibliotheek en Hero: kopie-schakelaar in de deploy-workflow (test), kiezer enkel en meervoud, hint bij gedeelde uitsnede, plan uitsnede per gebruik Co-Authored-By: Claude Sonnet 5.5 --- .gitea/workflows/continuous_integration.yaml | 7 ++ .gitea/workflows/deploy-scp.yaml | 50 ++++++++++++ .../assumptions-and-open-questions.md | 3 + .../application-design/migration-plan.md | 10 +++ .../application-design/per-use-crop.md | 24 ++++++ .../src/features/hero/pages/HeroPage.test.tsx | 11 +++ frontend/src/features/hero/pages/HeroPage.tsx | 5 ++ .../media/components/ImagePicker.test.tsx | 54 +++++++++++++ .../features/media/components/ImagePicker.tsx | 81 ++++++++++++++----- frontend/src/i18n/locales/en/translation.json | 3 +- frontend/src/i18n/locales/nl/translation.json | 3 +- 11 files changed, 228 insertions(+), 23 deletions(-) create mode 100644 aidlc-docs/features/media-library/inception/application-design/per-use-crop.md diff --git a/.gitea/workflows/continuous_integration.yaml b/.gitea/workflows/continuous_integration.yaml index f894507..19eac84 100644 --- a/.gitea/workflows/continuous_integration.yaml +++ b/.gitea/workflows/continuous_integration.yaml @@ -15,6 +15,11 @@ on: description: 'Deploy ASF test (Andrea Slop Fotografie)' type: boolean default: false + media_library_copy: + description: 'Media library copy on the TEST deploys (Media__Library__CopyOnStartup in shared/env): unchanged, on or off' + type: choice + options: [unchanged, 'on', 'off'] + default: unchanged pull_request: types: [opened, synchronize, reopened] push: @@ -555,6 +560,7 @@ jobs: service_name: ${{ vars.SERVICE_NAME_TEST }} health_check_url: ${{ vars.HEALTH_CHECK_URL_TEST }} run_db_backup: false + media_library_copy: ${{ github.event.inputs.media_library_copy || 'unchanged' }} # Production deploy ONLY on an explicit workflow_dispatch run with deploy_sls_production checked, and # only when that run is on a release/* branch (same rule as ASF) — never reachable from a plain push @@ -682,6 +688,7 @@ jobs: service_name: ${{ vars.SERVICE_NAME_ASF_TEST }} health_check_url: ${{ vars.HEALTH_CHECK_URL_ASF_TEST }} run_db_backup: false + media_library_copy: ${{ github.event.inputs.media_library_copy || 'unchanged' }} # --- Smoke tests of the deployed compositions (anonymous requests, see scripts/smoke-site.sh) --- # The CI tests the master CMS; this is the check that the composition of each site that was just deployed to test diff --git a/.gitea/workflows/deploy-scp.yaml b/.gitea/workflows/deploy-scp.yaml index 7bb47a1..9b5c873 100644 --- a/.gitea/workflows/deploy-scp.yaml +++ b/.gitea/workflows/deploy-scp.yaml @@ -37,6 +37,11 @@ on: required: false type: string default: scp + media_library_copy: + description: 'unchanged | on | off: sets Media__Library__CopyOnStartup in shared/env before the restart. TEST only, never production.' + required: false + type: string + default: unchanged jobs: deploy: @@ -211,6 +216,37 @@ jobs: ln -sf \"../../shared/modules/\$name\" \"$RELEASE_DIR/\$name\"; \ done" + # The media library copy switch (migration plan of the media library, decision 13): the application reads + # Media__Library__CopyOnStartup from the host environment file shared/env (D-16). The deploy account can edit that file, + # nobody else needs a shell on the host. Only this ONE key is touched (nothing else of the file is read or printed, the + # file holds secrets), only on a test environment, and only with a value that is exactly on, off or unchanged. + # `on` makes the next start copy the photos into the library's tables and verify the copy (log line + # "Media library copy verified: N photos and M uses"); `off` removes the key again (the default is off). + - name: Set the media library copy switch (test only) + if: inputs.media_library_copy != 'unchanged' + env: + SSH_USER: ${{ secrets.PI_MAIN_USERNAME }} + SSH_PASS: ${{ secrets.PI_MAIN_PASSWORD }} + SSH_PORT: ${{ secrets.PI_MAIN_PORT }} + SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }} + run: | + MODE="${{ inputs.media_library_copy }}" + if [ "${{ inputs.environment }}" != "test" ]; then + echo "The media library copy switch is for the test environment only (environment: ${{ inputs.environment }})." >&2 + exit 1 + fi + if [ "$MODE" != "on" ] && [ "$MODE" != "off" ]; then + echo "media_library_copy must be unchanged, on or off (got: $MODE)." >&2 + exit 1 + fi + ENV_FILE="${{ inputs.deploy_path }}/shared/env" + if [ "$MODE" = "on" ]; then + rssh "touch $ENV_FILE && sed -i '/^Media__Library__CopyOnStartup=/d' $ENV_FILE && echo 'Media__Library__CopyOnStartup=true' >> $ENV_FILE" + else + rssh "touch $ENV_FILE && sed -i '/^Media__Library__CopyOnStartup=/d' $ENV_FILE" + fi + echo "Media__Library__CopyOnStartup is now: $(rssh "grep '^Media__Library__CopyOnStartup=' $ENV_FILE || echo '(not set = off)'")" + # Atomic release switch (FR-06, D-27): `ln -sfn` replaces the `current` symlink target in a # single filesystem operation, so there is no moment where `current` points at a half-written # directory. The process is then restarted so it picks up the new assemblies — a running .NET @@ -227,6 +263,20 @@ jobs: "ln -sfn $RELEASE_DIR ${{ inputs.deploy_path }}/current && \ systemctl --user restart ${{ inputs.service_name }}" + # After a restart with the copy on, show the verification line of the copy in this run's log (the journal of the user + # service), so nobody needs a shell on the host to see "Media library copy verified: N photos and M uses". + - name: Report the media library copy (test only) + if: inputs.media_library_copy == 'on' + env: + SSH_USER: ${{ secrets.PI_MAIN_USERNAME }} + SSH_PASS: ${{ secrets.PI_MAIN_PASSWORD }} + SSH_PORT: ${{ secrets.PI_MAIN_PORT }} + SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }} + run: | + sleep 20 + rssh "journalctl --user -u ${{ inputs.service_name }} --since '-10 min' --no-pager 2>/dev/null | grep -E 'Media library copy|media library copy' | tail -5 || true" + echo "Look for 'Media library copy verified: N photos and M uses'. An error line means the copy was rolled back and nothing was copied." + # Verifies the restart actually produced a healthy process before this run is allowed to # report success. Retries absorb process-startup time, which is about 10 seconds normally but # 30 seconds or more when the host is busy (a migration step, two services restarting at once 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 6e7280c..65796eb 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -67,3 +67,6 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 36 | **Choose from the library in a hero slide** (built 2026-11-17 at Bryan's request, before the migration). | Each slide has "Choose from library" next to its photo: the shared `ImagePicker` lists the library photos of the modules that can be chosen (now the hero's own photos, also those in no slide, never the trash) and a new photo can be uploaded on the spot with the hero's own upload (same checks, limits and background processing). Choosing only sets the slide's existing image id (no data model change). A photo that is already in another slide can be chosen again: it is the same photo, so its **crop is shared by the slides that use it** (the crop belongs to the photo in the hero today; a crop per slide comes with the library's own use records). | A separate crop per slide now would need the use records of phase 2 (or a copy of the photo). | `features/hero/components/LibraryPickerDialog.tsx`, `HeroPage.tsx` | | 37 | **Removing from the trash for good** (Bryan, 2026-11-17). | `POST media-library/purge {ids}` (at most 100) or `{all:true}` (the server empties the whole trash in batches). Only photos that are in the trash and used nowhere are removed; the module checks it again and answers per photo (`purged`, `notInTrash`, `inUse`, `failed`). The original and the cut set go through `IMediaStore`; a file another photo still shares stays. The UI asks a clear confirmation that says it cannot be undone and names the number (and the size for the whole trash); "Empty the trash" is disabled when the trash is empty. No separate waiting period. | A short undo window for a purge: not built (the trash itself is the undo). | `MediaLibraryService.PurgeAsync`, `HeroImageService.PurgeAsync`, `PurgeDialog` | | 38 | **A new crop applies at once, without saving the hero** (Bryan, 2026-11-17; replaces Hero assumption 1 of 2026-11-16, which said a focus change only takes effect when the hero is saved). | The focus dialog's Apply sends the crop at once (`PUT hero/images/{id}/focus`); the server cuts the new variants in the background and the photo switches to them when they are complete, so what is live changes only then, without another Save. The photo shows "Wordt verwerkt…", a 0-100% bar and the percentage on itself (no spinner); the upload keeps its own display. The counter "x of y processed" counts the current upload batch only. | Back to applying only on Save: restore the focus edits kept locally in `HeroPage`. | `HeroImageService.SetFocusAsync`, `HeroPage.applyFocus`, `RecutThumbnail` | +| 39 | **Crop PER USE, not per photo** (Bryan, 2026-11-17: a photo on two slides can have its own crop on each slide). | Decided, **not built yet**: it is too large and risky for the hero as it is today, because the cut sets, their set hash and the public output all hang on the photo (`HeroImage.SetHash`, `Variants`), so a crop per slide means a set per slide. The smallest safe step is built instead: a photo may be chosen for several slides, the crop is shared and the slide says so ("This photo is in more slides; the crop applies to all of them"). Design of the rest in `inception/application-design/per-use-crop.md`: it comes with phase 2 of the migration, because the library's own use records (`MediaUses.Crops`, `MediaUses.SetHash`) are where a crop per slide lives and the renderer then cuts a set per distinct crop. No public address or set hash changes until then. | An additive nullable focus on the slide (x, y, zoom) that overrides the photo's default focus, with a set per (photo, crop) and the public hero choosing the slide's set: possible without the library tables, but it rebuilds the renderer and the public mapping of the hero first; then phase 2 would have to move it again. | `HeroSlide`, `HeroImageService.RenderNextPendingAsync`, `HeroMapping` | +| 40 | **Switching the copy on at the test hosts without access to the Pi** (Bryan, 2026-11-17: the copy may run on test). | The deploy workflow has a new input `media_library_copy` (unchanged, on, off; dispatch input of the CI workflow, passed to the SLS test and ASF test deploys). A step edits ONLY the key `Media__Library__CopyOnStartup` in `/shared/env` over the deploy account's SSH access (refuses any environment that is not `test`, accepts only on, off or unchanged, never prints the file), before the service restart; after the restart a step shows the journal line `Media library copy verified: N photos and M uses`. `off` removes the key again. | Set the variable by hand in `shared/env` on the Pi (needs a shell there). | `.gitea/workflows/deploy-scp.yaml`, `continuous_integration.yaml` | +| 41 | **The picker has a single and a multiple mode** (Bryan, 2026-11-17). | `ImagePicker` takes `mode="single"` (default, radio group, used by the hero slides) or `mode="multiple"` (checkboxes, several photos, several files per upload, ready for the gallery). Both use the same upload checks. | n/a | `ImagePicker.tsx` | diff --git a/aidlc-docs/features/media-library/inception/application-design/migration-plan.md b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md index bf74941..d8f126d 100644 --- a/aidlc-docs/features/media-library/inception/application-design/migration-plan.md +++ b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md @@ -107,3 +107,13 @@ After that deploy, check in the log: 5. Switch it off again (remove the variable, restart) when done: the copy can be repeated at any time; it is a mirror. **Rollback:** remove the variable (the tables stay, unused), or drop the tables with the EF `Down` migration of the Media module; the Hero's own tables are never changed by the copy. + +## Switching the copy on at the test hosts (no shell on the Pi needed) + +The application reads `Media__Library__CopyOnStartup` from the host's `shared/env` (the file the service starts with). The deploy workflow can set exactly this one key, so nobody needs a shell on the Raspberry Pi: + +1. Dispatch the CI workflow (`Continuous Integration`) on the branch with **deploy_sls_test** and/or **deploy_asf_test** checked and **media_library_copy = on**. Each test deploy then sets `Media__Library__CopyOnStartup=true` in its own `shared/env` before restarting the service, and the run log shows the line `Media library copy verified: N photos and M uses from hero` (or the error line that says the copy was rolled back). +2. Check N and M against the hero (photos and slides) and the library screen. +3. Dispatch once more with **media_library_copy = off** (and the deploy flags again): the key is removed and the next start does not copy. (`unchanged`, the default, never touches the file.) + +The input is refused for any environment other than `test`, and only the three values are accepted; the workflow never prints the file (it holds secrets). Production is not reachable. diff --git a/aidlc-docs/features/media-library/inception/application-design/per-use-crop.md b/aidlc-docs/features/media-library/inception/application-design/per-use-crop.md new file mode 100644 index 0000000..2d1fd45 --- /dev/null +++ b/aidlc-docs/features/media-library/inception/application-design/per-use-crop.md @@ -0,0 +1,24 @@ +# Crop per use (decision of Bryan, 2026-11-17) + +A photo on two slides can have its own crop on each slide. Decided; **not built yet**. What exists today, why it waits, and the plan. + +## Today + +- The crop (default focus and the `wide` and `tall` overrides) is a property of the **photo** (`HeroImage`). The cut set (`SetHash`, `Variants`) belongs to the photo too, and so does the public output of the hero. A photo chosen for two slides therefore has one crop; the slide says so. +- The set hash is `MediaPaths.SetHash(originalSha256, crops)`, so a set is already addressed by photo plus crops; the formula does not have to change. + +## Why not now + +A crop per slide means a set per (photo, crop). The renderer (`HeroRenderService`), the public hero mapping and the admin all assume one set per photo. Changing that on the hero's own tables and then moving it again when the library takes over (`MediaUses` already has `Crops` and `SetHash` per use) would be done twice and puts the public output at risk before the library is accepted. + +## Plan (with phase 2 of the migration) + +1. The library's `MediaUses` (one per slide) carry the crops and the set hash of that use (the copy already fills them from the photo). +2. The hero slide gets its own crop (nullable focus overriding the photo's default; empty = the default), edited in the same focus dialog, applied at once like today. +3. The renderer cuts one set per distinct (photo, crops); a set that two uses share (same crops) is cut once; a set nobody uses any more is cleaned up like a retired set. +4. The public hero maps each slide to the set of its use. With no override the set is exactly today's set hash, so existing addresses and the golden files do not change. +5. Tests: two slides with one photo and different crops give two sets and two addresses; with the same crop one set; no override gives today's hash. + +## Smallest safe step built now + +A photo may be chosen for several slides and the slide shows "This photo is in more slides; the crop applies to all of them" (assumption 36 and 39). diff --git a/frontend/src/features/hero/pages/HeroPage.test.tsx b/frontend/src/features/hero/pages/HeroPage.test.tsx index 907bcab..aada537 100644 --- a/frontend/src/features/hero/pages/HeroPage.test.tsx +++ b/frontend/src/features/hero/pages/HeroPage.test.tsx @@ -1282,6 +1282,17 @@ describe('Choose a photo from the library for a slide', () => { expect(getSavedHeroRequests()[0].slides.map((x) => x.imageId)).toEqual(['10000000-0000-0000-0000-000000000002', '10000000-0000-0000-0000-000000000002']); }); + it('tells that the crop is shared when the same photo is in more than one slide', async () => { + const one = slide(1); + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [one, { ...slide(2), imageId: one.imageId, image: one.image }, slide(3)] }); + + await openPage(); + + expect(screen.getByTestId('hero-slide-0-shared-crop')).toBeInTheDocument(); + expect(screen.getByTestId('hero-slide-1-shared-crop')).toBeInTheDocument(); + expect(screen.queryByTestId('hero-slide-2-shared-crop')).not.toBeInTheDocument(); + }); + it('uploads a new photo on the spot with the hero upload and puts it in the slide', async () => { setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] }); server.use(http.get('*/media-library/photos', () => HttpResponse.json({ photos: [], modules: ['hero'] }))); diff --git a/frontend/src/features/hero/pages/HeroPage.tsx b/frontend/src/features/hero/pages/HeroPage.tsx index 976d572..b4ccc91 100644 --- a/frontend/src/features/hero/pages/HeroPage.tsx +++ b/frontend/src/features/hero/pages/HeroPage.tsx @@ -574,6 +574,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) { + {watchedSlides.some((other, otherIndex) => otherIndex !== index && other?.imageId === field.imageId) && ( +

+ {t('hero.library.sharedCrop')} +

+ )}

diff --git a/frontend/src/features/media/components/ImagePicker.test.tsx b/frontend/src/features/media/components/ImagePicker.test.tsx index 48f9c8f..d24d11f 100644 --- a/frontend/src/features/media/components/ImagePicker.test.tsx +++ b/frontend/src/features/media/components/ImagePicker.test.tsx @@ -88,3 +88,57 @@ describe('ImagePicker', () => { expect(screen.getByTestId('picker-empty')).toHaveTextContent('nog geen foto'); }); }); + +function MultiHarness({ onUpload, initial = [] }: { onUpload?: (file: File) => Promise; initial?: string[] }) { + const [values, setValues] = useState(initial); + return ( + <> + + {values.join(',')} + + ); +} + +describe('ImagePicker in multiple mode', () => { + it('chooses several photos with checkboxes, in the order chosen, and unchooses one', async () => { + render(); + + expect(screen.getByRole('group', { name: "Foto's van de galerij" })).toBeInTheDocument(); + await userEvent.click(screen.getByRole('checkbox', { name: 'Foto B' })); + await userEvent.click(screen.getByRole('checkbox', { name: 'Foto A' })); + expect(screen.getByTestId('chosen')).toHaveTextContent('b,a'); + + await userEvent.click(screen.getByRole('checkbox', { name: 'Foto B' })); + expect(screen.getByTestId('chosen')).toHaveTextContent('a'); + expect(screen.getByRole('checkbox', { name: 'Foto B' })).not.toBeChecked(); + }); + + it('uploads several files on the spot and adds them all to the choice', async () => { + let n = 0; + const upload = vi.fn().mockImplementation(async () => photo(`new${++n}`, `Nieuw ${n}`)); + render(); + + await userEvent.upload(screen.getByTestId('picker-file'), [file('1.jpg'), file('2.jpg')]); + + await waitFor(() => expect(screen.getByTestId('chosen')).toHaveTextContent('a,new1,new2')); + expect(upload).toHaveBeenCalledTimes(2); + expect(screen.getByTestId('picker-file')).toHaveAttribute('multiple'); + }); + + it('stops at a file the host would refuse and keeps what was chosen', async () => { + const upload = vi.fn().mockResolvedValue(photo('new1', 'Nieuw')); + render(); + + await userEvent.upload(screen.getByTestId('picker-file'), [file('ok.jpg'), file('big.jpg', 'image/jpeg', 10 * MB + 1), file('later.jpg')]); + + await waitFor(() => expect(screen.getByTestId('picker-problem')).toHaveTextContent('maximaal 10 MB')); + expect(upload).toHaveBeenCalledTimes(1); + expect(screen.getByTestId('chosen')).toHaveTextContent('new1'); + }); + + it('single mode still takes one file only and has no multiple attribute', () => { + render(); + + expect(screen.getByTestId('picker-file')).not.toHaveAttribute('multiple'); + }); +}); diff --git a/frontend/src/features/media/components/ImagePicker.tsx b/frontend/src/features/media/components/ImagePicker.tsx index 47ef627..01317ee 100644 --- a/frontend/src/features/media/components/ImagePicker.tsx +++ b/frontend/src/features/media/components/ImagePicker.tsx @@ -6,12 +6,9 @@ import { cn } from '@/lib/utils'; import { validateUpload } from '../lib/validateUpload'; import type { PhotoItem } from './PhotoSelectionList'; -interface ImagePickerProps { +interface ImagePickerCommon { /** 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 @@ -26,30 +23,71 @@ interface ImagePickerProps { label: string; } +/** One photo: a radio group (the hero slides use this). */ +export interface ImagePickerSingleProps extends ImagePickerCommon { + mode?: 'single'; + /** The id of the chosen photo, or null. */ + value: string | null; + onChange: (id: string) => void; +} + +/** Several photos: checkboxes (ready for the gallery). Uploaded photos are added to the choice. */ +export interface ImagePickerMultipleProps extends ImagePickerCommon { + mode: 'multiple'; + /** The ids of the chosen photos, in the order they were chosen. */ + values: readonly string[]; + onChangeMany: (ids: string[]) => void; +} + +export type ImagePickerProps = ImagePickerSingleProps | ImagePickerMultipleProps; + /** - * "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. + * "Choose an image or upload one", one component for every module that needs an image. In single mode the library + * photos are a radio group (arrow keys move and choose); in multiple mode they are checkboxes and several photos can + * be chosen. An upload button adds the new photo to the library and chooses it at once. The picker 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) { +export function ImagePicker(props: ImagePickerProps) { + const { items, onUpload, maxUploadBytes, limitsText, label } = props; + const multiple = props.mode === 'multiple'; 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; + const chosen = (id: string) => (props.mode === 'multiple' ? props.values.includes(id) : props.value === id); + + const toggle = (id: string) => { + if (props.mode === 'multiple') { + props.onChangeMany(props.values.includes(id) ? props.values.filter((v) => v !== id) : [...props.values, id]); + } else { + props.onChange(id); } + }; + + const upload = async (files: FileList | null) => { + const list = Array.from(files ?? []); + if (list.length === 0 || !onUpload || uploading) return; setProblem(null); setUploading(true); + let current = props.mode === 'multiple' ? [...props.values] : []; try { - const photo = await onUpload(file); - onChange(photo.id); + for (const file of multiple ? list : list.slice(0, 1)) { + const refused = validateUpload(file, maxUploadBytes); + if (refused) { + setProblem(refused === 'tooLarge' ? t('media.picker.tooLarge', { max: Math.round(maxUploadBytes / (1024 * 1024)) }) : t('media.picker.notAnImage')); + break; + } + + const photo = await onUpload(file); + if (props.mode === 'multiple') { + current = [...current, photo.id]; + props.onChangeMany(current); + } else { + props.onChange(photo.id); + } + } } catch { setProblem(t('media.picker.failed')); } finally { @@ -66,10 +104,11 @@ export function ImagePicker({ items, value, onChange, onUpload, maxUploadBytes, ref={fileInput} type="file" accept="image/*" + multiple={multiple} className="sr-only" aria-label={t('media.picker.upload')} data-testid="picker-file" - onChange={(event) => void upload(event.target.files?.[0])} + onChange={(event) => void upload(event.target.files)} /> @@ -574,9 +572,6 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
?
)} - {watchedSlides.some((other, otherIndex) => otherIndex !== index && other?.imageId === field.imageId) && (

{t('hero.library.sharedCrop')} @@ -664,13 +659,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {

!open && setLibraryFor(null)} - currentImageId={libraryFor !== null ? (watchedSlides[libraryFor]?.imageId ?? null) : null} - onChoose={(imageId, uploaded) => libraryFor !== null && void chooseForSlide(libraryFor, imageId, uploaded)} + open={adding} + onOpenChange={setAdding} + onChoose={(imageId, uploaded) => void addSlideWithPhoto(imageId, uploaded)} maxUploadBytes={limits?.maxUploadBytes ?? MAX_UPLOAD_BYTES} limitsText={limits ? t('hero.slides.limits', { formats: limits.formats.join(', '), size: Math.round(limits.maxUploadBytes / (1024 * 1024)), megapixels: limits.maxMegapixels }) : undefined} - slideNumber={(libraryFor ?? 0) + 1} /> {{name}} an Owner. Owners have full access to the system, including the ability to manage and remove other Owners. Are you sure?", - "confirmButton": "Make Owner" - }, - "selfRoleChange": { - "title": "Change your own role", - "description": "You are about to change your own role to {{role}}. You will be logged out automatically so the change takes effect immediately.", - "confirmButton": "Change and log out" - }, - "errors": { - "lastOwnerRequired": "At least one Owner must remain. Assign another Owner before changing this role.", - "insufficientPermissions": "You do not have permission to perform this action." - } - }, - "profile": { - "title": "My Profile", - "name": "Display name", - "email": "Email address", - "role": "Role", - "save": "Save changes", - "saving": "Saving…", - "saveSuccess": "Profile updated successfully", - "securityTitle": "Change password", - "language": "Language", - "languageDefault": "Site default", - "languageHelp": "The language of the admin and of e-mails you receive.", - "changePassword": "Change password", - "changePasswordDialog": { - "title": "Change Password", - "new": "New password", - "confirm": "Confirm new password", - "submit": "Change password", - "submitting": "Changing…", - "success": "Password changed successfully", - "errorCurrent": "Current password is incorrect" - } - }, - "settings": { - "title": "System Settings", - "mail": { - "title": "E-mail", - "description": "The address and name this site sends e-mails from (invitations, password reset, notices).", - "fromAddress": "Sender address", - "fromAddressHelp": "Only addresses allowed for this installation (SPF/DKIM). Another address can only be added by whoever manages the server.", - "fromName": "Sender name", - "nameTooLong": "The name can be at most 80 characters.", - "save": "Save", - "reset": "Restore default", - "saveSuccess": "E-mail settings saved", - "resetSuccess": "Default settings restored", - "invalid": "These settings are not valid.", - "readOnly": "Only the owner can change these settings." - }, - "availability": { - "title": "System Availability", - "mode": "Availability mode", - "reason": "Message (optional)", - "save": "Update availability", - "saving": "Updating…", - "saveSuccess": "Availability updated", - "modes": { - "Available": "Available", - "Maintenance": "Maintenance", - "NotAvailable": "Unavailable" - }, - "masterControlledTitle": "Controlled by Master CMS", - "masterControlled": "This instance has been disabled by the Master CMS. Availability cannot be changed here until the Master releases it.", - "masterControlledSaveError": "Cannot be changed: the Master CMS controls this status." - }, - "modules": { - "title": "Module Management", - "comingSoon": "Coming soon" - }, - "systemConfig": { - "title": "System Configuration", - "comingSoon": "Coming soon" - }, - "branding": { - "title": "Branding / Theme", - "comingSoon": "Coming soon" - } - }, - "cms": { - "title": "CMS Instances", - "addButton": "Add CMS", - "emptyState": { - "heading": "No CMS instances yet", - "description": "Add your first CMS instance to get started." - }, - "table": { - "name": "Name", - "url": "URL", - "status": "Status", - "lastContact": "Last Contact", - "disableMessage": "Disable Message", - "actions": "Actions" - }, - "status": { - "Available": "Available", - "NotAvailable": "Unavailable", - "Inactive": "Inactive" - }, - "actions": { - "setStatus": "Set Status" - }, - "add": { - "title": "Add CMS Instance", - "nameLabel": "Name", - "urlLabel": "URL", - "apiKeyLabel": "API Key", - "submitButton": "Add", - "successToast": "CMS instance added successfully", - "errors": { - "conflict": "A CMS instance with this name or URL already exists." - } - }, - "setStatus": { - "title": "Set Status", - "statusLabel": "Status", - "disableMessageLabel": "Disable Message", - "disableMessagePlaceholder": "Reason for disabling…", - "submitButton": "Save", - "successContactedToast": "Status updated — cliënt confirmed", - "successUnreachableToast": "Status saved — cliënt unreachable" - } - }, - "offerings": { - "title": "Offerings", - "addButton": "Add Offering", - "banners": { - "intro": "A banner is a wide announcement or promotion on the website. Plan ahead with a start and end time. At most one banner is shown per location (top and bottom) at any time: the most recently changed active one.", - "position": { - "label": "Location", - "top": "Top", - "bottom": "Bottom" - }, - "shownBadge": "Live", - "notShownBadge": "Not shown", - "notShownHint": "Not shown: a newer banner at this location", - "turnOffButton": "Turn banner off", - "turnOnButton": "Turn banner on", - "titleLabelOptional": "Title (optional)", - "textTooLong": "The text is {{length}} characters; this location allows at most {{max}}. Shorten the text or pick another location.", - "textHintTop": "One short line, up to 120 characters.", - "addButton": "Add banner", - "empty": "No banners yet.", - "editButton": "Edit banner", - "deleteButton": "Delete banner", - "createTitle": "New banner", - "editTitle": "Edit banner", - "titleLabel": "Title", - "textLabel": "Text", - "linkLabelLabel": "Button text (optional)", - "linkUrlLabel": "Link (optional)", - "linkHint": "Button text and link go together. A link starts with https:// or is a path on the site, for example /privacy.", - "startsLabel": "Visible from (optional)", - "endsLabel": "Visible until (optional)", - "scheduleHint": "Times are in your time zone. On Andrea's website the schedule applies at the next (nightly) build.", - "activeLabel": "Enabled", - "savedToast": "Banner saved", - "deletedToast": "Banner deleted", - "deleteTitle": "Delete banner", - "deleteMessage": "Are you sure you want to delete the banner \"{{title}}\"?", - "deleteConfirm": "Delete", - "status": { - "live": "Active", - "scheduled": "Scheduled", - "expired": "Expired", - "off": "Off" - }, - "tabPackages": "Offerings", - "tabBanner": "Banner", - "tabsLabel": "Sections" - }, - "categories": { - "manageButton": "Manage categories", - "title": "Manage categories", - "emptyState": "No categories yet. Add the first one.", - "offeringCount_one": "{{count}} offering", - "offeringCount_other": "{{count}} offerings", - "newLabel": "New category", - "addButton": "Add", - "editButton": "Rename category", - "confirmEditButton": "Confirm name", - "cancelButton": "Cancel", - "deleteButton": "Delete category", - "deleteConfirm": "Are you sure?", - "deleteConfirmButton": "Delete", - "errors": { - "nameRequired": "Enter a name.", - "nameTooLong": "The name can be at most 100 characters.", - "duplicate": "A category named '{{name}}' already exists.", - "inUse": "This category is still used by {{count}} offering(s). Move them to another category first." - } - }, - "emptyState": { - "heading": "No offerings yet", - "description": "Add your first offering to get started." - }, - "table": { - "title": "Title", - "price": "Price", - "featured": "Featured", - "actions": "Actions" - }, - "actions": { - "turnOff": "Switch package off", - "turnOn": "Switch package on", - "drag": "Drag to reorder", - "edit": "Edit", - "delete": "Delete", - "moveUp": "Move up", - "moveDown": "Move down", - "markFeatured": "Mark as featured", - "unmarkFeatured": "Remove featured" - }, - "deleteDialog": { - "title": "Delete offering", - "message": "Are you sure you want to delete '{{title}}'?", - "confirmButton": "Delete", - "cancelButton": "Cancel" - }, - "form": { - "createTitle": "New Offering", - "editTitle": "Edit Offering", - "activeLabel": "Switched on", - "startsLabel": "Visible from (optional)", - "endsLabel": "Visible until (optional)", - "scheduleHint": "A switched-off or planned package is not shown on the website. Times are in your time zone. On Andrea's website the schedule applies at the next (nightly) build.", - "endBeforeStart": "The end must be after the start.", - "titleLabel": "Title", - "slugLabel": "Slug", - "slugAutoHint": "Auto-generated from the title", - "editSlugButton": "Edit", - "confirmSlugButton": "Confirm slug", - "cancelSlugEditButton": "Cancel slug edit", - "descriptionLabel": "Description (optional)", - "priceLabel": "Price", - "priceNoteLabel": "Price note (optional)", - "featuresLabel": "Features", - "addFeatureButton": "Add feature", - "removeFeatureButton": "Remove", - "ctaLabelLabel": "Button text", - "featuredLabel": "Featured", - "categoryLabel": "Category", - "noCategory": "No category", - "submitButton": "Save", - "successToast": "Offering saved successfully" - } - }, - "error": { - "403": { - "title": "Access Denied", - "message": "You don't have permission to view this page." - }, - "404": { - "title": "Page Not Found", - "message": "The page you're looking for doesn't exist." - }, - "backToDashboard": "Back to Dashboard", - "unexpected": { - "title": "Something went wrong", - "message": "This page could not be displayed. Try again, or go back to the dashboard." - } - }, - "errors": { - "network": "Unable to reach the server. Check your connection and try again.", - "generic": "Something went wrong. Please try again.", - "accessDenied": "You do not have permission to access this page.", - "setupRequired": "System setup required. Please initialize the system first.", - "invalidInvitationToken": "Invalid or expired invitation token.", - "featureUnavailableTitle": "Not available on this instance", - "featureUnavailable": "This feature is only available on a Master CMS instance." - }, - "contact": { - "title": "Messages", - "switch": { - "title": "Contact form on the website", - "stateOn": "The form is on: visitors can send you a message.", - "stateOff": "The form is off: visitors only see your e-mail address.", - "on": "On", - "off": "Off", - "turnOn": "Turn on", - "turnOff": "Turn off", - "nowOn": "The contact form is now on.", - "nowOff": "The contact form is now off.", - "shortLabel": "Contact form on/off", - "explanation": "While the form is off, visitors only see your e-mail address. Turning it off helps against spam or during maintenance.", - "firstTimeHint": "The form stays closed until you turn it on.", - "hostOff": "The form is switched off at server level.", - "noRecipientBanner": "No recipient address is set: messages are kept but not mailed. Enter an address below." - }, - "filter": { - "label": "Filter messages", - "inbox": "Inbox", - "new": "New", - "read": "Read", - "archived": "Archived", - "spam": "Spam" - }, - "table": { - "received": "Received", - "name": "Name", - "email": "E-mail address", - "subject": "Subject", - "status": "Status", - "mail": "Mail" - }, - "status": { - "new": "New", - "read": "Read", - "archived": "Archived", - "spam": "Spam", - "converted": "Converted" - }, - "mailStatus": { - "pending": "Mail waiting to be sent", - "sent": "Mail sent", - "failed": "Mail failed", - "notApplicable": "No mail applicable" - }, - "empty": { - "inbox": "No messages yet.", - "new": "No new messages.", - "read": "No read messages.", - "archived": "No archived messages.", - "spam": "No spam." - }, - "pager": { - "range": "{{from}}–{{to}} of {{total}}", - "previous": "Previous", - "next": "Next" - }, - "tabs": { - "label": "Messages sections", - "messages": "Messages", - "settings": "Settings" - }, - "unread": { - "label": "Unread" - }, - "tile": { - "unread_one": "unread message", - "unread_other": "unread messages", - "error": "The number of unread messages could not be loaded." - }, - "detail": { - "title": "Message", - "retention": "Kept until", - "attempts": "({{count}} attempts)", - "nextAttempt": "Next attempt: {{time}}", - "delete": "Delete", - "resend": "Send mail again", - "archive": "Archive", - "restore": "Restore", - "markUnread": "Mark as unread", - "notSpam": "Not spam" - }, - "resend": { - "sent": "Sent.", - "notSent": "Not sent (mail is off).", - "mailOff": "Mail is off on this site." - }, - "deleteDialog": { - "title": "Delete message?", - "message": "The message is deleted permanently. This cannot be undone.", - "confirm": "Delete" - }, - "errors": { - "rateLimited": "Try again in {{seconds}} seconds.", - "spamResend": "Mark the message as not spam first.", - "notFound": "This message no longer exists." - }, - "mailError": { - "disabled": "Mail is off.", - "recipient_not_configured": "No recipient is configured.", - "not_configured": "Mail is not configured.", - "timeout": "The mail server was too slow.", - "timeout_connect": "Connecting to the mail server took too long.", - "timeout_auth": "Logging in to the mail server took too long.", - "timeout_send": "Sending took too long.", - "auth_failed": "Logging in to the mail server failed.", - "rejected": "The mail server refused the message.", - "rejected_sender": "The mail server refused the sender address.", - "rejected_recipient": "The mail server refused the recipient.", - "tls_failed": "The secure connection to the mail server failed.", - "connection_failed": "Cannot reach the mail server.", - "unknown": "Unknown error while sending." - }, - "recipient": { - "title": "Recipient address for contact messages", - "description": "We mail every new message to this address. You can reply to that mail directly: the reply goes to the visitor.", - "label": "E-mail address", - "placeholder": "name@example.com", - "save": "Save", - "reset": "Back to the server setting", - "saved": "Recipient address saved.", - "cleared": "The server setting applies again.", - "invalid": "Enter a valid e-mail address.", - "source": { - "setting": "Messages go to this address.", - "config": "No address of your own is set: the server setting applies.", - "none": "There is no recipient address yet: messages are kept but not mailed." - } - } - }, - "hero": { - "title": "Hero", - "live": "Live", - "notLive": "Not live", - "intro": "The hero is the first thing visitors of the website see: a large heading with one or more photos. Here you manage the texts, the buttons and the photos. A change is visible within about a minute.", - "savedToast": "Hero saved", - "fields": { - "title": "Title", - "titleHint": "A new line in this field is a line break in the title (at most 5 lines).", - "tagline": "Short text above the title (optional)", - "lead": "Introduction (optional)", - "display": "Display" - }, - "display": { - "single": "Single", - "slideshow": "Slideshow" - }, - "buttons": { - "title": "Buttons", - "hint": "At most two buttons. As the target, choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…).", - "label": "Button {{n}}: text", - "target": "Button {{n}}: target" - }, - "library": { - "choose": "Choose from library", - "title": "Image for slide {{n}}", - "description": "Choose a photo from the media library or upload a new one. A photo that is already in another slide is fine too: it is the same photo, so its crop is shared.", - "group": "Image of slide {{n}}", - "sharedCrop": "This photo is in more slides; the crop applies to all of them." - }, - "slides": { - "title": "Images", - "add": "Add image", - "uploading": "Uploading…", - "hint": "Choose several files at once or drag them into this box. New photos are added at the bottom of the list. Drag a photo by its handle, or use the arrows, to change the order; visitors see the first photo first. With the Focus button you show where the subject is.", - "empty": "No images yet.", - "alt": "Description", - "decorative": "Hide from screen readers", - "up": "Move up", - "down": "Move down", - "remove": "Remove slide", - "ceiling": "Only the first {{max}} images are shown on the website.", - "focusPending": "Focus changed, not saved yet.", - "processing": "Processing…", - "processingHint": "The image is being prepared in the background; it appears on the website as soon as it is ready.", - "failed": "Failed", - "limits": "Allowed: {{formats}}. At most {{size}} MB per file and {{megapixels}} megapixels.", - "altHint": "Describes the photo for people who cannot see it and for search engines.", - "drag": "Move image {{n}}", - "dragInstructions": "Press space to pick up the image, use the arrow keys to move it and press space again to drop it. Escape cancels.", - "recut": "Making the new crop…", - "recutHint": "You still see the old crop. The change is only on the website when this is done.", - "activeOn": "Active", - "activeOff": "Not active", - "activeFor": "show image {{n}} on the website", - "number": "Slide {{n}}", - "done": "Processing finished", - "doneFor": "Slide {{n}}: processing finished", - "cropEdit": "Adjust crop" - }, - "processing": { - "count": "{{done}} of {{total}} photos processed", - "label": "Progress of processing the photos", - "explain": "The hero has been saved. The photos are prepared one by one and go live as soon as they are ready. Until the first photo is ready the website keeps its standard hero. You do not have to keep this page open.", - "failed_one": "Processing {{count}} photo failed.", - "failed_other": "Processing {{count}} photos failed.", - "failedHint": "The server tried three times. Try again, or upload the photo once more (the same photo is the same image).", - "retry": "Try again", - "current": "Working on photo {{n}} of {{total}}: step {{step}} of {{steps}}. A large photo can take a few minutes.", - "stuck": "Taking long?" - }, - "focus": { - "title": "Focus and crop", - "intro": "Click or drag on the photo to show where the subject is. The website crops the photo for landscape and portrait screens so that the subject stays in view.", - "targetLegend": "For which display", - "target": { - "general": "General", - "wide": "Landscape (3:2)", - "tall": "Portrait (4:5)" - }, - "override": "Own setting for this display", - "areaLabel": "Photo: choose the point of the subject", - "areaHint": "The arrow keys move the point (faster with Shift).", - "x": "Horizontal (%)", - "y": "Vertical (%)", - "zoom": "Zoom ({{value}}×)", - "preview": { - "wide": "Landscape preview", - "tall": "Portrait preview" - }, - "apply": "Apply", - "applyHint": "The change only takes effect when you save the hero. If you leave the page without saving it is dropped.", - "previewPending": "The preview of this photo is being prepared. Close this window and try again in a few seconds." - }, - "errors": { - "titleRequired": "A title is required.", - "titleTooLong": "The title can have at most 200 characters.", - "titleTooManyLines": "The title can have at most 5 lines.", - "taglineTooLong": "The short text above the title can have at most 120 characters.", - "leadTooLong": "The introduction can have at most 600 characters.", - "buttonLabelTooLong": "The button text can have at most 50 characters.", - "buttonTargetTooLong": "The target can have at most 500 characters.", - "buttonIncomplete": "Fill in both the text and the target of the button, or leave both empty.", - "buttonTargetInvalid": "Choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…).", - "altTooLong": "The description can have at most 300 characters.", - "altRequired": "Give a description or choose ‘Decoration only’." - }, - "upload": { - "tooLarge": "The image is too large (at most {{max}} MB).", - "interrupted": "The upload was interrupted. Check the connection and try again.", - "busy": "Too many uploads in a row. Try again in a few minutes.", - "notAnImage": "This file is not an image.", - "progress": "Uploading: {{done}} of {{total}}", - "summary": "{{ok}} of {{total}} photos added", - "waiting": "waiting", - "uploading": "uploading…", - "done": "added", - "close": "Close" - }, - "help": { - "heading": "Explanation of each part", - "save": "Changes only take effect after you save the hero.", - "title": { - "name": "Title", - "text": "The large heading. A new line in the field is a new line in the heading." - }, - "tagline": { - "name": "Short text above the title", - "text": "A short label above or before the title. Can stay empty." - }, - "lead": { - "name": "Introduction", - "text": "One or two sentences below the title. Can stay empty." - }, - "buttons": { - "name": "Buttons", - "text": "At most two, each with a text and a target. As the target, choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…)." - }, - "display": { - "name": "Display", - "text": "‘Single’ shows one photo, ‘Slideshow’ switches between the photos." - }, - "slides": { - "name": "Images", - "text": "Upload photos, describe what is in them and set the order (drag or use the arrows). The switch makes a photo active or not active. Choose ‘Hide from screen readers’ for a photo that adds nothing to the content." - }, - "focus": { - "name": "Focus", - "text": "Show where the subject is in the photo, so a crop never cuts it off. For portrait screens, such as a phone, you can choose a separate point." - } - }, - "unsaved": { - "badge": "Unsaved changes", - "text": "Save the hero to put them on the website.", - "leaveTitle": "Changes not saved", - "leaveText": "You have made changes that are not saved yet. If you leave this page they will be lost.", - "stay": "Stay", - "discard": "Discard changes" - }, - "saving": "Saving…", - "tabs": { - "label": "Hero sections", - "content": "Content", - "images": "Images", - "busy": "{{count}} busy", - "hasChanges": "unsaved changes", - "hasErrors": "has errors" - } - }, - "media": { - "progress": { - "working": "Processing…" - }, - "module": { - "hero": "Hero" - }, - "use": { - "slide": "slide", - "none": "Not used", - "off": "off", - "noneSince": "Not used since {{date}}" - }, - "list": { - "label": "Photos", - "empty": "There are no photos.", - "selectAll": "Select all", - "noThumbnail": "No preview", - "photoName": "Photo {{width}} × {{height}}" - }, - "bulk": { - "label": "Actions on the selection", - "selected_one": "{{count}} photo selected", - "selected_other": "{{count}} photos selected", - "clear": "Clear selection" - }, - "loading": "Loading...", - "error": "The media library could not be loaded.", - "page": { - "title": "Media library", - "noModules": "No module reports photos yet." - }, - "storage": { - "title": "Storage", - "used": "{{used}} used", - "usedOf": "{{used}} of {{limit}} used ({{percent}}%)", - "warning": "Storage is more than {{percent}}% full. Clean up photos before the limit is reached.", - "full": "Storage is full. No more photos can be uploaded until there is room." - }, - "cleanup": { - "open": "Clean up", - "title": "Clean up", - "description": "Photos older than the number of days below, newest first. Take out the photos you want to keep.", - "days_one": "Older than {{count}} day", - "days_other": "Older than {{count}} days", - "onlyUnused": "Only unused photos", - "summary_one": "{{count}} photo ({{size}}) qualifies.", - "summary_other": "{{count}} photos ({{size}}) qualify.", - "selectedSize": "Selected: {{size}}", - "trashNote": "The selected photos go to the trash and can be restored for 7 days.", - "confirm_one": "{{count}} photo to the trash", - "confirm_other": "{{count}} photos to the trash" - }, - "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." - }, - "view": { - "label": "View", - "library": "Library", - "trash": "Trash" - }, - "trash": { - "since": "In the trash since {{date}}", - "restore": "Restore", - "note": "Photos in the trash are removed for good after 7 days (default). Restore them while you can, or delete them for good now." - }, - "delete": { - "action": "Move to trash", - "title": "Move photos to the trash", - "confirm_one": "This photo goes to the trash. You can restore it for 7 days.", - "confirm_other": "These {{count}} photos go to the trash. You can restore them for 7 days.", - "inUseCount_one": "{{count}} photo is still in use.", - "inUseCount_other": "{{count}} photos are still in use.", - "secondTitle": "Delete photos that are in use?", - "secondText_one": "This photo is still in use. If you go on, it disappears from the places below (in the Hero the slide is removed).", - "secondText_other": "These photos are still in use. If you go on, they disappear from the places below (in the Hero the slide is removed).", - "confirmButton": "Move to trash", - "confirmSecond": "Yes, delete anyway", - "cancel": "Cancel", - "close": "Close", - "partial_one": "{{count}} photo could not be deleted. The rest went to the trash.", - "partial_other": "{{count}} photos could not be deleted. The rest went to the trash." - }, - "filter": { - "label": "Filter", - "all": "All photos", - "used": "Used", - "unused": "Unused" - }, - "purge": { - "action": "Delete for good", - "title": "Delete for good", - "emptyTitle": "Empty the trash", - "emptyButton": "Empty the trash", - "emptyConfirm": "Empty the trash", - "confirmButton": "Delete for good", - "confirm_one": "This photo is deleted for good, with its files.", - "confirm_other": "These {{count}} photos are deleted for good, with their files.", - "confirmAll_one": "The trash is emptied: {{count}} photo ({{size}}) is deleted for good.", - "confirmAll_other": "The trash is emptied: {{count}} photos ({{size}}) are deleted for good.", - "irreversible": "This cannot be undone.", - "partial_one": "{{count}} photo could not be deleted. The rest was deleted for good.", - "partial_other": "{{count}} photos could not be deleted. The rest was deleted for good." - } - } -} +{ + "common": { + "appName": "SlpModularCms", + "loading": "Loading…", + "cancel": "Cancel", + "save": "Save", + "retry": "Retry" + }, + "nav": { + "dashboard": "Dashboard", + "users": "Users", + "cms": "CMS", + "offerings": "Offerings", + "messages": "Messages", + "profile": "Profile", + "settings": "Settings", + "openMenu": "Open navigation", + "closeMenu": "Close navigation", + "hero": "Hero", + "media": "Media library", + "unreadMessages_one": "{{count}} new message", + "unreadMessages_other": "{{count}} new messages" + }, + "theme": { + "title": "Theme", + "label": "Theme: {{mode}}", + "labelAuto": "Theme: automatic (now {{now}})", + "mode": { + "light": "Light", + "dark": "Dark", + "auto": "Automatic" + } + }, + "session": { + "unreachable": { + "title": "Could not check your session", + "description": "The server is briefly unreachable or busy. You have not been signed out. Try again in a few seconds.", + "retry": "Try again", + "stillFailing": "Still no answer. Wait a moment and try again." + } + }, + "login": { + "title": "Sign in", + "subtitle": "Sign in to your SlpModularCms account", + "forgotPassword": "Forgot your password?", + "cmsDisabled": "This CMS is disabled.", + "cmsMaintenance": "This CMS is under maintenance.", + "cmsOffAdminsOnly": "Only administrators can sign in right now.", + "email": "Email", + "emailPlaceholder": "you@example.com", + "password": "Password", + "submit": "Sign in", + "submitting": "Signing in…", + "errors": { + "emailRequired": "Email is required", + "emailInvalid": "Enter a valid email address", + "passwordRequired": "Password is required", + "invalidCredentials": "Invalid email or password", + "generic": "Something went wrong. Please try again." + } + }, + "forgotPassword": { + "title": "Forgot password", + "description": "Enter your e-mail address. If it belongs to an account you will get an e-mail with a link to choose a new password.", + "submit": "Send link", + "sentTitle": "Check your e-mail", + "sentMessage": "If this address belongs to an account, an e-mail with a link is on its way. Nothing arrived? Check your spam folder or ask the administrator for help.", + "backToLogin": "Back to sign in", + "unavailable": "Resetting your password by e-mail is not available on this site. Ask the administrator for help." + }, + "resetPassword": { + "title": "Choose a new password", + "description": "Choose a new password for your account.", + "passwordLabel": "New password", + "confirmLabel": "Confirm new password", + "submit": "Save password", + "success": "Your password has been changed. You can sign in now.", + "passwordRejected": "This password does not meet the requirements. Choose another one.", + "invalidTitle": "Link invalid or expired", + "invalidMessage": "This link has expired, was already used or is invalid. Request a new link.", + "requestNew": "Request a new link" + }, + "setup": { + "title": "Create first account", + "nameLabel": "Display name", + "emailLabel": "Email", + "passwordLabel": "Password", + "confirmPasswordLabel": "Confirm password", + "languageLabel": "Language preference", + "tokenLabel": "Setup token", + "tokenHelp": "Required to create the first administrator. You received it from whoever installed this site.", + "tokenRequiredError": "Enter the setup token.", + "tokenInvalid": "The setup token is missing or incorrect.", + "submitButton": "Create owner account", + "successMessage": "Account created. You can now sign in." + }, + "inviteComplete": { + "title": "Complete your account", + "emailLabel": "Email", + "nameLabel": "Display name", + "passwordLabel": "Password", + "confirmPasswordLabel": "Confirm password", + "submitButton": "Complete setup", + "loadingMessage": "Validating your invitation…", + "invalidTitle": "Link invalid or expired", + "invalidTokenMessage": "This invitation link has expired or is invalid.", + "toLogin": "Go to sign in", + "successMessage": "Account setup complete. You can now sign in." + }, + "dashboard": { + "title": "Dashboard", + "welcome": "Welcome back, {{name}}" + }, + "availability": { + "title": "System Status", + "available": "Available", + "maintenance": "Maintenance", + "unavailable": "Unavailable", + "messageAvailable": "System is running normally.", + "messageMaintenance": "System is undergoing scheduled maintenance.", + "messageUnavailable": "System is currently unavailable.", + "errorTitle": "Could not load status", + "staleLabel": "Last known status", + "retry": "Retry" + }, + "userMenu": { + "language": "Language", + "logout": "Sign out" + }, + "users": { + "title": "Users", + "inviteButton": "Invite User", + "table": { + "name": "Name", + "email": "Email", + "role": "Role", + "status": "Status", + "createdAt": "Created", + "actions": "Actions" + }, + "status": { + "active": "Active", + "inactive": "Inactive", + "pendingInvite": "Pending invite", + "inviteExpired": "Invitation expired" + }, + "actions": { + "copyInviteLink": "Copy invite link", + "regenerateInvite": "Create new invite link", + "resendInvite": "Resend invitation by e-mail", + "inviteRegeneratedMailed": "New invite link created and e-mailed to {{email}}. The old link no longer works.", + "inviteRegenerated": "New invite link copied to clipboard. The old link no longer works.", + "changeRole": "Change role", + "deactivate": "Deactivate", + "activate": "Activate", + "delete": "Delete user", + "linkCopied": "Invite link copied to clipboard", + "roleChanged": "Role of {{name}} changed to {{role}}" + }, + "active": { + "successDeactivated": "{{name}} has been deactivated.", + "successActivated": "{{name}} has been activated." + }, + "regenerate": { + "title": "Create new invite link", + "description": "A new link is created for {{email}}. The old link stops working. The new link is copied so you can share it yourself.", + "descriptionMail": "A new link is created for {{email}}. The old link stops working. Do you also want to send the new link by e-mail?", + "copyOnly": "Copy link only", + "copyAndMail": "Copy link and send e-mail", + "create": "Create and copy link" + }, + "delete": { + "title": "Delete user", + "description": "Are you sure you want to delete {{name}} ({{email}})? This action cannot be undone.", + "descriptionNoName": "Are you sure you want to delete {{email}}? This action cannot be undone.", + "descriptionPending": "Are you sure you want to delete the pending invitation for {{email}}? This action cannot be undone.", + "confirmButton": "Delete", + "success": "{{name}} has been deleted." + }, + "invite": { + "title": "Invite User", + "emailLabel": "Email address", + "roleLabel": "Role", + "rolePlaceholder": "Select a role", + "submitButton": "Send invitation", + "step2Title": "Invitation created", + "languageLabel": "Invitation language", + "languageHelp": "The language of the e-mail and the preferred language of the new account.", + "mailSent": "Invitation e-mail sent to {{email}}.", + "mailFailed": "The e-mail could not be sent ({{reason}}). Copy the link and share it yourself, or try e-mailing again later.", + "mailErrors": { + "timeout": "the mail server did not respond in time", + "timeout_connect": "the mail server did not respond in time while connecting", + "timeout_auth": "the mail server did not respond in time while signing in", + "timeout_send": "the mail server did not respond in time while sending", + "auth_failed": "signing in to the mail server failed", + "rejected": "the mail server or the address refused the message", + "rejected_sender": "the mail server does not accept this sender address for this account", + "rejected_recipient": "the mail server will not deliver to this address", + "tls_failed": "the secure connection to the mail server failed", + "connection_failed": "no connection to the mail server", + "not_configured": "e-mail is not set up", + "unknown": "unknown error" + }, + "step2Description": "Share the link below with the invitee.", + "linkLabel": "Invite link", + "copyLink": "Copy link", + "close": "Close" + }, + "roles": { + "Owner": "Owner", + "Administrator": "Administrator", + "User": "User" + }, + "ownerAssign": { + "title": "Assign Owner role", + "description": "You are about to make {{name}} an Owner. Owners have full access to the system, including the ability to manage and remove other Owners. Are you sure?", + "confirmButton": "Make Owner" + }, + "selfRoleChange": { + "title": "Change your own role", + "description": "You are about to change your own role to {{role}}. You will be logged out automatically so the change takes effect immediately.", + "confirmButton": "Change and log out" + }, + "errors": { + "lastOwnerRequired": "At least one Owner must remain. Assign another Owner before changing this role.", + "insufficientPermissions": "You do not have permission to perform this action." + } + }, + "profile": { + "title": "My Profile", + "name": "Display name", + "email": "Email address", + "role": "Role", + "save": "Save changes", + "saving": "Saving…", + "saveSuccess": "Profile updated successfully", + "securityTitle": "Change password", + "language": "Language", + "languageDefault": "Site default", + "languageHelp": "The language of the admin and of e-mails you receive.", + "changePassword": "Change password", + "changePasswordDialog": { + "title": "Change Password", + "new": "New password", + "confirm": "Confirm new password", + "submit": "Change password", + "submitting": "Changing…", + "success": "Password changed successfully", + "errorCurrent": "Current password is incorrect" + } + }, + "settings": { + "title": "System Settings", + "mail": { + "title": "E-mail", + "description": "The address and name this site sends e-mails from (invitations, password reset, notices).", + "fromAddress": "Sender address", + "fromAddressHelp": "Only addresses allowed for this installation (SPF/DKIM). Another address can only be added by whoever manages the server.", + "fromName": "Sender name", + "nameTooLong": "The name can be at most 80 characters.", + "save": "Save", + "reset": "Restore default", + "saveSuccess": "E-mail settings saved", + "resetSuccess": "Default settings restored", + "invalid": "These settings are not valid.", + "readOnly": "Only the owner can change these settings." + }, + "availability": { + "title": "System Availability", + "mode": "Availability mode", + "reason": "Message (optional)", + "save": "Update availability", + "saving": "Updating…", + "saveSuccess": "Availability updated", + "modes": { + "Available": "Available", + "Maintenance": "Maintenance", + "NotAvailable": "Unavailable" + }, + "masterControlledTitle": "Controlled by Master CMS", + "masterControlled": "This instance has been disabled by the Master CMS. Availability cannot be changed here until the Master releases it.", + "masterControlledSaveError": "Cannot be changed: the Master CMS controls this status." + }, + "modules": { + "title": "Module Management", + "comingSoon": "Coming soon" + }, + "systemConfig": { + "title": "System Configuration", + "comingSoon": "Coming soon" + }, + "branding": { + "title": "Branding / Theme", + "comingSoon": "Coming soon" + } + }, + "cms": { + "title": "CMS Instances", + "addButton": "Add CMS", + "emptyState": { + "heading": "No CMS instances yet", + "description": "Add your first CMS instance to get started." + }, + "table": { + "name": "Name", + "url": "URL", + "status": "Status", + "lastContact": "Last Contact", + "disableMessage": "Disable Message", + "actions": "Actions" + }, + "status": { + "Available": "Available", + "NotAvailable": "Unavailable", + "Inactive": "Inactive" + }, + "actions": { + "setStatus": "Set Status" + }, + "add": { + "title": "Add CMS Instance", + "nameLabel": "Name", + "urlLabel": "URL", + "apiKeyLabel": "API Key", + "submitButton": "Add", + "successToast": "CMS instance added successfully", + "errors": { + "conflict": "A CMS instance with this name or URL already exists." + } + }, + "setStatus": { + "title": "Set Status", + "statusLabel": "Status", + "disableMessageLabel": "Disable Message", + "disableMessagePlaceholder": "Reason for disabling…", + "submitButton": "Save", + "successContactedToast": "Status updated — cliënt confirmed", + "successUnreachableToast": "Status saved — cliënt unreachable" + } + }, + "offerings": { + "title": "Offerings", + "addButton": "Add Offering", + "banners": { + "intro": "A banner is a wide announcement or promotion on the website. Plan ahead with a start and end time. At most one banner is shown per location (top and bottom) at any time: the most recently changed active one.", + "position": { + "label": "Location", + "top": "Top", + "bottom": "Bottom" + }, + "shownBadge": "Live", + "notShownBadge": "Not shown", + "notShownHint": "Not shown: a newer banner at this location", + "turnOffButton": "Turn banner off", + "turnOnButton": "Turn banner on", + "titleLabelOptional": "Title (optional)", + "textTooLong": "The text is {{length}} characters; this location allows at most {{max}}. Shorten the text or pick another location.", + "textHintTop": "One short line, up to 120 characters.", + "addButton": "Add banner", + "empty": "No banners yet.", + "editButton": "Edit banner", + "deleteButton": "Delete banner", + "createTitle": "New banner", + "editTitle": "Edit banner", + "titleLabel": "Title", + "textLabel": "Text", + "linkLabelLabel": "Button text (optional)", + "linkUrlLabel": "Link (optional)", + "linkHint": "Button text and link go together. A link starts with https:// or is a path on the site, for example /privacy.", + "startsLabel": "Visible from (optional)", + "endsLabel": "Visible until (optional)", + "scheduleHint": "Times are in your time zone. On Andrea's website the schedule applies at the next (nightly) build.", + "activeLabel": "Enabled", + "savedToast": "Banner saved", + "deletedToast": "Banner deleted", + "deleteTitle": "Delete banner", + "deleteMessage": "Are you sure you want to delete the banner \"{{title}}\"?", + "deleteConfirm": "Delete", + "status": { + "live": "Active", + "scheduled": "Scheduled", + "expired": "Expired", + "off": "Off" + }, + "tabPackages": "Offerings", + "tabBanner": "Banner", + "tabsLabel": "Sections" + }, + "categories": { + "manageButton": "Manage categories", + "title": "Manage categories", + "emptyState": "No categories yet. Add the first one.", + "offeringCount_one": "{{count}} offering", + "offeringCount_other": "{{count}} offerings", + "newLabel": "New category", + "addButton": "Add", + "editButton": "Rename category", + "confirmEditButton": "Confirm name", + "cancelButton": "Cancel", + "deleteButton": "Delete category", + "deleteConfirm": "Are you sure?", + "deleteConfirmButton": "Delete", + "errors": { + "nameRequired": "Enter a name.", + "nameTooLong": "The name can be at most 100 characters.", + "duplicate": "A category named '{{name}}' already exists.", + "inUse": "This category is still used by {{count}} offering(s). Move them to another category first." + } + }, + "emptyState": { + "heading": "No offerings yet", + "description": "Add your first offering to get started." + }, + "table": { + "title": "Title", + "price": "Price", + "featured": "Featured", + "actions": "Actions" + }, + "actions": { + "turnOff": "Switch package off", + "turnOn": "Switch package on", + "drag": "Drag to reorder", + "edit": "Edit", + "delete": "Delete", + "moveUp": "Move up", + "moveDown": "Move down", + "markFeatured": "Mark as featured", + "unmarkFeatured": "Remove featured" + }, + "deleteDialog": { + "title": "Delete offering", + "message": "Are you sure you want to delete '{{title}}'?", + "confirmButton": "Delete", + "cancelButton": "Cancel" + }, + "form": { + "createTitle": "New Offering", + "editTitle": "Edit Offering", + "activeLabel": "Switched on", + "startsLabel": "Visible from (optional)", + "endsLabel": "Visible until (optional)", + "scheduleHint": "A switched-off or planned package is not shown on the website. Times are in your time zone. On Andrea's website the schedule applies at the next (nightly) build.", + "endBeforeStart": "The end must be after the start.", + "titleLabel": "Title", + "slugLabel": "Slug", + "slugAutoHint": "Auto-generated from the title", + "editSlugButton": "Edit", + "confirmSlugButton": "Confirm slug", + "cancelSlugEditButton": "Cancel slug edit", + "descriptionLabel": "Description (optional)", + "priceLabel": "Price", + "priceNoteLabel": "Price note (optional)", + "featuresLabel": "Features", + "addFeatureButton": "Add feature", + "removeFeatureButton": "Remove", + "ctaLabelLabel": "Button text", + "featuredLabel": "Featured", + "categoryLabel": "Category", + "noCategory": "No category", + "submitButton": "Save", + "successToast": "Offering saved successfully" + } + }, + "error": { + "403": { + "title": "Access Denied", + "message": "You don't have permission to view this page." + }, + "404": { + "title": "Page Not Found", + "message": "The page you're looking for doesn't exist." + }, + "backToDashboard": "Back to Dashboard", + "unexpected": { + "title": "Something went wrong", + "message": "This page could not be displayed. Try again, or go back to the dashboard." + } + }, + "errors": { + "network": "Unable to reach the server. Check your connection and try again.", + "generic": "Something went wrong. Please try again.", + "accessDenied": "You do not have permission to access this page.", + "setupRequired": "System setup required. Please initialize the system first.", + "invalidInvitationToken": "Invalid or expired invitation token.", + "featureUnavailableTitle": "Not available on this instance", + "featureUnavailable": "This feature is only available on a Master CMS instance." + }, + "contact": { + "title": "Messages", + "switch": { + "title": "Contact form on the website", + "stateOn": "The form is on: visitors can send you a message.", + "stateOff": "The form is off: visitors only see your e-mail address.", + "on": "On", + "off": "Off", + "turnOn": "Turn on", + "turnOff": "Turn off", + "nowOn": "The contact form is now on.", + "nowOff": "The contact form is now off.", + "shortLabel": "Contact form on/off", + "explanation": "While the form is off, visitors only see your e-mail address. Turning it off helps against spam or during maintenance.", + "firstTimeHint": "The form stays closed until you turn it on.", + "hostOff": "The form is switched off at server level.", + "noRecipientBanner": "No recipient address is set: messages are kept but not mailed. Enter an address below." + }, + "filter": { + "label": "Filter messages", + "inbox": "Inbox", + "new": "New", + "read": "Read", + "archived": "Archived", + "spam": "Spam" + }, + "table": { + "received": "Received", + "name": "Name", + "email": "E-mail address", + "subject": "Subject", + "status": "Status", + "mail": "Mail" + }, + "status": { + "new": "New", + "read": "Read", + "archived": "Archived", + "spam": "Spam", + "converted": "Converted" + }, + "mailStatus": { + "pending": "Mail waiting to be sent", + "sent": "Mail sent", + "failed": "Mail failed", + "notApplicable": "No mail applicable" + }, + "empty": { + "inbox": "No messages yet.", + "new": "No new messages.", + "read": "No read messages.", + "archived": "No archived messages.", + "spam": "No spam." + }, + "pager": { + "range": "{{from}}–{{to}} of {{total}}", + "previous": "Previous", + "next": "Next" + }, + "tabs": { + "label": "Messages sections", + "messages": "Messages", + "settings": "Settings" + }, + "unread": { + "label": "Unread" + }, + "tile": { + "unread_one": "unread message", + "unread_other": "unread messages", + "error": "The number of unread messages could not be loaded." + }, + "detail": { + "title": "Message", + "retention": "Kept until", + "attempts": "({{count}} attempts)", + "nextAttempt": "Next attempt: {{time}}", + "delete": "Delete", + "resend": "Send mail again", + "archive": "Archive", + "restore": "Restore", + "markUnread": "Mark as unread", + "notSpam": "Not spam" + }, + "resend": { + "sent": "Sent.", + "notSent": "Not sent (mail is off).", + "mailOff": "Mail is off on this site." + }, + "deleteDialog": { + "title": "Delete message?", + "message": "The message is deleted permanently. This cannot be undone.", + "confirm": "Delete" + }, + "errors": { + "rateLimited": "Try again in {{seconds}} seconds.", + "spamResend": "Mark the message as not spam first.", + "notFound": "This message no longer exists." + }, + "mailError": { + "disabled": "Mail is off.", + "recipient_not_configured": "No recipient is configured.", + "not_configured": "Mail is not configured.", + "timeout": "The mail server was too slow.", + "timeout_connect": "Connecting to the mail server took too long.", + "timeout_auth": "Logging in to the mail server took too long.", + "timeout_send": "Sending took too long.", + "auth_failed": "Logging in to the mail server failed.", + "rejected": "The mail server refused the message.", + "rejected_sender": "The mail server refused the sender address.", + "rejected_recipient": "The mail server refused the recipient.", + "tls_failed": "The secure connection to the mail server failed.", + "connection_failed": "Cannot reach the mail server.", + "unknown": "Unknown error while sending." + }, + "recipient": { + "title": "Recipient address for contact messages", + "description": "We mail every new message to this address. You can reply to that mail directly: the reply goes to the visitor.", + "label": "E-mail address", + "placeholder": "name@example.com", + "save": "Save", + "reset": "Back to the server setting", + "saved": "Recipient address saved.", + "cleared": "The server setting applies again.", + "invalid": "Enter a valid e-mail address.", + "source": { + "setting": "Messages go to this address.", + "config": "No address of your own is set: the server setting applies.", + "none": "There is no recipient address yet: messages are kept but not mailed." + } + } + }, + "hero": { + "title": "Hero", + "live": "Live", + "notLive": "Not live", + "intro": "The hero is the first thing visitors of the website see: a large heading with one or more photos. Here you manage the texts, the buttons and the photos. A change is visible within about a minute.", + "savedToast": "Hero saved", + "fields": { + "title": "Title", + "titleHint": "A new line in this field is a line break in the title (at most 5 lines).", + "tagline": "Short text above the title (optional)", + "lead": "Introduction (optional)", + "display": "Display" + }, + "display": { + "single": "Single", + "slideshow": "Slideshow" + }, + "buttons": { + "title": "Buttons", + "hint": "At most two buttons. As the target, choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…).", + "label": "Button {{n}}: text", + "target": "Button {{n}}: target" + }, + "library": { + "title": "Add slide", + "description": "Choose a photo from the media library or upload a new one; it then lands in the library too. Every slide has one photo. A slide's photo is not changed: remove the slide and add a new one.", + "group": "Photo for the new slide", + "sharedCrop": "This photo is in more slides; the crop applies to all of them." + }, + "slides": { + "title": "Images", + "add": "Add slide", + "uploading": "Uploading…", + "hint": "Choose several files at once or drag them into this box. New photos are added at the bottom of the list. Drag a photo by its handle, or use the arrows, to change the order; visitors see the first photo first. With the Focus button you show where the subject is.", + "empty": "No images yet.", + "alt": "Description", + "decorative": "Hide from screen readers", + "up": "Move up", + "down": "Move down", + "remove": "Remove slide", + "ceiling": "Only the first {{max}} images are shown on the website.", + "focusPending": "Focus changed, not saved yet.", + "processing": "Processing…", + "processingHint": "The image is being prepared in the background; it appears on the website as soon as it is ready.", + "failed": "Failed", + "limits": "Allowed: {{formats}}. At most {{size}} MB per file and {{megapixels}} megapixels.", + "altHint": "Describes the photo for people who cannot see it and for search engines.", + "drag": "Move image {{n}}", + "dragInstructions": "Press space to pick up the image, use the arrow keys to move it and press space again to drop it. Escape cancels.", + "recut": "Making the new crop…", + "recutHint": "You still see the old crop. The change is only on the website when this is done.", + "activeOn": "Active", + "activeOff": "Not active", + "activeFor": "show image {{n}} on the website", + "number": "Slide {{n}}", + "done": "Processing finished", + "doneFor": "Slide {{n}}: processing finished", + "cropEdit": "Adjust crop" + }, + "processing": { + "count": "{{done}} of {{total}} photos processed", + "label": "Progress of processing the photos", + "explain": "The hero has been saved. The photos are prepared one by one and go live as soon as they are ready. Until the first photo is ready the website keeps its standard hero. You do not have to keep this page open.", + "failed_one": "Processing {{count}} photo failed.", + "failed_other": "Processing {{count}} photos failed.", + "failedHint": "The server tried three times. Try again, or upload the photo once more (the same photo is the same image).", + "retry": "Try again", + "current": "Working on photo {{n}} of {{total}}: step {{step}} of {{steps}}. A large photo can take a few minutes.", + "stuck": "Taking long?" + }, + "focus": { + "title": "Focus and crop", + "intro": "Click or drag on the photo to show where the subject is. The website crops the photo for landscape and portrait screens so that the subject stays in view.", + "targetLegend": "For which display", + "target": { + "general": "General", + "wide": "Landscape (3:2)", + "tall": "Portrait (4:5)" + }, + "override": "Own setting for this display", + "areaLabel": "Photo: choose the point of the subject", + "areaHint": "The arrow keys move the point (faster with Shift).", + "x": "Horizontal (%)", + "y": "Vertical (%)", + "zoom": "Zoom ({{value}}×)", + "preview": { + "wide": "Landscape preview", + "tall": "Portrait preview" + }, + "apply": "Apply", + "applyHint": "The change only takes effect when you save the hero. If you leave the page without saving it is dropped.", + "previewPending": "The preview of this photo is being prepared. Close this window and try again in a few seconds." + }, + "errors": { + "titleRequired": "A title is required.", + "titleTooLong": "The title can have at most 200 characters.", + "titleTooManyLines": "The title can have at most 5 lines.", + "taglineTooLong": "The short text above the title can have at most 120 characters.", + "leadTooLong": "The introduction can have at most 600 characters.", + "buttonLabelTooLong": "The button text can have at most 50 characters.", + "buttonTargetTooLong": "The target can have at most 500 characters.", + "buttonIncomplete": "Fill in both the text and the target of the button, or leave both empty.", + "buttonTargetInvalid": "Choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…).", + "altTooLong": "The description can have at most 300 characters.", + "altRequired": "Give a description or choose ‘Decoration only’." + }, + "upload": { + "tooLarge": "The image is too large (at most {{max}} MB).", + "interrupted": "The upload was interrupted. Check the connection and try again.", + "busy": "Too many uploads in a row. Try again in a few minutes.", + "notAnImage": "This file is not an image.", + "progress": "Uploading: {{done}} of {{total}}", + "summary": "{{ok}} of {{total}} photos added", + "waiting": "waiting", + "uploading": "uploading…", + "done": "added", + "close": "Close" + }, + "help": { + "heading": "Explanation of each part", + "save": "Changes only take effect after you save the hero.", + "title": { + "name": "Title", + "text": "The large heading. A new line in the field is a new line in the heading." + }, + "tagline": { + "name": "Short text above the title", + "text": "A short label above or before the title. Can stay empty." + }, + "lead": { + "name": "Introduction", + "text": "One or two sentences below the title. Can stay empty." + }, + "buttons": { + "name": "Buttons", + "text": "At most two, each with a text and a target. As the target, choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…)." + }, + "display": { + "name": "Display", + "text": "‘Single’ shows one photo, ‘Slideshow’ switches between the photos." + }, + "slides": { + "name": "Images", + "text": "Upload photos, describe what is in them and set the order (drag or use the arrows). The switch makes a photo active or not active. Choose ‘Hide from screen readers’ for a photo that adds nothing to the content." + }, + "focus": { + "name": "Focus", + "text": "Show where the subject is in the photo, so a crop never cuts it off. For portrait screens, such as a phone, you can choose a separate point." + } + }, + "unsaved": { + "badge": "Unsaved changes", + "text": "Save the hero to put them on the website.", + "leaveTitle": "Changes not saved", + "leaveText": "You have made changes that are not saved yet. If you leave this page they will be lost.", + "stay": "Stay", + "discard": "Discard changes" + }, + "saving": "Saving…", + "tabs": { + "label": "Hero sections", + "content": "Content", + "images": "Images", + "busy": "{{count}} busy", + "hasChanges": "unsaved changes", + "hasErrors": "has errors" + } + }, + "media": { + "progress": { + "working": "Processing…" + }, + "module": { + "hero": "Hero" + }, + "use": { + "slide": "slide", + "none": "Not used", + "off": "off", + "noneSince": "Not used since {{date}}" + }, + "list": { + "label": "Photos", + "empty": "There are no photos.", + "selectAll": "Select all", + "noThumbnail": "No preview", + "photoName": "Photo {{width}} × {{height}}" + }, + "bulk": { + "label": "Actions on the selection", + "selected_one": "{{count}} photo selected", + "selected_other": "{{count}} photos selected", + "clear": "Clear selection" + }, + "loading": "Loading...", + "error": "The media library could not be loaded.", + "page": { + "title": "Media library", + "noModules": "No module reports photos yet." + }, + "storage": { + "title": "Storage", + "used": "{{used}} used", + "usedOf": "{{used}} of {{limit}} used ({{percent}}%)", + "warning": "Storage is more than {{percent}}% full. Clean up photos before the limit is reached.", + "full": "Storage is full. No more photos can be uploaded until there is room." + }, + "cleanup": { + "open": "Clean up", + "title": "Clean up", + "description": "Photos older than the number of days below, newest first. Take out the photos you want to keep.", + "days_one": "Older than {{count}} day", + "days_other": "Older than {{count}} days", + "onlyUnused": "Only unused photos", + "summary_one": "{{count}} photo ({{size}}) qualifies.", + "summary_other": "{{count}} photos ({{size}}) qualify.", + "selectedSize": "Selected: {{size}}", + "trashNote": "The selected photos go to the trash and can be restored for 7 days.", + "confirm_one": "{{count}} photo to the trash", + "confirm_other": "{{count}} photos to the trash" + }, + "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." + }, + "view": { + "label": "View", + "library": "Library", + "trash": "Trash" + }, + "trash": { + "since": "In the trash since {{date}}", + "restore": "Restore", + "note": "Photos in the trash are removed for good after 7 days (default). Restore them while you can, or delete them for good now." + }, + "delete": { + "action": "Move to trash", + "title": "Move photos to the trash", + "confirm_one": "This photo goes to the trash. You can restore it for 7 days.", + "confirm_other": "These {{count}} photos go to the trash. You can restore them for 7 days.", + "inUseCount_one": "{{count}} photo is still in use.", + "inUseCount_other": "{{count}} photos are still in use.", + "secondTitle": "Delete photos that are in use?", + "secondText_one": "This photo is still in use. If you go on, it disappears from the places below (in the Hero the slide is removed).", + "secondText_other": "These photos are still in use. If you go on, they disappear from the places below (in the Hero the slide is removed).", + "confirmButton": "Move to trash", + "confirmSecond": "Yes, delete anyway", + "cancel": "Cancel", + "close": "Close", + "partial_one": "{{count}} photo could not be deleted. The rest went to the trash.", + "partial_other": "{{count}} photos could not be deleted. The rest went to the trash." + }, + "filter": { + "label": "Filter", + "all": "All photos", + "used": "Used", + "unused": "Unused" + }, + "purge": { + "action": "Delete for good", + "title": "Delete for good", + "emptyTitle": "Empty the trash", + "emptyButton": "Empty the trash", + "emptyConfirm": "Empty the trash", + "confirmButton": "Delete for good", + "confirm_one": "This photo is deleted for good, with its files.", + "confirm_other": "These {{count}} photos are deleted for good, with their files.", + "confirmAll_one": "The trash is emptied: {{count}} photo ({{size}}) is deleted for good.", + "confirmAll_other": "The trash is emptied: {{count}} photos ({{size}}) are deleted for good.", + "irreversible": "This cannot be undone.", + "partial_one": "{{count}} photo could not be deleted. The rest was deleted for good.", + "partial_other": "{{count}} photos could not be deleted. The rest was deleted for good." + } + } +} diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index bca6a5a..ce0d1d6 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -1,901 +1,900 @@ -{ - "common": { - "appName": "SlpModularCms", - "loading": "Laden…", - "cancel": "Annuleren", - "save": "Opslaan", - "retry": "Opnieuw" - }, - "nav": { - "dashboard": "Dashboard", - "users": "Gebruikers", - "cms": "CMS", - "offerings": "Aanbiedingen", - "messages": "Berichten", - "profile": "Profiel", - "settings": "Instellingen", - "openMenu": "Navigatie openen", - "closeMenu": "Navigatie sluiten", - "hero": "Hero", - "media": "Mediabibliotheek", - "unreadMessages_one": "{{count}} nieuw bericht", - "unreadMessages_other": "{{count}} nieuwe berichten" - }, - "theme": { - "title": "Thema", - "label": "Thema: {{mode}}", - "labelAuto": "Thema: automatisch (nu {{now}})", - "mode": { - "light": "Licht", - "dark": "Donker", - "auto": "Automatisch" - } - }, - "session": { - "unreachable": { - "title": "Sessie kon niet worden gecontroleerd", - "description": "De server is even niet bereikbaar of te druk. Je bent niet uitgelogd. Probeer het over een paar seconden opnieuw.", - "retry": "Opnieuw proberen", - "stillFailing": "Nog steeds geen antwoord. Wacht even en probeer opnieuw." - } - }, - "login": { - "title": "Inloggen", - "subtitle": "Log in op je SlpModularCms-account", - "forgotPassword": "Wachtwoord vergeten?", - "cmsDisabled": "Dit CMS is uitgeschakeld.", - "cmsMaintenance": "Dit CMS is in onderhoud.", - "cmsOffAdminsOnly": "Alleen beheerders kunnen nu inloggen.", - "email": "E-mail", - "emailPlaceholder": "jij@voorbeeld.nl", - "password": "Wachtwoord", - "submit": "Inloggen", - "submitting": "Bezig met inloggen…", - "errors": { - "emailRequired": "E-mail is verplicht", - "emailInvalid": "Voer een geldig e-mailadres in", - "passwordRequired": "Wachtwoord is verplicht", - "invalidCredentials": "Ongeldige e-mail of wachtwoord", - "generic": "Er is iets misgegaan. Probeer het opnieuw." - } - }, - "forgotPassword": { - "title": "Wachtwoord vergeten", - "description": "Vul je e-mailadres in. Hoort het bij een account, dan krijg je een e-mail met een link om een nieuw wachtwoord te kiezen.", - "submit": "Link versturen", - "sentTitle": "Controleer je e-mail", - "sentMessage": "Als dit adres bij een account hoort, is er een e-mail met een link onderweg. Geen e-mail gekregen? Kijk ook in je spam of vraag de beheerder om hulp.", - "backToLogin": "Terug naar inloggen", - "unavailable": "Wachtwoord opnieuw instellen per e-mail is op deze site niet beschikbaar. Vraag de beheerder om hulp." - }, - "resetPassword": { - "title": "Nieuw wachtwoord kiezen", - "description": "Kies een nieuw wachtwoord voor je account.", - "passwordLabel": "Nieuw wachtwoord", - "confirmLabel": "Nieuw wachtwoord bevestigen", - "submit": "Wachtwoord opslaan", - "success": "Je wachtwoord is gewijzigd. Je kunt nu inloggen.", - "passwordRejected": "Dit wachtwoord voldoet niet aan de eisen. Kies een ander wachtwoord.", - "invalidTitle": "Link ongeldig of verlopen", - "invalidMessage": "Deze link is verlopen, al gebruikt of ongeldig. Vraag een nieuwe link aan.", - "requestNew": "Nieuwe link aanvragen" - }, - "setup": { - "title": "Eerste account aanmaken", - "nameLabel": "Weergavenaam", - "emailLabel": "E-mail", - "passwordLabel": "Wachtwoord", - "confirmPasswordLabel": "Wachtwoord bevestigen", - "languageLabel": "Taalkeuze", - "tokenLabel": "Setup-token", - "tokenHelp": "Nodig om de eerste beheerder aan te maken. Je hebt het ontvangen van degene die deze site heeft geïnstalleerd.", - "tokenRequiredError": "Vul het setup-token in.", - "tokenInvalid": "Het setup-token ontbreekt of is onjuist.", - "submitButton": "Owner-account aanmaken", - "successMessage": "Account aangemaakt. Je kunt nu inloggen." - }, - "inviteComplete": { - "title": "Account voltooien", - "emailLabel": "E-mail", - "nameLabel": "Weergavenaam", - "passwordLabel": "Wachtwoord", - "confirmPasswordLabel": "Wachtwoord bevestigen", - "submitButton": "Setup voltooien", - "loadingMessage": "Uitnodiging valideren…", - "invalidTitle": "Link ongeldig of verlopen", - "invalidTokenMessage": "Deze uitnodigingslink is verlopen, ingetrokken of ongeldig. Vraag de beheerder om een nieuwe uitnodiging.", - "toLogin": "Naar inloggen", - "successMessage": "Account-setup voltooid. Je kunt nu inloggen." - }, - "dashboard": { - "title": "Dashboard", - "welcome": "Welkom terug, {{name}}" - }, - "availability": { - "title": "Systeemstatus", - "available": "Beschikbaar", - "maintenance": "Onderhoud", - "unavailable": "Niet beschikbaar", - "messageAvailable": "Systeem werkt normaal.", - "messageMaintenance": "Het systeem ondergaat gepland onderhoud.", - "messageUnavailable": "Het systeem is momenteel niet beschikbaar.", - "errorTitle": "Status kon niet worden geladen", - "staleLabel": "Laatste bekende status", - "retry": "Opnieuw proberen" - }, - "userMenu": { - "language": "Taal", - "logout": "Uitloggen" - }, - "users": { - "title": "Gebruikers", - "inviteButton": "Gebruiker uitnodigen", - "table": { - "name": "Naam", - "email": "E-mail", - "role": "Rol", - "status": "Status", - "createdAt": "Aangemaakt", - "actions": "Acties" - }, - "status": { - "active": "Actief", - "inactive": "Inactief", - "pendingInvite": "Uitnodiging in behandeling", - "inviteExpired": "Uitnodiging verlopen" - }, - "actions": { - "copyInviteLink": "Uitnodigingslink kopiëren", - "regenerateInvite": "Nieuwe uitnodigingslink maken", - "resendInvite": "Uitnodiging opnieuw mailen", - "inviteRegeneratedMailed": "Nieuwe uitnodigingslink gemaakt en gemaild naar {{email}}. De oude link werkt niet meer.", - "inviteRegenerated": "Nieuwe uitnodigingslink gekopieerd naar klembord. De oude link werkt niet meer.", - "changeRole": "Rol wijzigen", - "deactivate": "Deactiveren", - "activate": "Activeren", - "delete": "Gebruiker verwijderen", - "linkCopied": "Uitnodigingslink gekopieerd naar klembord", - "roleChanged": "Rol van {{name}} gewijzigd naar {{role}}" - }, - "active": { - "successDeactivated": "{{name}} is gedeactiveerd.", - "successActivated": "{{name}} is geactiveerd." - }, - "regenerate": { - "title": "Nieuwe uitnodigingslink maken", - "description": "Er wordt een nieuwe link gemaakt voor {{email}}. De oude link werkt daarna niet meer. De nieuwe link wordt gekopieerd, zodat je hem zelf kunt delen.", - "descriptionMail": "Er wordt een nieuwe link gemaakt voor {{email}}. De oude link werkt daarna niet meer. Wil je de nieuwe link ook per e-mail versturen?", - "copyOnly": "Alleen link kopiëren", - "copyAndMail": "Link kopiëren en mailen", - "create": "Link maken en kopiëren" - }, - "delete": { - "title": "Gebruiker verwijderen", - "description": "Weet je zeker dat je {{name}} ({{email}}) wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.", - "descriptionNoName": "Weet je zeker dat je {{email}} wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.", - "descriptionPending": "Weet je zeker dat je de openstaande uitnodiging voor {{email}} wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.", - "confirmButton": "Verwijderen", - "success": "{{name}} is verwijderd." - }, - "invite": { - "title": "Gebruiker uitnodigen", - "emailLabel": "E-mailadres", - "roleLabel": "Rol", - "rolePlaceholder": "Selecteer een rol", - "submitButton": "Uitnodiging versturen", - "step2Title": "Uitnodiging aangemaakt", - "step2Description": "Deel de onderstaande link met de genodigde.", - "languageLabel": "Taal van de uitnodiging", - "languageHelp": "De taal van de e-mail en de voorkeurstaal van het nieuwe account.", - "mailSent": "E-mail met de uitnodiging verstuurd naar {{email}}.", - "mailFailed": "De e-mail kon niet worden verstuurd ({{reason}}). Kopieer de link en deel die zelf, of probeer later opnieuw te mailen.", - "mailErrors": { - "timeout": "de mailserver reageerde niet op tijd", - "timeout_connect": "de mailserver reageerde niet op tijd tijdens het verbinden", - "timeout_auth": "de mailserver reageerde niet op tijd tijdens het inloggen", - "timeout_send": "de mailserver reageerde niet op tijd tijdens het versturen", - "auth_failed": "inloggen op de mailserver mislukt", - "rejected": "de mailserver of het adres weigerde het bericht", - "rejected_sender": "de mailserver accepteert dit afzenderadres niet voor dit account", - "rejected_recipient": "de mailserver wil niet naar dit adres versturen", - "tls_failed": "beveiligde verbinding met de mailserver mislukt", - "connection_failed": "geen verbinding met de mailserver", - "not_configured": "e-mail is niet ingesteld", - "unknown": "onbekende fout" - }, - "linkLabel": "Uitnodigingslink", - "copyLink": "Link kopiëren", - "close": "Sluiten" - }, - "roles": { - "Owner": "Eigenaar", - "Administrator": "Beheerder", - "User": "Gebruiker" - }, - "ownerAssign": { - "title": "Eigenaarrol toewijzen", - "description": "Je staat op het punt {{name}} eigenaar te maken. Eigenaars hebben volledige toegang tot het systeem, inclusief het kunnen beheren en verwijderen van andere eigenaars. Weet je het zeker?", - "confirmButton": "Eigenaar maken" - }, - "selfRoleChange": { - "title": "Eigen rol wijzigen", - "description": "Je staat op het punt je eigen rol te wijzigen naar {{role}}. Je wordt daarna automatisch uitgelogd zodat de wijziging direct ingaat.", - "confirmButton": "Wijzigen en uitloggen" - }, - "errors": { - "lastOwnerRequired": "Er moet minimaal één Eigenaar blijven. Wijs eerst een andere Eigenaar aan voor je deze rol wijzigt.", - "insufficientPermissions": "Je hebt geen toestemming om deze actie uit te voeren." - } - }, - "profile": { - "title": "Mijn profiel", - "name": "Weergavenaam", - "email": "E-mailadres", - "role": "Rol", - "save": "Wijzigingen opslaan", - "saving": "Opslaan…", - "saveSuccess": "Profiel succesvol bijgewerkt", - "securityTitle": "Wachtwoord wijzigen", - "language": "Taal", - "languageDefault": "Standaard van de site", - "languageHelp": "De taal van de beheeromgeving en van e-mails die je ontvangt.", - "changePassword": "Wachtwoord wijzigen", - "changePasswordDialog": { - "title": "Wachtwoord wijzigen", - "new": "Nieuw wachtwoord", - "confirm": "Nieuw wachtwoord bevestigen", - "submit": "Wachtwoord wijzigen", - "submitting": "Bezig…", - "success": "Wachtwoord succesvol gewijzigd", - "errorCurrent": "Huidig wachtwoord is onjuist" - } - }, - "settings": { - "title": "Systeeminstellingen", - "mail": { - "title": "E-mail", - "description": "Van welk adres en onder welke naam deze site e-mails verstuurt (uitnodigingen, wachtwoord opnieuw instellen, meldingen).", - "fromAddress": "Afzenderadres", - "fromAddressHelp": "Alleen adressen die voor deze installatie zijn toegestaan (SPF/DKIM). Een ander adres kan alleen door de beheerder van de server worden toegevoegd.", - "fromName": "Afzendernaam", - "nameTooLong": "De naam mag hooguit 80 tekens bevatten.", - "save": "Opslaan", - "reset": "Standaard herstellen", - "saveSuccess": "E-mailinstellingen opgeslagen", - "resetSuccess": "Standaardinstellingen hersteld", - "invalid": "Deze instellingen zijn niet geldig.", - "readOnly": "Alleen de eigenaar kan deze instellingen wijzigen." - }, - "availability": { - "title": "Systeembeschikbaarheid", - "mode": "Beschikbaarheidsmodus", - "reason": "Bericht (optioneel)", - "save": "Beschikbaarheid bijwerken", - "saving": "Bijwerken…", - "saveSuccess": "Beschikbaarheid bijgewerkt", - "modes": { - "Available": "Beschikbaar", - "Maintenance": "Onderhoud", - "NotAvailable": "Niet beschikbaar" - }, - "masterControlledTitle": "Beheerd door Master-CMS", - "masterControlled": "Deze instantie is door de Master-CMS uitgeschakeld. De beschikbaarheid kan hier niet worden gewijzigd totdat de Master de status weer vrijgeeft.", - "masterControlledSaveError": "Kan niet worden gewijzigd: de Master-CMS beheert deze status." - }, - "modules": { - "title": "Modulebeheer", - "comingSoon": "Binnenkort beschikbaar" - }, - "systemConfig": { - "title": "Systeemconfiguratie", - "comingSoon": "Binnenkort beschikbaar" - }, - "branding": { - "title": "Huisstijl / Thema", - "comingSoon": "Binnenkort beschikbaar" - } - }, - "cms": { - "title": "CMS-instanties", - "addButton": "CMS toevoegen", - "emptyState": { - "heading": "Nog geen CMS-instanties", - "description": "Voeg uw eerste CMS-instantie toe om aan de slag te gaan." - }, - "table": { - "name": "Naam", - "url": "URL", - "status": "Status", - "lastContact": "Laatste contact", - "disableMessage": "Uitschakelreden", - "actions": "Acties" - }, - "status": { - "Available": "Beschikbaar", - "NotAvailable": "Niet beschikbaar", - "Inactive": "Inactief" - }, - "actions": { - "setStatus": "Status instellen" - }, - "add": { - "title": "CMS-instantie toevoegen", - "nameLabel": "Naam", - "urlLabel": "URL", - "apiKeyLabel": "API-sleutel", - "submitButton": "Toevoegen", - "successToast": "CMS-instantie succesvol toegevoegd", - "errors": { - "conflict": "Er bestaat al een CMS-instantie met deze naam of URL." - } - }, - "setStatus": { - "title": "Status instellen", - "statusLabel": "Status", - "disableMessageLabel": "Uitschakelreden", - "disableMessagePlaceholder": "Reden voor uitschakelen…", - "submitButton": "Opslaan", - "successContactedToast": "Status bijgewerkt — cliënt bevestigd", - "successUnreachableToast": "Status opgeslagen — cliënt niet bereikbaar" - } - }, - "offerings": { - "title": "Aanbiedingen", - "addButton": "Aanbieding toevoegen", - "banners": { - "intro": "Een banner is een brede mededeling of actie op de website. Plan vooruit met een begin- en eindtijd. Per locatie (boven en onder) wordt maximaal één banner getoond: de laatst gewijzigde actieve.", - "position": { - "label": "Locatie", - "top": "Boven", - "bottom": "Onder" - }, - "shownBadge": "Live", - "notShownBadge": "Wordt niet getoond", - "notShownHint": "Wordt niet getoond: nieuwere banner op deze locatie", - "turnOffButton": "Banner uitzetten", - "turnOnButton": "Banner aanzetten", - "titleLabelOptional": "Titel (optioneel)", - "textTooLong": "De tekst is {{length}} tekens; voor deze locatie zijn maximaal {{max}} tekens toegestaan. Kort de tekst in of kies een andere locatie.", - "textHintTop": "Eén korte regel, maximaal 120 tekens.", - "addButton": "Banner toevoegen", - "empty": "Nog geen banners.", - "editButton": "Banner bewerken", - "deleteButton": "Banner verwijderen", - "createTitle": "Nieuwe banner", - "editTitle": "Banner bewerken", - "titleLabel": "Titel", - "textLabel": "Tekst", - "linkLabelLabel": "Knoptekst (optioneel)", - "linkUrlLabel": "Link (optioneel)", - "linkHint": "Knoptekst en link horen bij elkaar. Een link begint met https:// of is een pad op de site, bijvoorbeeld /privacy.", - "startsLabel": "Zichtbaar vanaf (optioneel)", - "endsLabel": "Zichtbaar tot (optioneel)", - "scheduleHint": "Tijden gelden in jouw tijdzone. Bij de website van Andrea geldt de planning bij de eerstvolgende (nachtelijke) build.", - "activeLabel": "Ingeschakeld", - "savedToast": "Banner opgeslagen", - "deletedToast": "Banner verwijderd", - "deleteTitle": "Banner verwijderen", - "deleteMessage": "Weet je zeker dat je de banner \"{{title}}\" wilt verwijderen?", - "deleteConfirm": "Verwijderen", - "status": { - "live": "Actief", - "scheduled": "Gepland", - "expired": "Verlopen", - "off": "Uit" - }, - "tabPackages": "Aanbiedingen", - "tabBanner": "Banner", - "tabsLabel": "Onderdelen" - }, - "categories": { - "manageButton": "Categorieën beheren", - "title": "Categorieën beheren", - "emptyState": "Nog geen categorieën. Voeg de eerste toe.", - "offeringCount_one": "{{count}} aanbieding", - "offeringCount_other": "{{count}} aanbiedingen", - "newLabel": "Nieuwe categorie", - "addButton": "Toevoegen", - "editButton": "Categorie hernoemen", - "confirmEditButton": "Naam bevestigen", - "cancelButton": "Annuleren", - "deleteButton": "Categorie verwijderen", - "deleteConfirm": "Weet je het zeker?", - "deleteConfirmButton": "Verwijderen", - "errors": { - "nameRequired": "Vul een naam in.", - "nameTooLong": "De naam mag maximaal 100 tekens bevatten.", - "duplicate": "Er bestaat al een categorie met de naam '{{name}}'.", - "inUse": "Deze categorie wordt nog gebruikt door {{count}} aanbieding(en). Verplaats die eerst naar een andere categorie." - } - }, - "emptyState": { - "heading": "Nog geen aanbiedingen", - "description": "Voeg je eerste aanbieding toe om te beginnen." - }, - "table": { - "title": "Titel", - "price": "Prijs", - "featured": "Uitgelicht", - "actions": "Acties" - }, - "actions": { - "turnOff": "Pakket uitzetten", - "turnOn": "Pakket aanzetten", - "drag": "Sleep om te herordenen", - "edit": "Bewerken", - "delete": "Verwijderen", - "moveUp": "Omhoog verplaatsen", - "moveDown": "Omlaag verplaatsen", - "markFeatured": "Markeren als uitgelicht", - "unmarkFeatured": "Uitgelicht verwijderen" - }, - "deleteDialog": { - "title": "Aanbieding verwijderen", - "message": "Weet je zeker dat je '{{title}}' wilt verwijderen?", - "confirmButton": "Verwijderen", - "cancelButton": "Annuleren" - }, - "form": { - "createTitle": "Nieuwe aanbieding", - "editTitle": "Aanbieding bewerken", - "activeLabel": "Ingeschakeld", - "startsLabel": "Zichtbaar vanaf (optioneel)", - "endsLabel": "Zichtbaar tot (optioneel)", - "scheduleHint": "Een uitgeschakeld of gepland pakket wordt niet op de website getoond. Tijden gelden in jouw tijdzone. Bij de website van Andrea geldt de planning bij de eerstvolgende (nachtelijke) build.", - "endBeforeStart": "Het einde moet na het begin liggen.", - "titleLabel": "Titel", - "slugLabel": "Slug", - "slugAutoHint": "Wordt automatisch gegenereerd uit de titel", - "editSlugButton": "Aanpassen", - "confirmSlugButton": "Slug bevestigen", - "cancelSlugEditButton": "Slug-bewerking annuleren", - "descriptionLabel": "Beschrijving (optioneel)", - "priceLabel": "Prijs", - "priceNoteLabel": "Prijsnotitie (optioneel)", - "featuresLabel": "Kenmerken", - "addFeatureButton": "Kenmerk toevoegen", - "removeFeatureButton": "Verwijderen", - "ctaLabelLabel": "Knoptekst", - "featuredLabel": "Uitgelicht", - "categoryLabel": "Categorie", - "noCategory": "Geen categorie", - "submitButton": "Opslaan", - "successToast": "Aanbieding succesvol opgeslagen" - } - }, - "error": { - "403": { - "title": "Toegang geweigerd", - "message": "Je hebt geen toestemming om deze pagina te bekijken." - }, - "404": { - "title": "Pagina niet gevonden", - "message": "De pagina die je zoekt bestaat niet." - }, - "backToDashboard": "Terug naar dashboard", - "unexpected": { - "title": "Er is iets misgegaan", - "message": "Deze pagina kon niet worden weergegeven. Probeer het opnieuw of ga terug naar het dashboard." - } - }, - "errors": { - "network": "Kan de server niet bereiken. Controleer je verbinding en probeer opnieuw.", - "generic": "Er is iets misgegaan. Probeer het opnieuw.", - "accessDenied": "Je hebt geen toestemming om deze pagina te bekijken.", - "setupRequired": "Systeeminstallatie vereist. Initialiseer eerst het systeem.", - "invalidInvitationToken": "Ongeldig of verlopen uitnodigingstoken.", - "featureUnavailableTitle": "Niet beschikbaar op deze instantie", - "featureUnavailable": "Deze functie is alleen beschikbaar op een Master-CMS-instantie." - }, - "contact": { - "title": "Berichten", - "switch": { - "title": "Contactformulier op de website", - "stateOn": "Het formulier staat aan: bezoekers kunnen je een bericht sturen.", - "stateOff": "Het formulier staat uit: bezoekers zien alleen je e-mailadres.", - "on": "Aan", - "off": "Uit", - "turnOn": "Aanzetten", - "turnOff": "Uitzetten", - "nowOn": "Het contactformulier staat nu aan.", - "nowOff": "Het contactformulier staat nu uit.", - "shortLabel": "Contactformulier aan/uit", - "explanation": "Als het formulier uit staat, ziet de bezoeker alleen je e-mailadres. Uitzetten helpt bij spam of onderhoud.", - "firstTimeHint": "Het formulier is nog gesloten tot je het aanzet.", - "hostOff": "Het formulier is op serverniveau uitgeschakeld.", - "noRecipientBanner": "Er is geen ontvangstadres ingesteld: berichten worden bewaard maar niet gemaild. Vul hieronder een adres in." - }, - "filter": { - "label": "Filter berichten", - "inbox": "Inbox", - "new": "Nieuw", - "read": "Gelezen", - "archived": "Gearchiveerd", - "spam": "Spam" - }, - "table": { - "received": "Ontvangen", - "name": "Naam", - "email": "E-mailadres", - "subject": "Onderwerp", - "status": "Status", - "mail": "Mail" - }, - "status": { - "new": "Nieuw", - "read": "Gelezen", - "archived": "Gearchiveerd", - "spam": "Spam", - "converted": "Omgezet" - }, - "mailStatus": { - "pending": "Mail wacht op verzending", - "sent": "Mail verstuurd", - "failed": "Mail mislukt", - "notApplicable": "Geen mail van toepassing" - }, - "empty": { - "inbox": "Nog geen berichten.", - "new": "Geen nieuwe berichten.", - "read": "Geen gelezen berichten.", - "archived": "Geen gearchiveerde berichten.", - "spam": "Geen spam." - }, - "pager": { - "range": "{{from}}–{{to}} van {{total}}", - "previous": "Vorige", - "next": "Volgende" - }, - "tabs": { - "label": "Onderdelen van Berichten", - "messages": "Berichten", - "settings": "Instellingen" - }, - "unread": { - "label": "Ongelezen" - }, - "tile": { - "unread_one": "ongelezen bericht", - "unread_other": "ongelezen berichten", - "error": "Het aantal ongelezen berichten kon niet worden opgehaald." - }, - "detail": { - "title": "Bericht", - "retention": "Bewaard tot", - "attempts": "({{count}} pogingen)", - "nextAttempt": "Volgende poging: {{time}}", - "delete": "Verwijderen", - "resend": "Opnieuw mailen", - "archive": "Archiveren", - "restore": "Terugzetten", - "markUnread": "Markeer als ongelezen", - "notSpam": "Geen spam" - }, - "resend": { - "sent": "Verstuurd.", - "notSent": "Niet verstuurd (mail staat uit).", - "mailOff": "Mail staat uit op deze site." - }, - "deleteDialog": { - "title": "Bericht verwijderen?", - "message": "Het bericht wordt definitief verwijderd. Dit kan niet ongedaan worden gemaakt.", - "confirm": "Verwijderen" - }, - "errors": { - "rateLimited": "Probeer het over {{seconds}} seconden opnieuw.", - "spamResend": "Markeer het bericht eerst als geen spam.", - "notFound": "Dit bericht bestaat niet meer." - }, - "mailError": { - "disabled": "Mail staat uit.", - "recipient_not_configured": "Er is geen ontvanger ingesteld.", - "not_configured": "Mail is niet ingesteld.", - "timeout": "De mailserver reageerde te langzaam.", - "timeout_connect": "Verbinden met de mailserver duurde te lang.", - "timeout_auth": "Inloggen bij de mailserver duurde te lang.", - "timeout_send": "Versturen duurde te lang.", - "auth_failed": "Inloggen bij de mailserver is mislukt.", - "rejected": "De mailserver weigerde het bericht.", - "rejected_sender": "De mailserver weigerde het afzenderadres.", - "rejected_recipient": "De mailserver weigerde de ontvanger.", - "tls_failed": "De beveiligde verbinding met de mailserver is mislukt.", - "connection_failed": "Geen verbinding met de mailserver.", - "unknown": "Onbekende fout bij het versturen." - }, - "recipient": { - "title": "Ontvangstadres contactberichten", - "description": "Hierheen sturen we een mail bij elk nieuw bericht. Je kunt direct op die mail antwoorden: het antwoord gaat naar de bezoeker.", - "label": "E-mailadres", - "placeholder": "naam@voorbeeld.nl", - "save": "Opslaan", - "reset": "Terug naar serverinstelling", - "saved": "Ontvangstadres opgeslagen.", - "cleared": "De serverinstelling geldt weer.", - "invalid": "Voer een geldig e-mailadres in.", - "source": { - "setting": "Berichten gaan naar dit adres.", - "config": "Er is geen eigen adres ingesteld: de serverinstelling geldt.", - "none": "Er is nog geen ontvangstadres: berichten worden bewaard maar niet gemaild." - } - } - }, - "hero": { - "title": "Hero", - "live": "Live", - "notLive": "Niet live", - "intro": "De hero is het eerste wat bezoekers van de website zien: een grote kop met een of meer foto’s. Hier beheer je de teksten, de knoppen en de foto’s. Een wijziging is binnen ongeveer een minuut zichtbaar.", - "savedToast": "Hero opgeslagen", - "fields": { - "title": "Titel", - "titleHint": "Een nieuwe regel in dit veld is een regelafbreking in de titel (maximaal 5 regels).", - "tagline": "Korte tekst boven de titel (optioneel)", - "lead": "Introductietekst (optioneel)", - "display": "Weergave" - }, - "display": { - "single": "Enkel", - "slideshow": "Diavoorstelling" - }, - "buttons": { - "title": "Knoppen", - "hint": "Maximaal twee knoppen. Als doel kies je een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…).", - "label": "Knop {{n}}: tekst", - "target": "Knop {{n}}: doel" - }, - "library": { - "choose": "Kies uit bibliotheek", - "title": "Afbeelding voor slide {{n}}", - "description": "Kies een foto uit de mediabibliotheek of upload een nieuwe foto. Een foto die al in een andere slide staat mag ook: het is dezelfde foto, dus de uitsnede is gedeeld.", - "group": "Afbeelding van slide {{n}}", - "sharedCrop": "Deze foto staat in meer slides; de uitsnede geldt voor allemaal." - }, - "slides": { - "title": "Afbeeldingen", - "add": "Afbeelding toevoegen", - "uploading": "Bezig met uploaden…", - "hint": "Kies meerdere bestanden tegelijk of sleep ze naar dit vak. Nieuwe foto’s komen onderaan de lijst. Sleep een foto aan het greepje, of gebruik de pijltjes, om de volgorde te wijzigen; de eerste foto zien bezoekers als eerste. Met de knop Focus geef je aan waar het onderwerp staat.", - "empty": "Nog geen afbeeldingen.", - "alt": "Beschrijving", - "decorative": "Verberg voor schermlezers", - "up": "Omhoog", - "down": "Omlaag", - "remove": "Slide verwijderen", - "ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website.", - "focusPending": "Focus gewijzigd, nog niet opgeslagen.", - "processing": "Wordt verwerkt…", - "processingHint": "De afbeelding wordt klaargezet op de achtergrond; hij verschijnt op de website zodra hij klaar is.", - "failed": "Mislukt", - "limits": "Toegestaan: {{formats}}. Maximaal {{size}} MB per bestand en {{megapixels}} megapixel.", - "altHint": "Beschrijft de foto voor mensen die hem niet kunnen zien en voor zoekmachines.", - "drag": "Verplaats afbeelding {{n}}", - "dragInstructions": "Druk op spatie om de afbeelding op te pakken, gebruik de pijltjestoetsen om hem te verplaatsen en druk nogmaals op spatie om hem neer te zetten. Escape annuleert.", - "recut": "Nieuwe uitsnede wordt gemaakt…", - "recutHint": "Je ziet nog de oude uitsnede. De wijziging staat pas op de website als dit klaar is.", - "activeOn": "Actief", - "activeOff": "Niet actief", - "activeFor": "afbeelding {{n}} tonen op de website", - "number": "Slide {{n}}", - "done": "Verwerking afgerond", - "doneFor": "Slide {{n}}: verwerking afgerond", - "cropEdit": "Uitsnede aanpassen" - }, - "processing": { - "count": "{{done}} van {{total}} foto’s verwerkt", - "label": "Voortgang van het verwerken van de foto’s", - "explain": "De hero is al opgeslagen. De foto’s worden één voor één klaargezet en gaan live zodra ze klaar zijn. Tot de eerste foto klaar is, blijft de standaard hero van de website staan. Je hoeft deze pagina niet open te houden.", - "failed_one": "Het verwerken van {{count}} foto is mislukt.", - "failed_other": "Het verwerken van {{count}} foto’s is mislukt.", - "failedHint": "De server heeft het drie keer geprobeerd. Probeer het opnieuw, of upload de foto nog een keer (dezelfde foto is dezelfde afbeelding).", - "retry": "Opnieuw proberen", - "current": "Bezig met foto {{n}} van {{total}}: stap {{step}} van {{steps}}. Een grote foto kan enkele minuten duren.", - "stuck": "Duurt het lang?" - }, - "focus": { - "title": "Focus en uitsnede", - "intro": "Klik of sleep op de foto om aan te geven waar het onderwerp staat. De website snijdt de foto voor liggende en staande schermen zo uit dat het onderwerp in beeld blijft.", - "targetLegend": "Voor welke weergave", - "target": { - "general": "Algemeen", - "wide": "Liggend (3:2)", - "tall": "Staand (4:5)" - }, - "override": "Eigen instelling voor deze weergave", - "areaLabel": "Foto: kies het punt van het onderwerp", - "areaHint": "Pijltjestoetsen verplaatsen het punt (met Shift sneller).", - "x": "Horizontaal (%)", - "y": "Verticaal (%)", - "zoom": "Inzoomen ({{value}}×)", - "preview": { - "wide": "Voorbeeld liggend", - "tall": "Voorbeeld staand" - }, - "apply": "Toepassen", - "applyHint": "De wijziging geldt pas nadat je de hero opslaat. Verlaat je de pagina zonder op te slaan, dan vervalt ze.", - "previewPending": "Het voorbeeld van deze foto wordt klaargezet. Sluit dit venster en probeer het over een paar seconden opnieuw." - }, - "errors": { - "titleRequired": "Een titel is verplicht.", - "titleTooLong": "De titel mag maximaal 200 tekens bevatten.", - "titleTooManyLines": "De titel mag maximaal 5 regels hebben.", - "taglineTooLong": "De korte tekst boven de titel mag maximaal 120 tekens bevatten.", - "leadTooLong": "De introductietekst mag maximaal 600 tekens bevatten.", - "buttonLabelTooLong": "De knoptekst mag maximaal 50 tekens bevatten.", - "buttonTargetTooLong": "Het doel mag maximaal 500 tekens bevatten.", - "buttonIncomplete": "Vul zowel de tekst als het doel van de knop in, of laat beide leeg.", - "buttonTargetInvalid": "Kies een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…).", - "altTooLong": "De beschrijving mag maximaal 300 tekens bevatten.", - "altRequired": "Geef een beschrijving of kies ‘Alleen versiering’." - }, - "upload": { - "tooLarge": "De afbeelding is te groot (maximaal {{max}} MB).", - "interrupted": "De upload is afgebroken. Controleer de verbinding en probeer het opnieuw.", - "busy": "Er zijn te veel uploads achter elkaar. Probeer het over een paar minuten opnieuw.", - "notAnImage": "Dit bestand is geen afbeelding.", - "progress": "Bezig met uploaden: {{done}} van {{total}}", - "summary": "{{ok}} van {{total}} foto’s toegevoegd", - "waiting": "wacht", - "uploading": "bezig…", - "done": "toegevoegd", - "close": "Sluiten" - }, - "help": { - "heading": "Uitleg per onderdeel", - "save": "Wijzigingen gelden pas nadat je de hero opslaat.", - "title": { - "name": "Titel", - "text": "De grote kop. Een nieuwe regel in het veld is een nieuwe regel in de kop." - }, - "tagline": { - "name": "Korte tekst boven de titel", - "text": "Een kort label dat boven of voor de titel staat. Mag leeg blijven." - }, - "lead": { - "name": "Introductietekst", - "text": "Een of twee zinnen onder de titel. Mag leeg blijven." - }, - "buttons": { - "name": "Knoppen", - "text": "Maximaal twee, elk met een tekst en een doel. Als doel kies je een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…)." - }, - "display": { - "name": "Weergave", - "text": "‘Enkel’ toont één foto, ‘Diavoorstelling’ wisselt tussen de foto’s." - }, - "slides": { - "name": "Afbeeldingen", - "text": "Upload foto’s, beschrijf wat erop staat en bepaal de volgorde (slepen of de pijltjes). Met de schakelaar zet je een foto actief of niet actief. Kies ‘Verberg voor schermlezers’ voor een foto die niets toevoegt aan de inhoud." - }, - "focus": { - "name": "Focus", - "text": "Geef aan waar het onderwerp op de foto staat, zodat een uitsnede er niets van afhakt. Voor staande schermen, zoals een telefoon, kun je een apart punt kiezen." - } - }, - "unsaved": { - "badge": "Niet-opgeslagen wijzigingen", - "text": "Sla de hero op om ze door te voeren op de website.", - "leaveTitle": "Wijzigingen niet opgeslagen", - "leaveText": "Je hebt wijzigingen gemaakt die nog niet zijn opgeslagen. Als je deze pagina verlaat, gaan ze verloren.", - "stay": "Blijven", - "discard": "Wijzigingen weggooien" - }, - "saving": "Bezig met opslaan…", - "tabs": { - "label": "Onderdelen van de hero", - "content": "Inhoud", - "images": "Afbeeldingen", - "busy": "{{count}} bezig", - "hasChanges": "niet-opgeslagen wijzigingen", - "hasErrors": "bevat fouten" - } - }, - "media": { - "progress": { - "working": "Wordt verwerkt…" - }, - "module": { - "hero": "Hero" - }, - "use": { - "slide": "slide", - "none": "Niet gebruikt", - "off": "uit", - "noneSince": "Niet gebruikt sinds {{date}}" - }, - "list": { - "label": "Foto's", - "empty": "Er zijn geen foto's.", - "selectAll": "Alles selecteren", - "noThumbnail": "Geen voorbeeld", - "photoName": "Foto {{width}} × {{height}}" - }, - "bulk": { - "label": "Acties op de selectie", - "selected_one": "{{count}} foto geselecteerd", - "selected_other": "{{count}} foto's geselecteerd", - "clear": "Selectie wissen" - }, - "loading": "Laden...", - "error": "De mediabibliotheek kon niet worden geladen.", - "page": { - "title": "Mediabibliotheek", - "noModules": "Er is nog geen module die foto's meldt." - }, - "storage": { - "title": "Opslag", - "used": "{{used}} in gebruik", - "usedOf": "{{used}} van {{limit}} in gebruik ({{percent}}%)", - "warning": "De opslag is voor meer dan {{percent}}% vol. Ruim foto's op voordat de limiet bereikt is.", - "full": "De opslag is vol. Er kunnen geen foto's meer worden geüpload tot er ruimte is." - }, - "cleanup": { - "open": "Opruimen", - "title": "Opruimen", - "description": "Foto's die ouder zijn dan het aantal dagen hieronder, nieuwste eerst. Haal foto's uit de selectie die je wilt houden.", - "days_one": "Ouder dan {{count}} dag", - "days_other": "Ouder dan {{count}} dagen", - "onlyUnused": "Alleen ongebruikte foto's", - "summary_one": "{{count}} foto ({{size}}) komt in aanmerking.", - "summary_other": "{{count}} foto's ({{size}}) komen in aanmerking.", - "selectedSize": "Geselecteerd: {{size}}", - "trashNote": "De geselecteerde foto's gaan naar de prullenbak en kunnen 7 dagen worden teruggezet.", - "confirm_one": "{{count}} foto naar de prullenbak", - "confirm_other": "{{count}} foto's naar de prullenbak" - }, - "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." - }, - "view": { - "label": "Weergave", - "library": "Bibliotheek", - "trash": "Prullenbak" - }, - "trash": { - "since": "In de prullenbak sinds {{date}}", - "restore": "Terugzetten", - "note": "Foto's in de prullenbak worden na 7 dagen definitief verwijderd (standaard). Zet ze terug zolang het kan, of verwijder ze nu definitief." - }, - "delete": { - "action": "Naar prullenbak", - "title": "Foto's naar de prullenbak", - "confirm_one": "Deze foto gaat naar de prullenbak. Je kunt hem 7 dagen terugzetten.", - "confirm_other": "Deze {{count}} foto's gaan naar de prullenbak. Je kunt ze 7 dagen terugzetten.", - "inUseCount_one": "{{count}} foto wordt nog gebruikt.", - "inUseCount_other": "{{count}} foto's worden nog gebruikt.", - "secondTitle": "Foto's in gebruik verwijderen?", - "secondText_one": "Deze foto wordt nog gebruikt. Als je doorgaat, verdwijnt hij van de plekken hieronder (bij de Hero verdwijnt de slide).", - "secondText_other": "Deze foto's worden nog gebruikt. Als je doorgaat, verdwijnen ze van de plekken hieronder (bij de Hero verdwijnt de slide).", - "confirmButton": "Naar prullenbak", - "confirmSecond": "Ja, toch verwijderen", - "cancel": "Annuleren", - "close": "Sluiten", - "partial_one": "{{count}} foto kon niet worden verwijderd. De rest is naar de prullenbak.", - "partial_other": "{{count}} foto's konden niet worden verwijderd. De rest is naar de prullenbak." - }, - "filter": { - "label": "Filter", - "all": "Alle foto's", - "used": "Gebruikt", - "unused": "Ongebruikt" - }, - "purge": { - "action": "Definitief verwijderen", - "title": "Definitief verwijderen", - "emptyTitle": "Prullenbak legen", - "emptyButton": "Prullenbak legen", - "emptyConfirm": "Prullenbak legen", - "confirmButton": "Definitief verwijderen", - "confirm_one": "Deze foto wordt definitief verwijderd, met zijn bestanden.", - "confirm_other": "Deze {{count}} foto's worden definitief verwijderd, met hun bestanden.", - "confirmAll_one": "De prullenbak wordt geleegd: {{count}} foto ({{size}}) wordt definitief verwijderd.", - "confirmAll_other": "De prullenbak wordt geleegd: {{count}} foto's ({{size}}) worden definitief verwijderd.", - "irreversible": "Dit kan niet ongedaan worden gemaakt.", - "partial_one": "{{count}} foto kon niet worden verwijderd. De rest is definitief verwijderd.", - "partial_other": "{{count}} foto's konden niet worden verwijderd. De rest is definitief verwijderd." - } - } -} +{ + "common": { + "appName": "SlpModularCms", + "loading": "Laden…", + "cancel": "Annuleren", + "save": "Opslaan", + "retry": "Opnieuw" + }, + "nav": { + "dashboard": "Dashboard", + "users": "Gebruikers", + "cms": "CMS", + "offerings": "Aanbiedingen", + "messages": "Berichten", + "profile": "Profiel", + "settings": "Instellingen", + "openMenu": "Navigatie openen", + "closeMenu": "Navigatie sluiten", + "hero": "Hero", + "media": "Mediabibliotheek", + "unreadMessages_one": "{{count}} nieuw bericht", + "unreadMessages_other": "{{count}} nieuwe berichten" + }, + "theme": { + "title": "Thema", + "label": "Thema: {{mode}}", + "labelAuto": "Thema: automatisch (nu {{now}})", + "mode": { + "light": "Licht", + "dark": "Donker", + "auto": "Automatisch" + } + }, + "session": { + "unreachable": { + "title": "Sessie kon niet worden gecontroleerd", + "description": "De server is even niet bereikbaar of te druk. Je bent niet uitgelogd. Probeer het over een paar seconden opnieuw.", + "retry": "Opnieuw proberen", + "stillFailing": "Nog steeds geen antwoord. Wacht even en probeer opnieuw." + } + }, + "login": { + "title": "Inloggen", + "subtitle": "Log in op je SlpModularCms-account", + "forgotPassword": "Wachtwoord vergeten?", + "cmsDisabled": "Dit CMS is uitgeschakeld.", + "cmsMaintenance": "Dit CMS is in onderhoud.", + "cmsOffAdminsOnly": "Alleen beheerders kunnen nu inloggen.", + "email": "E-mail", + "emailPlaceholder": "jij@voorbeeld.nl", + "password": "Wachtwoord", + "submit": "Inloggen", + "submitting": "Bezig met inloggen…", + "errors": { + "emailRequired": "E-mail is verplicht", + "emailInvalid": "Voer een geldig e-mailadres in", + "passwordRequired": "Wachtwoord is verplicht", + "invalidCredentials": "Ongeldige e-mail of wachtwoord", + "generic": "Er is iets misgegaan. Probeer het opnieuw." + } + }, + "forgotPassword": { + "title": "Wachtwoord vergeten", + "description": "Vul je e-mailadres in. Hoort het bij een account, dan krijg je een e-mail met een link om een nieuw wachtwoord te kiezen.", + "submit": "Link versturen", + "sentTitle": "Controleer je e-mail", + "sentMessage": "Als dit adres bij een account hoort, is er een e-mail met een link onderweg. Geen e-mail gekregen? Kijk ook in je spam of vraag de beheerder om hulp.", + "backToLogin": "Terug naar inloggen", + "unavailable": "Wachtwoord opnieuw instellen per e-mail is op deze site niet beschikbaar. Vraag de beheerder om hulp." + }, + "resetPassword": { + "title": "Nieuw wachtwoord kiezen", + "description": "Kies een nieuw wachtwoord voor je account.", + "passwordLabel": "Nieuw wachtwoord", + "confirmLabel": "Nieuw wachtwoord bevestigen", + "submit": "Wachtwoord opslaan", + "success": "Je wachtwoord is gewijzigd. Je kunt nu inloggen.", + "passwordRejected": "Dit wachtwoord voldoet niet aan de eisen. Kies een ander wachtwoord.", + "invalidTitle": "Link ongeldig of verlopen", + "invalidMessage": "Deze link is verlopen, al gebruikt of ongeldig. Vraag een nieuwe link aan.", + "requestNew": "Nieuwe link aanvragen" + }, + "setup": { + "title": "Eerste account aanmaken", + "nameLabel": "Weergavenaam", + "emailLabel": "E-mail", + "passwordLabel": "Wachtwoord", + "confirmPasswordLabel": "Wachtwoord bevestigen", + "languageLabel": "Taalkeuze", + "tokenLabel": "Setup-token", + "tokenHelp": "Nodig om de eerste beheerder aan te maken. Je hebt het ontvangen van degene die deze site heeft geïnstalleerd.", + "tokenRequiredError": "Vul het setup-token in.", + "tokenInvalid": "Het setup-token ontbreekt of is onjuist.", + "submitButton": "Owner-account aanmaken", + "successMessage": "Account aangemaakt. Je kunt nu inloggen." + }, + "inviteComplete": { + "title": "Account voltooien", + "emailLabel": "E-mail", + "nameLabel": "Weergavenaam", + "passwordLabel": "Wachtwoord", + "confirmPasswordLabel": "Wachtwoord bevestigen", + "submitButton": "Setup voltooien", + "loadingMessage": "Uitnodiging valideren…", + "invalidTitle": "Link ongeldig of verlopen", + "invalidTokenMessage": "Deze uitnodigingslink is verlopen, ingetrokken of ongeldig. Vraag de beheerder om een nieuwe uitnodiging.", + "toLogin": "Naar inloggen", + "successMessage": "Account-setup voltooid. Je kunt nu inloggen." + }, + "dashboard": { + "title": "Dashboard", + "welcome": "Welkom terug, {{name}}" + }, + "availability": { + "title": "Systeemstatus", + "available": "Beschikbaar", + "maintenance": "Onderhoud", + "unavailable": "Niet beschikbaar", + "messageAvailable": "Systeem werkt normaal.", + "messageMaintenance": "Het systeem ondergaat gepland onderhoud.", + "messageUnavailable": "Het systeem is momenteel niet beschikbaar.", + "errorTitle": "Status kon niet worden geladen", + "staleLabel": "Laatste bekende status", + "retry": "Opnieuw proberen" + }, + "userMenu": { + "language": "Taal", + "logout": "Uitloggen" + }, + "users": { + "title": "Gebruikers", + "inviteButton": "Gebruiker uitnodigen", + "table": { + "name": "Naam", + "email": "E-mail", + "role": "Rol", + "status": "Status", + "createdAt": "Aangemaakt", + "actions": "Acties" + }, + "status": { + "active": "Actief", + "inactive": "Inactief", + "pendingInvite": "Uitnodiging in behandeling", + "inviteExpired": "Uitnodiging verlopen" + }, + "actions": { + "copyInviteLink": "Uitnodigingslink kopiëren", + "regenerateInvite": "Nieuwe uitnodigingslink maken", + "resendInvite": "Uitnodiging opnieuw mailen", + "inviteRegeneratedMailed": "Nieuwe uitnodigingslink gemaakt en gemaild naar {{email}}. De oude link werkt niet meer.", + "inviteRegenerated": "Nieuwe uitnodigingslink gekopieerd naar klembord. De oude link werkt niet meer.", + "changeRole": "Rol wijzigen", + "deactivate": "Deactiveren", + "activate": "Activeren", + "delete": "Gebruiker verwijderen", + "linkCopied": "Uitnodigingslink gekopieerd naar klembord", + "roleChanged": "Rol van {{name}} gewijzigd naar {{role}}" + }, + "active": { + "successDeactivated": "{{name}} is gedeactiveerd.", + "successActivated": "{{name}} is geactiveerd." + }, + "regenerate": { + "title": "Nieuwe uitnodigingslink maken", + "description": "Er wordt een nieuwe link gemaakt voor {{email}}. De oude link werkt daarna niet meer. De nieuwe link wordt gekopieerd, zodat je hem zelf kunt delen.", + "descriptionMail": "Er wordt een nieuwe link gemaakt voor {{email}}. De oude link werkt daarna niet meer. Wil je de nieuwe link ook per e-mail versturen?", + "copyOnly": "Alleen link kopiëren", + "copyAndMail": "Link kopiëren en mailen", + "create": "Link maken en kopiëren" + }, + "delete": { + "title": "Gebruiker verwijderen", + "description": "Weet je zeker dat je {{name}} ({{email}}) wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.", + "descriptionNoName": "Weet je zeker dat je {{email}} wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.", + "descriptionPending": "Weet je zeker dat je de openstaande uitnodiging voor {{email}} wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.", + "confirmButton": "Verwijderen", + "success": "{{name}} is verwijderd." + }, + "invite": { + "title": "Gebruiker uitnodigen", + "emailLabel": "E-mailadres", + "roleLabel": "Rol", + "rolePlaceholder": "Selecteer een rol", + "submitButton": "Uitnodiging versturen", + "step2Title": "Uitnodiging aangemaakt", + "step2Description": "Deel de onderstaande link met de genodigde.", + "languageLabel": "Taal van de uitnodiging", + "languageHelp": "De taal van de e-mail en de voorkeurstaal van het nieuwe account.", + "mailSent": "E-mail met de uitnodiging verstuurd naar {{email}}.", + "mailFailed": "De e-mail kon niet worden verstuurd ({{reason}}). Kopieer de link en deel die zelf, of probeer later opnieuw te mailen.", + "mailErrors": { + "timeout": "de mailserver reageerde niet op tijd", + "timeout_connect": "de mailserver reageerde niet op tijd tijdens het verbinden", + "timeout_auth": "de mailserver reageerde niet op tijd tijdens het inloggen", + "timeout_send": "de mailserver reageerde niet op tijd tijdens het versturen", + "auth_failed": "inloggen op de mailserver mislukt", + "rejected": "de mailserver of het adres weigerde het bericht", + "rejected_sender": "de mailserver accepteert dit afzenderadres niet voor dit account", + "rejected_recipient": "de mailserver wil niet naar dit adres versturen", + "tls_failed": "beveiligde verbinding met de mailserver mislukt", + "connection_failed": "geen verbinding met de mailserver", + "not_configured": "e-mail is niet ingesteld", + "unknown": "onbekende fout" + }, + "linkLabel": "Uitnodigingslink", + "copyLink": "Link kopiëren", + "close": "Sluiten" + }, + "roles": { + "Owner": "Eigenaar", + "Administrator": "Beheerder", + "User": "Gebruiker" + }, + "ownerAssign": { + "title": "Eigenaarrol toewijzen", + "description": "Je staat op het punt {{name}} eigenaar te maken. Eigenaars hebben volledige toegang tot het systeem, inclusief het kunnen beheren en verwijderen van andere eigenaars. Weet je het zeker?", + "confirmButton": "Eigenaar maken" + }, + "selfRoleChange": { + "title": "Eigen rol wijzigen", + "description": "Je staat op het punt je eigen rol te wijzigen naar {{role}}. Je wordt daarna automatisch uitgelogd zodat de wijziging direct ingaat.", + "confirmButton": "Wijzigen en uitloggen" + }, + "errors": { + "lastOwnerRequired": "Er moet minimaal één Eigenaar blijven. Wijs eerst een andere Eigenaar aan voor je deze rol wijzigt.", + "insufficientPermissions": "Je hebt geen toestemming om deze actie uit te voeren." + } + }, + "profile": { + "title": "Mijn profiel", + "name": "Weergavenaam", + "email": "E-mailadres", + "role": "Rol", + "save": "Wijzigingen opslaan", + "saving": "Opslaan…", + "saveSuccess": "Profiel succesvol bijgewerkt", + "securityTitle": "Wachtwoord wijzigen", + "language": "Taal", + "languageDefault": "Standaard van de site", + "languageHelp": "De taal van de beheeromgeving en van e-mails die je ontvangt.", + "changePassword": "Wachtwoord wijzigen", + "changePasswordDialog": { + "title": "Wachtwoord wijzigen", + "new": "Nieuw wachtwoord", + "confirm": "Nieuw wachtwoord bevestigen", + "submit": "Wachtwoord wijzigen", + "submitting": "Bezig…", + "success": "Wachtwoord succesvol gewijzigd", + "errorCurrent": "Huidig wachtwoord is onjuist" + } + }, + "settings": { + "title": "Systeeminstellingen", + "mail": { + "title": "E-mail", + "description": "Van welk adres en onder welke naam deze site e-mails verstuurt (uitnodigingen, wachtwoord opnieuw instellen, meldingen).", + "fromAddress": "Afzenderadres", + "fromAddressHelp": "Alleen adressen die voor deze installatie zijn toegestaan (SPF/DKIM). Een ander adres kan alleen door de beheerder van de server worden toegevoegd.", + "fromName": "Afzendernaam", + "nameTooLong": "De naam mag hooguit 80 tekens bevatten.", + "save": "Opslaan", + "reset": "Standaard herstellen", + "saveSuccess": "E-mailinstellingen opgeslagen", + "resetSuccess": "Standaardinstellingen hersteld", + "invalid": "Deze instellingen zijn niet geldig.", + "readOnly": "Alleen de eigenaar kan deze instellingen wijzigen." + }, + "availability": { + "title": "Systeembeschikbaarheid", + "mode": "Beschikbaarheidsmodus", + "reason": "Bericht (optioneel)", + "save": "Beschikbaarheid bijwerken", + "saving": "Bijwerken…", + "saveSuccess": "Beschikbaarheid bijgewerkt", + "modes": { + "Available": "Beschikbaar", + "Maintenance": "Onderhoud", + "NotAvailable": "Niet beschikbaar" + }, + "masterControlledTitle": "Beheerd door Master-CMS", + "masterControlled": "Deze instantie is door de Master-CMS uitgeschakeld. De beschikbaarheid kan hier niet worden gewijzigd totdat de Master de status weer vrijgeeft.", + "masterControlledSaveError": "Kan niet worden gewijzigd: de Master-CMS beheert deze status." + }, + "modules": { + "title": "Modulebeheer", + "comingSoon": "Binnenkort beschikbaar" + }, + "systemConfig": { + "title": "Systeemconfiguratie", + "comingSoon": "Binnenkort beschikbaar" + }, + "branding": { + "title": "Huisstijl / Thema", + "comingSoon": "Binnenkort beschikbaar" + } + }, + "cms": { + "title": "CMS-instanties", + "addButton": "CMS toevoegen", + "emptyState": { + "heading": "Nog geen CMS-instanties", + "description": "Voeg uw eerste CMS-instantie toe om aan de slag te gaan." + }, + "table": { + "name": "Naam", + "url": "URL", + "status": "Status", + "lastContact": "Laatste contact", + "disableMessage": "Uitschakelreden", + "actions": "Acties" + }, + "status": { + "Available": "Beschikbaar", + "NotAvailable": "Niet beschikbaar", + "Inactive": "Inactief" + }, + "actions": { + "setStatus": "Status instellen" + }, + "add": { + "title": "CMS-instantie toevoegen", + "nameLabel": "Naam", + "urlLabel": "URL", + "apiKeyLabel": "API-sleutel", + "submitButton": "Toevoegen", + "successToast": "CMS-instantie succesvol toegevoegd", + "errors": { + "conflict": "Er bestaat al een CMS-instantie met deze naam of URL." + } + }, + "setStatus": { + "title": "Status instellen", + "statusLabel": "Status", + "disableMessageLabel": "Uitschakelreden", + "disableMessagePlaceholder": "Reden voor uitschakelen…", + "submitButton": "Opslaan", + "successContactedToast": "Status bijgewerkt — cliënt bevestigd", + "successUnreachableToast": "Status opgeslagen — cliënt niet bereikbaar" + } + }, + "offerings": { + "title": "Aanbiedingen", + "addButton": "Aanbieding toevoegen", + "banners": { + "intro": "Een banner is een brede mededeling of actie op de website. Plan vooruit met een begin- en eindtijd. Per locatie (boven en onder) wordt maximaal één banner getoond: de laatst gewijzigde actieve.", + "position": { + "label": "Locatie", + "top": "Boven", + "bottom": "Onder" + }, + "shownBadge": "Live", + "notShownBadge": "Wordt niet getoond", + "notShownHint": "Wordt niet getoond: nieuwere banner op deze locatie", + "turnOffButton": "Banner uitzetten", + "turnOnButton": "Banner aanzetten", + "titleLabelOptional": "Titel (optioneel)", + "textTooLong": "De tekst is {{length}} tekens; voor deze locatie zijn maximaal {{max}} tekens toegestaan. Kort de tekst in of kies een andere locatie.", + "textHintTop": "Eén korte regel, maximaal 120 tekens.", + "addButton": "Banner toevoegen", + "empty": "Nog geen banners.", + "editButton": "Banner bewerken", + "deleteButton": "Banner verwijderen", + "createTitle": "Nieuwe banner", + "editTitle": "Banner bewerken", + "titleLabel": "Titel", + "textLabel": "Tekst", + "linkLabelLabel": "Knoptekst (optioneel)", + "linkUrlLabel": "Link (optioneel)", + "linkHint": "Knoptekst en link horen bij elkaar. Een link begint met https:// of is een pad op de site, bijvoorbeeld /privacy.", + "startsLabel": "Zichtbaar vanaf (optioneel)", + "endsLabel": "Zichtbaar tot (optioneel)", + "scheduleHint": "Tijden gelden in jouw tijdzone. Bij de website van Andrea geldt de planning bij de eerstvolgende (nachtelijke) build.", + "activeLabel": "Ingeschakeld", + "savedToast": "Banner opgeslagen", + "deletedToast": "Banner verwijderd", + "deleteTitle": "Banner verwijderen", + "deleteMessage": "Weet je zeker dat je de banner \"{{title}}\" wilt verwijderen?", + "deleteConfirm": "Verwijderen", + "status": { + "live": "Actief", + "scheduled": "Gepland", + "expired": "Verlopen", + "off": "Uit" + }, + "tabPackages": "Aanbiedingen", + "tabBanner": "Banner", + "tabsLabel": "Onderdelen" + }, + "categories": { + "manageButton": "Categorieën beheren", + "title": "Categorieën beheren", + "emptyState": "Nog geen categorieën. Voeg de eerste toe.", + "offeringCount_one": "{{count}} aanbieding", + "offeringCount_other": "{{count}} aanbiedingen", + "newLabel": "Nieuwe categorie", + "addButton": "Toevoegen", + "editButton": "Categorie hernoemen", + "confirmEditButton": "Naam bevestigen", + "cancelButton": "Annuleren", + "deleteButton": "Categorie verwijderen", + "deleteConfirm": "Weet je het zeker?", + "deleteConfirmButton": "Verwijderen", + "errors": { + "nameRequired": "Vul een naam in.", + "nameTooLong": "De naam mag maximaal 100 tekens bevatten.", + "duplicate": "Er bestaat al een categorie met de naam '{{name}}'.", + "inUse": "Deze categorie wordt nog gebruikt door {{count}} aanbieding(en). Verplaats die eerst naar een andere categorie." + } + }, + "emptyState": { + "heading": "Nog geen aanbiedingen", + "description": "Voeg je eerste aanbieding toe om te beginnen." + }, + "table": { + "title": "Titel", + "price": "Prijs", + "featured": "Uitgelicht", + "actions": "Acties" + }, + "actions": { + "turnOff": "Pakket uitzetten", + "turnOn": "Pakket aanzetten", + "drag": "Sleep om te herordenen", + "edit": "Bewerken", + "delete": "Verwijderen", + "moveUp": "Omhoog verplaatsen", + "moveDown": "Omlaag verplaatsen", + "markFeatured": "Markeren als uitgelicht", + "unmarkFeatured": "Uitgelicht verwijderen" + }, + "deleteDialog": { + "title": "Aanbieding verwijderen", + "message": "Weet je zeker dat je '{{title}}' wilt verwijderen?", + "confirmButton": "Verwijderen", + "cancelButton": "Annuleren" + }, + "form": { + "createTitle": "Nieuwe aanbieding", + "editTitle": "Aanbieding bewerken", + "activeLabel": "Ingeschakeld", + "startsLabel": "Zichtbaar vanaf (optioneel)", + "endsLabel": "Zichtbaar tot (optioneel)", + "scheduleHint": "Een uitgeschakeld of gepland pakket wordt niet op de website getoond. Tijden gelden in jouw tijdzone. Bij de website van Andrea geldt de planning bij de eerstvolgende (nachtelijke) build.", + "endBeforeStart": "Het einde moet na het begin liggen.", + "titleLabel": "Titel", + "slugLabel": "Slug", + "slugAutoHint": "Wordt automatisch gegenereerd uit de titel", + "editSlugButton": "Aanpassen", + "confirmSlugButton": "Slug bevestigen", + "cancelSlugEditButton": "Slug-bewerking annuleren", + "descriptionLabel": "Beschrijving (optioneel)", + "priceLabel": "Prijs", + "priceNoteLabel": "Prijsnotitie (optioneel)", + "featuresLabel": "Kenmerken", + "addFeatureButton": "Kenmerk toevoegen", + "removeFeatureButton": "Verwijderen", + "ctaLabelLabel": "Knoptekst", + "featuredLabel": "Uitgelicht", + "categoryLabel": "Categorie", + "noCategory": "Geen categorie", + "submitButton": "Opslaan", + "successToast": "Aanbieding succesvol opgeslagen" + } + }, + "error": { + "403": { + "title": "Toegang geweigerd", + "message": "Je hebt geen toestemming om deze pagina te bekijken." + }, + "404": { + "title": "Pagina niet gevonden", + "message": "De pagina die je zoekt bestaat niet." + }, + "backToDashboard": "Terug naar dashboard", + "unexpected": { + "title": "Er is iets misgegaan", + "message": "Deze pagina kon niet worden weergegeven. Probeer het opnieuw of ga terug naar het dashboard." + } + }, + "errors": { + "network": "Kan de server niet bereiken. Controleer je verbinding en probeer opnieuw.", + "generic": "Er is iets misgegaan. Probeer het opnieuw.", + "accessDenied": "Je hebt geen toestemming om deze pagina te bekijken.", + "setupRequired": "Systeeminstallatie vereist. Initialiseer eerst het systeem.", + "invalidInvitationToken": "Ongeldig of verlopen uitnodigingstoken.", + "featureUnavailableTitle": "Niet beschikbaar op deze instantie", + "featureUnavailable": "Deze functie is alleen beschikbaar op een Master-CMS-instantie." + }, + "contact": { + "title": "Berichten", + "switch": { + "title": "Contactformulier op de website", + "stateOn": "Het formulier staat aan: bezoekers kunnen je een bericht sturen.", + "stateOff": "Het formulier staat uit: bezoekers zien alleen je e-mailadres.", + "on": "Aan", + "off": "Uit", + "turnOn": "Aanzetten", + "turnOff": "Uitzetten", + "nowOn": "Het contactformulier staat nu aan.", + "nowOff": "Het contactformulier staat nu uit.", + "shortLabel": "Contactformulier aan/uit", + "explanation": "Als het formulier uit staat, ziet de bezoeker alleen je e-mailadres. Uitzetten helpt bij spam of onderhoud.", + "firstTimeHint": "Het formulier is nog gesloten tot je het aanzet.", + "hostOff": "Het formulier is op serverniveau uitgeschakeld.", + "noRecipientBanner": "Er is geen ontvangstadres ingesteld: berichten worden bewaard maar niet gemaild. Vul hieronder een adres in." + }, + "filter": { + "label": "Filter berichten", + "inbox": "Inbox", + "new": "Nieuw", + "read": "Gelezen", + "archived": "Gearchiveerd", + "spam": "Spam" + }, + "table": { + "received": "Ontvangen", + "name": "Naam", + "email": "E-mailadres", + "subject": "Onderwerp", + "status": "Status", + "mail": "Mail" + }, + "status": { + "new": "Nieuw", + "read": "Gelezen", + "archived": "Gearchiveerd", + "spam": "Spam", + "converted": "Omgezet" + }, + "mailStatus": { + "pending": "Mail wacht op verzending", + "sent": "Mail verstuurd", + "failed": "Mail mislukt", + "notApplicable": "Geen mail van toepassing" + }, + "empty": { + "inbox": "Nog geen berichten.", + "new": "Geen nieuwe berichten.", + "read": "Geen gelezen berichten.", + "archived": "Geen gearchiveerde berichten.", + "spam": "Geen spam." + }, + "pager": { + "range": "{{from}}–{{to}} van {{total}}", + "previous": "Vorige", + "next": "Volgende" + }, + "tabs": { + "label": "Onderdelen van Berichten", + "messages": "Berichten", + "settings": "Instellingen" + }, + "unread": { + "label": "Ongelezen" + }, + "tile": { + "unread_one": "ongelezen bericht", + "unread_other": "ongelezen berichten", + "error": "Het aantal ongelezen berichten kon niet worden opgehaald." + }, + "detail": { + "title": "Bericht", + "retention": "Bewaard tot", + "attempts": "({{count}} pogingen)", + "nextAttempt": "Volgende poging: {{time}}", + "delete": "Verwijderen", + "resend": "Opnieuw mailen", + "archive": "Archiveren", + "restore": "Terugzetten", + "markUnread": "Markeer als ongelezen", + "notSpam": "Geen spam" + }, + "resend": { + "sent": "Verstuurd.", + "notSent": "Niet verstuurd (mail staat uit).", + "mailOff": "Mail staat uit op deze site." + }, + "deleteDialog": { + "title": "Bericht verwijderen?", + "message": "Het bericht wordt definitief verwijderd. Dit kan niet ongedaan worden gemaakt.", + "confirm": "Verwijderen" + }, + "errors": { + "rateLimited": "Probeer het over {{seconds}} seconden opnieuw.", + "spamResend": "Markeer het bericht eerst als geen spam.", + "notFound": "Dit bericht bestaat niet meer." + }, + "mailError": { + "disabled": "Mail staat uit.", + "recipient_not_configured": "Er is geen ontvanger ingesteld.", + "not_configured": "Mail is niet ingesteld.", + "timeout": "De mailserver reageerde te langzaam.", + "timeout_connect": "Verbinden met de mailserver duurde te lang.", + "timeout_auth": "Inloggen bij de mailserver duurde te lang.", + "timeout_send": "Versturen duurde te lang.", + "auth_failed": "Inloggen bij de mailserver is mislukt.", + "rejected": "De mailserver weigerde het bericht.", + "rejected_sender": "De mailserver weigerde het afzenderadres.", + "rejected_recipient": "De mailserver weigerde de ontvanger.", + "tls_failed": "De beveiligde verbinding met de mailserver is mislukt.", + "connection_failed": "Geen verbinding met de mailserver.", + "unknown": "Onbekende fout bij het versturen." + }, + "recipient": { + "title": "Ontvangstadres contactberichten", + "description": "Hierheen sturen we een mail bij elk nieuw bericht. Je kunt direct op die mail antwoorden: het antwoord gaat naar de bezoeker.", + "label": "E-mailadres", + "placeholder": "naam@voorbeeld.nl", + "save": "Opslaan", + "reset": "Terug naar serverinstelling", + "saved": "Ontvangstadres opgeslagen.", + "cleared": "De serverinstelling geldt weer.", + "invalid": "Voer een geldig e-mailadres in.", + "source": { + "setting": "Berichten gaan naar dit adres.", + "config": "Er is geen eigen adres ingesteld: de serverinstelling geldt.", + "none": "Er is nog geen ontvangstadres: berichten worden bewaard maar niet gemaild." + } + } + }, + "hero": { + "title": "Hero", + "live": "Live", + "notLive": "Niet live", + "intro": "De hero is het eerste wat bezoekers van de website zien: een grote kop met een of meer foto’s. Hier beheer je de teksten, de knoppen en de foto’s. Een wijziging is binnen ongeveer een minuut zichtbaar.", + "savedToast": "Hero opgeslagen", + "fields": { + "title": "Titel", + "titleHint": "Een nieuwe regel in dit veld is een regelafbreking in de titel (maximaal 5 regels).", + "tagline": "Korte tekst boven de titel (optioneel)", + "lead": "Introductietekst (optioneel)", + "display": "Weergave" + }, + "display": { + "single": "Enkel", + "slideshow": "Diavoorstelling" + }, + "buttons": { + "title": "Knoppen", + "hint": "Maximaal twee knoppen. Als doel kies je een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…).", + "label": "Knop {{n}}: tekst", + "target": "Knop {{n}}: doel" + }, + "library": { + "title": "Slide toevoegen", + "description": "Kies een foto uit de mediabibliotheek of upload een nieuwe foto; die komt dan ook in de bibliotheek. Elke slide heeft één foto. Een foto wijzig je niet op een slide: verwijder de slide en voeg een nieuwe toe.", + "group": "Foto voor de nieuwe slide", + "sharedCrop": "Deze foto staat in meer slides; de uitsnede geldt voor allemaal." + }, + "slides": { + "title": "Afbeeldingen", + "add": "Slide toevoegen", + "uploading": "Bezig met uploaden…", + "hint": "Kies meerdere bestanden tegelijk of sleep ze naar dit vak. Nieuwe foto’s komen onderaan de lijst. Sleep een foto aan het greepje, of gebruik de pijltjes, om de volgorde te wijzigen; de eerste foto zien bezoekers als eerste. Met de knop Focus geef je aan waar het onderwerp staat.", + "empty": "Nog geen afbeeldingen.", + "alt": "Beschrijving", + "decorative": "Verberg voor schermlezers", + "up": "Omhoog", + "down": "Omlaag", + "remove": "Slide verwijderen", + "ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website.", + "focusPending": "Focus gewijzigd, nog niet opgeslagen.", + "processing": "Wordt verwerkt…", + "processingHint": "De afbeelding wordt klaargezet op de achtergrond; hij verschijnt op de website zodra hij klaar is.", + "failed": "Mislukt", + "limits": "Toegestaan: {{formats}}. Maximaal {{size}} MB per bestand en {{megapixels}} megapixel.", + "altHint": "Beschrijft de foto voor mensen die hem niet kunnen zien en voor zoekmachines.", + "drag": "Verplaats afbeelding {{n}}", + "dragInstructions": "Druk op spatie om de afbeelding op te pakken, gebruik de pijltjestoetsen om hem te verplaatsen en druk nogmaals op spatie om hem neer te zetten. Escape annuleert.", + "recut": "Nieuwe uitsnede wordt gemaakt…", + "recutHint": "Je ziet nog de oude uitsnede. De wijziging staat pas op de website als dit klaar is.", + "activeOn": "Actief", + "activeOff": "Niet actief", + "activeFor": "afbeelding {{n}} tonen op de website", + "number": "Slide {{n}}", + "done": "Verwerking afgerond", + "doneFor": "Slide {{n}}: verwerking afgerond", + "cropEdit": "Uitsnede aanpassen" + }, + "processing": { + "count": "{{done}} van {{total}} foto’s verwerkt", + "label": "Voortgang van het verwerken van de foto’s", + "explain": "De hero is al opgeslagen. De foto’s worden één voor één klaargezet en gaan live zodra ze klaar zijn. Tot de eerste foto klaar is, blijft de standaard hero van de website staan. Je hoeft deze pagina niet open te houden.", + "failed_one": "Het verwerken van {{count}} foto is mislukt.", + "failed_other": "Het verwerken van {{count}} foto’s is mislukt.", + "failedHint": "De server heeft het drie keer geprobeerd. Probeer het opnieuw, of upload de foto nog een keer (dezelfde foto is dezelfde afbeelding).", + "retry": "Opnieuw proberen", + "current": "Bezig met foto {{n}} van {{total}}: stap {{step}} van {{steps}}. Een grote foto kan enkele minuten duren.", + "stuck": "Duurt het lang?" + }, + "focus": { + "title": "Focus en uitsnede", + "intro": "Klik of sleep op de foto om aan te geven waar het onderwerp staat. De website snijdt de foto voor liggende en staande schermen zo uit dat het onderwerp in beeld blijft.", + "targetLegend": "Voor welke weergave", + "target": { + "general": "Algemeen", + "wide": "Liggend (3:2)", + "tall": "Staand (4:5)" + }, + "override": "Eigen instelling voor deze weergave", + "areaLabel": "Foto: kies het punt van het onderwerp", + "areaHint": "Pijltjestoetsen verplaatsen het punt (met Shift sneller).", + "x": "Horizontaal (%)", + "y": "Verticaal (%)", + "zoom": "Inzoomen ({{value}}×)", + "preview": { + "wide": "Voorbeeld liggend", + "tall": "Voorbeeld staand" + }, + "apply": "Toepassen", + "applyHint": "De wijziging geldt pas nadat je de hero opslaat. Verlaat je de pagina zonder op te slaan, dan vervalt ze.", + "previewPending": "Het voorbeeld van deze foto wordt klaargezet. Sluit dit venster en probeer het over een paar seconden opnieuw." + }, + "errors": { + "titleRequired": "Een titel is verplicht.", + "titleTooLong": "De titel mag maximaal 200 tekens bevatten.", + "titleTooManyLines": "De titel mag maximaal 5 regels hebben.", + "taglineTooLong": "De korte tekst boven de titel mag maximaal 120 tekens bevatten.", + "leadTooLong": "De introductietekst mag maximaal 600 tekens bevatten.", + "buttonLabelTooLong": "De knoptekst mag maximaal 50 tekens bevatten.", + "buttonTargetTooLong": "Het doel mag maximaal 500 tekens bevatten.", + "buttonIncomplete": "Vul zowel de tekst als het doel van de knop in, of laat beide leeg.", + "buttonTargetInvalid": "Kies een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…).", + "altTooLong": "De beschrijving mag maximaal 300 tekens bevatten.", + "altRequired": "Geef een beschrijving of kies ‘Alleen versiering’." + }, + "upload": { + "tooLarge": "De afbeelding is te groot (maximaal {{max}} MB).", + "interrupted": "De upload is afgebroken. Controleer de verbinding en probeer het opnieuw.", + "busy": "Er zijn te veel uploads achter elkaar. Probeer het over een paar minuten opnieuw.", + "notAnImage": "Dit bestand is geen afbeelding.", + "progress": "Bezig met uploaden: {{done}} van {{total}}", + "summary": "{{ok}} van {{total}} foto’s toegevoegd", + "waiting": "wacht", + "uploading": "bezig…", + "done": "toegevoegd", + "close": "Sluiten" + }, + "help": { + "heading": "Uitleg per onderdeel", + "save": "Wijzigingen gelden pas nadat je de hero opslaat.", + "title": { + "name": "Titel", + "text": "De grote kop. Een nieuwe regel in het veld is een nieuwe regel in de kop." + }, + "tagline": { + "name": "Korte tekst boven de titel", + "text": "Een kort label dat boven of voor de titel staat. Mag leeg blijven." + }, + "lead": { + "name": "Introductietekst", + "text": "Een of twee zinnen onder de titel. Mag leeg blijven." + }, + "buttons": { + "name": "Knoppen", + "text": "Maximaal twee, elk met een tekst en een doel. Als doel kies je een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…)." + }, + "display": { + "name": "Weergave", + "text": "‘Enkel’ toont één foto, ‘Diavoorstelling’ wisselt tussen de foto’s." + }, + "slides": { + "name": "Afbeeldingen", + "text": "Upload foto’s, beschrijf wat erop staat en bepaal de volgorde (slepen of de pijltjes). Met de schakelaar zet je een foto actief of niet actief. Kies ‘Verberg voor schermlezers’ voor een foto die niets toevoegt aan de inhoud." + }, + "focus": { + "name": "Focus", + "text": "Geef aan waar het onderwerp op de foto staat, zodat een uitsnede er niets van afhakt. Voor staande schermen, zoals een telefoon, kun je een apart punt kiezen." + } + }, + "unsaved": { + "badge": "Niet-opgeslagen wijzigingen", + "text": "Sla de hero op om ze door te voeren op de website.", + "leaveTitle": "Wijzigingen niet opgeslagen", + "leaveText": "Je hebt wijzigingen gemaakt die nog niet zijn opgeslagen. Als je deze pagina verlaat, gaan ze verloren.", + "stay": "Blijven", + "discard": "Wijzigingen weggooien" + }, + "saving": "Bezig met opslaan…", + "tabs": { + "label": "Onderdelen van de hero", + "content": "Inhoud", + "images": "Afbeeldingen", + "busy": "{{count}} bezig", + "hasChanges": "niet-opgeslagen wijzigingen", + "hasErrors": "bevat fouten" + } + }, + "media": { + "progress": { + "working": "Wordt verwerkt…" + }, + "module": { + "hero": "Hero" + }, + "use": { + "slide": "slide", + "none": "Niet gebruikt", + "off": "uit", + "noneSince": "Niet gebruikt sinds {{date}}" + }, + "list": { + "label": "Foto's", + "empty": "Er zijn geen foto's.", + "selectAll": "Alles selecteren", + "noThumbnail": "Geen voorbeeld", + "photoName": "Foto {{width}} × {{height}}" + }, + "bulk": { + "label": "Acties op de selectie", + "selected_one": "{{count}} foto geselecteerd", + "selected_other": "{{count}} foto's geselecteerd", + "clear": "Selectie wissen" + }, + "loading": "Laden...", + "error": "De mediabibliotheek kon niet worden geladen.", + "page": { + "title": "Mediabibliotheek", + "noModules": "Er is nog geen module die foto's meldt." + }, + "storage": { + "title": "Opslag", + "used": "{{used}} in gebruik", + "usedOf": "{{used}} van {{limit}} in gebruik ({{percent}}%)", + "warning": "De opslag is voor meer dan {{percent}}% vol. Ruim foto's op voordat de limiet bereikt is.", + "full": "De opslag is vol. Er kunnen geen foto's meer worden geüpload tot er ruimte is." + }, + "cleanup": { + "open": "Opruimen", + "title": "Opruimen", + "description": "Foto's die ouder zijn dan het aantal dagen hieronder, nieuwste eerst. Haal foto's uit de selectie die je wilt houden.", + "days_one": "Ouder dan {{count}} dag", + "days_other": "Ouder dan {{count}} dagen", + "onlyUnused": "Alleen ongebruikte foto's", + "summary_one": "{{count}} foto ({{size}}) komt in aanmerking.", + "summary_other": "{{count}} foto's ({{size}}) komen in aanmerking.", + "selectedSize": "Geselecteerd: {{size}}", + "trashNote": "De geselecteerde foto's gaan naar de prullenbak en kunnen 7 dagen worden teruggezet.", + "confirm_one": "{{count}} foto naar de prullenbak", + "confirm_other": "{{count}} foto's naar de prullenbak" + }, + "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." + }, + "view": { + "label": "Weergave", + "library": "Bibliotheek", + "trash": "Prullenbak" + }, + "trash": { + "since": "In de prullenbak sinds {{date}}", + "restore": "Terugzetten", + "note": "Foto's in de prullenbak worden na 7 dagen definitief verwijderd (standaard). Zet ze terug zolang het kan, of verwijder ze nu definitief." + }, + "delete": { + "action": "Naar prullenbak", + "title": "Foto's naar de prullenbak", + "confirm_one": "Deze foto gaat naar de prullenbak. Je kunt hem 7 dagen terugzetten.", + "confirm_other": "Deze {{count}} foto's gaan naar de prullenbak. Je kunt ze 7 dagen terugzetten.", + "inUseCount_one": "{{count}} foto wordt nog gebruikt.", + "inUseCount_other": "{{count}} foto's worden nog gebruikt.", + "secondTitle": "Foto's in gebruik verwijderen?", + "secondText_one": "Deze foto wordt nog gebruikt. Als je doorgaat, verdwijnt hij van de plekken hieronder (bij de Hero verdwijnt de slide).", + "secondText_other": "Deze foto's worden nog gebruikt. Als je doorgaat, verdwijnen ze van de plekken hieronder (bij de Hero verdwijnt de slide).", + "confirmButton": "Naar prullenbak", + "confirmSecond": "Ja, toch verwijderen", + "cancel": "Annuleren", + "close": "Sluiten", + "partial_one": "{{count}} foto kon niet worden verwijderd. De rest is naar de prullenbak.", + "partial_other": "{{count}} foto's konden niet worden verwijderd. De rest is naar de prullenbak." + }, + "filter": { + "label": "Filter", + "all": "Alle foto's", + "used": "Gebruikt", + "unused": "Ongebruikt" + }, + "purge": { + "action": "Definitief verwijderen", + "title": "Definitief verwijderen", + "emptyTitle": "Prullenbak legen", + "emptyButton": "Prullenbak legen", + "emptyConfirm": "Prullenbak legen", + "confirmButton": "Definitief verwijderen", + "confirm_one": "Deze foto wordt definitief verwijderd, met zijn bestanden.", + "confirm_other": "Deze {{count}} foto's worden definitief verwijderd, met hun bestanden.", + "confirmAll_one": "De prullenbak wordt geleegd: {{count}} foto ({{size}}) wordt definitief verwijderd.", + "confirmAll_other": "De prullenbak wordt geleegd: {{count}} foto's ({{size}}) worden definitief verwijderd.", + "irreversible": "Dit kan niet ongedaan worden gemaakt.", + "partial_one": "{{count}} foto kon niet worden verwijderd. De rest is definitief verwijderd.", + "partial_other": "{{count}} foto's konden niet worden verwijderd. De rest is definitief verwijderd." + } + } +} -- 2.39.5 From e2d353b54d69d11f43f7d02a7719cfe0c75f9024 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 20:01:07 +0100 Subject: [PATCH 18/22] Mediabibliotheek: tegels als standaardweergave, schakelaar tegels/lijst met onthouden keuze Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 1 + .../media/components/PhotoSelectionList.tsx | 120 +++++++++++------- .../features/media/lib/layoutPreference.ts | 28 ++++ .../media/pages/MediaLibraryPage.test.tsx | 31 +++++ .../features/media/pages/MediaLibraryPage.tsx | 30 +++-- frontend/src/i18n/locales/en/translation.json | 5 + frontend/src/i18n/locales/nl/translation.json | 5 + 7 files changed, 165 insertions(+), 55 deletions(-) create mode 100644 frontend/src/features/media/lib/layoutPreference.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 c9a185f..53b6c14 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -72,3 +72,4 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 41 | **The picker has a single and a multiple mode** (Bryan, 2026-11-17). | `ImagePicker` takes `mode="single"` (default, radio group, used by the hero slides) or `mode="multiple"` (checkboxes, several photos, several files per upload, ready for the gallery). Both use the same upload checks. | n/a | `ImagePicker.tsx` | | 42 | **One progress pattern for upload, processing and a new crop** (Bryan, 2026-11-17, after seeing it on test). | A shared `ProcessingProgress` (text "Wordt verwerkt…", one 0-100% bar, the percentage, no spinner, no step counts) is used on every photo and for the batch. The batch bar covers upload and processing together; there are no byte counts from the upload, so a photo's percentage is staged: waiting 0, uploading 15, uploaded 30, then 30-100 from the server's processing steps. A new crop uses the full 0-100 from its steps. The counter "x van y verwerkt" stays per batch. | Real upload byte progress (needs XHR progress in the API client). | `features/media/components/ProcessingProgress.tsx`, `lib/photoProgress.ts`, `hero/components/ProcessingStatus.tsx` | | 43 | **"Slide toevoegen" replaces the per-slide library button** (Bryan, 2026-11-17, after seeing it on test; replaces assumption 36's per-slide button). | The per-slide "Kies uit bibliotheek" is gone. The existing add button is "Slide toevoegen" and opens the shared picker: choose a library photo or upload one on the spot (it also lands in the library, ML-17); one photo makes one NEW slide. A slide's photo cannot be changed or replaced: remove the slide and add another. Dropping files on the section still adds one slide per file (same upload as before). The crop per slide stays a goal (phase 2). | Keep a per-slide change button: Bryan said no. | `HeroPage.addSlideWithPhoto`, `LibraryPickerDialog` | +| 44 | **Tiles or list in the library** (Bryan, 2026-11-17). | The library and the trash show the photos as tiles (grid of thumbnails, selectable, same usage and links) by default, with a switch Tiles / List next to the filters. The choice is remembered in the browser (`localStorage`, guarded; it falls back to tiles). The clean-up dialog keeps its list. The picker already is a grid. | Remember the choice on the server per user: needs a user-settings store. | `PhotoSelectionList` (`layout`), `lib/layoutPreference.ts`, `MediaLibraryPage` | diff --git a/frontend/src/features/media/components/PhotoSelectionList.tsx b/frontend/src/features/media/components/PhotoSelectionList.tsx index 543e7a5..d53d795 100644 --- a/frontend/src/features/media/components/PhotoSelectionList.tsx +++ b/frontend/src/features/media/components/PhotoSelectionList.tsx @@ -1,6 +1,7 @@ import { useRef, type ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; import { Checkbox } from '@/components/ui/checkbox'; +import { cn } from '@/lib/utils'; import { formatBytes } from '../lib/format'; import { BulkActionBar, type BulkActionBarProps } from './BulkActionBar'; import { usageLabel } from '../lib/usageLabel'; @@ -38,13 +39,15 @@ interface PhotoSelectionListProps { renderUse?: (use: PhotoUse, label: string) => ReactNode; /** The actions on the selection. They appear in the header of the list, above the photos, once something is selected. */ bulk?: Omit; + /** A list of rows (default) or a grid of tiles with big thumbnails. Everything works in both. */ + layout?: 'list' | 'tiles'; } /** * 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, renderUse, bulk }: PhotoSelectionListProps) { +export function PhotoSelectionList({ items, selection, onSelectionChange, isDisabled, renderUse, bulk, layout = 'list' }: PhotoSelectionListProps) { const { t, i18n } = useTranslation(); const anchor = useRef(null); const selectable = items.filter((item) => !isDisabled?.(item)); @@ -85,56 +88,79 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa {t('media.bulk.selected', { count: selection.size })}
-
    +
      {items.map((item) => { const disabled = isDisabled?.(item) ?? false; const labelId = `photo-${item.id}-label`; - return ( + const tiles = layout === 'tiles'; + const checkbox = ( + undefined} + onClick={(event) => onItemClick(item.id, event.currentTarget.checked, event.shiftKey)} + /> + ); + const thumbnail = item.thumbnailUrl ? ( + + ) : ( + + {t('media.list.noThumbnail')} + + ); + const details = ( +
      +

      + {item.name} +

      +

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

      +

      + {item.deletedAt ? ( + {t('media.trash.since', { date: dateFormat.format(new Date(item.deletedAt)) })} + ) : item.uses.length === 0 ? ( + + {item.unusedSince ? t('media.use.noneSince', { date: dateFormat.format(new Date(item.unusedSince)) }) : t('media.use.none')} + + ) : ( + + {item.uses.map((use, index) => { + const label = usageLabel(t, use); + return ( + + {index > 0 && '; '} + {renderUse ? renderUse(use, label) : label} + + ); + })} + + )} +

      +
      + ); + return tiles ? ( +
    • +
      {checkbox}
      + {thumbnail} +
      {details}
      +
    • + ) : (
    • - 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.deletedAt ? ( - {t('media.trash.since', { date: dateFormat.format(new Date(item.deletedAt)) })} - ) : item.uses.length === 0 ? ( - - {item.unusedSince ? t('media.use.noneSince', { date: dateFormat.format(new Date(item.unusedSince)) }) : t('media.use.none')} - - ) : ( - - {item.uses.map((use, index) => { - const label = usageLabel(t, use); - return ( - - {index > 0 && '; '} - {renderUse ? renderUse(use, label) : label} - - ); - })} - - )} -

      -
      + {checkbox} + {thumbnail} + {details}
    • ); })} diff --git a/frontend/src/features/media/lib/layoutPreference.ts b/frontend/src/features/media/lib/layoutPreference.ts new file mode 100644 index 0000000..831aa1a --- /dev/null +++ b/frontend/src/features/media/lib/layoutPreference.ts @@ -0,0 +1,28 @@ +import { useCallback, useState } from 'react'; + +export type PhotoLayout = 'tiles' | 'list'; + +const KEY = 'slp.media.layout'; + +/** The layout this user chose last (tiles by default). Browser storage may be blocked, so every access is guarded. */ +export function readLayout(): PhotoLayout { + try { + return window.localStorage.getItem(KEY) === 'list' ? 'list' : 'tiles'; + } catch { + return 'tiles'; + } +} + +/** The layout of the photos and a setter that remembers the choice per user (per browser). */ +export function useLayoutPreference(): [PhotoLayout, (layout: PhotoLayout) => void] { + const [layout, setLayoutState] = useState(readLayout); + const setLayout = useCallback((next: PhotoLayout) => { + setLayoutState(next); + try { + window.localStorage.setItem(KEY, next); + } catch { + // Blocked or full: the choice then only lasts for this visit. + } + }, []); + return [layout, setLayout]; +} diff --git a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx index cf4378a..64662c0 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx @@ -23,6 +23,7 @@ function renderPage() { } beforeEach(async () => { + window.localStorage.removeItem('slp.media.layout'); await i18n.changeLanguage('nl'); }); @@ -289,6 +290,36 @@ describe('MediaLibraryPage', () => { expect(await screen.findByTestId('purge-partial')).toHaveTextContent('1 foto kon niet worden verwijderd'); }); + it('shows tiles by default, switches to a list, remembers the choice and keeps every function in both', async () => { + const first = renderPage(); + await screen.findByTestId('photo-selection-list'); + expect(screen.getByTestId('photo-items')).toHaveAttribute('data-layout', 'tiles'); + expect(screen.getByTestId('layout-tiles')).toHaveAttribute('aria-pressed', 'true'); + + // Selecting and the bulk bar work on tiles. + await userEvent.click(screen.getByRole('checkbox', { name: 'zomer.jpg' })); + expect(await screen.findByTestId('bulk-count')).toHaveTextContent('1 foto geselecteerd'); + + // The filter works on tiles. + await userEvent.click(screen.getByTestId('filter-unused')); + expect(within(screen.getByTestId('photo-items')).getAllByRole('listitem')).toHaveLength(1); + await userEvent.click(screen.getByTestId('filter-all')); + + await userEvent.click(screen.getByTestId('layout-list')); + expect(screen.getByTestId('photo-items')).toHaveAttribute('data-layout', 'list'); + expect(screen.getByTestId('layout-list')).toHaveAttribute('aria-pressed', 'true'); + expect(window.localStorage.getItem('slp.media.layout')).toBe('list'); + first.unmount(); + + // A later visit starts with the remembered layout, also in the trash view. + renderPage(); + await screen.findByTestId('photo-selection-list'); + expect(screen.getByTestId('photo-items')).toHaveAttribute('data-layout', 'list'); + await userEvent.click(screen.getByTestId('view-trash')); + await screen.findByTestId('trash-note'); + expect(screen.getByTestId('layout-list')).toBeInTheDocument(); + }); + it('shows an error when the library cannot be loaded', async () => { server.use(http.get('*/media-library/photos', () => new HttpResponse(null, { status: 500 }))); renderPage(); diff --git a/frontend/src/features/media/pages/MediaLibraryPage.tsx b/frontend/src/features/media/pages/MediaLibraryPage.tsx index 1727c5f..5bf5208 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.tsx @@ -1,13 +1,14 @@ import { useMemo, useState, type ReactNode } from 'react'; import { Link } from '@tanstack/react-router'; import { useTranslation } from 'react-i18next'; -import { Eraser, RotateCcw, Trash2, XCircle } from 'lucide-react'; +import { Eraser, LayoutGrid, List, RotateCcw, Trash2, XCircle } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { CleanupDialog } from '../components/CleanupDialog'; import { DeleteDialog } from '../components/DeleteDialog'; import { PurgeDialog } from '../components/PurgeDialog'; import { PhotoSelectionList, type PhotoUse } from '../components/PhotoSelectionList'; import { StorageMeter } from '../components/StorageMeter'; +import { useLayoutPreference } from '../lib/layoutPreference'; import { emptySelection, prune, type Selection } from '../lib/selection'; import { rememberHeroImagesTab, usageTarget } from '../lib/usageLabel'; import { toPhotoItem } from '../lib/toPhotoItem'; @@ -44,6 +45,7 @@ export function MediaLibraryPage() { const [deleting, setDeleting] = useState(false); const [purging, setPurging] = useState<'selected' | 'all' | null>(null); const [filter, setFilter] = useState('all'); + const [layout, setLayout] = useLayoutPreference(); const source = view === 'library' ? photos : trash; const items = useMemo( @@ -97,15 +99,27 @@ export function MediaLibraryPage() { ))}
- {view === 'library' && ( -
- {(['all', 'used', 'unused'] as const).map((value) => ( - + ))} +
+ ) : ( + + )} +
+ {([['tiles', LayoutGrid], ['list', List]] as const).map(([value, Icon]) => ( + ))}
- )} +
{view === 'trash' && (
@@ -128,7 +142,7 @@ export function MediaLibraryPage() { {t('media.page.noModules')}

)} - {source.data && setSelection(emptySelection) }} />} + {source.data && setSelection(emptySelection) }} />} Date: Tue, 17 Nov 2026 20:34:54 +0100 Subject: [PATCH 19/22] Mediabibliotheek: gelijke ruimte rond het selectievakje op de tegel Co-Authored-By: Claude Sonnet 5.5 --- frontend/src/features/media/components/PhotoSelectionList.tsx | 3 ++- frontend/src/features/media/pages/MediaLibraryPage.test.tsx | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/frontend/src/features/media/components/PhotoSelectionList.tsx b/frontend/src/features/media/components/PhotoSelectionList.tsx index d53d795..d2987e8 100644 --- a/frontend/src/features/media/components/PhotoSelectionList.tsx +++ b/frontend/src/features/media/components/PhotoSelectionList.tsx @@ -152,7 +152,8 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa className={cn('relative overflow-hidden rounded-md border bg-card', selection.has(item.id) && 'ring-2 ring-primary')} data-testid={`photo-row-${item.id}`} > -
{checkbox}
+ {/* flex (not a block with an inline box inside): no line box, so no extra space under the checkbox and equal padding on all four sides */} +
{checkbox}
{thumbnail}
{details}
diff --git a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx index 64662c0..fdcb7d7 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx @@ -295,6 +295,9 @@ describe('MediaLibraryPage', () => { await screen.findByTestId('photo-selection-list'); expect(screen.getByTestId('photo-items')).toHaveAttribute('data-layout', 'tiles'); expect(screen.getByTestId('layout-tiles')).toHaveAttribute('aria-pressed', 'true'); + // The checkbox chip is a flex box with equal padding: no inline line box that would add space under the box. + const chip = screen.getAllByTestId(/^photo-chip-/)[0]!; + expect(chip).toHaveClass('flex', 'p-1'); // Selecting and the bulk bar work on tiles. await userEvent.click(screen.getByRole('checkbox', { name: 'zomer.jpg' })); -- 2.39.5 From 723226c7c46407b83ac75cbe1464f3b31a3f5e50 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 21:03:05 +0100 Subject: [PATCH 20/22] Mediascherm: vaste hoogte van de bulkbalk, hele tegel selecteert, kleinere tegels, 0 dagen bij opruimen Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 1 + .../media/components/BulkActionBar.tsx | 6 +- .../media/components/CleanupDialog.tsx | 11 +++- .../components/PhotoSelectionList.test.tsx | 61 ++++++++++++++++++- .../media/components/PhotoSelectionList.tsx | 10 ++- .../media/pages/MediaLibraryPage.test.tsx | 18 +++++- frontend/src/i18n/locales/en/translation.json | 6 +- frontend/src/i18n/locales/nl/translation.json | 6 +- .../Media/MediaLibraryTests.cs | 14 ++++- .../Media/Library/CleanupSelection.cs | 3 +- 10 files changed, 120 insertions(+), 16 deletions(-) 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 53b6c14..344c1e6 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -73,3 +73,4 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 42 | **One progress pattern for upload, processing and a new crop** (Bryan, 2026-11-17, after seeing it on test). | A shared `ProcessingProgress` (text "Wordt verwerkt…", one 0-100% bar, the percentage, no spinner, no step counts) is used on every photo and for the batch. The batch bar covers upload and processing together; there are no byte counts from the upload, so a photo's percentage is staged: waiting 0, uploading 15, uploaded 30, then 30-100 from the server's processing steps. A new crop uses the full 0-100 from its steps. The counter "x van y verwerkt" stays per batch. | Real upload byte progress (needs XHR progress in the API client). | `features/media/components/ProcessingProgress.tsx`, `lib/photoProgress.ts`, `hero/components/ProcessingStatus.tsx` | | 43 | **"Slide toevoegen" replaces the per-slide library button** (Bryan, 2026-11-17, after seeing it on test; replaces assumption 36's per-slide button). | The per-slide "Kies uit bibliotheek" is gone. The existing add button is "Slide toevoegen" and opens the shared picker: choose a library photo or upload one on the spot (it also lands in the library, ML-17); one photo makes one NEW slide. A slide's photo cannot be changed or replaced: remove the slide and add another. Dropping files on the section still adds one slide per file (same upload as before). The crop per slide stays a goal (phase 2). | Keep a per-slide change button: Bryan said no. | `HeroPage.addSlideWithPhoto`, `LibraryPickerDialog` | | 44 | **Tiles or list in the library** (Bryan, 2026-11-17). | The library and the trash show the photos as tiles (grid of thumbnails, selectable, same usage and links) by default, with a switch Tiles / List next to the filters. The choice is remembered in the browser (`localStorage`, guarded; it falls back to tiles). The clean-up dialog keeps its list. The picker already is a grid. | Remember the choice on the server per user: needs a user-settings store. | `PhotoSelectionList` (`layout`), `lib/layoutPreference.ts`, `MediaLibraryPage` | +| 45 | **Media screen details** (Bryan, 2026-11-17): bulk bar keeps its height; the whole tile selects; smaller tiles; 0 days in the clean-up; no time-basis choice. | The bar is an invisible placeholder of the same height (h-9) while nothing is selected. A click on a tile selects it (shift for a range); links, buttons and the box itself do their own thing. One more tile per row at every width. The clean-up slider goes from 0: 0 days means every photo that is not in use right now qualifies at the next clean-up (preview and confirmation unchanged, with a note at 0). The period always counts from the last use (assumption 29); there was no separate checkbox for the time basis in the clean-up (the only checkbox is "Alleen ongebruikte foto's", a filter, which stays because it protects photos in use), so nothing was removed. | If Bryan meant "Alleen ongebruikte foto's": removing it would put photos in use in the clean-up (counted from their upload date). | `BulkActionBar`, `PhotoSelectionList`, `CleanupDialog`, `CleanupSelection.MinDays` | diff --git a/frontend/src/features/media/components/BulkActionBar.tsx b/frontend/src/features/media/components/BulkActionBar.tsx index 96ab255..15153a1 100644 --- a/frontend/src/features/media/components/BulkActionBar.tsx +++ b/frontend/src/features/media/components/BulkActionBar.tsx @@ -23,11 +23,13 @@ export interface BulkActionBarProps { /** * The actions on the selected photos: the count, a way to clear the selection and the actions. It sits in the header of * the photo list (see PhotoSelectionList), which is the one shared place for it. The actions are data, so more of - * them (tags, move) can be added without touching the list. It shows nothing while nothing is selected. + * them (tags, move) can be added without touching the list. While nothing is selected it is an empty box of the same height. */ export function BulkActionBar({ count, actions, onClear, summary }: BulkActionBarProps) { const { t } = useTranslation(); - if (count === 0) return null; + // The bar keeps its height while nothing is selected (an invisible placeholder), so the photos never jump when the first + // photo is selected. + if (count === 0) return