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
@@ -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 (
<div
className={`relative h-20 w-28 shrink-0 overflow-hidden rounded ${failed ? 'ring-2 ring-destructive' : 'hero-shimmer'}`}
role="status"
aria-busy={!failed}
title={t('hero.slides.recutHint')}
data-testid={testId}
>
<div className={`relative h-20 w-28 shrink-0 overflow-hidden rounded ${failed ? 'ring-2 ring-destructive' : ''}`} title={t('hero.slides.recutHint')} data-testid={testId}>
<img src={src} alt="" className="h-full w-full object-cover" />
<span className={`absolute inset-x-0 bottom-0 flex items-center justify-center gap-1 px-1 py-0.5 text-center text-[10px] leading-tight ${failed ? 'bg-destructive text-destructive-foreground' : 'bg-background/85 text-foreground'}`}>
{failed ? null : <Spinner className="size-3" />}
<span>{failed ? t('hero.slides.failed') : t('hero.slides.recut')}</span>
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
</span>
<div
className={`absolute inset-x-0 bottom-0 space-y-1 px-1.5 py-1 text-xs ${failed ? 'bg-destructive text-destructive-foreground' : 'bg-background text-foreground'}`}
role="status"
aria-busy={!failed}
>
{failed ? (
<span>{t('hero.slides.failed')}</span>
) : (
<>
<div className="flex items-center justify-between gap-1">
<span data-testid={`${testId}-text`}>{t('hero.slides.processing')}</span>
<span className="tabular-nums" data-testid={`${testId}-percent`}>{percent}%</span>
</div>
<div
role="progressbar"
aria-label={t('hero.slides.processing')}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={percent}
aria-valuetext={`${percent}%`}
className="h-1.5 w-full overflow-hidden rounded bg-muted"
data-testid={`${testId}-bar`}
>
<div className="h-full bg-primary transition-all motion-reduce:transition-none" style={{ width: `${percent}%` }} />
</div>
</>
)}
</div>
</div>
);
}
+17 -1
View File
@@ -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 }),
),
@@ -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<string>();
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 () => {
+36 -23
View File
@@ -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<string, HeroFocusRequest>): HeroSaveRequest {
function toRequest(values: HeroFormData): HeroSaveRequest {
return {
title: values.title,
tagline: values.tagline || null,
@@ -50,7 +50,6 @@ function toRequest(values: HeroFormData, focusEdits: Record<string, HeroFocusReq
display: values.display,
buttons: values.buttons.filter((b) => 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<Record<string, HeroImageDto>>({});
const [focusImageId, setFocusImageId] = useState<string | null>(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<Record<string, HeroFocusRequest>>({});
// 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<string[]>([]);
const [recutIds, setRecutIds] = useState<string[]>([]);
const fileInput = useRef<HTMLInputElement>(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<HeroImageDto | 'failed' | undefined>(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 (
<form onSubmit={(event) => void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8" noValidate data-testid="hero-form">
<ProcessingStatus images={slides.fields.map((f) => images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} />
<ProcessingStatus images={statusImages} />
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
<HeroTabs
@@ -531,7 +545,6 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
<CropThumbnail
image={image}
savedSrc={thumbnail(image)}
edit={focusEdits[field.imageId]}
onClick={() => setFocusImageId(field.imageId)}
testId={`hero-slide-${index}-focus`}
/>
@@ -624,8 +637,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
</div>
<FocusDialog
image={withPendingFocus(focusImageId ? images[focusImageId] ?? null : null)}
onApply={(imageId, edit) => setFocusEdits((current) => ({ ...current, [imageId]: edit }))}
image={focusImageId ? images[focusImageId] ?? null : null}
onApply={applyFocus}
onClose={() => setFocusImageId(null)}
/>
</form>
+16 -1
View File
@@ -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<HeroImageDto, Error, { imageId: string; request: HeroFocusRequest }>({
mutationFn: ({ imageId, request }) => api.put<HeroImageDto>(`/api/v1/hero/images/${imageId}/focus`, request),
onSuccess: (image) => {
queryClient.setQueryData(['hero', 'image', image.id], image);
return queryClient.invalidateQueries({ queryKey: HERO_KEY });
},
});
}
+1 -1
View File
@@ -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 {
@@ -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;
}
+16 -1
View File
@@ -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."
}
}
}
+16 -1
View File
@@ -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."
}
}
}
@@ -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<IMediaLibraryService>();
library.PurgeAsync(Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ci => ci.Arg<IReadOnlyCollection<string>>().Select(id => new MediaTrashResult(id, "purged", [])).ToList());
library.PurgeAllAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).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<BadRequestResult>();
(await controller.Purge(new MediaPurgeRequest(null), CancellationToken.None)).Should().BeOfType<BadRequestResult>();
(await controller.Purge(new MediaPurgeRequest(Enumerable.Range(0, 101).Select(i => $"hero:{i}").ToList()), CancellationToken.None)).Should().BeOfType<BadRequestResult>();
}
[Fact]
public async Task Storage_without_a_media_store_reports_zero_and_ok()
{
@@ -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<ArgumentOutOfRangeException>();
}
private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses, MediaPhoto[]? trash = null) : IMediaUsageProvider
{
public string Module => module;
public List<Guid> Purged { get; } = [];
public Guid? InUsePurge { get; init; }
public Task<MediaPurgeOutcome> 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<Guid> Trashed { get; } = [];
public Guid? FailFor { get; init; }
@@ -33,6 +33,10 @@ public sealed record MediaTrashRequest(IReadOnlyList<string> Ids, bool Confirmed
public sealed record MediaRestoreRequest(IReadOnlyList<string> Ids);
/// <param name="Ids">Photos in the trash to remove for good (at most 100). Ignored when <paramref name="All"/> is true.</param>
/// <param name="All">Remove everything that is in the trash (the trash is emptied, in batches on the server).</param>
public sealed record MediaPurgeRequest(IReadOnlyList<string>? Ids = null, bool All = false);
public sealed record MediaUseResultDto(string Id, string Status, IReadOnlyList<MediaUseDto> Uses);
public sealed record MediaTrashResponse(IReadOnlyList<MediaUseResultDto> Results);
@@ -110,12 +114,34 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t
return Ok(new MediaTrashResponse(results.Select(ToDto).ToList()));
}
/// <summary>Removes photos from the trash for good: not reversible. Only photos in the trash that are used nowhere.</summary>
[HttpPost("purge")]
[ProducesResponseType<MediaTrashResponse>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> 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<string>? 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;
}
@@ -27,6 +27,15 @@ public interface IMediaLibraryService
Task<IReadOnlyList<MediaTrashResult>> TrashAsync(IReadOnlyCollection<string> ids, bool confirmedInUse, Guid callerId, CancellationToken cancellationToken);
Task<IReadOnlyList<MediaTrashResult>> RestoreAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken);
/// <summary>
/// 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 <c>purged</c>, <c>notInTrash</c>, <c>inUse</c>, <c>notFound</c>, <c>failed</c>).
/// </summary>
Task<IReadOnlyList<MediaTrashResult>> PurgeAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken);
/// <summary>Removes everything that is in the trash for good, in batches of <see cref="MediaLibraryService.MaxIdsPerRequest"/>.</summary>
Task<IReadOnlyList<MediaTrashResult>> PurgeAllAsync(Guid callerId, CancellationToken cancellationToken);
}
public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> providers, ILogger<MediaLibraryService>? logger = null) : IMediaLibraryService
@@ -129,6 +138,55 @@ public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> provide
return results;
}
public async Task<IReadOnlyList<MediaTrashResult>> PurgeAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken)
{
EnsureWithinLimit(ids);
var results = new List<MediaTrashResult>();
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<IReadOnlyList<MediaTrashResult>> PurgeAllAsync(Guid callerId, CancellationToken cancellationToken)
{
var ids = (await ListTrashAsync(cancellationToken)).Select(i => $"{i.Photo.Module}:{i.Photo.Id}").ToList();
var results = new List<MediaTrashResult>();
foreach (var batch in ids.Chunk(MaxIdsPerRequest))
{
results.AddRange(await PurgeAsync(batch, callerId, cancellationToken));
}
return results;
}
private static void EnsureWithinLimit(IReadOnlyCollection<string> ids)
{
if (ids.Count > MaxIdsPerRequest)
@@ -56,4 +56,23 @@ public interface IMediaUsageProvider
/// <summary>Takes a photo out of the trash. False when it is not in the trash.</summary>
Task<bool> RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken);
/// <summary>
/// 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.
/// </summary>
Task<MediaPurgeOutcome> PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken);
}
/// <summary>What happened to a photo that was to be removed for good.</summary>
public enum MediaPurgeOutcome
{
/// <summary>Removed: the files and the record are gone.</summary>
Purged,
/// <summary>There is no such photo in the trash (not trashed, or already gone). Nothing was changed.</summary>
NotInTrash,
/// <summary>The photo is used somewhere after all. Nothing was changed.</summary>
InUse,
}
@@ -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()
{
@@ -0,0 +1,45 @@
using FluentAssertions;
using SlpModularCms.Modules.Hero.Models;
using SlpModularCms.Modules.Hero.Services;
using Xunit;
namespace SlpModularCms.Modules.Hero.Tests;
/// <summary>A new crop works at once, without saving the hero (Bryan, 2026-11-17).</summary>
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();
}
}
@@ -105,6 +105,20 @@ public class HeroImagesController(IHeroImageService service, IOptions<MediaOptio
return image is null ? NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) }) : Ok(image);
}
/// <summary>
/// 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).
/// </summary>
[HttpPut("{id:guid}/focus")]
[ProducesResponseType<HeroImageDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> 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);
}
/// <summary>The formats and limits an upload has to meet on this host (what the validation uses).</summary>
[HttpGet("limits")]
[ProducesResponseType<HeroUploadLimitsDto>(StatusCodes.Status200OK)]
@@ -34,6 +34,9 @@ public interface IHeroRepository
/// <summary>Photos that were trashed before the cutoff, tracked (the trash is emptied for them).</summary>
Task<IReadOnlyList<HeroImage>> GetTrashedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken);
/// <summary>True when an image other than the given one has this set hash or this original key (the files are shared).</summary>
Task<(bool SetShared, bool OriginalShared)> FilesSharedWithOthersAsync(Guid imageId, string setHash, string originalKey, CancellationToken cancellationToken);
/// <summary>The slides that use an image, tracked (they are removed when the image goes to the trash).</summary>
Task<IReadOnlyList<HeroSlide>> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken);
@@ -99,6 +102,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
public async Task<IReadOnlyList<HeroImage>> 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<IReadOnlyList<HeroSlide>> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken)
=> await context.HeroSlides.Where(s => s.ImageId == imageId).ToListAsync(cancellationToken);
@@ -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
/// <summary>The variant the renderer is busy with: (done, total), or null when the image is not being cut right now.</summary>
(int Done, int Total)? RenderProgress(Guid imageId);
/// <summary>
/// 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.
/// </summary>
Task<HeroImageDto?> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken);
/// <summary>One image as the admin sees it now (including whether it is still being prepared). Null when there is no such image.</summary>
Task<HeroImageDto?> GetImageAsync(Guid imageId, CancellationToken cancellationToken);
@@ -77,6 +85,12 @@ public interface IHeroImageService
/// <summary>Takes an image out of the trash again. False when it is not in the trash.</summary>
Task<bool> RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
/// <summary>
/// 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.
/// </summary>
Task<MediaPurgeOutcome> 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<HeroImageDto?> 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<HeroImageDto?> 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<MediaPurgeOutcome> 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<bool> RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
{
var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken);
@@ -59,6 +59,9 @@ public class HeroMediaUsageProvider(IHeroRepository repository, IHeroImageServic
public Task<bool> RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
=> images.RestoreAsync(photoId, callerId, cancellationToken);
public Task<MediaPurgeOutcome> 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);