Mediabibliotheek: endpoints (foto's, opslag, opruimvoorbeeld) en scherm; ASF-verhoudingen in ontwerp en aannamelijst
Continuous Integration / config-asf (pull_request) Successful in 6s
Continuous Integration / config-sls (pull_request) Successful in 7s
Continuous Integration / changes (pull_request) Successful in 11s
Continuous Integration / compile-sites (pull_request) Successful in 1m44s
Continuous Integration / backend-build (pull_request) Successful in 1m49s
Continuous Integration / vulnerability-scan (pull_request) Successful in 1m51s
Continuous Integration / frontend-prepare (pull_request) Successful in 2m2s
Continuous Integration / frontend-build (pull_request) Successful in 42s
Continuous Integration / backend-test (pull_request) Failing after 3m56s
Continuous Integration / frontend-lint (pull_request) Successful in 39s
Continuous Integration / frontend-test (pull_request) Successful in 2m33s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 14:12:15 +01:00
co-authored by Claude Sonnet 5.5
parent 7e2e6a430f
commit caa178a58c
24 changed files with 1141 additions and 21 deletions
@@ -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<ReadonlySet<string>>(new Set());
const timer = useRef<ReturnType<typeof setTimeout> | 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<Selection>(() => 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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[90vh] max-w-3xl overflow-y-auto" data-testid="cleanup-dialog">
<DialogHeader>
<DialogTitle>{t('media.cleanup.title')}</DialogTitle>
<DialogDescription>{t('media.cleanup.description')}</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-1">
<Label htmlFor="cleanup-days">{t('media.cleanup.days', { count: days })}</Label>
<input
id="cleanup-days"
type="range"
min={MIN_DAYS}
max={MAX_DAYS}
step={1}
value={days}
onChange={(event) => changeDays(Number(event.target.value))}
className="w-full accent-primary"
data-testid="cleanup-days"
/>
</div>
<CheckboxField
checked={onlyUnused}
onChange={(event) => {
setOnlyUnused(event.target.checked);
setExcluded(new Set());
}}
label={t('media.cleanup.onlyUnused')}
data-testid="cleanup-only-unused"
/>
<p className="rounded-md border border-dashed p-3 text-sm text-muted-foreground" data-testid="cleanup-preview-note">
{t('media.cleanup.previewNote')}
</p>
{preview.isError && (
<p role="alert" className="text-sm text-destructive">
{t('media.error')}
</p>
)}
{preview.isPending && <p className="text-sm text-muted-foreground">{t('media.loading')}</p>}
{preview.data && (
<>
<p className="text-sm" data-testid="cleanup-summary">
{t('media.cleanup.summary', { count: preview.data.count, size: formatBytes(preview.data.bytes, i18n.language) })}
</p>
<PhotoSelectionList items={items} selection={selection} onSelectionChange={setSelection} />
<BulkActionBar
count={selection.size}
actions={[]}
onClear={() => setSelection(new Set())}
summary={t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) })}
/>
</>
)}
</div>
</DialogContent>
</Dialog>
);
}
@@ -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.
@@ -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 (
<section aria-labelledby="storage-title" className="space-y-2 rounded-md border p-4" data-testid="storage-meter" data-level={storage.level}>
<h2 id="storage-title" className="text-sm font-medium">
{t('media.storage.title')}
</h2>
<p className="text-sm" data-testid="storage-text">
{hasLimit ? t('media.storage.usedOf', { used, limit: formatBytes(storage.limitBytes, i18n.language), percent }) : t('media.storage.used', { used })}
</p>
{hasLimit && (
<div
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={percent}
aria-labelledby="storage-title"
className="h-2 w-full overflow-hidden rounded-full bg-muted"
>
<div
className={cn('h-full', storage.level === 'full' ? 'bg-destructive' : storage.level === 'warning' ? 'bg-amber-500' : 'bg-primary')}
style={{ width: `${percent}%` }}
/>
</div>
)}
{storage.level !== 'ok' && (
<p role="alert" className={cn('text-sm font-medium', storage.level === 'full' ? 'text-destructive' : 'text-amber-700 dark:text-amber-400')} data-testid="storage-warning">
{storage.level === 'full' ? t('media.storage.full') : t('media.storage.warning', { percent: storage.warningPercent })}
</p>
)}
</section>
);
}
+12
View File
@@ -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]}`;
}
@@ -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,
};
}
@@ -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);
}),
];
@@ -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(<MediaLibraryPage />);
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(<MediaLibraryPage />);
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(<MediaLibraryPage />);
expect(await screen.findByTestId('storage-warning')).toHaveTextContent('vol');
});
it('selects photos and shows the bulk bar without any delete action yet', async () => {
renderWithProviders(<MediaLibraryPage />);
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(<MediaLibraryPage />);
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(<MediaLibraryPage />);
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(<MediaLibraryPage />);
expect(await screen.findByTestId('media-error')).toBeInTheDocument();
});
});
@@ -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<Selection>(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 (
<div className="space-y-6" data-testid="media-library-page">
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-2xl font-semibold">{t('media.page.title')}</h1>
<Button type="button" variant="outline" onClick={() => setCleanupOpen(true)} data-testid="cleanup-open">
<Eraser className="mr-2 size-4" aria-hidden="true" />
{t('media.cleanup.open')}
</Button>
</div>
{storage.data && <StorageMeter storage={storage.data} />}
{photos.isError && (
<p role="alert" className="text-sm text-destructive" data-testid="media-error">
{t('media.error')}
</p>
)}
{photos.isPending && <p className="text-sm text-muted-foreground">{t('media.loading')}</p>}
{photos.data && photos.data.modules.length === 0 && (
<p className="text-sm text-muted-foreground" data-testid="media-no-modules">
{t('media.page.noModules')}
</p>
)}
{photos.data && <PhotoSelectionList items={items} selection={selection} onSelectionChange={setSelection} />}
<BulkActionBar count={selection.size} actions={[]} onClear={() => setSelection(emptySelection)} />
<CleanupDialog open={cleanupOpen} onOpenChange={setCleanupOpen} />
</div>
);
}
@@ -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<MediaLibraryDto, Error>({
queryKey: [...MEDIA_KEY, 'photos'],
queryFn: () => api.get<MediaLibraryDto>('/api/v1/media-library/photos'),
});
}
/** The space the media directory takes against its limit. */
export function useMediaStorage() {
return useQuery<MediaStorageDto, Error>({
queryKey: [...MEDIA_KEY, 'storage'],
queryFn: () => api.get<MediaStorageDto>('/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<MediaCleanupPreviewDto, Error>({
queryKey: [...MEDIA_KEY, 'cleanup-preview', days, onlyUnused],
queryFn: () => api.get<MediaCleanupPreviewDto>(`/api/v1/media-library/cleanup-preview?days=${days}&onlyUnused=${onlyUnused}`),
enabled,
placeholderData: keepPreviousData,
});
}
@@ -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[];
}