Hero-admin: voortgangsindicator voor foto's die worden verwerkt, mislukt-melding met opnieuw proberen

Spinner per foto zonder varianten, totaal met voortgangsbalk (aria-valuenow/max), uitleg dat de hero al is opgeslagen, bij 3 mislukte pogingen een melding met 'Opnieuw proberen' (POST /hero/images/{id}/retry; foutstatus staat in het geheugen van de renderer). Test dat een refetch van 5 s onopgeslagen wijzigingen niet overschrijft.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 21:41:29 +01:00
co-authored by Claude Sonnet 5.5
parent 852a162bc3
commit 49302c3228
16 changed files with 323 additions and 15 deletions
@@ -0,0 +1,68 @@
import { 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';
/** A spinner that stands still for people who asked for less motion. */
export function Spinner({ className = 'size-4' }: { className?: string }) {
return <Loader2 className={`${className} animate-spin motion-reduce:animate-none`} aria-hidden="true" />;
}
/**
* 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 }) {
const { t } = useTranslation();
const retry = useRetryHeroImage();
const total = hero.slides.length;
const waiting = hero.slides.filter((s) => s.image.processing);
if (waiting.length === 0) return null;
const done = total - waiting.length;
const failed = waiting.filter((s) => s.image.failed);
const working = waiting.length - failed.length;
return (
<div className="space-y-3 rounded-md border bg-muted/40 p-4" data-testid="hero-processing">
{working > 0 && (
<div className="space-y-2" role="status">
<p className="flex items-center gap-2 text-sm font-medium">
<Spinner />
<span data-testid="hero-processing-count">{t('hero.processing.count', { done, total })}</span>
</p>
<div
role="progressbar"
aria-label={t('hero.processing.label')}
aria-valuemin={0}
aria-valuemax={total}
aria-valuenow={done}
aria-valuetext={t('hero.processing.count', { done, total })}
className="h-2 w-full overflow-hidden rounded bg-muted"
data-testid="hero-processing-bar"
>
<div className="h-full bg-primary transition-all" style={{ width: `${total === 0 ? 0 : (done / total) * 100}%` }} />
</div>
<p className="text-sm text-muted-foreground">{t('hero.processing.explain')}</p>
</div>
)}
{failed.length > 0 && (
<div className="space-y-2" role="alert" data-testid="hero-processing-failed">
<p className="text-sm font-medium text-destructive">{t('hero.processing.failed', { count: failed.length })}</p>
<p className="text-sm text-muted-foreground">{t('hero.processing.failedHint')}</p>
<Button
type="button"
variant="outline"
size="sm"
disabled={retry.isPending}
onClick={() => failed.forEach((s) => retry.mutate(s.imageId))}
data-testid="hero-processing-retry"
>
{t('hero.processing.retry')}
</Button>
</div>
)}
</div>
);
}
@@ -16,6 +16,7 @@ const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({
{ ratio: 'tall', width: 640, height: 800, type: 'image/webp', url: '/media/hero/0123456789abcdef/tall-640.webp' },
],
processing: false,
failed: false,
});
export const emptyHero = (): HeroAdminDto => ({
@@ -57,6 +58,7 @@ export const resetMockHero = (): void => {
saved = [];
uploads = 0;
uploadFailure = null;
retried = [];
};
export const setMockHero = (next: HeroAdminDto): void => {
@@ -64,6 +66,9 @@ export const setMockHero = (next: HeroAdminDto): void => {
images = Object.fromEntries(next.slides.map((s) => [s.imageId, s.image]));
};
let retried: string[] = [];
export const getRetriedImages = (): string[] => retried;
export const getSavedHeroRequests = (): HeroSaveRequest[] => saved;
export const failNextUpload = (failure: { status: number; error: string; message: string } | null): void => {
@@ -107,6 +112,11 @@ export const heroHandlers = [
return HttpResponse.json(hero);
}),
http.post(`${API_BASE}/api/v1/hero/images/:id/retry`, ({ params }) => {
retried.push(String(params.id));
return new HttpResponse(null, { status: 204 });
}),
http.post(`${API_BASE}/api/v1/hero/images`, () => {
if (uploadFailure) {
const { status, error, message } = uploadFailure;
@@ -5,7 +5,7 @@ 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, getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers';
import { emptyHero, failNextUpload, getRetriedImages, getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers';
import { _resetSetupStatusCache } from '@/router';
const T = { timeout: 10000 };
@@ -41,6 +41,59 @@ describe('Hero page', () => {
expect(screen.getByTestId('hero-slide-0-focus')).toBeDisabled();
});
it('shows how many photos are ready, 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');
});
it('keeps unsaved edits when the background refresh brings a finished photo', async () => {
const waiting = { ...slide(1), image: { ...slide(1).image, variants: [], src: '', processing: true } };
setMockHero({ ...emptyHero(), id: 'h1', title: 'Oude titel', slides: [waiting] });
await openPage();
expect(await screen.findByTestId('hero-slide-0-processing', {}, T)).toBeInTheDocument();
const title = screen.getByTestId('hero-title-input');
await userEvent.clear(title);
await userEvent.type(title, 'Nieuwe titel');
const alt = screen.getByTestId('hero-slide-0-alt');
await userEvent.clear(alt);
await userEvent.type(alt, 'Mijn eigen alt');
// The server finishes the photo; the page asks again by itself (every 5 seconds).
setMockHero({ ...emptyHero(), id: 'h1', title: 'Oude titel', slides: [slide(1)] });
await waitFor(() => expect(screen.queryByTestId('hero-slide-0-processing')).not.toBeInTheDocument(), { timeout: 12000 });
expect(screen.getByTestId('hero-title-input')).toHaveValue('Nieuwe titel');
expect(screen.getByTestId('hero-slide-0-alt')).toHaveValue('Mijn eigen alt');
expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled();
}, 20000);
it('does not show the progress panel when every photo is ready', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
await openPage();
expect(screen.queryByTestId('hero-processing')).not.toBeInTheDocument();
});
it('shows a failed photo with a retry that asks the server to try again', async () => {
const failed = { ...slide(1), image: { ...slide(1).image, variants: [], src: '', processing: true, failed: true } };
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [failed] });
await openPage();
await userEvent.click(await screen.findByTestId('hero-processing-retry', {}, T));
await waitFor(() => expect(getRetriedImages()).toEqual([failed.imageId]), T);
expect(screen.getByTestId('hero-processing-failed')).toBeInTheDocument();
});
it('is reachable from the navigation for an administrator', async () => {
mockAuthenticated();
renderApp('/dashboard');
@@ -12,6 +12,7 @@ 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 { ProcessingStatus, Spinner } from '../components/ProcessingStatus';
import { mediaUrl } from '../lib/media';
import { fromLocalInput, heroFormSchema, toLocalInput, type HeroFormData } from '../schemas/hero';
import { useHero, useSaveHero, useUploadHeroImage } from '../services/hooks';
@@ -113,6 +114,7 @@ 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>
);
@@ -300,8 +302,13 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
return (
<li key={field.id} className="flex flex-wrap items-start gap-3 rounded-md border p-3" data-testid={`hero-slide-${index}`}>
{image && image.variants.length === 0 ? (
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted p-1 text-center text-xs" title={t('hero.slides.processingHint')} data-testid={`hero-slide-${index}-processing`}>
{t('hero.slides.processing')}
<div
className={`flex h-20 w-28 flex-col items-center justify-center gap-1 rounded p-1 text-center text-xs ${image.failed ? 'bg-destructive/10 text-destructive' : 'bg-muted'}`}
title={t('hero.slides.processingHint')}
data-testid={`hero-slide-${index}-processing`}
>
{image.failed ? null : <Spinner />}
{image.failed ? t('hero.slides.failed') : t('hero.slides.processing')}
</div>
) : image ? (
<img src={thumbnail(image)} alt="" className="h-20 w-28 rounded object-cover" />
@@ -40,3 +40,12 @@ export function useDeleteHeroImage() {
mutationFn: (imageId) => api.delete<void>(`/api/v1/hero/images/${imageId}`),
});
}
/** Asks the server to try an image again that the background renderer gave up on. */
export function useRetryHeroImage() {
const queryClient = useQueryClient();
return useMutation<void, Error, string>({
mutationFn: (imageId) => api.post<void>(`/api/v1/hero/images/${imageId}/retry`, {}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: HERO_KEY }),
});
}
@@ -25,6 +25,8 @@ export interface HeroImageDto {
variants: HeroVariantDto[];
/** The variants of this image are still being cut in the background; it is not published yet. */
processing: boolean;
/** The background renderer gave up on this image after a few tries; it can be retried. */
failed: boolean;
}
export interface HeroButtonDto {