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 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 17:05:34 +01:00
co-authored by Claude Sonnet 5.5
parent 4436a40ddf
commit e09304c2e9
10 changed files with 498 additions and 3 deletions
@@ -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<PhotoItem> => {
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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[90vh] max-w-3xl overflow-y-auto" data-testid="library-picker">
<DialogHeader>
<DialogTitle>{t('hero.library.title', { n: slideNumber })}</DialogTitle>
<DialogDescription>{t('hero.library.description')}</DialogDescription>
</DialogHeader>
{library.isError && (
<p role="alert" className="text-sm text-destructive">
{t('media.error')}
</p>
)}
{library.isPending ? (
<p className="text-sm text-muted-foreground">{t('media.loading')}</p>
) : (
<ImagePicker
items={items}
value={currentImageId ? `${MODULE}:${currentImageId}` : null}
onChange={(id) => onChoose(id.slice(MODULE.length + 1))}
onUpload={uploadHere}
maxUploadBytes={maxUploadBytes}
limitsText={limitsText}
label={t('hero.library.group', { n: slideNumber })}
/>
)}
</DialogContent>
</Dialog>
);
}
@@ -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<string, unknown> = {}) => ({
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');
});
});
+33 -1
View File
@@ -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<string[]>([]);
const [recutIds, setRecutIds] = useState<string[]>([]);
// The slide (by position) whose photo is being chosen from the library.
const [libraryFor, setLibraryFor] = useState<number | null>(null);
const fileInput = useRef<HTMLInputElement>(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 }) {
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted text-xs">?</div>
)}
<DoneStatus done={Boolean(image && justDone[image.id] && !image.processing)} slideNumber={index + 1} testId={`hero-slide-${index}-done`} />
<Button type="button" variant="outline" size="sm" onClick={() => setLibraryFor(index)} data-testid={`hero-slide-${index}-library`}>
{t('hero.library.choose')}
</Button>
</div>
<div className="min-w-[12rem] flex-1 space-y-2" role="group" aria-labelledby={`hero-slide-title-${field.id}`}>
<h3 id={`hero-slide-title-${field.id}`} className="text-xs font-medium uppercase tracking-wide text-muted-foreground" data-testid={`hero-slide-${index}-title`}>
@@ -632,6 +655,15 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
</Button>
</div>
<LibraryPickerDialog
open={libraryFor !== null}
onOpenChange={(open) => !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}
/>
<FocusDialog
image={focusImageId ? images[focusImageId] ?? null : null}
onApply={applyFocus}
@@ -216,6 +216,79 @@ describe('MediaLibraryPage', () => {
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();
@@ -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<MediaLibraryDto, Error>({
enabled,
queryKey: [...MEDIA_KEY, 'photos'],
queryFn: () => api.get<MediaLibraryDto>('/api/v1/media-library/photos'),
});
@@ -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",
@@ -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",