Hero-admin: foto klikbaar voor de uitsnede, direct voorbeeld na Toepassen, Opslaan uitgegrijsd zonder wijzigingen

- De thumbnail is de knop 'Uitsnede aanpassen' (hint bij hover/focus, kleine crop-icoon altijd zichtbaar voor touch); losse focusknop vervalt
- Na Toepassen toont de thumbnail direct de nieuwe uitsnede (zelfde rekenlogica als de host) met 'Focus gewijzigd, nog niet opgeslagen'
- Opslaan is uitgeschakeld (aria-disabled) zolang er niets te bewaren is, bezig-indicator tijdens opslaan, weer uit na opslaan
- Test van de keten: Toepassen, Opslaan (imageFocus in de PUT), 'Nieuwe uitsnede wordt gemaakt', 'Verwerking afgerond'; backend: PUT-body bindt, status direct pending, renderer klaar
- Logregel 'recut superseded' als een nieuwere focus de lopende uitsnede overneemt

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 23:58:48 +01:00
co-authored by Claude Sonnet 5.5
parent 6999f5b2ba
commit 606af0aec2
7 changed files with 295 additions and 21 deletions
@@ -0,0 +1,74 @@
import { Crop } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { WIDE, cropFor } from '../lib/focusMath';
import { mediaUrl } from '../lib/media';
import type { HeroFocusRequest, HeroImageDto } from '../services/types';
interface CropThumbnailProps {
image: HeroImageDto;
/** The small picture of the published (saved) crop. */
savedSrc: string;
/** A focus change that was applied in the dialog and is not saved yet: the thumbnail then shows that crop already. */
edit?: HeroFocusRequest;
onClick: () => void;
testId: string;
}
/**
* The picture of a slide, and at the same time the way to change its crop: a real button (so keyboard and screen reader
* users have it too). A hint with a crop icon and "Adjust crop" shows on hover and on keyboard focus, and a small crop
* icon is always there, so it can be found on a touch screen as well. After "Apply" in the dialog the thumbnail shows
* the new crop right away (the same calculation as the host) with a clear "not saved yet" note.
*/
export function CropThumbnail({ image, savedSrc, edit, onClick, testId }: CropThumbnailProps) {
const { t } = useTranslation();
const local = edit && image.previewSrc ? localCrop(image, edit) : null;
return (
<button
type="button"
onClick={onClick}
aria-label={t('hero.slides.cropEdit')}
className={`group relative block aspect-[3/2] w-28 shrink-0 cursor-pointer overflow-hidden rounded bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${edit ? 'ring-2 ring-amber-500' : ''}`}
data-testid={testId}
>
{local && image.previewSrc ? (
<img src={mediaUrl(image.previewSrc)} alt="" draggable={false} className="absolute max-w-none" style={local} data-testid={`${testId}-local`} />
) : (
<img src={savedSrc} alt="" draggable={false} className="h-full w-full object-cover" />
)}
{/* Always there, so it is found without hovering (touch screens). */}
<span className="pointer-events-none absolute right-1 top-1 rounded bg-black/55 p-1 text-white" aria-hidden="true">
<Crop className="size-3" />
</span>
{/* The explanation on hover and keyboard focus. */}
<span
className="pointer-events-none absolute inset-0 flex items-center justify-center gap-1 bg-black/55 px-1 text-center text-[11px] font-medium leading-tight text-white opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100 motion-reduce:transition-none"
aria-hidden="true"
>
<Crop className="size-4 shrink-0" />
{t('hero.slides.cropEdit')}
</span>
{edit && (
<span
className="pointer-events-none absolute inset-x-0 bottom-0 bg-amber-500 px-1 py-0.5 text-center text-[10px] font-medium leading-tight text-black"
data-testid={`${testId}-pending`}
>
{t('hero.slides.focusPending')}
</span>
)}
</button>
);
}
/** Places the whole picture in the box so exactly the crop of the host shows (the same calculation as the dialog). */
function localCrop(image: HeroImageDto, edit: HeroFocusRequest) {
const focus = edit.wide ?? edit.focus;
const crop = cropFor(image.width, image.height, WIDE, focus);
return {
width: `${(image.width / crop.width) * 100}%`,
left: `${(-crop.x / crop.width) * 100}%`,
// top is a percentage of the box height: the box width times denominator over numerator.
top: `${(-crop.y / crop.width) * (WIDE.numerator / WIDE.denominator) * 100}%`,
};
}
@@ -38,7 +38,7 @@ describe('Hero page', () => {
await openPage();
expect(await screen.findByTestId('hero-slide-0-processing', {}, T)).toBeInTheDocument();
expect(screen.getByTestId('hero-slide-0-focus')).toBeDisabled();
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 () => {
@@ -134,6 +134,7 @@ describe('Hero page', () => {
it('does not save without a title and says why', async () => {
await openPage();
await userEvent.type(screen.getByTestId('hero-lead'), 'Alleen een lead');
await userEvent.click(screen.getByTestId('hero-save'));
@@ -339,6 +340,8 @@ describe('Focus dialog', () => {
it('sends no focus edits when nothing was changed', 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'));
@@ -886,7 +889,7 @@ describe('Each photo shows by itself when its processing is finished', () => {
await userEvent.upload(screen.getByTestId('hero-upload'), jpg('groot.jpg'));
expect(await screen.findByTestId('hero-slide-0-processing', {}, T)).toHaveClass('hero-shimmer');
expect(screen.getByTestId('hero-slide-0-focus')).toBeDisabled();
expect(screen.queryByTestId('hero-slide-0-focus')).not.toBeInTheDocument();
expect(screen.queryByTestId('hero-slide-0-done-text')).not.toBeInTheDocument();
// The server is done; nobody saves or reloads: the page asks again by itself.
@@ -934,7 +937,140 @@ describe('Each photo shows by itself when its processing is finished', () => {
expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled();
expect(screen.getByTestId('hero-slide-1-processing')).toBeInTheDocument();
expect(screen.getByTestId('hero-slide-1-focus')).toBeDisabled();
expect(screen.queryByTestId('hero-slide-1-focus')).not.toBeInTheDocument();
expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/1 van 2|1 of 2/);
}, 30000);
});
describe('The picture of a slide is the way to adjust its crop', () => {
beforeEach(() => {
resetMockHero();
});
it('is a real button named Adjust crop, with a hint that is there without hovering, and it opens the dialog', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
await openPage();
const thumb = screen.getByTestId('hero-slide-0-focus');
expect(thumb.tagName).toBe('BUTTON');
expect(thumb).toHaveAccessibleName(/Uitsnede aanpassen|Adjust crop/);
expect(thumb.querySelector('svg')).not.toBeNull();
expect(within(thumb).getAllByText(/Uitsnede aanpassen|Adjust crop/).length).toBeGreaterThan(0);
expect(screen.queryByRole('button', { name: /Focus instellen|Set focus/ })).not.toBeInTheDocument();
thumb.focus();
await userEvent.keyboard('{Enter}');
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 () => {
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/);
});
it('follows the whole chain: Apply, Save sends the focus, the new crop is made (animation), then it is finished', 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.
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(screen.queryByTestId('hero-slide-0-recut')).not.toBeInTheDocument();
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');
}, 30000);
});
describe('The Save button', () => {
beforeEach(() => {
resetMockHero();
});
it('is greyed out while there is nothing to save, active after a change, busy while saving, and greyed out again after saving', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'Titel', slides: [slide(1)] });
let release: () => void = () => undefined;
const gate = new Promise<void>((resolve) => { release = resolve; });
server.use(
http.put(`${API_BASE}/api/v1/hero`, async ({ request }) => {
await gate;
const body = (await request.json()) as { title: string };
return HttpResponse.json({ ...emptyHero(), id: 'h1', title: body.title, slides: [slide(1)] });
}),
);
await openPage();
const save = screen.getByTestId('hero-save');
expect(save).toBeDisabled();
expect(save).toHaveAttribute('aria-disabled', 'true');
await userEvent.type(screen.getByTestId('hero-title-input'), '!');
await waitFor(() => expect(save).toBeEnabled());
expect(save).toHaveAttribute('aria-disabled', 'false');
await userEvent.click(save);
await waitFor(() => expect(save).toHaveAttribute('aria-busy', 'true'));
expect(save).toBeDisabled();
expect(save).toHaveTextContent(/Bezig met opslaan|Saving/);
release();
await waitFor(() => expect(save).toHaveAttribute('aria-busy', 'false'));
await waitFor(() => expect(save).toBeDisabled());
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 () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
await openPage();
const save = screen.getByTestId('hero-save');
await userEvent.type(screen.getByTestId('hero-title-input'), 'X');
await waitFor(() => expect(save).toBeEnabled());
await userEvent.type(screen.getByTestId('hero-title-input'), '{backspace}');
await waitFor(() => expect(save).toBeDisabled());
await userEvent.click(screen.getByTestId('hero-slide-0-focus'));
fireEvent.change(await screen.findByTestId('focus-x', {}, T), { target: { value: '15' } });
await userEvent.click(screen.getByTestId('focus-save'));
await waitFor(() => expect(save).toBeEnabled());
});
it('stays active when saving failed, so it can be tried again', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
server.use(http.put(`${API_BASE}/api/v1/hero`, () => HttpResponse.json({ error: 'x', message: 'Het lukt niet.' }, { status: 500 })));
await openPage();
await userEvent.type(screen.getByTestId('hero-title-input'), 'X');
await userEvent.click(screen.getByTestId('hero-save'));
await waitFor(() => expect(screen.getByTestId('hero-save')).toHaveAttribute('aria-busy', 'false'));
expect(screen.getByTestId('hero-save')).toBeEnabled();
});
});
+26 -11
View File
@@ -4,7 +4,7 @@ import { useFieldArray, useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { ArrowDown, ArrowUp, Crosshair, ImagePlus, Trash2 } from 'lucide-react';
import { ArrowDown, ArrowUp, ImagePlus, Trash2 } from 'lucide-react';
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core';
import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { Badge } from '@/components/ui/badge';
@@ -15,7 +15,8 @@ import { FieldError } from '@/components/ui/FieldError';
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
import { FocusDialog } from '../components/FocusDialog';
import { DoneStatus, PhotoPlaceholder, ProcessingStatus, RecutThumbnail } from '../components/ProcessingStatus';
import { CropThumbnail } from '../components/CropThumbnail';
import { DoneStatus, PhotoPlaceholder, ProcessingStatus, RecutThumbnail, Spinner } from '../components/ProcessingStatus';
import { SlideSwitch } from '../components/SlideSwitch';
import { SortableSlide } from '../components/SortableSlide';
import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard';
@@ -472,7 +473,13 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
) : image?.processing ? (
<RecutThumbnail src={thumbnail(image)} failed={image.failed} testId={`hero-slide-${index}-recut`} step={image.renderTotal ? { done: image.renderDone ?? 0, total: image.renderTotal } : null} />
) : image ? (
<img src={thumbnail(image)} alt="" className="h-20 w-28 rounded object-cover" />
<CropThumbnail
image={image}
savedSrc={thumbnail(image)}
edit={focusEdits[field.imageId]}
onClick={() => setFocusImageId(field.imageId)}
testId={`hero-slide-${index}-focus`}
/>
) : (
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted text-xs">?</div>
)}
@@ -486,9 +493,6 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
<Input id={`hero-slide-${index}-alt`} maxLength={300} disabled={decorative} aria-describedby={`hero-slide-${index}-alt-hint`} data-testid={`hero-slide-${index}-alt`} {...register(`slides.${index}.alt` as const)} />
<p id={`hero-slide-${index}-alt-hint`} className="text-xs text-muted-foreground">{t('hero.slides.altHint')}</p>
<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>
)}
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" className="size-4 rounded border-input" data-testid={`hero-slide-${index}-decorative`} {...register(`slides.${index}.decorative` as const)} />
{t('hero.slides.decorative')}
@@ -507,9 +511,6 @@ 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={focusEdits[field.imageId] ? 'default' : 'outline'} size="icon" aria-label={t('hero.slides.focus')} disabled={!image || image.variants.length === 0} onClick={() => setFocusImageId(field.imageId)} data-testid={`hero-slide-${index}-focus`}>
<Crosshair className="size-4" aria-hidden="true" />
</Button>
<Button type="button" variant="destructive" size="icon" aria-label={t('hero.slides.remove')} title={t('hero.slides.remove')} onClick={() => slides.remove(index)} data-testid={`hero-slide-${index}-remove`}>
<Trash2 className="size-4" aria-hidden="true" />
</Button>
@@ -537,8 +538,22 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
</span>
)}
</div>
<Button type="submit" disabled={save.isPending} className={hasUnsaved ? 'ring-2 ring-primary ring-offset-2' : undefined} data-testid="hero-save">
{save.isPending ? '…' : t('common.save')}
<Button
type="submit"
disabled={save.isPending || !hasUnsaved}
aria-disabled={save.isPending || !hasUnsaved}
aria-busy={save.isPending}
className={hasUnsaved && !save.isPending ? 'ring-2 ring-primary ring-offset-2' : undefined}
data-testid="hero-save"
>
{save.isPending ? (
<>
<Spinner className="mr-2 size-4" />
{t('hero.saving')}
</>
) : (
t('common.save')
)}
</Button>
</div>
@@ -651,7 +651,6 @@
"decorative": "Hide from screen readers",
"up": "Move up",
"down": "Move down",
"focus": "Set focus",
"remove": "Remove slide",
"ceiling": "Only the first {{max}} images are shown on the website.",
"focusPending": "Focus changed, not saved yet.",
@@ -670,7 +669,8 @@
"queued": "in the queue",
"number": "Slide {{n}}",
"done": "Processing finished",
"doneFor": "Slide {{n}}: processing finished"
"doneFor": "Slide {{n}}: processing finished",
"cropEdit": "Adjust crop"
},
"processing": {
"count": "{{done}} of {{total}} photos processed",
@@ -775,6 +775,7 @@
"leaveText": "You have made changes that are not saved yet. If you leave this page they will be lost.",
"stay": "Stay",
"discard": "Discard changes"
}
},
"saving": "Saving…"
}
}
@@ -651,7 +651,6 @@
"decorative": "Verberg voor schermlezers",
"up": "Omhoog",
"down": "Omlaag",
"focus": "Focus instellen",
"remove": "Slide verwijderen",
"ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website.",
"focusPending": "Focus gewijzigd, nog niet opgeslagen.",
@@ -670,7 +669,8 @@
"queued": "in de wachtrij",
"number": "Slide {{n}}",
"done": "Verwerking afgerond",
"doneFor": "Slide {{n}}: verwerking afgerond"
"doneFor": "Slide {{n}}: verwerking afgerond",
"cropEdit": "Uitsnede aanpassen"
},
"processing": {
"count": "{{done}} van {{total}} foto’s verwerkt",
@@ -775,6 +775,7 @@
"leaveText": "Je hebt wijzigingen gemaakt die nog niet zijn opgeslagen. Als je deze pagina verlaat, gaan ze verloren.",
"stay": "Blijven",
"discard": "Wijzigingen weggooien"
}
},
"saving": "Bezig met opslaan…"
}
}
@@ -372,4 +372,51 @@ public class HeroFocusSaveTests
done.Variants.Should().NotBeEmpty();
(await rig.Images.GetImageAsync(Guid.NewGuid(), default)).Should().BeNull();
}
[Fact]
public async Task APutWithAChangedFocus_ShowsTheImageAsBeingRecut_InTheNextAdminRead_AndAsReadyAfterTheRenderer()
{
using var rig = new HeroTestRig();
var image = await rig.Upload(HeroTestRig.Photo(2400, 1600));
var id = Guid.Parse(image.Id);
await rig.Service.SaveAsync(Save(id, null), HeroTestRig.Admin, default);
(await rig.Service.GetAsync(default)).Slides[0].Image.Processing.Should().BeFalse();
// The body of the PUT as the admin sends it (camelCase JSON), bound the way the controller binds it.
var json = $$"""
{"title":"Andrea Slop","tagline":null,"lead":null,"display":"single","buttons":[],"isActive":true,"startsAt":null,"endsAt":null,
"slides":[{"id":null,"imageId":"{{id}}","alt":"foto","decorative":false,"isActive":true}],
"imageFocus":[{"imageId":"{{id}}","focus":{"x":0.2,"y":0.3,"zoom":1.5},"wide":null,"tall":null}]}
""";
var request = System.Text.Json.JsonSerializer.Deserialize<HeroSaveRequest>(json, new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web))!;
request.ImageFocus.Should().ContainSingle().Which.Focus.Should().Be(new FocusDto(0.2, 0.3, 1.5));
var response = await rig.Service.SaveAsync(request, HeroTestRig.Admin, default);
response.Slides.Single(s => s.ImageId == image.Id).Image.Processing.Should().BeTrue("the answer of the PUT already says the new crop is being made");
var read = (await rig.Service.GetAsync(default)).Slides.Single(s => s.ImageId == image.Id).Image;
read.Processing.Should().BeTrue();
read.Variants.Should().NotBeEmpty("the old crop stays published meanwhile");
(await rig.RenderPending()).Should().Be(1);
var done = (await rig.Service.GetAsync(default)).Slides.Single(s => s.ImageId == image.Id).Image;
done.Processing.Should().BeFalse();
done.Focus.Should().Be(new FocusDto(0.2, 0.3, 1.5));
}
[Fact]
public async Task AHigherZoom_GivesASmallerSet_BecauseNoVariantIsMadeLargerThanItsCrop()
{
using var rig = new HeroTestRig();
var image = await rig.Upload(HeroTestRig.Photo(2400, 1600));
var id = Guid.Parse(image.Id);
await rig.Service.SaveAsync(Save(id, null), HeroTestRig.Admin, default);
var normal = rig.Db.HeroImages.Single().Variants.Count;
await rig.Service.SaveAsync(Save(id, [new HeroImageFocusRequest(id, new FocusDto(0.5, 0.5, 3))]), HeroTestRig.Admin, default);
await rig.RenderPending();
rig.Db.HeroImages.Single().Variants.Count.Should().BeLessThan(normal, "a zoomed crop is smaller, so the wide sizes above it are left out");
}
}
@@ -283,7 +283,7 @@ public class HeroImageService(
var current = await repository.GetImageFreshAsync(image.Id, cancellationToken);
if (current is null || HeroMapping.TargetSetHash(current) != target)
{
logger.LogInformation("Hero image {ImageId}: the focus changed while its variants were cut; cutting again.", image.Id);
logger.LogInformation("Hero image {ImageId}: recut superseded, the focus changed while its variants were being cut; the finished set is dropped and the image is cut again at the newest focus.", image.Id);
return image.Id;
}