diff --git a/frontend/src/features/hero/components/ProcessingStatus.tsx b/frontend/src/features/hero/components/ProcessingStatus.tsx index 9b0c11d..7ac85d2 100644 --- a/frontend/src/features/hero/components/ProcessingStatus.tsx +++ b/frontend/src/features/hero/components/ProcessingStatus.tsx @@ -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 ( -
+
- - {failed ? null : } - {failed ? t('hero.slides.failed') : t('hero.slides.recut')} - {!failed && step ? {step.done}/{step.total} : null} - +
+ {failed ? ( + {t('hero.slides.failed')} + ) : ( + <> +
+ {t('hero.slides.processing')} + {percent}% +
+
+
+
+ + )} +
); } diff --git a/frontend/src/features/hero/mocks/handlers.ts b/frontend/src/features/hero/mocks/handlers.ts index 582e79f..74db8d7 100644 --- a/frontend/src/features/hero/mocks/handlers.ts +++ b/frontend/src/features/hero/mocks/handlers.ts @@ -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 }), ), diff --git a/frontend/src/features/hero/pages/HeroPage.test.tsx b/frontend/src/features/hero/pages/HeroPage.test.tsx index 645f0d8..7a76294 100644 --- a/frontend/src/features/hero/pages/HeroPage.test.tsx +++ b/frontend/src/features/hero/pages/HeroPage.test.tsx @@ -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(); + 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 () => { diff --git a/frontend/src/features/hero/pages/HeroPage.tsx b/frontend/src/features/hero/pages/HeroPage.tsx index 285f4b9..4a0d2a1 100644 --- a/frontend/src/features/hero/pages/HeroPage.tsx +++ b/frontend/src/features/hero/pages/HeroPage.tsx @@ -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): HeroSaveRequest { +function toRequest(values: HeroFormData): HeroSaveRequest { return { title: values.title, tagline: values.tagline || null, @@ -50,7 +50,6 @@ function toRequest(values: HeroFormData, focusEdits: Record 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>({}); const [focusImageId, setFocusImageId] = useState(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>({}); + // 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([]); + const [recutIds, setRecutIds] = useState([]); const fileInput = useRef(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(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 (
void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8" noValidate data-testid="hero-form"> - images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} /> + setServerError(null)} /> setFocusImageId(field.imageId)} testId={`hero-slide-${index}-focus`} /> @@ -624,8 +637,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
setFocusEdits((current) => ({ ...current, [imageId]: edit }))} + image={focusImageId ? images[focusImageId] ?? null : null} + onApply={applyFocus} onClose={() => setFocusImageId(null)} /> diff --git a/frontend/src/features/hero/services/hooks.ts b/frontend/src/features/hero/services/hooks.ts index 2a8faf5..34cf3ba 100644 --- a/frontend/src/features/hero/services/hooks.ts +++ b/frontend/src/features/hero/services/hooks.ts @@ -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({ + mutationFn: ({ imageId, request }) => api.put(`/api/v1/hero/images/${imageId}/focus`, request), + onSuccess: (image) => { + queryClient.setQueryData(['hero', 'image', image.id], image); + return queryClient.invalidateQueries({ queryKey: HERO_KEY }); + }, + }); +} diff --git a/frontend/src/features/hero/services/types.ts b/frontend/src/features/hero/services/types.ts index d032d6e..d573e04 100644 --- a/frontend/src/features/hero/services/types.ts +++ b/frontend/src/features/hero/services/types.ts @@ -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 { diff --git a/frontend/src/features/media/components/BulkActionBar.tsx b/frontend/src/features/media/components/BulkActionBar.tsx index f58084d..96ab255 100644 --- a/frontend/src/features/media/components/BulkActionBar.tsx +++ b/frontend/src/features/media/components/BulkActionBar.tsx @@ -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 PhotoSelectionList), 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 ( -
+
{t('media.bulk.selected', { count })} diff --git a/frontend/src/features/media/components/CleanupDialog.tsx b/frontend/src/features/media/components/CleanupDialog.tsx index 11851ee..6449d59 100644 --- a/frontend/src/features/media/components/CleanupDialog.tsx +++ b/frontend/src/features/media/components/CleanupDialog.tsx @@ -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

{t('media.cleanup.summary', { count: preview.data.count, size: formatBytes(preview.data.bytes, i18n.language) })}

- - setSelection(new Set())} - summary={t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) })} + setSelection(new Set()), + summary: t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) }), + }} />
+ + + ); + } + + return ( + <> + + {all ? t('media.purge.emptyTitle') : t('media.purge.title')} + + {all ? t('media.purge.confirmAll', { count, size: formatBytes(bytes, i18n.language) }) : t('media.purge.confirm', { count })} + + +

+ {t('media.purge.irreversible')} +

+ {purge.isError && ( +

+ {t('media.error')} +

+ )} + + + + + + ); +} diff --git a/frontend/src/features/media/mocks/handlers.ts b/frontend/src/features/media/mocks/handlers.ts index 8463631..f56cd28 100644 --- a/frontend/src/features/media/mocks/handlers.ts +++ b/frontend/src/features/media/mocks/handlers.ts @@ -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())), diff --git a/frontend/src/features/media/pages/MediaLibraryPage.tsx b/frontend/src/features/media/pages/MediaLibraryPage.tsx index a8ce2d8..1727c5f 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.tsx @@ -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(emptySelection); const [cleanupOpen, setCleanupOpen] = useState(false); const [deleting, setDeleting] = useState(false); + const [purging, setPurging] = useState<'selected' | 'all' | null>(null); const [filter, setFilter] = useState('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:
); diff --git a/frontend/src/features/media/services/hooks.ts b/frontend/src/features/media/services/hooks.ts index 92338d4..86a15a0 100644 --- a/frontend/src/features/media/services/hooks.ts +++ b/frontend/src/features/media/services/hooks.ts @@ -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({ + mutationFn: (body) => api.post('/api/v1/media-library/purge', body), + onSuccess: () => queryClient.invalidateQueries({ queryKey: MEDIA_KEY }), + }); +} diff --git a/frontend/src/features/media/services/types.ts b/frontend/src/features/media/services/types.ts index 0934c2a..12b9177 100644 --- a/frontend/src/features/media/services/types.ts +++ b/frontend/src/features/media/services/types.ts @@ -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; +} diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 7514f16..b4f2c11 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -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." } } } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index 29f047e..b278a09 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -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." } } } diff --git a/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs index fc44359..161cf50 100644 --- a/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs +++ b/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs @@ -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(); + library.PurgeAsync(Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(ci => ci.Arg>().Select(id => new MediaTrashResult(id, "purged", [])).ToList()); + library.PurgeAllAsync(Arg.Any(), Arg.Any()).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(); + (await controller.Purge(new MediaPurgeRequest(null), CancellationToken.None)).Should().BeOfType(); + (await controller.Purge(new MediaPurgeRequest(Enumerable.Range(0, 101).Select(i => $"hero:{i}").ToList()), CancellationToken.None)).Should().BeOfType(); + } + [Fact] public async Task Storage_without_a_media_store_reports_zero_and_ok() { diff --git a/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs index 3353bce..09b416c 100644 --- a/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs +++ b/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs @@ -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(); + } + private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses, MediaPhoto[]? trash = null) : IMediaUsageProvider { public string Module => module; + public List Purged { get; } = []; + + public Guid? InUsePurge { get; init; } + + public Task 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 Trashed { get; } = []; public Guid? FailFor { get; init; } diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs index 491b58b..6b01c28 100644 --- a/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs @@ -33,6 +33,10 @@ public sealed record MediaTrashRequest(IReadOnlyList Ids, bool Confirmed public sealed record MediaRestoreRequest(IReadOnlyList Ids); +/// Photos in the trash to remove for good (at most 100). Ignored when is true. +/// Remove everything that is in the trash (the trash is emptied, in batches on the server). +public sealed record MediaPurgeRequest(IReadOnlyList? Ids = null, bool All = false); + public sealed record MediaUseResultDto(string Id, string Status, IReadOnlyList Uses); public sealed record MediaTrashResponse(IReadOnlyList Results); @@ -110,12 +114,34 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t return Ok(new MediaTrashResponse(results.Select(ToDto).ToList())); } + /// Removes photos from the trash for good: not reversible. Only photos in the trash that are used nowhere. + [HttpPost("purge")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task 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? 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; } diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs index 0938646..7b446c9 100644 --- a/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs @@ -27,6 +27,15 @@ public interface IMediaLibraryService Task> TrashAsync(IReadOnlyCollection ids, bool confirmedInUse, Guid callerId, CancellationToken cancellationToken); Task> RestoreAsync(IReadOnlyCollection ids, Guid callerId, CancellationToken cancellationToken); + + /// + /// 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 purged, notInTrash, inUse, notFound, failed). + /// + Task> PurgeAsync(IReadOnlyCollection ids, Guid callerId, CancellationToken cancellationToken); + + /// Removes everything that is in the trash for good, in batches of . + Task> PurgeAllAsync(Guid callerId, CancellationToken cancellationToken); } public sealed class MediaLibraryService(IEnumerable providers, ILogger? logger = null) : IMediaLibraryService @@ -129,6 +138,55 @@ public sealed class MediaLibraryService(IEnumerable provide return results; } + public async Task> PurgeAsync(IReadOnlyCollection ids, Guid callerId, CancellationToken cancellationToken) + { + EnsureWithinLimit(ids); + var results = new List(); + 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> PurgeAllAsync(Guid callerId, CancellationToken cancellationToken) + { + var ids = (await ListTrashAsync(cancellationToken)).Select(i => $"{i.Photo.Module}:{i.Photo.Id}").ToList(); + var results = new List(); + foreach (var batch in ids.Chunk(MaxIdsPerRequest)) + { + results.AddRange(await PurgeAsync(batch, callerId, cancellationToken)); + } + + return results; + } + private static void EnsureWithinLimit(IReadOnlyCollection ids) { if (ids.Count > MaxIdsPerRequest) diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs index 6d303c2..fcdbb0c 100644 --- a/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs @@ -56,4 +56,23 @@ public interface IMediaUsageProvider /// Takes a photo out of the trash. False when it is not in the trash. Task RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken); + + /// + /// 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. + /// + Task PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken); +} + +/// What happened to a photo that was to be removed for good. +public enum MediaPurgeOutcome +{ + /// Removed: the files and the record are gone. + Purged, + + /// There is no such photo in the trash (not trashed, or already gone). Nothing was changed. + NotInTrash, + + /// The photo is used somewhere after all. Nothing was changed. + InUse, } diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs index 6d38ce1..3d005d3 100644 --- a/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs @@ -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() { diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroSetFocusTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroSetFocusTests.cs new file mode 100644 index 0000000..7e7554c --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroSetFocusTests.cs @@ -0,0 +1,45 @@ +using FluentAssertions; +using SlpModularCms.Modules.Hero.Models; +using SlpModularCms.Modules.Hero.Services; +using Xunit; + +namespace SlpModularCms.Modules.Hero.Tests; + +/// A new crop works at once, without saving the hero (Bryan, 2026-11-17). +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(); + } +} diff --git a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs index 9c727e2..e1d05f9 100644 --- a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs +++ b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs @@ -105,6 +105,20 @@ public class HeroImagesController(IHeroImageService service, IOptions + /// 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). + /// + [HttpPut("{id:guid}/focus")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task 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); + } + /// The formats and limits an upload has to meet on this host (what the validation uses). [HttpGet("limits")] [ProducesResponseType(StatusCodes.Status200OK)] diff --git a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs index edec1d5..9aa01c1 100644 --- a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs +++ b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs @@ -34,6 +34,9 @@ public interface IHeroRepository /// Photos that were trashed before the cutoff, tracked (the trash is emptied for them). Task> GetTrashedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken); + /// True when an image other than the given one has this set hash or this original key (the files are shared). + Task<(bool SetShared, bool OriginalShared)> FilesSharedWithOthersAsync(Guid imageId, string setHash, string originalKey, CancellationToken cancellationToken); + /// The slides that use an image, tracked (they are removed when the image goes to the trash). Task> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken); @@ -99,6 +102,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository public async Task> 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> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken) => await context.HeroSlides.Where(s => s.ImageId == imageId).ToListAsync(cancellationToken); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs index 3759993..80eca6d 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs @@ -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 /// The variant the renderer is busy with: (done, total), or null when the image is not being cut right now. (int Done, int Total)? RenderProgress(Guid imageId); + /// + /// 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. + /// + Task SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken); + /// One image as the admin sees it now (including whether it is still being prepared). Null when there is no such image. Task GetImageAsync(Guid imageId, CancellationToken cancellationToken); @@ -77,6 +85,12 @@ public interface IHeroImageService /// Takes an image out of the trash again. False when it is not in the trash. Task RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); + + /// + /// 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. + /// + Task 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 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 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 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 RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken) { var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs index 5c088e2..86f96de 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs @@ -59,6 +59,9 @@ public class HeroMediaUsageProvider(IHeroRepository repository, IHeroImageServic public Task RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken) => images.RestoreAsync(photoId, callerId, cancellationToken); + public Task 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);