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 (