Hero: een gewijzigd focuspunt geldt pas bij het opslaan van de hero (Bryan); het focus-venster houdt de wijziging lokaal

Het eindpunt PUT /hero/images/{id}/focus is vervallen; de focus gaat mee in de opslag (imageFocus) en de varianten worden dan in nieuwe bestanden opnieuw gesneden.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 20:05:17 +01:00
co-authored by Claude Sonnet 5.5
parent 01703ccddf
commit 0b56fa6294
20 changed files with 318 additions and 197 deletions
@@ -1,25 +1,24 @@
import { useRef, useState, type KeyboardEvent, type PointerEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { mediaUrl } from '../lib/media';
import { CENTRE, MAX_ZOOM, TALL, WIDE, cropFor, normalizeFocus, type Ratio } from '../lib/focusMath';
import { useSetImageFocus } from '../services/hooks';
import type { FocusDto, HeroImageDto } from '../services/types';
import type { FocusDto, HeroFocusRequest, HeroImageDto } from '../services/types';
type Target = 'general' | 'wide' | 'tall';
interface FocusDialogProps {
/** The image to edit; null = closed. */
/** The image to edit, with a not yet saved change of its focus already applied; null = closed. */
image: HeroImageDto | null;
/** Keeps the change locally: it is sent and made live when the hero is saved, and dropped when the page is left. */
onApply: (imageId: string, request: HeroFocusRequest) => void;
onClose: () => void;
}
export function FocusDialog({ image, onClose }: FocusDialogProps) {
export function FocusDialog({ image, onApply, onClose }: FocusDialogProps) {
const { t } = useTranslation();
return (
<Dialog open={image !== null} onOpenChange={(next) => { if (!next) onClose(); }}>
@@ -28,7 +27,7 @@ export function FocusDialog({ image, onClose }: FocusDialogProps) {
<DialogTitle>{t('hero.focus.title')}</DialogTitle>
</DialogHeader>
{/* Mounted only while open, so every opening starts from the stored values. */}
{image && <FocusEditor image={image} onClose={onClose} />}
{image && <FocusEditor image={image} onApply={onApply} onClose={onClose} />}
</DialogContent>
</Dialog>
);
@@ -36,11 +35,9 @@ export function FocusDialog({ image, onClose }: FocusDialogProps) {
const percent = (fraction: number) => Math.round(fraction * 1000) / 10;
function FocusEditor({ image, onClose }: { image: HeroImageDto; onClose: () => void }) {
function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply: (imageId: string, request: HeroFocusRequest) => void; onClose: () => void }) {
const { t } = useTranslation();
const save = useSetImageFocus();
const area = useRef<HTMLDivElement>(null);
const [serverError, setServerError] = useState<string | null>(null);
const [target, setTarget] = useState<Target>('general');
const [general, setGeneral] = useState<FocusDto>(image.focus ?? CENTRE);
const [wide, setWide] = useState<FocusDto | null>(image.wideFocus);
@@ -79,16 +76,9 @@ function FocusEditor({ image, onClose }: { image: HeroImageDto; onClose: () => v
update({ ...active, x: active.x + move[0], y: active.y + move[1] });
};
const onSave = async () => {
setServerError(null);
try {
await save.mutateAsync({ imageId: image.id, body: { focus: general, wide, tall } });
toast.success(t('hero.focus.savedToast'));
onClose();
} catch (error) {
const message = (error as { problem?: { message?: unknown } }).problem?.message;
setServerError(typeof message === 'string' ? message : t('errors.generic'));
}
const onSave = () => {
onApply(image.id, { focus: general, wide, tall });
onClose();
};
const outline = (ratio: Ratio, focus: FocusDto) => {
@@ -103,8 +93,8 @@ function FocusEditor({ image, onClose }: { image: HeroImageDto; onClose: () => v
return (
<div className="space-y-4" data-testid="focus-dialog">
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
<p className="text-sm text-muted-foreground">{t('hero.focus.intro')}</p>
<p className="text-sm font-medium" data-testid="focus-apply-hint">{t('hero.focus.applyHint')}</p>
<fieldset className="flex flex-wrap gap-4">
<legend className="sr-only">{t('hero.focus.targetLegend')}</legend>
@@ -244,8 +234,8 @@ function FocusEditor({ image, onClose }: { image: HeroImageDto; onClose: () => v
<Button type="button" variant="outline" onClick={onClose} data-testid="focus-cancel">
{t('common.cancel')}
</Button>
<Button type="button" onClick={onSave} disabled={save.isPending} data-testid="focus-save">
{save.isPending ? '…' : t('common.save')}
<Button type="button" onClick={onSave} data-testid="focus-save">
{t('hero.focus.apply')}
</Button>
</div>
</div>
+6 -12
View File
@@ -1,6 +1,6 @@
import { http, HttpResponse } from 'msw';
import { API_BASE } from '@/features/auth/mocks/fixtures';
import type { FocusDto, HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types';
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types';
const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({
id,
@@ -75,6 +75,11 @@ export const heroHandlers = [
http.put(`${API_BASE}/api/v1/hero`, async ({ request }) => {
const body = (await request.json()) as HeroSaveRequest;
saved.push(body);
// A changed focus takes effect with the save of the hero.
for (const edit of body.imageFocus ?? []) {
const current = images[edit.imageId] ?? hero.slides.find((s) => s.imageId === edit.imageId)?.image ?? seedImage(edit.imageId);
images[edit.imageId] = { ...current, focus: edit.focus, wideFocus: edit.wide, tallFocus: edit.tall };
}
hero = {
...hero,
id: hero.id ?? '99999999-9999-9999-9999-999999999999',
@@ -112,15 +117,4 @@ export const heroHandlers = [
images[image.id] = image;
return HttpResponse.json(image, { status: 201 });
}),
http.put(`${API_BASE}/api/v1/hero/images/:id/focus`, async ({ params, request }) => {
const body = (await request.json()) as HeroFocusRequest;
const id = String(params.id);
const current = images[id] ?? hero.slides.find((s) => s.imageId === id)?.image ?? seedImage(id);
const asDto = (f: FocusDto | null) => (f ? { ...f } : null);
const next: HeroImageDto = { ...current, focus: body.focus, wideFocus: asDto(body.wide), tallFocus: asDto(body.tall) };
images[id] = next;
hero = { ...hero, slides: hero.slides.map((s) => (s.imageId === id ? { ...s, image: next } : s)) };
return HttpResponse.json(next);
}),
];
@@ -214,13 +214,14 @@ describe('Focus dialog', () => {
return screen.findByTestId('focus-dialog');
};
it('starts with the stored point and shows both previews', async () => {
it('starts with the stored point, shows both previews and says the change needs a save', async () => {
await open();
expect(screen.getByTestId('focus-x')).toHaveValue(50);
expect(screen.getByTestId('focus-y')).toHaveValue(50);
expect(screen.getByTestId('focus-preview-wide')).toBeInTheDocument();
expect(screen.getByTestId('focus-preview-tall')).toBeInTheDocument();
expect(screen.getByTestId('focus-apply-hint')).toHaveTextContent(/pas nadat je de hero opslaat|only takes effect when you save the hero/);
});
it('moves the point with the keyboard', async () => {
@@ -234,7 +235,7 @@ describe('Focus dialog', () => {
expect(screen.getByTestId('focus-y')).toHaveValue(55);
});
it('saves a general point and an own setting for the tall display', async () => {
it('keeps a change locally until the hero is saved, then sends it with the save', async () => {
await open();
fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '30' } });
@@ -246,13 +247,40 @@ describe('Focus dialog', () => {
await userEvent.click(screen.getByTestId('focus-save'));
await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument());
// The dialog closed after the server accepted it; reopening shows the stored values.
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());
});
it('sends no focus edits when nothing was changed', async () => {
await open();
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([]);
});
it('goes back to the general point when the own setting is switched off', async () => {
@@ -266,12 +294,14 @@ describe('Focus dialog', () => {
expect(screen.getByTestId('focus-x')).toBeDisabled();
});
it('closes without saving', async () => {
it('drops a change when the dialog is cancelled', async () => {
await open();
fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '10' } });
await userEvent.click(screen.getByTestId('focus-cancel'));
await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument());
expect(screen.queryByTestId('hero-slide-0-focus-pending')).not.toBeInTheDocument();
});
});
+25 -7
View File
@@ -15,7 +15,7 @@ import { FocusDialog } from '../components/FocusDialog';
import { mediaUrl } from '../lib/media';
import { fromLocalInput, heroFormSchema, toLocalInput, type HeroFormData } from '../schemas/hero';
import { useHero, useSaveHero, useUploadHeroImage } from '../services/hooks';
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest } from '../services/types';
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from '../services/types';
const textareaClass =
'w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
@@ -35,7 +35,7 @@ function toForm(hero: HeroAdminDto): HeroFormData {
};
}
function toRequest(values: HeroFormData): HeroSaveRequest {
function toRequest(values: HeroFormData, focusEdits: Record<string, HeroFocusRequest>): HeroSaveRequest {
return {
title: values.title,
tagline: values.tagline || null,
@@ -46,6 +46,7 @@ function toRequest(values: HeroFormData): HeroSaveRequest {
startsAt: fromLocalInput(values.startsAt),
endsAt: fromLocalInput(values.endsAt),
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 })),
};
}
@@ -125,6 +126,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const [uploadError, setUploadError] = useState<string | null>(null);
const [localImages, setLocalImages] = useState<Record<string, HeroImageDto>>({});
const [focusImageId, setFocusImageId] = useState<string | null>(null);
// Changed focus points are kept here until the hero is saved: they are sent with the save and dropped when the page is left.
const [focusEdits, setFocusEdits] = useState<Record<string, HeroFocusRequest>>({});
const fileInput = useRef<HTMLInputElement>(null);
const {
@@ -143,14 +146,21 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
return map;
}, [hero.slides, localImages]);
const hasPendingFocus = Object.keys(focusEdits).length > 0;
useEffect(() => {
if (!isDirty) return undefined;
if (!isDirty && !hasPendingFocus) return undefined;
const warn = (event: BeforeUnloadEvent) => {
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [isDirty]);
}, [isDirty, hasPendingFocus]);
// 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;
};
const onUpload = async (files: FileList | null) => {
const file = files?.[0];
@@ -176,7 +186,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const onSubmit = async (values: HeroFormData) => {
setServerError(null);
try {
await save.mutateAsync(toRequest(values));
await save.mutateAsync(toRequest(values, focusEdits));
setFocusEdits({});
toast.success(t('hero.savedToast'));
} catch (error) {
setServerError(serverMessage(error, t('errors.generic'), t('errors.network')));
@@ -297,6 +308,9 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
<Label htmlFor={`hero-slide-${index}-alt`}>{t('hero.slides.alt', { n: index + 1 })}</Label>
<Input id={`hero-slide-${index}-alt`} maxLength={300} disabled={decorative} data-testid={`hero-slide-${index}-alt`} {...register(`slides.${index}.alt` as const)} />
<FieldError message={err(heroErrors.slides?.[index]?.alt?.message)} testId={`hero-slide-${index}-alt-error`} />
{focusEdits[field.imageId] && (
<p className="text-xs font-medium" data-testid={`hero-slide-${index}-focus-pending`}>{t('hero.slides.focusPending')}</p>
)}
<div className="flex flex-wrap gap-4 text-sm">
<label className="flex items-center gap-2">
<input type="checkbox" className="size-4 rounded border-input" data-testid={`hero-slide-${index}-decorative`} {...register(`slides.${index}.decorative` as const)} />
@@ -315,7 +329,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.down')} disabled={index === slides.fields.length - 1} onClick={() => slides.move(index, index + 1)} data-testid={`hero-slide-${index}-down`}>
<ArrowDown className="size-4" aria-hidden="true" />
</Button>
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.focus')} disabled={!image} onClick={() => setFocusImageId(field.imageId)} data-testid={`hero-slide-${index}-focus`}>
<Button type="button" variant={focusEdits[field.imageId] ? 'default' : 'outline'} size="icon" aria-label={t('hero.slides.focus')} disabled={!image} onClick={() => setFocusImageId(field.imageId)} data-testid={`hero-slide-${index}-focus`}>
<Crosshair className="size-4" aria-hidden="true" />
</Button>
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.remove')} onClick={() => slides.remove(index)} data-testid={`hero-slide-${index}-remove`}>
@@ -339,7 +353,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
</Button>
</div>
<FocusDialog image={focusImageId ? images[focusImageId] ?? null : null} onClose={() => setFocusImageId(null)} />
<FocusDialog
image={withPendingFocus(focusImageId ? images[focusImageId] ?? null : null)}
onApply={(imageId, edit) => setFocusEdits((current) => ({ ...current, [imageId]: edit }))}
onClose={() => setFocusImageId(null)}
/>
</form>
);
}
+1 -12
View File
@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from './types';
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest } from './types';
export const HERO_KEY = ['hero'];
@@ -33,17 +33,6 @@ export function useUploadHeroImage() {
});
}
export function useSetImageFocus() {
const queryClient = useQueryClient();
return useMutation<HeroImageDto, Error, { imageId: string; body: HeroFocusRequest }>({
mutationFn: ({ imageId, body }) => api.put<HeroImageDto>(`/api/v1/hero/images/${imageId}/focus`, body),
onSuccess: () => {
// The slide list shows the image variants; they have new addresses after a change of focus.
void queryClient.invalidateQueries({ queryKey: HERO_KEY });
},
});
}
export function useDeleteHeroImage() {
return useMutation<void, Error, string>({
mutationFn: (imageId) => api.delete<void>(`/api/v1/hero/images/${imageId}`),
@@ -74,6 +74,12 @@ export interface HeroSaveRequest {
startsAt: string | null;
endsAt: string | null;
slides: HeroSlideRequest[];
/** Changed focus points of images; they take effect with this save. */
imageFocus: HeroImageFocusRequest[];
}
export interface HeroImageFocusRequest extends HeroFocusRequest {
imageId: string;
}
export interface HeroFocusRequest {