WIP: bulkbalk boven de lijst, definitief verwijderen en prullenbak legen, uitsnede direct zonder opslaan, teller per batch

This commit is contained in:
2026-11-17 16:58:23 +01:00
parent 8ad071da1c
commit 1384cafa7b
28 changed files with 816 additions and 134 deletions
@@ -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 <c>PhotoSelectionList</c>), 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 (
<div
role="toolbar"
aria-label={t('media.bulk.label')}
data-testid="bulk-action-bar"
className="sticky bottom-0 z-10 flex flex-wrap items-center gap-3 rounded-md border bg-background px-4 py-2 shadow-md"
>
<div role="toolbar" aria-label={t('media.bulk.label')} data-testid="bulk-action-bar" className="flex flex-1 flex-wrap items-center gap-3">
<span className="text-sm font-medium" data-testid="bulk-count">
{t('media.bulk.selected', { count })}
</span>
@@ -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
<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) })}
<PhotoSelectionList
items={items}
selection={selection}
onSelectionChange={setSelection}
bulk={{
actions: [],
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">
@@ -4,7 +4,6 @@ import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import i18n from '@/i18n/config';
import { emptySelection, type Selection } from '../lib/selection';
import { BulkActionBar } from './BulkActionBar';
import { PhotoSelectionList, type PhotoItem } from './PhotoSelectionList';
const items: PhotoItem[] = [
@@ -18,8 +17,13 @@ function Harness({ disabled }: { disabled?: (item: PhotoItem) => boolean }) {
const [selection, setSelection] = useState<Selection>(emptySelection);
return (
<>
<PhotoSelectionList items={items} selection={selection} onSelectionChange={setSelection} isDisabled={disabled} />
<BulkActionBar count={selection.size} actions={[{ id: 'delete', label: 'Verwijderen', destructive: true, run: vi.fn() }]} onClear={() => setSelection(emptySelection)} />
<PhotoSelectionList
items={items}
selection={selection}
onSelectionChange={setSelection}
isDisabled={disabled}
bulk={{ actions: [{ id: 'delete', label: 'Verwijderen', destructive: true, run: vi.fn() }], onClear: () => setSelection(emptySelection) }}
/>
</>
);
}
@@ -119,3 +123,21 @@ describe('BulkActionBar', () => {
expect(screen.getByRole('checkbox', { name: 'Foto 1' })).not.toBeChecked();
});
});
describe('the bulk bar is part of the list header, above the photos', () => {
it('sits in the sticky opaque header before the first photo, and only once something is selected', async () => {
render(<Harness />);
const header = screen.getByTestId('photo-list-header');
expect(header).toHaveClass('sticky', 'bg-background');
expect(header.className).not.toMatch(/bg-background\//);
expect(screen.queryByTestId('bulk-action-bar')).not.toBeInTheDocument();
await userEvent.click(screen.getByRole('checkbox', { name: 'Foto 2' }));
const bar = screen.getByTestId('bulk-action-bar');
expect(header).toContainElement(bar);
const first = screen.getByTestId('photo-row-p1');
expect(bar.compareDocumentPosition(first) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
});
@@ -2,6 +2,7 @@ import { useRef, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Checkbox } from '@/components/ui/checkbox';
import { formatBytes } from '../lib/format';
import { BulkActionBar, type BulkActionBarProps } from './BulkActionBar';
import { usageLabel } from '../lib/usageLabel';
import { selectAll, selectRange, stateOf, type Selection } from '../lib/selection';
@@ -35,13 +36,15 @@ interface PhotoSelectionListProps {
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 actions on the selection. They appear in the header of the list, above the photos, once something is selected. */
bulk?: Omit<BulkActionBarProps, 'count'>;
}
/**
* 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 }: PhotoSelectionListProps) {
export function PhotoSelectionList({ items, selection, onSelectionChange, isDisabled, renderUse, bulk }: PhotoSelectionListProps) {
const { t, i18n } = useTranslation();
const anchor = useRef<string | null>(null);
const selectable = items.filter((item) => !isDisabled?.(item));
@@ -64,7 +67,10 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa
return (
<div data-testid="photo-selection-list">
<div className="flex items-center gap-3 border-b px-2 py-2">
{/* The header of the list: select all, the count and the actions. Sticky and opaque so it stays in view above long
lists without anything showing through. A sticky box measures from the content edge of the scrolling area, which
has p-6 (the page and the dialogs), so -top-6 puts it on the edge. */}
<div className="sticky -top-6 z-10 flex flex-wrap items-center gap-3 border-b bg-background px-2 py-2" data-testid="photo-list-header">
<Checkbox
aria-label={t('media.list.selectAll')}
data-testid="photo-select-all"
@@ -74,6 +80,7 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa
onChange={() => onSelectionChange(state === 'all' ? new Set() : selectAll(selectableIds))}
/>
<span className="text-sm text-muted-foreground">{t('media.list.selectAll')}</span>
{bulk && <BulkActionBar count={selection.size} actions={bulk.actions} onClear={bulk.onClear} summary={bulk.summary} />}
<span className="sr-only" role="status" aria-live="polite" data-testid="photo-selection-status">
{t('media.bulk.selected', { count: selection.size })}
</span>
@@ -0,0 +1,95 @@
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 { formatBytes } from '../lib/format';
import { usePurgePhotos } from '../services/hooks';
interface PurgeDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
/** The photos to remove for good (ids as listed). Ignored when `all` is true. */
ids: readonly string[];
/** Empty the whole trash: the server removes everything that is in it. */
all?: boolean;
/** How many photos and how many bytes the confirmation names. */
count: number;
bytes: number;
onDone?: () => void;
}
/**
* Removing photos from the trash for good cannot be undone: the confirmation says so and names the number of photos (and
* their size when the whole trash is emptied). The server checks every photo again; a photo that went wrong is reported.
*/
export function PurgeDialog({ open, onOpenChange, ids, all = false, count, bytes, onDone }: PurgeDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent data-testid="purge-dialog">
{open && <PurgeDialogBody ids={ids} all={all} count={count} bytes={bytes} onClose={() => onOpenChange(false)} onDone={onDone} />}
</DialogContent>
</Dialog>
);
}
function PurgeDialogBody({ ids, all, count, bytes, onClose, onDone }: { ids: readonly string[]; all: boolean; count: number; bytes: number; onClose: () => void; onDone?: () => void }) {
const { t, i18n } = useTranslation();
const purge = usePurgePhotos();
const [failed, setFailed] = useState(0);
const submit = () =>
purge.mutate(all ? { all: true } : { ids: [...ids] }, {
onSuccess: ({ results }) => {
const removed = results.filter((r) => r.status === 'purged').length;
onDone?.();
const problems = results.length - removed;
if (problems === 0) onClose();
else setFailed(problems);
},
});
if (failed > 0) {
return (
<>
<DialogHeader>
<DialogTitle>{t('media.purge.title')}</DialogTitle>
<DialogDescription role="alert" data-testid="purge-partial">
{t('media.purge.partial', { count: failed })}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button type="button" onClick={onClose} data-testid="purge-close">
{t('media.delete.close')}
</Button>
</DialogFooter>
</>
);
}
return (
<>
<DialogHeader>
<DialogTitle>{all ? t('media.purge.emptyTitle') : t('media.purge.title')}</DialogTitle>
<DialogDescription data-testid="purge-text">
{all ? t('media.purge.confirmAll', { count, size: formatBytes(bytes, i18n.language) }) : t('media.purge.confirm', { count })}
</DialogDescription>
</DialogHeader>
<p className="text-sm font-medium text-destructive" data-testid="purge-warning">
{t('media.purge.irreversible')}
</p>
{purge.isError && (
<p role="alert" className="text-sm text-destructive">
{t('media.error')}
</p>
)}
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose} disabled={purge.isPending} data-testid="purge-cancel">
{t('media.delete.cancel')}
</Button>
<Button type="button" variant="destructive" onClick={submit} disabled={purge.isPending || count === 0} data-testid="purge-confirm">
{all ? t('media.purge.emptyConfirm') : t('media.purge.confirmButton')}
</Button>
</DialogFooter>
</>
);
}
@@ -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())),
@@ -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<Selection>(emptySelection);
const [cleanupOpen, setCleanupOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const [purging, setPurging] = useState<'selected' | 'all' | null>(null);
const [filter, setFilter] = useState<UseFilter>('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: <RotateCcw className="mr-2 size-4" aria-hidden="true" />,
run: () => restore.mutate(selectedItems.map((i) => i.id), { onSuccess: () => setSelection(emptySelection) }),
},
{ id: 'purge', label: t('media.purge.action'), destructive: true, icon: <XCircle className="mr-2 size-4" aria-hidden="true" />, run: () => setPurging('selected') },
];
return (
@@ -105,9 +108,14 @@ export function MediaLibraryPage() {
)}
{view === 'trash' && (
<p className="text-sm text-muted-foreground" data-testid="trash-note">
{t('media.trash.note')}
</p>
<div className="flex flex-wrap items-center justify-between gap-3">
<p className="text-sm text-muted-foreground" data-testid="trash-note">
{t('media.trash.note')}
</p>
<Button type="button" variant="outline" size="sm" disabled={!trash.data || trash.data.photos.length === 0} onClick={() => setPurging('all')} data-testid="trash-empty">
{t('media.purge.emptyButton')}
</Button>
</div>
)}
{source.isError && (
<p role="alert" className="text-sm text-destructive" data-testid="media-error">
@@ -120,10 +128,18 @@ export function MediaLibraryPage() {
{t('media.page.noModules')}
</p>
)}
{source.data && <PhotoSelectionList items={items} selection={selection} onSelectionChange={setSelection} renderUse={renderUse} />}
<BulkActionBar count={selection.size} actions={actions} onClear={() => setSelection(emptySelection)} />
{source.data && <PhotoSelectionList items={items} selection={selection} onSelectionChange={setSelection} renderUse={renderUse} bulk={{ actions, onClear: () => setSelection(emptySelection) }} />}
<CleanupDialog open={cleanupOpen} onOpenChange={setCleanupOpen} />
<PurgeDialog
open={purging !== null}
onOpenChange={(open) => !open && setPurging(null)}
ids={selectedItems.map((i) => i.id)}
all={purging === 'all'}
count={purging === 'all' ? (trash.data?.photos.length ?? 0) : selectedItems.length}
bytes={trashBytes}
onDone={() => setSelection(emptySelection)}
/>
<DeleteDialog open={deleting} onOpenChange={setDeleting} items={selectedItems} onDone={() => setSelection(emptySelection)} />
</div>
);
+10 -1
View File
@@ -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<MediaTrashResponse, Error, MediaPurgeRequest>({
mutationFn: (body) => api.post<MediaTrashResponse>('/api/v1/media-library/purge', body),
onSuccess: () => queryClient.invalidateQueries({ queryKey: MEDIA_KEY }),
});
}
@@ -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;
}