H5: admin-scherm voor de hero (formulier, slides, upload, focus-editor met voorbeeld, TypeScript-tweeling van FocusMath)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 16:07:49 +01:00
co-authored by Claude Sonnet 5.5
parent 4369c905cd
commit 5559d459c3
21 changed files with 1635 additions and 15 deletions
@@ -0,0 +1,321 @@
import { useEffect, useMemo, useRef, useState } from 'react';
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 { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
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 { 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';
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';
function toForm(hero: HeroAdminDto): HeroFormData {
const buttons = [0, 1].map((i) => ({ label: hero.buttons[i]?.label ?? '', target: hero.buttons[i]?.target ?? '' }));
return {
title: hero.title,
tagline: hero.tagline ?? '',
lead: hero.lead ?? '',
display: hero.display,
buttons,
isActive: hero.isActive,
startsAt: toLocalInput(hero.startsAt),
endsAt: toLocalInput(hero.endsAt),
slides: hero.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.alt, decorative: s.decorative, isActive: s.isActive })),
};
}
function toRequest(values: HeroFormData): HeroSaveRequest {
return {
title: values.title,
tagline: values.tagline || null,
lead: values.lead || null,
display: values.display,
buttons: values.buttons.filter((b) => b.label !== '' && b.target !== ''),
isActive: values.isActive,
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 })),
};
}
/** The messages a failed save carries: the field errors of a 400, or a generic text. */
function serverMessage(error: unknown, generic: string, network: string): string {
if (error instanceof NetworkError) return network;
if (error instanceof ProblemDetailsError && error.status === 400) {
const errors = error.problem.errors;
if (errors && typeof errors === 'object') {
const messages = Object.values(errors as Record<string, unknown>).flatMap((v) => (Array.isArray(v) ? v : [v])).filter((v): v is string => typeof v === 'string');
if (messages.length > 0) return messages.join(' ');
}
}
return generic;
}
/** The smallest WebP of the wide ratio for a thumbnail; the plain source when there is none. */
function thumbnail(image: HeroImageDto): string {
const small = image.variants
.filter((v) => v.type === 'image/webp' && v.ratio === 'wide')
.sort((a, b) => a.width - b.width)[0];
return mediaUrl(small?.url ?? image.src);
}
export function HeroPage() {
const { t } = useTranslation();
const { data: hero, isLoading, isError, refetch } = useHero();
return (
<div className="space-y-6" data-testid="hero-page">
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-2xl font-semibold" data-testid="hero-title">{t('hero.title')}</h1>
{hero && (
<Badge variant={hero.isLive ? 'default' : 'secondary'} data-testid="hero-live-badge">
{hero.isLive ? t('hero.live') : t('hero.notLive')}
</Badge>
)}
</div>
<p className="max-w-3xl text-sm text-muted-foreground">{t('hero.intro')}</p>
{isLoading && <p data-testid="hero-loading">{t('common.loading')}</p>}
{isError && (
<div className="space-y-2" data-testid="hero-error">
<p>{t('errors.generic')}</p>
<Button variant="outline" onClick={() => void refetch()}>{t('common.retry')}</Button>
</div>
)}
{hero && <HeroEditor key={hero.id ?? 'new'} hero={hero} />}
</div>
);
}
function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const { t } = useTranslation();
const save = useSaveHero();
const upload = useUploadHeroImage();
const [serverError, setServerError] = useState<string | null>(null);
const [uploadError, setUploadError] = useState<string | null>(null);
const [localImages, setLocalImages] = useState<Record<string, HeroImageDto>>({});
const [focusImageId, setFocusImageId] = useState<string | null>(null);
const fileInput = useRef<HTMLInputElement>(null);
const {
register,
handleSubmit,
control,
formState: { errors, isDirty },
} = useForm<HeroFormData>({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', defaultValues: toForm(hero) });
const slides = useFieldArray({ control, name: 'slides' });
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.
const images = useMemo(() => {
const map: Record<string, HeroImageDto> = { ...localImages };
for (const s of hero.slides) map[s.imageId] = s.image;
return map;
}, [hero.slides, localImages]);
useEffect(() => {
if (!isDirty) return undefined;
const warn = (event: BeforeUnloadEvent) => {
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [isDirty]);
const onUpload = async (files: FileList | null) => {
const file = files?.[0];
if (!file) return;
setUploadError(null);
try {
const image = await upload.mutateAsync(file);
setLocalImages((current) => ({ ...current, [image.id]: image }));
slides.append({ id: null, imageId: image.id, alt: '', decorative: false, isActive: true }, { shouldFocus: false });
} catch (error) {
const message = error instanceof ProblemDetailsError ? error.problem.message : undefined;
setUploadError(typeof message === 'string' ? message : error instanceof NetworkError ? t('errors.network') : t('errors.generic'));
} finally {
if (fileInput.current) fileInput.current.value = '';
}
};
const onSubmit = async (values: HeroFormData) => {
setServerError(null);
try {
await save.mutateAsync(toRequest(values));
toast.success(t('hero.savedToast'));
} catch (error) {
setServerError(serverMessage(error, t('errors.generic'), t('errors.network')));
}
};
const err = (message?: string) => (message ? t(message) : undefined);
const heroErrors = errors;
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-8" noValidate data-testid="hero-form">
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
<section className="space-y-4">
<div className="space-y-2">
<Label htmlFor="hero-title-input">{t('hero.fields.title')}</Label>
<textarea id="hero-title-input" rows={3} className={textareaClass} data-testid="hero-title-input" {...register('title')} />
<p className="text-xs text-muted-foreground">{t('hero.fields.titleHint')}</p>
<FieldError message={err(heroErrors.title?.message)} testId="hero-title-error" />
</div>
<div className="space-y-2">
<Label htmlFor="hero-tagline">{t('hero.fields.tagline')}</Label>
<Input id="hero-tagline" maxLength={120} data-testid="hero-tagline" {...register('tagline')} />
<FieldError message={err(heroErrors.tagline?.message)} />
</div>
<div className="space-y-2">
<Label htmlFor="hero-lead">{t('hero.fields.lead')}</Label>
<textarea id="hero-lead" rows={3} className={textareaClass} data-testid="hero-lead" {...register('lead')} />
<FieldError message={err(heroErrors.lead?.message)} />
</div>
<fieldset className="space-y-2">
<legend className="text-sm font-medium">{t('hero.fields.display')}</legend>
<div className="flex flex-wrap gap-4 text-sm">
{(['single', 'slideshow'] as const).map((value) => (
<label key={value} className="flex items-center gap-2">
<input type="radio" value={value} data-testid={`hero-display-${value}`} {...register('display')} />
{t(`hero.display.${value}`)}
</label>
))}
</div>
</fieldset>
</section>
<section className="space-y-3">
<h2 className="text-lg font-medium">{t('hero.buttons.title')}</h2>
<p className="text-xs text-muted-foreground">{t('hero.buttons.hint')}</p>
{[0, 1].map((i) => (
<div key={i} className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1">
<Label htmlFor={`hero-button-${i}-label`}>{t('hero.buttons.label', { n: i + 1 })}</Label>
<Input id={`hero-button-${i}-label`} maxLength={50} data-testid={`hero-button-${i}-label`} {...register(`buttons.${i}.label` as const)} />
<FieldError message={err(heroErrors.buttons?.[i]?.label?.message)} testId={`hero-button-${i}-label-error`} />
</div>
<div className="space-y-1">
<Label htmlFor={`hero-button-${i}-target`}>{t('hero.buttons.target', { n: i + 1 })}</Label>
<Input id={`hero-button-${i}-target`} maxLength={500} placeholder="#contact, /over-mij, https://…" data-testid={`hero-button-${i}-target`} {...register(`buttons.${i}.target` as const)} />
<FieldError message={err(heroErrors.buttons?.[i]?.target?.message)} testId={`hero-button-${i}-target-error`} />
</div>
</div>
))}
</section>
<section className="space-y-3">
<h2 className="text-lg font-medium">{t('hero.schedule.title')}</h2>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" className="size-4 rounded border-input" data-testid="hero-active" {...register('isActive')} />
{t('hero.schedule.active')}
</label>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1">
<Label htmlFor="hero-starts">{t('hero.schedule.starts')}</Label>
<Input id="hero-starts" type="datetime-local" data-testid="hero-starts" {...register('startsAt')} />
</div>
<div className="space-y-1">
<Label htmlFor="hero-ends">{t('hero.schedule.ends')}</Label>
<Input id="hero-ends" type="datetime-local" data-testid="hero-ends" {...register('endsAt')} />
<FieldError message={err(heroErrors.endsAt?.message)} testId="hero-ends-error" />
</div>
</div>
<p className="text-xs text-muted-foreground">{t('hero.schedule.hint')}</p>
</section>
<section className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-medium">{t('hero.slides.title')}</h2>
<div>
<input
ref={fileInput}
id="hero-upload"
type="file"
accept="image/*"
className="sr-only"
data-testid="hero-upload"
onChange={(event) => void onUpload(event.target.files)}
/>
<Button type="button" variant="outline" disabled={upload.isPending} onClick={() => fileInput.current?.click()} data-testid="hero-upload-button">
<ImagePlus className="mr-2 size-4" aria-hidden="true" />
{upload.isPending ? t('hero.slides.uploading') : t('hero.slides.add')}
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">{t('hero.slides.hint')}</p>
{uploadError && <p className="text-sm text-destructive" role="alert" data-testid="hero-upload-error">{uploadError}</p>}
{slides.fields.length === 0 && <p className="text-sm text-muted-foreground" data-testid="hero-slides-empty">{t('hero.slides.empty')}</p>}
<ol className="space-y-3" data-testid="hero-slides">
{slides.fields.map((field, index) => {
const image = images[field.imageId];
const decorative = watchedSlides[index]?.decorative ?? false;
return (
<li key={field.id} className="flex flex-wrap items-start gap-3 rounded-md border p-3" data-testid={`hero-slide-${index}`}>
{image ? (
<img src={thumbnail(image)} alt="" className="h-20 w-28 rounded object-cover" />
) : (
<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>
<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`} />
<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)} />
{t('hero.slides.decorative')}
</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>
</div>
<div className="flex gap-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>
<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`}>
<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`}>
<Trash2 className="size-4" aria-hidden="true" />
</Button>
</div>
</li>
);
})}
</ol>
{slides.fields.length > hero.maxPublishedSlides && (
<p className="text-xs text-muted-foreground" data-testid="hero-ceiling-note">
{t('hero.slides.ceiling', { max: hero.maxPublishedSlides })}
</p>
)}
</section>
<div className="flex justify-end">
<Button type="submit" disabled={save.isPending} data-testid="hero-save">
{save.isPending ? '…' : t('common.save')}
</Button>
</div>
<FocusDialog image={focusImageId ? images[focusImageId] ?? null : null} onClose={() => setFocusImageId(null)} />
</form>
);
}