Mediabibliotheek: verwijderen naar prullenbak in de UI, terugzetten, opruimen bevestigen, migratieplan, besluiten van Bryan in de docs
Continuous Integration / changes (pull_request) Successful in 14s
Continuous Integration / config-sls (pull_request) Successful in 9s
Continuous Integration / config-asf (pull_request) Successful in 8s
Continuous Integration / backend-test (pull_request) Canceled after 0s
Continuous Integration / frontend-prepare (pull_request) Canceled after 0s
Continuous Integration / frontend-build (pull_request) Canceled after 0s
Continuous Integration / frontend-test (pull_request) Canceled after 0s
Continuous Integration / frontend-lint (pull_request) Canceled after 0s
Continuous Integration / publish-sls-test (pull_request) Canceled after 0s
Continuous Integration / publish-sls-production (pull_request) Canceled after 0s
Continuous Integration / deploy-sls-test (pull_request) Canceled after 0s
Continuous Integration / deploy-sls-production (pull_request) Canceled after 0s
Continuous Integration / publish-asf-test (pull_request) Canceled after 0s
Continuous Integration / deploy-asf-test (pull_request) Canceled after 0s
Continuous Integration / smoke-sls-test (pull_request) Canceled after 0s
Continuous Integration / smoke-asf-test (pull_request) Canceled after 0s
Continuous Integration / backend-build (pull_request) Canceled after 48s
Continuous Integration / compile-sites (pull_request) Canceled after 52s
Continuous Integration / vulnerability-scan (pull_request) Canceled after 57s
Continuous Integration / changes (pull_request) Successful in 14s
Continuous Integration / config-sls (pull_request) Successful in 9s
Continuous Integration / config-asf (pull_request) Successful in 8s
Continuous Integration / backend-test (pull_request) Canceled after 0s
Continuous Integration / frontend-prepare (pull_request) Canceled after 0s
Continuous Integration / frontend-build (pull_request) Canceled after 0s
Continuous Integration / frontend-test (pull_request) Canceled after 0s
Continuous Integration / frontend-lint (pull_request) Canceled after 0s
Continuous Integration / publish-sls-test (pull_request) Canceled after 0s
Continuous Integration / publish-sls-production (pull_request) Canceled after 0s
Continuous Integration / deploy-sls-test (pull_request) Canceled after 0s
Continuous Integration / deploy-sls-production (pull_request) Canceled after 0s
Continuous Integration / publish-asf-test (pull_request) Canceled after 0s
Continuous Integration / deploy-asf-test (pull_request) Canceled after 0s
Continuous Integration / smoke-sls-test (pull_request) Canceled after 0s
Continuous Integration / smoke-asf-test (pull_request) Canceled after 0s
Continuous Integration / backend-build (pull_request) Canceled after 48s
Continuous Integration / compile-sites (pull_request) Canceled after 52s
Continuous Integration / vulnerability-scan (pull_request) Canceled after 57s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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<ReadonlySet<string>>(new Set());
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | 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
|
||||
/>
|
||||
|
||||
<p className="rounded-md border border-dashed p-3 text-sm text-muted-foreground" data-testid="cleanup-preview-note">
|
||||
{t('media.cleanup.previewNote')}
|
||||
{t('media.cleanup.trashNote')}
|
||||
</p>
|
||||
|
||||
{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) })}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" variant="destructive" disabled={selectedItems.length === 0} onClick={() => setDeleting(true)} data-testid="cleanup-confirm">
|
||||
{t('media.cleanup.confirm', { count: selectedItems.length })}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<DeleteDialog
|
||||
open={deleting}
|
||||
onOpenChange={setDeleting}
|
||||
items={selectedItems}
|
||||
onDone={() => {
|
||||
setExcluded(new Set());
|
||||
onOpenChange(false);
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -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 (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent data-testid="delete-dialog">{open && <DeleteDialogBody items={items} onClose={() => onOpenChange(false)} onDone={onDone} />}</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('media.delete.title')}</DialogTitle>
|
||||
<DialogDescription role="alert" data-testid="delete-partial">
|
||||
{t('media.delete.partial', { count: failed })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button type="button" onClick={onClose} data-testid="delete-close">
|
||||
{t('media.delete.close')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{step === 'first' ? t('media.delete.title') : t('media.delete.secondTitle')}</DialogTitle>
|
||||
<DialogDescription data-testid="delete-text">
|
||||
{step === 'first' ? t('media.delete.confirm', { count: items.length }) : t('media.delete.secondText', { count: inUse.length })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{step === 'first' && inUse.length > 0 && (
|
||||
<p className="text-sm font-medium" data-testid="delete-inuse-count">
|
||||
{t('media.delete.inUseCount', { count: inUse.length })}
|
||||
</p>
|
||||
)}
|
||||
{step === 'second' && (
|
||||
<ul className="max-h-60 space-y-1 overflow-y-auto text-sm" data-testid="delete-places">
|
||||
{inUse.map((item) => (
|
||||
<li key={item.id}>
|
||||
<span className="font-medium">{item.name}</span>: {item.uses.map((use) => usageLabel(t, use)).join('; ')}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{trash.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t('media.error')}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={trash.isPending} data-testid="delete-cancel">
|
||||
{t('media.delete.cancel')}
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" onClick={onConfirm} disabled={trash.isPending || items.length === 0} data-testid="delete-confirm">
|
||||
{step === 'second' ? t('media.delete.confirmSecond') : t('media.delete.confirmButton')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<p className="rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground" data-testid="photo-list-empty">
|
||||
@@ -106,10 +105,14 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa
|
||||
{dateFormat.format(new Date(item.createdAt))} · {formatBytes(item.bytes, i18n.language)}
|
||||
</p>
|
||||
<p className="text-xs" data-testid={`photo-usage-${item.id}`}>
|
||||
{item.uses.length === 0 ? (
|
||||
<span className="text-muted-foreground">{t('media.use.none')}</span>
|
||||
{item.deletedAt ? (
|
||||
<span className="text-muted-foreground">{t('media.trash.since', { date: dateFormat.format(new Date(item.deletedAt)) })}</span>
|
||||
) : item.uses.length === 0 ? (
|
||||
<span className="text-muted-foreground">
|
||||
{item.unusedSince ? t('media.use.noneSince', { date: dateFormat.format(new Date(item.unusedSince)) }) : t('media.use.none')}
|
||||
</span>
|
||||
) : (
|
||||
<span>{item.uses.map(usageLabel).join('; ')}</span>
|
||||
<span>{item.uses.map((use) => usageLabel(t, use)).join('; ')}</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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')})`}`;
|
||||
}
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -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(<MediaLibraryPage />);
|
||||
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(<MediaLibraryPage />);
|
||||
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(<MediaLibraryPage />);
|
||||
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(<MediaLibraryPage />);
|
||||
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(<MediaLibraryPage />);
|
||||
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(<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-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(<MediaLibraryPage />);
|
||||
|
||||
@@ -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<View>('library');
|
||||
const photos = useMediaPhotos();
|
||||
const trash = useMediaTrash(view === 'trash');
|
||||
const storage = useMediaStorage();
|
||||
const restore = useRestorePhotos();
|
||||
const [chosen, setSelection] = useState<Selection>(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: <Trash2 className="mr-2 size-4" aria-hidden="true" />, run: () => setDeleting(true) }]
|
||||
: [
|
||||
{
|
||||
id: 'restore',
|
||||
label: t('media.trash.restore'),
|
||||
disabled: restore.isPending,
|
||||
icon: <RotateCcw className="mr-2 size-4" aria-hidden="true" />,
|
||||
run: () => restore.mutate(selectedItems.map((i) => i.id), { onSuccess: () => setSelection(emptySelection) }),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6" data-testid="media-library-page">
|
||||
@@ -37,21 +64,35 @@ export function MediaLibraryPage() {
|
||||
|
||||
{storage.data && <StorageMeter storage={storage.data} />}
|
||||
|
||||
{photos.isError && (
|
||||
<div className="flex gap-2" role="group" aria-label={t('media.view.label')}>
|
||||
{(['library', 'trash'] as const).map((value) => (
|
||||
<Button key={value} type="button" size="sm" variant={view === value ? 'default' : 'outline'} aria-pressed={view === value} onClick={() => switchView(value)} data-testid={`view-${value}`}>
|
||||
{t(`media.view.${value}`)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{view === 'trash' && (
|
||||
<p className="text-sm text-muted-foreground" data-testid="trash-note">
|
||||
{t('media.trash.note')}
|
||||
</p>
|
||||
)}
|
||||
{source.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 && (
|
||||
{source.isPending && <p className="text-sm text-muted-foreground">{t('media.loading')}</p>}
|
||||
{view === 'library' && 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)} />
|
||||
{source.data && <PhotoSelectionList items={items} selection={selection} onSelectionChange={setSelection} />}
|
||||
<BulkActionBar count={selection.size} actions={actions} onClear={() => setSelection(emptySelection)} />
|
||||
|
||||
<CleanupDialog open={cleanupOpen} onOpenChange={setCleanupOpen} />
|
||||
<DeleteDialog open={deleting} onOpenChange={setDeleting} items={selectedItems} onDone={() => setSelection(emptySelection)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaStorageDto } from './types';
|
||||
import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from './types';
|
||||
|
||||
export const MEDIA_KEY = ['media-library'];
|
||||
|
||||
@@ -30,3 +30,30 @@ export function useCleanupPreview(days: number, onlyUnused: boolean, enabled: bo
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
/** The photos in the trash, most recently trashed first. */
|
||||
export function useMediaTrash(enabled = true) {
|
||||
return useQuery<MediaLibraryDto, Error>({
|
||||
queryKey: [...MEDIA_KEY, 'trash'],
|
||||
queryFn: () => api.get<MediaLibraryDto>('/api/v1/media-library/trash'),
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
/** Moves photos to the trash. The answer says per photo what happened. */
|
||||
export function useTrashPhotos() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<MediaTrashResponse, Error, MediaTrashRequest>({
|
||||
mutationFn: (body) => api.post<MediaTrashResponse>('/api/v1/media-library/delete', body),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: MEDIA_KEY }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Takes photos out of the trash again. */
|
||||
export function useRestorePhotos() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<MediaTrashResponse, Error, string[]>({
|
||||
mutationFn: (ids) => api.post<MediaTrashResponse>('/api/v1/media-library/restore', { ids }),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: MEDIA_KEY }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -15,6 +15,11 @@ export interface MediaPhotoDto {
|
||||
createdAt: string;
|
||||
thumbnailUrl: string | null;
|
||||
uses: MediaUseDto[];
|
||||
originalFileName: string | null;
|
||||
/** When the photo was last detached from where it was used; null while it was never used. */
|
||||
unusedSince: string | null;
|
||||
/** When the photo went to the trash; null for a photo in the library. */
|
||||
deletedAt: string | null;
|
||||
}
|
||||
|
||||
export interface MediaLibraryDto {
|
||||
@@ -39,3 +44,21 @@ export interface MediaCleanupPreviewDto {
|
||||
bytes: number;
|
||||
photos: MediaPhotoDto[];
|
||||
}
|
||||
|
||||
export type MediaTrashStatus = 'trashed' | 'restored' | 'inUse' | 'notFound' | 'failed';
|
||||
|
||||
export interface MediaTrashResultDto {
|
||||
id: string;
|
||||
status: MediaTrashStatus;
|
||||
uses: MediaUseDto[];
|
||||
}
|
||||
|
||||
export interface MediaTrashResponse {
|
||||
results: MediaTrashResultDto[];
|
||||
}
|
||||
|
||||
export interface MediaTrashRequest {
|
||||
ids: string[];
|
||||
/** True when the person confirmed a second time, knowing where the photos in use are used. */
|
||||
confirmedInUse: boolean;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user