Hero-admin: schakelaar Actief, destructieve knoppen rood, slide-kopjes, juiste voorvertoning in het focusvenster, status per foto

- Schakelaar (role=switch) Actief / Niet actief bij de knoppen, gedimde rij; 'Verberg voor schermlezers'; veld 'Beschrijving' binnen een groep 'Slide N'
- Alle foto's zonder complete set tonen 'Wordt verwerkt' (voortgang bij de foto die bezig is, 'in de wachtrij' bij de rest); totaal bovenaan telt ook nog niet opgeslagen foto's
- Per foto 'Verwerking afgerond' (zelfde weergave voor een hergebruikte foto), foto direct bruikbaar; niet-opgeslagen foto's worden zelf ververst (GET /hero/images/{id}), ook in een achtergrondtab
- Focusvenster toont de hele foto (full-preview in elke set, achtergrond-aanvulling voor oude sets) in plaats van de uitgesneden wide-variant (vervorming)
- Prullenbak en 'Wijzigingen weggooien' in de destructieve stijl
- upload-respons: reused (intern)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 23:26:47 +01:00
co-authored by Claude Sonnet 5.5
parent 9f07934f9e
commit 6999f5b2ba
25 changed files with 794 additions and 73 deletions
@@ -38,6 +38,8 @@ const percent = (fraction: number) => Math.round(fraction * 1000) / 10;
function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply: (imageId: string, request: HeroFocusRequest) => void; onClose: () => void }) {
const { t } = useTranslation();
const area = useRef<HTMLDivElement>(null);
// The whole picture: image.src is already a crop of the wide shape and would be shown stretched and out of place.
const previewUrl = image.previewSrc ? mediaUrl(image.previewSrc) : null;
const [target, setTarget] = useState<Target>('general');
const [general, setGeneral] = useState<FocusDto>(image.focus ?? CENTRE);
const [wide, setWide] = useState<FocusDto | null>(image.wideFocus);
@@ -143,7 +145,13 @@ function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply
onKeyDown={onKeyDown}
data-testid="focus-area"
>
<img src={mediaUrl(image.src)} alt="" draggable={false} className="pointer-events-none absolute inset-0 h-full w-full" />
{previewUrl ? (
<img src={previewUrl} alt="" draggable={false} className="pointer-events-none absolute inset-0 h-full w-full object-cover" />
) : (
<p className="absolute inset-0 flex items-center justify-center bg-muted p-4 text-center text-sm text-muted-foreground" role="status" data-testid="focus-preview-pending">
{t('hero.focus.previewPending')}
</p>
)}
<div className="pointer-events-none absolute border-2 border-sky-400" style={outline(WIDE, effective.wide)} data-testid="focus-outline-wide" />
<div className="pointer-events-none absolute border-2 border-amber-400" style={outline(TALL, effective.tall)} data-testid="focus-outline-tall" />
<div
@@ -212,8 +220,8 @@ function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply
style={{ aspectRatio: `${ratio.numerator} / ${ratio.denominator}`, maxWidth: ratio.name === 'tall' ? '8rem' : '12rem' }}
data-testid={`focus-preview-${ratio.name}`}
>
<img
src={mediaUrl(image.src)}
{previewUrl && <img
src={previewUrl}
alt=""
className="absolute max-w-none"
style={{
@@ -222,7 +230,7 @@ function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply
// top is a percentage of the box height, which is the box width times denominator over numerator.
top: `${(-crop.y / crop.width) * (ratio.numerator / ratio.denominator) * 100}%`,
}}
/>
/>}
</div>
</div>
);
@@ -1,8 +1,8 @@
import { Loader2 } from 'lucide-react';
import { Check, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { useRetryHeroImage } from '../services/hooks';
import type { HeroAdminDto } from '../services/types';
import type { HeroImageDto } from '../services/types';
/** A spinner that stands still for people who asked for less motion. */
export function Spinner({ className = 'size-4' }: { className?: string }) {
@@ -13,19 +13,18 @@ export function Spinner({ className = 'size-4' }: { className?: string }) {
* Shown above the form while photos of the saved hero are still being prepared in the background: how many are ready,
* what that means for the website, and a way to try again for a photo that failed.
*/
export function ProcessingStatus({ hero }: { hero: HeroAdminDto }) {
export function ProcessingStatus({ images }: { images: HeroImageDto[] }) {
const { t } = useTranslation();
const retry = useRetryHeroImage();
const total = hero.slides.length;
const waiting = hero.slides.filter((s) => s.image.processing);
const total = images.length;
const waiting = images.filter((image) => image.processing);
if (waiting.length === 0) return null;
const done = total - waiting.length;
const failed = waiting.filter((s) => s.image.failed);
const failed = waiting.filter((image) => image.failed);
const working = waiting.length - failed.length;
// The photo the server is busy with right now, and how far along it is (a photo that waits has no step yet).
const busyIndex = waiting.findIndex((s) => s.image.renderTotal);
const busy = busyIndex === -1 ? null : waiting[busyIndex].image;
const busy = waiting.find((image) => image.renderTotal) ?? null;
const fraction = busy && busy.renderTotal ? (busy.renderDone ?? 0) / busy.renderTotal : 0;
const percent = total === 0 ? 0 : Math.min(100, ((done + fraction) / total) * 100);
@@ -61,7 +60,7 @@ export function ProcessingStatus({ hero }: { hero: HeroAdminDto }) {
type="button"
className="underline underline-offset-2 hover:text-foreground disabled:opacity-50"
disabled={retry.isPending}
onClick={() => waiting.forEach((s) => retry.mutate(s.imageId))}
onClick={() => waiting.forEach((image) => retry.mutate(image.id))}
data-testid="hero-processing-retry-all"
>
{t('hero.processing.retry')}
@@ -78,7 +77,7 @@ export function ProcessingStatus({ hero }: { hero: HeroAdminDto }) {
variant="outline"
size="sm"
disabled={retry.isPending}
onClick={() => failed.forEach((s) => retry.mutate(s.imageId))}
onClick={() => failed.forEach((image) => retry.mutate(image.id))}
data-testid="hero-processing-retry"
>
{t('hero.processing.retry')}
@@ -107,6 +106,7 @@ export function PhotoPlaceholder({ failed, testId, step }: { failed: boolean; te
{failed ? null : <Spinner className="size-3.5" />}
<span>{failed ? t('hero.slides.failed') : t('hero.slides.processing')}</span>
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
{!failed && !step ? <span className="opacity-70" data-testid={`${testId}-queued`}>{t('hero.slides.queued')}</span> : null}
</div>
);
}
@@ -134,3 +134,23 @@ export function RecutThumbnail({ src, failed, testId, step }: { src: string; fai
</div>
);
}
/**
* Per photo: shortly after its processing is done a check mark with "Processing finished" shows on that photo itself and
* fades away. The region is always there (empty) so a screen reader announces the text when it appears; the text names
* the slide. With reduced motion it does not fade but disappears after the same time.
*/
export function DoneStatus({ done, slideNumber, testId }: { done: boolean; slideNumber: number; testId: string }) {
const { t } = useTranslation();
return (
<div role="status" aria-live="polite" className="min-h-4 text-[11px] leading-tight" data-testid={testId}>
{done && (
<span className="hero-done inline-flex items-center gap-1 font-medium text-green-700 dark:text-green-400" data-testid={`${testId}-text`}>
<Check className="size-3.5" aria-hidden="true" />
<span className="sr-only">{t('hero.slides.doneFor', { n: slideNumber })}</span>
<span aria-hidden="true">{t('hero.slides.done')}</span>
</span>
)}
</div>
);
}
@@ -0,0 +1,33 @@
import { useTranslation } from 'react-i18next';
interface SlideSwitchProps {
checked: boolean;
onChange: (checked: boolean) => void;
testId: string;
/** What a screen reader says besides the visible text, so the switch is clearly about this slide. */
slideNumber: number;
}
/** A switch (role="switch") that turns a slide on or off; the text next to it says the current state. */
export function SlideSwitch({ checked, onChange, testId, slideNumber }: SlideSwitchProps) {
const { t } = useTranslation();
return (
<button
type="button"
role="switch"
aria-checked={checked}
onClick={() => onChange(!checked)}
className="flex items-center gap-2 rounded-md px-1 py-1 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
data-testid={testId}
>
<span
aria-hidden="true"
className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border transition-colors ${checked ? 'border-primary bg-primary' : 'border-input bg-muted'}`}
>
<span className={`inline-block size-4 rounded-full bg-background shadow transition-transform motion-reduce:transition-none ${checked ? 'translate-x-[1.1rem]' : 'translate-x-0.5'}`} />
</span>
<span className="min-w-[4.5rem] text-left">{checked ? t('hero.slides.activeOn') : t('hero.slides.activeOff')}</span>
<span className="sr-only">{t('hero.slides.activeFor', { n: slideNumber })}</span>
</button>
);
}
@@ -8,6 +8,8 @@ interface SortableSlideProps {
/** The id of the form field of this slide (stable while the order changes). */
id: string;
index: number;
/** A slide that is switched off is shown dimmed. */
dimmed?: boolean;
children: ReactNode;
}
@@ -16,7 +18,7 @@ interface SortableSlideProps {
* use the arrow keys, press Space again). The arrow buttons of the row stay as another way to change the order. While
* dragging, the row gets a frame and a shadow and the other rows make room, so it is clear where it will land.
*/
export function SortableSlide({ id, index, children }: SortableSlideProps) {
export function SortableSlide({ id, index, dimmed = false, children }: SortableSlideProps) {
const { t } = useTranslation();
const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id });
@@ -24,9 +26,10 @@ export function SortableSlide({ id, index, children }: SortableSlideProps) {
<li
ref={setNodeRef}
style={{ transform: CSS.Transform.toString(transform), transition, position: 'relative', zIndex: isDragging ? 10 : undefined }}
className={`flex flex-wrap items-start gap-3 rounded-md border bg-background p-3 ${isDragging ? 'shadow-lg ring-2 ring-primary' : ''}`}
className={`flex flex-wrap items-start gap-3 rounded-md border bg-background p-3 ${isDragging ? 'shadow-lg ring-2 ring-primary' : ''} ${dimmed ? 'opacity-60' : ''}`}
data-testid={`hero-slide-${index}`}
data-dragging={isDragging ? 'true' : undefined}
data-inactive={dimmed ? 'true' : undefined}
>
<button
type="button"
@@ -27,7 +27,7 @@ export function UnsavedChangesGuard({ dirty }: { dirty: boolean }) {
<Button type="button" onClick={() => blocker.reset?.()} data-testid="hero-leave-stay">
{t('hero.unsaved.stay')}
</Button>
<Button type="button" variant="outline" onClick={() => blocker.proceed?.()} data-testid="hero-leave-discard">
<Button type="button" variant="destructive" onClick={() => blocker.proceed?.()} data-testid="hero-leave-discard">
{t('hero.unsaved.discard')}
</Button>
</DialogFooter>
@@ -59,3 +59,49 @@ describe('normalizeFocus and roundHalfUp', () => {
expect(roundHalfUp(2.4)).toBe(2);
});
});
describe('the crop of both shapes for every kind of picture', () => {
// landscape 3:2, the two common cameras, portrait, square, a panorama and a very tall strip
const sources: [string, number, number][] = [
['landscape 3:2', 3000, 2000],
['landscape 4:3', 2048, 1536],
['portrait 2:3', 2000, 3000],
['square', 1500, 1500],
['panorama 3:1', 6000, 2000],
['tall strip 1:3', 800, 2400],
];
const points = [CENTRE, { x: 0, y: 0, zoom: 1 }, { x: 1, y: 1, zoom: 1 }, { x: 0.2, y: 0.8, zoom: 2 }, { x: 0.5, y: 0.5, zoom: 4 }];
it.each(sources)('%s: both crops have exactly their shape (to the pixel), lie inside the picture and keep the point', (_name, width, height) => {
for (const ratio of [WIDE, TALL]) {
for (const focus of points) {
const crop = cropFor(width, height, ratio, focus);
// One pixel of rounding at most: the crop is never stretched to another shape.
expect(Math.abs(crop.width * ratio.denominator - crop.height * ratio.numerator)).toBeLessThanOrEqual(Math.max(ratio.numerator, ratio.denominator));
expect(crop.x).toBeGreaterThanOrEqual(0);
expect(crop.y).toBeGreaterThanOrEqual(0);
expect(crop.x + crop.width).toBeLessThanOrEqual(width);
expect(crop.y + crop.height).toBeLessThanOrEqual(height);
}
}
});
it.each(sources)('%s: the preview box shows the crop at its own shape (no stretching)', (_name, width, height) => {
// The preview places the WHOLE picture inside a box of the crop shape: scale = box width / crop width, so the
// picture keeps its own shape when its height follows from its width.
for (const ratio of [WIDE, TALL]) {
const crop = cropFor(width, height, ratio, CENTRE);
const boxWidth = 100;
const scale = boxWidth / crop.width;
const pictureWidth = width * scale;
const pictureHeight = pictureWidth * (height / width);
const boxHeight = (boxWidth * ratio.denominator) / ratio.numerator;
// What is visible of the picture in the box is exactly the crop rectangle (same shape as the box).
const visibleWidth = boxWidth / (pictureWidth / width);
const visibleHeight = boxHeight / (pictureHeight / height);
expect(visibleWidth).toBeCloseTo(crop.width, 6);
expect(visibleHeight / visibleWidth).toBeCloseTo(ratio.denominator / ratio.numerator, 2);
}
});
});
@@ -17,6 +17,7 @@ const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({
],
processing: false,
failed: false,
previewSrc: '/media/hero/0123456789abcdef/full-1280.webp',
});
export const emptyHero = (): HeroAdminDto => ({
@@ -127,6 +128,11 @@ export const heroHandlers = [
HttpResponse.json({ formats: ['JPEG', 'PNG', 'GIF', 'BMP', 'TIFF', 'WebP', 'AVIF'], maxUploadBytes: 10 * 1024 * 1024, maxMegapixels: 64 }),
),
http.get(`${API_BASE}/api/v1/hero/images/:id`, ({ params }) => {
const image = images[String(params.id)];
return image ? HttpResponse.json(image) : new HttpResponse(null, { status: 404 });
}),
http.post(`${API_BASE}/api/v1/hero/images/:id/retry`, ({ params }) => {
retried.push(String(params.id));
return new HttpResponse(null, { status: 204 });
@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -634,14 +634,15 @@ describe('Order by dragging, wording and calm waiting', () => {
}
});
it('speaks plain language: no alt text, decoration with an explanation, and a short guide per part', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
it('speaks plain language: a plain Description field inside a titled slide, no alt text, and a short guide per part', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
await openPage();
expect(screen.getByLabelText(/Beschrijving afbeelding 1$|Description of image 1$/)).toBeInTheDocument();
const row = within(screen.getByTestId('hero-slide-0'));
expect(row.getByText(/Alleen versiering|Decoration only/)).toBeInTheDocument();
expect(row.getByText(/niets toevoegt aan de inhoud|adds nothing to the content/)).toBeInTheDocument();
const first = screen.getByRole('group', { name: /^Slide 1$/ });
expect(within(first).getByLabelText(/^(Beschrijving|Description)$/)).toBeInTheDocument();
expect(within(first).getByText(/Verberg voor schermlezers|Hide from screen readers/)).toBeInTheDocument();
expect(within(first).queryByText(/niets toevoegt aan de inhoud|adds nothing to the content/)).not.toBeInTheDocument();
expect(screen.getByRole('group', { name: /^Slide 2$/ })).toBeInTheDocument();
expect(screen.queryByText(/alt-tekst|alt text/i)).not.toBeInTheDocument();
const help = screen.getByTestId('hero-help');
expect(help).toHaveTextContent(/#contact/);
@@ -649,6 +650,55 @@ describe('Order by dragging, wording and calm waiting', () => {
expect(help).toHaveTextContent(/Planning|Schedule/);
});
it('numbers the slides by their current order, also after the order changed', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
await openPage();
await userEvent.click(screen.getByTestId('hero-slide-1-up'));
expect(within(screen.getByRole('group', { name: /^Slide 1$/ })).getByTestId('hero-slide-0-alt')).toHaveValue('Foto 2');
});
it('has a switch per slide: role switch, Active or Not active, keyboard, and a dimmed row when off', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
await openPage();
const toggle = screen.getByTestId('hero-slide-0-active');
expect(toggle).toHaveAttribute('role', 'switch');
expect(toggle).toBeChecked();
expect(toggle).toHaveTextContent(/^(Actief|Active)/);
expect(screen.getByTestId('hero-slide-0')).not.toHaveAttribute('data-inactive');
toggle.focus();
await userEvent.keyboard('{Enter}');
expect(toggle).not.toBeChecked();
expect(toggle).toHaveTextContent(/^(Niet actief|Not active)/);
expect(screen.getByTestId('hero-slide-0')).toHaveAttribute('data-inactive', 'true');
expect(screen.getByTestId('hero-slide-1')).not.toHaveAttribute('data-inactive');
await userEvent.click(screen.getByTestId('hero-save'));
await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1));
expect(getSavedHeroRequests()[0].slides.map((x) => x.isActive)).toEqual([false, true]);
});
it('marks every photo without a complete set as being processed, the one being cut with its step and the rest as queued', async () => {
const waiting = (n: number, step?: [number, number]) => ({
...slide(n),
image: { ...slide(n).image, variants: [], src: '', processing: true, renderDone: step?.[0] ?? null, renderTotal: step?.[1] ?? null },
});
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [waiting(1, [3, 16]), waiting(2), waiting(3)] });
await openPage();
for (const i of [0, 1, 2]) {
const box = await screen.findByTestId(`hero-slide-${i}-processing`, {}, T);
expect(box).toHaveClass('hero-shimmer');
expect(box).toHaveTextContent(/Wordt verwerkt|Processing/);
}
expect(screen.getByTestId('hero-slide-0-processing-step')).toHaveTextContent('3/16');
expect(screen.getByTestId('hero-slide-1-processing-queued')).toBeInTheDocument();
expect(screen.getByTestId('hero-slide-2-processing-queued')).toBeInTheDocument();
expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/0 van 3|0 of 3/);
});
it('keeps the waiting placeholder mounted through the background refresh, so its animation keeps running', async () => {
const waiting = { ...slide(1), image: { ...slide(1).image, variants: [], src: '', processing: true } };
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [waiting, slide(2)] });
@@ -736,3 +786,155 @@ describe('A changed focus point makes a new crop in the background', () => {
await waitFor(() => expect(getRetriedImages()).toEqual([waiting.imageId]), T);
});
});
describe('Focus dialog shows the whole picture', () => {
beforeEach(() => {
resetMockHero();
});
const portraitSlide = () => {
const base = slide(1);
// A portrait photo of 2000x3000: the published crops are wide/tall, but the dialog needs the whole picture.
return { ...base, image: { ...base.image, width: 2000, height: 3000, src: '/media/hero/0123456789abcdef/wide-1600.webp', previewSrc: '/media/hero/0123456789abcdef/full-1280.webp' } };
};
it('uses the full-frame preview at the shape of the original, not the wide crop', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [portraitSlide()] });
await openPage();
await userEvent.click(screen.getByTestId('hero-slide-0-focus'));
const area = await screen.findByTestId('focus-area', {}, T);
expect(area.style.aspectRatio.replace(/\s/g, '')).toBe('2000/3000');
const picture = area.querySelector('img')!;
expect(picture.getAttribute('src')).toContain('full-1280.webp');
expect(picture.getAttribute('src')).not.toContain('wide-1600');
expect(picture).toHaveClass('object-cover');
for (const ratio of ['wide', 'tall']) {
expect(screen.getByTestId(`focus-preview-${ratio}`).querySelector('img')!.getAttribute('src')).toContain('full-1280.webp');
}
});
it('says the preview is being prepared when the server has none yet, instead of showing a wrong picture', async () => {
const base = portraitSlide();
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [{ ...base, image: { ...base.image, previewSrc: null } }] });
await openPage();
await userEvent.click(screen.getByTestId('hero-slide-0-focus'));
expect(await screen.findByTestId('focus-preview-pending', {}, T)).toBeInTheDocument();
expect(screen.getByTestId('focus-area').querySelector('img')).toBeNull();
});
});
describe('Destructive actions are red', () => {
beforeEach(() => {
resetMockHero();
});
it('shows the remove button of every slide in the destructive style, with a name', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
await openPage();
for (const i of [0, 1]) {
const remove = screen.getByTestId(`hero-slide-${i}-remove`);
expect(remove).toHaveClass('bg-destructive');
expect(remove).toHaveAccessibleName(/Slide verwijderen|Remove slide/);
}
});
it('shows Discard changes in the destructive style', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
await openPage();
await userEvent.type(screen.getByTestId('hero-title-input'), 'X');
await screen.findByTestId('hero-unsaved');
await userEvent.click(screen.getByTestId('nav-dashboard'));
expect(await screen.findByTestId('hero-leave-discard', {}, T)).toHaveClass('bg-destructive');
expect(screen.getByTestId('hero-leave-stay')).not.toHaveClass('bg-destructive');
});
});
describe('Each photo shows by itself when its processing is finished', () => {
beforeEach(() => {
resetMockHero();
vi.restoreAllMocks();
});
const jpg = (name: string) => new File(['x'], name, { type: 'image/jpeg' });
const cutting = (id: string) => ({
id, width: 5757, height: 3838, focus: { x: 0.5, y: 0.5, zoom: 1 }, wideFocus: null, tallFocus: null,
src: '', variants: [], processing: true, failed: false, previewSrc: null,
});
const ready = (id: string) => ({
...cutting(id), src: '/media/hero/0123456789abcdef/wide-1600.webp', processing: false,
variants: [{ ratio: 'wide', width: 960, height: 640, type: 'image/webp', url: '/media/hero/0123456789abcdef/wide-960.webp' }],
previewSrc: '/media/hero/0123456789abcdef/full-1280.webp',
});
it('turns the placeholder of a photo that was not saved yet into a finished note on that photo, by itself, and the photo can be worked on at once', async () => {
const id = '70000000-0000-0000-0000-000000000001';
let finished = false;
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(finished ? ready(id) : cutting(id))),
);
await openPage();
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-done-text')).not.toBeInTheDocument();
// The server is done; nobody saves or reloads: the page asks again by itself.
finished = true;
const note = await screen.findByTestId('hero-slide-0-done-text', {}, { timeout: 12000 });
expect(note).toHaveTextContent(/Verwerking afgerond|Processing finished/);
expect(screen.getByTestId('hero-slide-0-done')).toHaveAttribute('role', 'status');
expect(screen.getByTestId('hero-slide-0-done')).toHaveAttribute('aria-live', 'polite');
expect(screen.queryByTestId('hero-slide-0-processing')).not.toBeInTheDocument();
expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled();
// The note names the slide for a screen reader, and goes away by itself after a few seconds.
expect(note.textContent).toMatch(/Slide 1: (verwerking afgerond|processing finished)/);
await waitFor(() => expect(screen.queryByTestId('hero-slide-0-done-text')).not.toBeInTheDocument(), { timeout: 8000 });
}, 30000);
it('shows the same finished note, at once and without a placeholder, for a photo that was already in the CMS', async () => {
const id = '70000000-0000-0000-0000-000000000002';
server.use(http.post(`${API_BASE}/api/v1/hero/images`, () => HttpResponse.json({ ...ready(id), reused: true }, { status: 201 })));
await openPage();
await userEvent.upload(screen.getByTestId('hero-upload'), jpg('zelfde.jpg'));
expect(await screen.findByTestId('hero-slide-0-done-text', {}, T)).toHaveTextContent(/Verwerking afgerond|Processing finished/);
expect(screen.queryByTestId('hero-slide-0-processing')).not.toBeInTheDocument();
expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled();
expect(screen.queryByText(/stond al|already/i)).not.toBeInTheDocument();
});
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;
const finished = new Set<string>();
server.use(
http.post(`${API_BASE}/api/v1/hero/images`, () => HttpResponse.json(cutting(ids[n++]), { status: 201 })),
http.get(`${API_BASE}/api/v1/hero/images/${ids[0]}`, () => HttpResponse.json(finished.has(ids[0]) ? ready(ids[0]) : cutting(ids[0]))),
http.get(`${API_BASE}/api/v1/hero/images/${ids[1]}`, () => HttpResponse.json(finished.has(ids[1]) ? ready(ids[1]) : cutting(ids[1]))),
);
await openPage();
await userEvent.upload(screen.getByTestId('hero-upload'), [jpg('a.jpg'), jpg('b.jpg')]);
await screen.findByTestId('hero-slide-1-processing', {}, T);
expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/0 van 2|0 of 2/);
finished.add(ids[0]);
await screen.findByTestId('hero-slide-0-done-text', {}, { timeout: 12000 });
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.getByTestId('hero-processing-count')).toHaveTextContent(/1 van 2|1 of 2/);
}, 30000);
});
+67 -22
View File
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useQueries } from '@tanstack/react-query';
import { useFieldArray, useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useTranslation } from 'react-i18next';
@@ -14,13 +15,14 @@ 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 { PhotoPlaceholder, ProcessingStatus, RecutThumbnail } from '../components/ProcessingStatus';
import { DoneStatus, PhotoPlaceholder, ProcessingStatus, RecutThumbnail } from '../components/ProcessingStatus';
import { SlideSwitch } from '../components/SlideSwitch';
import { SortableSlide } from '../components/SortableSlide';
import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard';
import { UploadProgress, type UploadItem } from '../components/UploadProgress';
import { mediaUrl } from '../lib/media';
import { fromLocalInput, heroFormSchema, toLocalInput, type HeroFormData } from '../schemas/hero';
import { useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks';
import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks';
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from '../services/types';
const textareaClass =
@@ -131,7 +133,6 @@ export function HeroPage() {
<Button variant="outline" onClick={() => void refetch()}>{t('common.retry')}</Button>
</div>
)}
{hero && <ProcessingStatus hero={hero} />}
{hero && <HeroEditor key={hero.id ?? 'new'} hero={hero} />}
</div>
);
@@ -155,6 +156,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const {
register,
setValue,
handleSubmit,
control,
formState: { errors, isDirty },
@@ -164,11 +166,48 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const watchedSlides = useWatch({ control, name: 'slides' }) ?? [];
// The images of the saved hero (always current: a change of focus refreshes them) plus the ones uploaded in this session.
// Photos uploaded here and not saved yet are not in the saved hero: they are asked for one by one until they are ready,
// so a photo that is finished never stays "processing" because nothing refreshed it.
const unsavedIds = useMemo(
() => Object.keys(localImages).filter((id) => !hero.slides.some((s) => s.imageId === id)),
[hero.slides, localImages],
);
const polled = useQueries({
queries: unsavedIds.map((id) => heroImageQuery(id)),
combine: (results) => results.map((r) => r.data),
});
const images = useMemo(() => {
const map: Record<string, HeroImageDto> = { ...localImages };
for (const image of polled) if (image) map[image.id] = image;
for (const s of hero.slides) map[s.imageId] = s.image;
return map;
}, [hero.slides, localImages]);
}, [hero.slides, localImages, polled]);
// Per photo: when its processing is done it shows "Processing finished" for a few seconds, and can be worked on at once.
// A photo that was ready at once (the same photo was already in the CMS) shows the same note, without a placeholder.
const [justDone, setJustDone] = useState<Record<string, true>>({});
const wasProcessing = useRef<Record<string, boolean>>({});
const markDone = (imageId: string) => {
setJustDone((current) => ({ ...current, [imageId]: true }));
window.setTimeout(() => {
setJustDone((current) => {
const { [imageId]: _removed, ...rest } = current;
return rest;
});
}, 4500);
};
useEffect(() => {
for (const field of slides.fields) {
const image = images[field.imageId];
if (!image) continue;
if (image.processing) {
wasProcessing.current[image.id] = true;
} else if (wasProcessing.current[image.id]) {
wasProcessing.current[image.id] = false;
markDone(image.id);
}
}
}, [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);
@@ -219,6 +258,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const result = results[flushed];
if (result && result !== 'failed') {
setLocalImages((current) => ({ ...current, [result.id]: result }));
// 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 });
}
flushed += 1;
@@ -293,6 +334,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-8" noValidate data-testid="hero-form">
<ProcessingStatus images={slides.fields.map((f) => images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} />
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
<section className="space-y-4">
@@ -423,7 +465,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const image = images[field.imageId];
const decorative = watchedSlides[index]?.decorative ?? false;
return (
<SortableSlide key={field.id} id={field.id} index={index}>
<SortableSlide key={field.id} id={field.id} index={index} dimmed={!(watchedSlides[index]?.isActive ?? true)}>
<div className="flex shrink-0 flex-col gap-1">
{image && image.variants.length === 0 ? (
<PhotoPlaceholder failed={image.failed} testId={`hero-slide-${index}-processing`} step={image.renderTotal ? { done: image.renderDone ?? 0, total: image.renderTotal } : null} />
) : image?.processing ? (
@@ -433,29 +476,31 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
) : (
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted text-xs">?</div>
)}
<div className="min-w-[12rem] flex-1 space-y-2">
<Label htmlFor={`hero-slide-${index}-alt`}>{t('hero.slides.alt', { n: index + 1 })}</Label>
<DoneStatus done={Boolean(image && justDone[image.id] && !image.processing)} slideNumber={index + 1} testId={`hero-slide-${index}-done`} />
</div>
<div className="min-w-[12rem] flex-1 space-y-2" role="group" aria-labelledby={`hero-slide-title-${field.id}`}>
<h3 id={`hero-slide-title-${field.id}`} className="text-xs font-medium uppercase tracking-wide text-muted-foreground" data-testid={`hero-slide-${index}-title`}>
{t('hero.slides.number', { n: index + 1 })}
</h3>
<Label htmlFor={`hero-slide-${index}-alt`}>{t('hero.slides.alt')}</Label>
<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>
)}
<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)} />
<span>
{t('hero.slides.decorative')}
<span className="block text-xs text-muted-foreground">{t('hero.slides.decorativeHint')}</span>
</span>
</label>
<label className="flex items-center gap-2">
<input type="checkbox" className="size-4 rounded border-input" data-testid={`hero-slide-${index}-active`} {...register(`slides.${index}.isActive` as const)} />
{t('hero.slides.active')}
</label>
</div>
<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')}
</label>
</div>
<div className="flex gap-1">
<div className="flex flex-wrap items-center gap-1">
<SlideSwitch
checked={watchedSlides[index]?.isActive ?? true}
onChange={(value) => setValue(`slides.${index}.isActive` as const, value, { shouldDirty: true })}
testId={`hero-slide-${index}-active`}
slideNumber={index + 1}
/>
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.up')} disabled={index === 0} onClick={() => slides.move(index, index - 1)} data-testid={`hero-slide-${index}-up`}>
<ArrowUp className="size-4" aria-hidden="true" />
</Button>
@@ -465,7 +510,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
<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="outline" size="icon" aria-label={t('hero.slides.remove')} onClick={() => slides.remove(index)} data-testid={`hero-slide-${index}-remove`}>
<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>
</div>
@@ -11,6 +11,8 @@ export function useHero() {
queryFn: () => api.get<HeroAdminDto>('/api/v1/hero/all'),
// Images are cut in the background after an upload or a saved focus change: look again until they are all ready.
refetchInterval: (query) => (query.state.data?.slides.some((s) => s.image.processing) ? 5000 : false),
// Also while the tab is in the background or the connection came back: the state must never stay stale.
refetchIntervalInBackground: true,
});
}
@@ -58,3 +60,11 @@ export function useHeroUploadLimits() {
staleTime: 10 * 60 * 1000,
});
}
/** The query of one image: the page asks it for photos that were uploaded but not saved yet, until they are ready. */
export const heroImageQuery = (imageId: string) => ({
queryKey: ['hero', 'image', imageId],
queryFn: () => api.get<HeroImageDto>(`/api/v1/hero/images/${imageId}`),
refetchInterval: (query: { state: { data?: HeroImageDto } }) => (query.state.data?.processing ? 5000 : false),
refetchIntervalInBackground: true,
});
@@ -30,6 +30,10 @@ export interface HeroImageDto {
/** While the image is being cut: the step it is at, out of how many (null when it is not being cut right now). */
renderDone?: number | null;
renderTotal?: number | null;
/** The whole picture (not cut around a point), for choosing the focus point; null while the server has not made it yet. */
previewSrc?: string | null;
/** The photo was already in the CMS (same bytes). For internal use: the administrator sees no difference. */
reused?: boolean;
}
export interface HeroButtonDto {