Merge origin/master into feature/messages-badge
Continuous Integration / config-asf (pull_request) Successful in 7s
Continuous Integration / config-sls (pull_request) Successful in 8s
Continuous Integration / changes (pull_request) Successful in 11s
Continuous Integration / backend-build (pull_request) Successful in 1m46s
Continuous Integration / compile-sites (pull_request) Successful in 1m51s
Continuous Integration / frontend-prepare (pull_request) Successful in 1m57s
Continuous Integration / vulnerability-scan (pull_request) Successful in 2m2s
Continuous Integration / frontend-build (pull_request) Successful in 43s
Continuous Integration / frontend-test (pull_request) Successful in 2m30s
Continuous Integration / backend-test (pull_request) Successful in 2m43s
Continuous Integration / frontend-lint (pull_request) Successful in 2m28s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 12:58:12 +01:00
co-authored by Claude Sonnet 5.5
180 changed files with 17199 additions and 193 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}%`,
};
}
@@ -0,0 +1,251 @@
import { useRef, useState, type KeyboardEvent, type PointerEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
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 type { FocusDto, HeroFocusRequest, HeroImageDto } from '../services/types';
type Target = 'general' | 'wide' | 'tall';
interface FocusDialogProps {
/** 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, onApply, onClose }: FocusDialogProps) {
const { t } = useTranslation();
return (
<Dialog open={image !== null} onOpenChange={(next) => { if (!next) onClose(); }}>
<DialogContent className="max-h-[92vh] overflow-y-auto sm:max-w-3xl">
<DialogHeader>
<DialogTitle>{t('hero.focus.title')}</DialogTitle>
</DialogHeader>
{/* Mounted only while open, so every opening starts from the stored values. */}
{image && <FocusEditor image={image} onApply={onApply} onClose={onClose} />}
</DialogContent>
</Dialog>
);
}
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);
const [tall, setTall] = useState<FocusDto | null>(image.tallFocus);
const effective = { wide: wide ?? general, tall: tall ?? general };
const active: FocusDto = target === 'general' ? general : (target === 'wide' ? wide : tall) ?? general;
const editable = target === 'general' || (target === 'wide' ? wide : tall) !== null;
const update = (next: FocusDto) => {
const clean = normalizeFocus(next);
if (target === 'general') setGeneral(clean);
else if (target === 'wide') setWide(clean);
else setTall(clean);
};
const toggleOverride = (checked: boolean) => {
const value = checked ? { ...general } : null;
if (target === 'wide') setWide(value);
if (target === 'tall') setTall(value);
};
const moveTo = (event: PointerEvent<HTMLDivElement>) => {
const box = area.current?.getBoundingClientRect();
if (!box || box.width === 0 || box.height === 0 || !editable) return;
update({ ...active, x: (event.clientX - box.left) / box.width, y: (event.clientY - box.top) / box.height });
};
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!editable) return;
const step = event.shiftKey ? 0.05 : 0.01;
const moves: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };
const move = moves[event.key];
if (!move) return;
event.preventDefault();
update({ ...active, x: active.x + move[0], y: active.y + move[1] });
};
const onSave = () => {
onApply(image.id, { focus: general, wide, tall });
onClose();
};
const outline = (ratio: Ratio, focus: FocusDto) => {
const c = cropFor(image.width, image.height, ratio, focus);
return {
left: `${(c.x / image.width) * 100}%`,
top: `${(c.y / image.height) * 100}%`,
width: `${(c.width / image.width) * 100}%`,
height: `${(c.height / image.height) * 100}%`,
};
};
return (
<div className="space-y-4" data-testid="focus-dialog">
<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>
{(['general', 'wide', 'tall'] as const).map((value) => (
<label key={value} className="flex items-center gap-2 text-sm">
<input
type="radio"
name="focus-target"
checked={target === value}
onChange={() => setTarget(value)}
data-testid={`focus-target-${value}`}
/>
{t(`hero.focus.target.${value}`)}
</label>
))}
</fieldset>
{target !== 'general' && (
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={editable}
onChange={(event) => toggleOverride(event.target.checked)}
data-testid={`focus-override-${target}`}
/>
{t('hero.focus.override')}
</label>
)}
<div className="grid gap-4 md:grid-cols-[2fr_1fr]">
<div>
<div
ref={area}
role="group"
tabIndex={0}
aria-label={t('hero.focus.areaLabel')}
className="relative touch-none select-none overflow-hidden rounded-md border"
style={{ aspectRatio: `${image.width} / ${image.height}` }}
onPointerDown={(event) => {
event.currentTarget.setPointerCapture?.(event.pointerId);
moveTo(event);
}}
onPointerMove={(event) => {
if (event.buttons === 1) moveTo(event);
}}
onKeyDown={onKeyDown}
data-testid="focus-area"
>
{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
className="pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-red-500/80 shadow"
style={{ left: `${active.x * 100}%`, top: `${active.y * 100}%` }}
data-testid="focus-marker"
/>
</div>
<p className="mt-1 text-xs text-muted-foreground">{t('hero.focus.areaHint')}</p>
</div>
<div className="space-y-3">
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label htmlFor="focus-x">{t('hero.focus.x')}</Label>
<Input
id="focus-x"
type="number"
min={0}
max={100}
step={0.5}
disabled={!editable}
value={percent(active.x)}
onChange={(event) => update({ ...active, x: Number(event.target.value) / 100 })}
data-testid="focus-x"
/>
</div>
<div className="space-y-1">
<Label htmlFor="focus-y">{t('hero.focus.y')}</Label>
<Input
id="focus-y"
type="number"
min={0}
max={100}
step={0.5}
disabled={!editable}
value={percent(active.y)}
onChange={(event) => update({ ...active, y: Number(event.target.value) / 100 })}
data-testid="focus-y"
/>
</div>
</div>
<div className="space-y-1">
<Label htmlFor="focus-zoom">{t('hero.focus.zoom', { value: active.zoom.toFixed(2) })}</Label>
<input
id="focus-zoom"
type="range"
min={1}
max={MAX_ZOOM}
step={0.05}
disabled={!editable}
value={active.zoom}
onChange={(event) => update({ ...active, zoom: Number(event.target.value) })}
className="w-full"
data-testid="focus-zoom"
/>
</div>
{([WIDE, TALL] as const).map((ratio) => {
const crop = cropFor(image.width, image.height, ratio, effective[ratio.name]);
return (
<div key={ratio.name}>
<p className="mb-1 text-xs font-medium">{t(`hero.focus.preview.${ratio.name}`)}</p>
<div
className="relative overflow-hidden rounded border bg-muted"
style={{ aspectRatio: `${ratio.numerator} / ${ratio.denominator}`, maxWidth: ratio.name === 'tall' ? '8rem' : '12rem' }}
data-testid={`focus-preview-${ratio.name}`}
>
{previewUrl && <img
src={previewUrl}
alt=""
className="absolute max-w-none"
style={{
width: `${(image.width / crop.width) * 100}%`,
left: `${(-crop.x / crop.width) * 100}%`,
// 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>
);
})}
</div>
</div>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose} data-testid="focus-cancel">
{t('common.cancel')}
</Button>
<Button type="button" onClick={onSave} data-testid="focus-save">
{t('hero.focus.apply')}
</Button>
</div>
</div>
);
}
@@ -0,0 +1,106 @@
import { useRef, type KeyboardEvent, type ReactNode } from 'react';
export interface HeroTab<Id extends string> {
id: Id;
label: ReactNode;
/** Short note after the label, for example "2 busy". */
note?: string;
/** There are unsaved changes in this tab: a dot and a text for screen readers. */
changed?: boolean;
changedText?: string;
/** This tab holds a field with an error: a red mark and a text for screen readers. */
invalid?: boolean;
invalidText?: string;
}
interface HeroTabsProps<Id extends string> {
label: string;
tabs: HeroTab<Id>[];
selected: Id;
onSelect: (id: Id) => void;
idPrefix: string;
}
/**
* Accessible tabs (role tablist, tab, tabpanel): the arrow keys move between the tabs (and select, "automatic activation"),
* Home and End go to the first and the last, only the selected tab is in the tab order. The panels themselves are rendered
* by the page, with <c>id="{idPrefix}-panel-{id}"</c> and <c>aria-labelledby="{idPrefix}-tab-{id}"</c>.
*/
export function HeroTabs<Id extends string>({ label, tabs, selected, onSelect, idPrefix }: HeroTabsProps<Id>) {
const refs = useRef<Record<string, HTMLButtonElement | null>>({});
const move = (index: number) => {
const next = tabs[(index + tabs.length) % tabs.length];
onSelect(next.id);
refs.current[next.id]?.focus();
};
const onKeyDown = (event: KeyboardEvent, index: number) => {
switch (event.key) {
case 'ArrowRight':
case 'ArrowDown':
event.preventDefault();
move(index + 1);
break;
case 'ArrowLeft':
case 'ArrowUp':
event.preventDefault();
move(index - 1);
break;
case 'Home':
event.preventDefault();
move(0);
break;
case 'End':
event.preventDefault();
move(tabs.length - 1);
break;
default:
}
};
return (
<div role="tablist" aria-label={label} className="flex gap-1 border-b" data-testid="hero-tabs">
{tabs.map((tab, index) => {
const active = tab.id === selected;
return (
<button
key={tab.id}
ref={(element) => {
refs.current[tab.id] = element;
}}
type="button"
role="tab"
id={`${idPrefix}-tab-${tab.id}`}
aria-selected={active}
aria-controls={`${idPrefix}-panel-${tab.id}`}
tabIndex={active ? 0 : -1}
onClick={() => onSelect(tab.id)}
onKeyDown={(event) => onKeyDown(event, index)}
className={`-mb-px inline-flex items-center gap-2 rounded-t-md border-b-2 px-4 py-2 text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${
active ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'
}`}
data-testid={`hero-tab-${tab.id}`}
>
{tab.label}
{tab.note && <span className="text-xs font-normal text-muted-foreground">({tab.note})</span>}
{tab.changed && (
<>
<span className="size-2 rounded-full bg-amber-500" aria-hidden="true" data-testid={`hero-tab-${tab.id}-changed`} />
<span className="sr-only">{tab.changedText}</span>
</>
)}
{tab.invalid && (
<>
<span className="inline-flex size-4 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-destructive-foreground" aria-hidden="true" data-testid={`hero-tab-${tab.id}-invalid`}>
!
</span>
<span className="sr-only">{tab.invalidText}</span>
</>
)}
</button>
);
})}
</div>
);
}
@@ -0,0 +1,156 @@
import { Check, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { useRetryHeroImage } from '../services/hooks';
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 }) {
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({ images }: { images: HeroImageDto[] }) {
const { t } = useTranslation();
const retry = useRetryHeroImage();
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((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 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);
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: `${percent}%` }} />
</div>
{busy && (
<p className="text-sm" data-testid="hero-processing-current">
{t('hero.processing.current', { n: done + 1, total, step: busy.renderDone ?? 0, steps: busy.renderTotal })}
</p>
)}
<p className="text-sm text-muted-foreground">{t('hero.processing.explain')}</p>
<p className="text-sm text-muted-foreground">
{t('hero.processing.stuck')}{' '}
<button
type="button"
className="underline underline-offset-2 hover:text-foreground disabled:opacity-50"
disabled={retry.isPending}
onClick={() => waiting.forEach((image) => retry.mutate(image.id))}
data-testid="hero-processing-retry-all"
>
{t('hero.processing.retry')}
</button>
</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((image) => retry.mutate(image.id))}
data-testid="hero-processing-retry"
>
{t('hero.processing.retry')}
</Button>
</div>
)}
</div>
);
}
/**
* The place of a photo that has no pictures yet: one calm shimmer (hidden from assistive technology) and a readable
* text. It lives in the row of the slide, so it stays mounted (and the animation keeps running) while the page asks the
* server again every few seconds, and it disappears when the photo is ready.
*/
export function PhotoPlaceholder({ failed, testId, step }: { failed: boolean; testId: string; step?: { done: number; total: number } | null }) {
const { t } = useTranslation();
return (
<div
className={`flex h-20 w-28 flex-col items-center justify-center gap-1 rounded p-1 text-center text-xs ${failed ? 'bg-destructive/10 text-destructive' : 'hero-shimmer bg-muted'}`}
role="status"
aria-busy={!failed}
title={t('hero.slides.processingHint')}
data-testid={testId}
>
{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>
);
}
/**
* The photo of a slide whose crop is being made again (a changed focus point): the old picture stays visible underneath,
* with the same calm shimmer and a short text, so it is clear that the change is not on the website yet.
*/
export function RecutThumbnail({ src, failed, testId, step }: { src: string; failed: boolean; testId: string; step?: { done: number; total: number } | null }) {
const { t } = useTranslation();
return (
<div
className={`relative h-20 w-28 shrink-0 overflow-hidden rounded ${failed ? 'ring-2 ring-destructive' : 'hero-shimmer'}`}
role="status"
aria-busy={!failed}
title={t('hero.slides.recutHint')}
data-testid={testId}
>
<img src={src} alt="" className="h-full w-full object-cover" />
<span className={`absolute inset-x-0 bottom-0 flex items-center justify-center gap-1 px-1 py-0.5 text-center text-[10px] leading-tight ${failed ? 'bg-destructive text-destructive-foreground' : 'bg-background/85 text-foreground'}`}>
{failed ? null : <Spinner className="size-3" />}
<span>{failed ? t('hero.slides.failed') : t('hero.slides.recut')}</span>
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
</span>
</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>
);
}
@@ -0,0 +1,48 @@
import type { ReactNode } from 'react';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { GripVertical } from 'lucide-react';
import { useTranslation } from 'react-i18next';
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;
}
/**
* One row of the image list that can be dragged by its handle (mouse, touch or keyboard: focus the handle, press Space,
* 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, dimmed = false, children }: SortableSlideProps) {
const { t } = useTranslation();
const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id });
return (
<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' : ''} ${dimmed ? 'opacity-60' : ''}`}
data-testid={`hero-slide-${index}`}
data-dragging={isDragging ? 'true' : undefined}
data-inactive={dimmed ? 'true' : undefined}
>
<button
type="button"
ref={setActivatorNodeRef}
className="mt-1 cursor-grab touch-none rounded p-1 text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
aria-label={t('hero.slides.drag', { n: index + 1 })}
data-testid={`hero-slide-${index}-drag`}
{...attributes}
{...listeners}
>
<GripVertical className="size-5" aria-hidden="true" />
</button>
{children}
</li>
);
}
@@ -0,0 +1,37 @@
import { useBlocker } from '@tanstack/react-router';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
/**
* Asks for confirmation before the administrator leaves the page through the menu or a link while the form holds changes
* that are not saved. (Closing the tab or reloading is covered by the browser warning in the page itself.)
*/
export function UnsavedChangesGuard({ dirty }: { dirty: boolean }) {
const { t } = useTranslation();
const blocker = useBlocker({
shouldBlockFn: () => dirty,
disabled: !dirty,
enableBeforeUnload: false,
withResolver: true,
});
return (
<Dialog open={blocker.status === 'blocked'} onOpenChange={(open) => { if (!open) blocker.reset?.(); }}>
<DialogContent data-testid="hero-leave-dialog">
<DialogHeader>
<DialogTitle>{t('hero.unsaved.leaveTitle')}</DialogTitle>
<DialogDescription>{t('hero.unsaved.leaveText')}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button type="button" onClick={() => blocker.reset?.()} data-testid="hero-leave-stay">
{t('hero.unsaved.stay')}
</Button>
<Button type="button" variant="destructive" onClick={() => blocker.proceed?.()} data-testid="hero-leave-discard">
{t('hero.unsaved.discard')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,54 @@
import { AlertCircle, Check, Clock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Spinner } from './ProcessingStatus';
export interface UploadItem {
key: number;
name: string;
status: 'waiting' | 'uploading' | 'done' | 'failed';
/** Why it failed, in words for the administrator. */
message?: string;
}
/** The files of the last choice, one row each: waiting, busy (spinner), added, or failed with the reason. */
export function UploadProgress({ items, busy, onClose }: { items: UploadItem[]; busy: boolean; onClose: () => void }) {
const { t } = useTranslation();
if (items.length === 0) return null;
const finished = items.filter((i) => i.status === 'done' || i.status === 'failed').length;
const added = items.filter((i) => i.status === 'done').length;
return (
<div className="space-y-2 rounded-md border p-3" data-testid="hero-upload-list" aria-busy={busy}>
<p className="text-sm font-medium" role="status" data-testid="hero-upload-summary">
{busy ? t('hero.upload.progress', { done: finished, total: items.length }) : t('hero.upload.summary', { ok: added, total: items.length })}
</p>
<ul className="space-y-1 text-sm">
{items.map((item) => (
<li key={item.key} className="flex items-start gap-2" data-testid={`hero-upload-item-${item.key}`} data-status={item.status}>
<span className="mt-0.5 shrink-0">
{item.status === 'uploading' && <Spinner />}
{item.status === 'waiting' && <Clock className="size-4 text-muted-foreground" aria-hidden="true" />}
{item.status === 'done' && <Check className="size-4 text-green-600" aria-hidden="true" />}
{item.status === 'failed' && <AlertCircle className="size-4 text-destructive" aria-hidden="true" />}
</span>
<span className="min-w-0 flex-1 break-words">
<span className="font-medium">{item.name}</span>
{' – '}
{item.status === 'failed' ? (
<span className="text-destructive" role="alert" data-testid="hero-upload-error">{item.message}</span>
) : (
<span className="text-muted-foreground">{t(`hero.upload.${item.status}`)}</span>
)}
</span>
</li>
))}
</ul>
{!busy && (
<Button type="button" variant="outline" size="sm" onClick={onClose} data-testid="hero-upload-close">
{t('hero.upload.close')}
</Button>
)}
</div>
);
}
@@ -0,0 +1,107 @@
import { describe, expect, it } from 'vitest';
import { CENTRE, TALL, WIDE, cropFor, normalizeFocus, roundHalfUp } from './focusMath';
// The same vectors as src/SlpModularCms.Core.Tests/Media/MediaPureFunctionTests.cs (FocusMathTests.KnownVectors).
const vectors: [number, number, 'wide' | 'tall', number, number, number, [number, number, number, number]][] = [
[1600, 1067, 'wide', 0.5, 0.5, 1.0, [0, 0, 1600, 1067]],
[1600, 1067, 'tall', 0.5, 0.5, 1.0, [374, 1, 853, 1066]],
[1600, 1067, 'tall', 0.0, 0.5, 1.0, [0, 1, 853, 1066]],
[1600, 1067, 'tall', 1.0, 0.5, 1.0, [747, 1, 853, 1066]],
[1600, 1067, 'wide', 0.45, 0.35, 2.0, [320, 107, 800, 533]],
[2560, 1702, 'tall', 0.55, 0.6, 1.0, [728, 1, 1361, 1701]],
[1000, 2000, 'wide', 0.5, 0.5, 1.0, [0, 667, 1000, 667]],
];
describe('cropFor', () => {
it.each(vectors)('%i x %i %s at (%d, %d) zoom %d', (w, h, ratio, x, y, zoom, [cx, cy, cw, ch]) => {
expect(cropFor(w, h, ratio === 'tall' ? TALL : WIDE, { x, y, zoom })).toEqual({ x: cx, y: cy, width: cw, height: ch });
});
it('always stays inside the image and keeps the focus point inside the crop', () => {
for (let i = 0; i < 2000; i++) {
const w = 1 + Math.floor(Math.random() * 6000);
const h = 1 + Math.floor(Math.random() * 6000);
const focus = { x: Math.random(), y: Math.random(), zoom: 1 + Math.random() * 3 };
for (const ratio of [WIDE, TALL]) {
const c = cropFor(w, h, ratio, focus);
expect(c.x).toBeGreaterThanOrEqual(0);
expect(c.y).toBeGreaterThanOrEqual(0);
expect(c.x + c.width).toBeLessThanOrEqual(w);
expect(c.y + c.height).toBeLessThanOrEqual(h);
expect(focus.x * w).toBeGreaterThanOrEqual(c.x - 1);
expect(focus.x * w).toBeLessThanOrEqual(c.x + c.width + 1);
expect(focus.y * h).toBeGreaterThanOrEqual(c.y - 1);
expect(focus.y * h).toBeLessThanOrEqual(c.y + c.height + 1);
}
}
});
it('survives values that are out of range or not numbers', () => {
const c = cropFor(1600, 1067, TALL, { x: Number.NaN, y: Infinity, zoom: -Infinity });
expect(c.x).toBeGreaterThanOrEqual(0);
expect(c.x + c.width).toBeLessThanOrEqual(1600);
});
it('rejects an image without a size', () => {
expect(() => cropFor(0, 100, WIDE, CENTRE)).toThrow(RangeError);
});
});
describe('normalizeFocus and roundHalfUp', () => {
it('clamps and defaults', () => {
expect(normalizeFocus({ x: -1, y: 2, zoom: 9 })).toEqual({ x: 0, y: 1, zoom: 4 });
expect(normalizeFocus({ x: Number.NaN, y: Number.NaN, zoom: Number.NaN })).toEqual({ x: 0.5, y: 0.5, zoom: 1 });
});
it('rounds .5 up like the host', () => {
expect(roundHalfUp(373.5)).toBe(374);
expect(roundHalfUp(0.5)).toBe(1);
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);
}
});
});
@@ -0,0 +1,65 @@
import type { FocusDto } from '../services/types';
/** A named aspect ratio (width:height). The same two as the host cuts. */
export interface Ratio {
name: 'wide' | 'tall';
numerator: number;
denominator: number;
}
export const WIDE: Ratio = { name: 'wide', numerator: 3, denominator: 2 };
export const TALL: Ratio = { name: 'tall', numerator: 4, denominator: 5 };
export const MAX_ZOOM = 4;
export const CENTRE: FocusDto = { x: 0.5, y: 0.5, zoom: 1 };
export interface CropRect {
x: number;
y: number;
width: number;
height: number;
}
/** Rounds .5 up, like the host (C# FocusMath.RoundHalfUp), so the preview is the same crop as the stored file. */
export const roundHalfUp = (value: number): number => Math.floor(value + 0.5);
const clamp = (value: number, min: number, max: number): number => Math.min(Math.max(value, min), max);
/** Clamps every value into its valid range; anything that is not a number becomes the default. */
export function normalizeFocus(focus: FocusDto): FocusDto {
const finite = (v: number, fallback: number) => (Number.isNaN(v) ? fallback : v);
return {
x: clamp(finite(focus.x, 0.5), 0, 1),
y: clamp(finite(focus.y, 0.5), 0, 1),
zoom: clamp(finite(focus.zoom, 1), 1, MAX_ZOOM),
};
}
/**
* The crop for a ratio around a focus point: the largest rectangle of the ratio that fits the image, shrunk by the
* zoom, centred on the point and moved the smallest amount needed to stay inside. Twin of the host's C# `FocusMath`;
* `focusMath.test.ts` and the C# tests share their vectors.
*/
export function cropFor(imageWidth: number, imageHeight: number, ratio: Ratio, focus: FocusDto): CropRect {
if (imageWidth <= 0 || imageHeight <= 0) {
throw new RangeError('The image must have a size.');
}
const f = normalizeFocus(focus);
// The largest crop of the ratio inside the image: as wide as the image, or as high as the image.
const cw0 =
imageWidth * ratio.denominator > imageHeight * ratio.numerator
? (imageHeight * ratio.numerator) / ratio.denominator
: imageWidth;
let cw = clamp(Math.floor(cw0 / f.zoom), 1, imageWidth);
let ch = Math.max(1, roundHalfUp((cw * ratio.denominator) / ratio.numerator));
if (ch > imageHeight) {
ch = imageHeight;
cw = clamp(Math.floor((ch * ratio.numerator) / ratio.denominator), 1, imageWidth);
}
const x = clamp(roundHalfUp(f.x * imageWidth - cw / 2), 0, imageWidth - cw);
const y = clamp(roundHalfUp(f.y * imageHeight - ch / 2), 0, imageHeight - ch);
return { x, y, width: cw, height: ch };
}
+4
View File
@@ -0,0 +1,4 @@
import { getAppConfig } from '@/lib/config';
/** A media address of the host (<c>/media/...</c>) as the browser must request it from the admin. */
export const mediaUrl = (path: string): string => `${getAppConfig().apiBaseUrl.replace(/\/$/, '')}${path}`;
@@ -0,0 +1,146 @@
import { http, HttpResponse } from 'msw';
import { API_BASE } from '@/features/auth/mocks/fixtures';
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types';
const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({
id,
width,
height,
focus: { x: 0.5, y: 0.5, zoom: 1 },
wideFocus: null,
tallFocus: null,
src: `/media/hero/0123456789abcdef/wide-${width}.webp`,
variants: [
{ ratio: 'wide', width: 960, height: 640, type: 'image/webp', url: '/media/hero/0123456789abcdef/wide-960.webp' },
{ ratio: 'wide', width, height, type: 'image/webp', url: `/media/hero/0123456789abcdef/wide-${width}.webp` },
{ ratio: 'tall', width: 640, height: 800, type: 'image/webp', url: '/media/hero/0123456789abcdef/tall-640.webp' },
],
processing: false,
failed: false,
previewSrc: '/media/hero/0123456789abcdef/full-1280.webp',
});
export const emptyHero = (): HeroAdminDto => ({
id: null,
title: '',
tagline: null,
lead: null,
display: 'single',
buttons: [],
slides: [],
isLive: false,
updatedAt: null,
maxPublishedSlides: 50,
});
export const slide = (index: number, over: Partial<HeroSlideAdminDto> = {}): HeroSlideAdminDto => ({
id: `00000000-0000-0000-0000-00000000000${index}`,
imageId: `10000000-0000-0000-0000-00000000000${index}`,
alt: `Foto ${index}`,
decorative: false,
isActive: true,
sortOrder: index - 1,
image: seedImage(`10000000-0000-0000-0000-00000000000${index}`),
...over,
});
let hero: HeroAdminDto = emptyHero();
let images: Record<string, HeroImageDto> = {};
let saved: HeroSaveRequest[] = [];
let uploads = 0;
let uploadFailure: { status: number; error: string; message: string } | null = null;
export const resetMockHero = (): void => {
hero = emptyHero();
images = {};
saved = [];
uploads = 0;
uploadFailure = null;
retried = [];
recutting = new Set();
};
export const setMockHero = (next: HeroAdminDto): void => {
hero = next;
images = Object.fromEntries(next.slides.map((s) => [s.imageId, s.image]));
};
let retried: string[] = [];
let recutting = new Set<string>();
/** The background work of the mock server is done: images whose crop was being made are ready. */
export const finishMockRecut = (): void => {
recutting.forEach((id) => {
if (images[id]) images[id] = { ...images[id], processing: false };
hero = { ...hero, slides: hero.slides.map((s) => (s.imageId === id ? { ...s, image: { ...s.image, processing: false } } : s)) };
});
recutting = new Set();
};
export const getRetriedImages = (): string[] => retried;
export const getSavedHeroRequests = (): HeroSaveRequest[] => saved;
export const failNextUpload = (failure: { status: number; error: string; message: string } | null): void => {
uploadFailure = failure;
};
export const heroHandlers = [
http.get(`${API_BASE}/api/v1/hero/all`, () => HttpResponse.json(hero)),
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, processing: true };
recutting.add(edit.imageId);
}
hero = {
...hero,
id: hero.id ?? '99999999-9999-9999-9999-999999999999',
title: body.title,
tagline: body.tagline,
lead: body.lead,
display: body.display,
buttons: body.buttons,
isLive: body.title.trim() !== '',
updatedAt: '2026-11-16T12:00:00Z',
slides: body.slides.map((s, i) => ({
id: s.id ?? `20000000-0000-0000-0000-00000000000${i}`,
imageId: s.imageId,
alt: s.alt ?? '',
decorative: s.decorative,
isActive: s.isActive,
sortOrder: i,
image: images[s.imageId] ?? seedImage(s.imageId),
})),
};
return HttpResponse.json(hero);
}),
http.get(`${API_BASE}/api/v1/hero/images/limits`, () =>
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 });
}),
http.post(`${API_BASE}/api/v1/hero/images`, () => {
if (uploadFailure) {
const { status, error, message } = uploadFailure;
uploadFailure = null;
return HttpResponse.json({ error, message }, { status });
}
uploads += 1;
const image = seedImage(`30000000-0000-0000-0000-00000000000${uploads}`);
images[image.id] = image;
return HttpResponse.json(image, { status: 201 });
}),
];
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,629 @@
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';
import { toast } from 'sonner';
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';
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 { CropThumbnail } from '../components/CropThumbnail';
import { DoneStatus, PhotoPlaceholder, ProcessingStatus, RecutThumbnail, Spinner } from '../components/ProcessingStatus';
import { SlideSwitch } from '../components/SlideSwitch';
import { SortableSlide } from '../components/SortableSlide';
import { HeroTabs } from '../components/HeroTabs';
import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard';
import { UploadProgress, type UploadItem } from '../components/UploadProgress';
import { mediaUrl } from '../lib/media';
import { heroFormSchema, type HeroFormData } from '../schemas/hero';
import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks';
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';
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,
slides: hero.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.alt, decorative: s.decorative, isActive: s.isActive })),
};
}
function toRequest(values: HeroFormData, focusEdits: Record<string, HeroFocusRequest>): 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 !== ''),
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 })),
};
}
/** 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 most the host accepts for one image (Media:MaxUploadBytes). */
const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
/**
* What to tell the administrator when an upload fails: the message of the host when it sent one, a clear text for a
* refusal by the proxy (413, which has no JSON body) or a rate limit, and a retry hint when the connection broke off.
*/
function uploadMessage(error: unknown, t: (key: string, options?: Record<string, unknown>) => string): string {
if (error instanceof ProblemDetailsError) {
const message = error.problem.message;
if (typeof message === 'string' && message !== '') return message;
if (error.status === 413) return t('hero.upload.tooLarge', { max: MAX_UPLOAD_BYTES / (1024 * 1024) });
if (error.status === 429) return t('hero.upload.busy');
return t('errors.generic');
}
if (error instanceof NetworkError) return t('hero.upload.interrupted');
return t('errors.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>
<details className="max-w-3xl rounded-md border p-3 text-sm" data-testid="hero-help">
<summary className="cursor-pointer font-medium">{t('hero.help.heading')}</summary>
<dl className="mt-3 space-y-2">
{(['title', 'tagline', 'lead', 'buttons', 'display', 'slides', 'focus'] as const).map((key) => (
<div key={key}>
<dt className="font-medium">{t(`hero.help.${key}.name`)}</dt>
<dd className="text-muted-foreground">{t(`hero.help.${key}.text`)}</dd>
</div>
))}
</dl>
<p className="mt-3 text-muted-foreground">{t('hero.help.save')}</p>
</details>
{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 [uploads, setUploads] = useState<UploadItem[]>([]);
const [uploading, setUploading] = useState(false);
const [draggingFiles, setDraggingFiles] = useState(false);
const nextUploadKey = useRef(0);
const limits = useHeroUploadLimits().data;
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 {
register,
setValue,
handleSubmit,
control,
formState: { errors, isDirty, dirtyFields },
setFocus,
reset,
} = useForm<HeroFormData>({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', shouldFocusError: false, defaultValues: toForm(hero) });
const slides = useFieldArray({ control, name: 'slides' });
const watchedSlides = useWatch({ control, name: 'slides' }) ?? [];
// The two tabs share one form, one Save button and one "unsaved changes" state. The chosen tab is remembered for this
// browser session.
type TabId = 'content' | 'images';
const [tab, setTabState] = useState<TabId>(() => {
try {
return window.sessionStorage.getItem('cms-hero-tab') === 'images' ? 'images' : 'content';
} catch {
return 'content';
}
});
const setTab = (next: TabId) => {
setTabState(next);
try {
window.sessionStorage.setItem('cms-hero-tab', next);
} catch {
// Remembering the tab is a convenience only.
}
};
// After a failed save: go to the tab of the first field with an error and put the cursor in that field.
const pendingFocus = useRef<{ name: string; tab: TabId } | null>(null);
useEffect(() => {
if (pendingFocus.current && tab === pendingFocus.current.tab) {
setFocus(pendingFocus.current.name as never);
pendingFocus.current = null;
}
}, [tab, setFocus]);
const goToField = (name: string, target: TabId) => {
if (target === tab) {
setFocus(name as never);
return;
}
pendingFocus.current = { name, tab: target };
setTab(target);
};
// 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, 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);
const hasPendingFocus = Object.entries(focusEdits).some(([imageId, edit]) => {
const saved = images[imageId];
return !saved || !samePoint(saved.focus, edit.focus) || !samePoint(saved.wideFocus, edit.wide) || !samePoint(saved.tallFocus, edit.tall);
});
// The form is compared with the last saved state (react-hook-form keeps it), so a change that is undone no longer counts.
// Photos still being prepared on the server and the background refresh are not changes of the administrator.
const hasUnsaved = isDirty || hasPendingFocus;
const contentChanged = Object.keys(dirtyFields).some((key) => key !== 'slides');
const imagesChanged = Boolean(dirtyFields.slides?.some?.(Boolean)) || hasPendingFocus;
const contentInvalid = Object.keys(errors).some((key) => key !== 'slides');
const imagesInvalid = Boolean(errors.slides);
const busyCount = slides.fields.filter((f) => images[f.imageId]?.processing).length;
useEffect(() => {
if (!hasUnsaved) return undefined;
const warn = (event: BeforeUnloadEvent) => {
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [hasUnsaved]);
// 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;
};
// Up to this many files go to the host at the same time; the variants are cut in the background, so an upload itself
// is quick, and two at a time keeps the memory use of a small server in check.
const UPLOAD_PARALLEL = 2;
const onFiles = async (chosen: FileList | File[] | null) => {
const files = Array.from(chosen ?? []);
if (files.length === 0 || uploading) return;
const maxBytes = limits?.maxUploadBytes ?? MAX_UPLOAD_BYTES;
const maxMb = Math.round(maxBytes / (1024 * 1024));
const items: UploadItem[] = files.map((file) => ({ key: nextUploadKey.current++, name: file.name, status: 'waiting' }));
setUploads(items);
setUploading(true);
const update = (i: number, patch: Partial<UploadItem>) =>
setUploads((current) => current.map((u) => (u.key === items[i].key ? { ...u, ...patch } : u)));
// The images are added to the list in the order they were chosen, whichever upload finishes first.
const results: (HeroImageDto | 'failed' | undefined)[] = new Array<HeroImageDto | 'failed' | undefined>(files.length).fill(undefined);
let flushed = 0;
let cursor = 0;
const flush = () => {
while (flushed < files.length && results[flushed] !== undefined) {
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;
}
};
const worker = async () => {
while (cursor < files.length) {
const i = cursor++;
const file = files[i];
// Refuse what the host would refuse without sending the whole file first.
if (file.type !== '' && !file.type.startsWith('image/')) {
results[i] = 'failed';
update(i, { status: 'failed', message: t('hero.upload.notAnImage') });
} else if (file.size > maxBytes) {
results[i] = 'failed';
update(i, { status: 'failed', message: t('hero.upload.tooLarge', { max: maxMb }) });
} else {
update(i, { status: 'uploading' });
try {
const image = await upload.mutateAsync(file);
results[i] = image;
update(i, { status: 'done' });
} catch (error) {
results[i] = 'failed';
update(i, { status: 'failed', message: uploadMessage(error, t) });
}
}
flush();
}
};
try {
await Promise.all(Array.from({ length: Math.min(UPLOAD_PARALLEL, files.length) }, () => worker()));
} finally {
setUploading(false);
if (fileInput.current) fileInput.current.value = '';
}
};
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
// The order changes in the form only; it goes live when the hero is saved, like every other change.
const onDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
const from = slides.fields.findIndex((f) => f.id === active.id);
const to = slides.fields.findIndex((f) => f.id === over.id);
if (from !== -1 && to !== -1) slides.move(from, to);
};
const isFileDrag = (event: React.DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes('Files');
const onSubmit = async (values: HeroFormData) => {
setServerError(null);
try {
const savedHero = await save.mutateAsync(toRequest(values, focusEdits));
setFocusEdits({});
// What was just saved is the new starting point: nothing is unsaved any more.
reset(toForm(savedHero));
toast.success(t('hero.savedToast'));
} catch (error) {
setServerError(serverMessage(error, t('errors.generic'), t('errors.network')));
}
};
const onInvalid = (formErrors: typeof errors) => {
const order = ['title', 'tagline', 'lead', 'display', 'buttons', 'slides'] as const;
for (const key of order) {
const entry = formErrors[key] as unknown;
if (!entry) continue;
if (Array.isArray(entry)) {
const index = entry.findIndex(Boolean);
const field = Object.keys(entry[index] ?? {})[0] ?? 'alt';
goToField(`${key}.${index}.${field}`, key === 'slides' ? 'images' : 'content');
} else {
goToField(key, 'content');
}
return;
}
};
const err = (message?: string) => (message ? t(message) : undefined);
const heroErrors = errors;
return (
<form onSubmit={(event) => void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8 pb-4" 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)} />
<HeroTabs
idPrefix="hero"
label={t('hero.tabs.label')}
selected={tab}
onSelect={setTab}
tabs={[
{ id: 'content', label: t('hero.tabs.content'), changed: contentChanged, changedText: t('hero.tabs.hasChanges'), invalid: contentInvalid, invalidText: t('hero.tabs.hasErrors') },
{
id: 'images',
label: t('hero.tabs.images'),
note: busyCount > 0 ? t('hero.tabs.busy', { count: busyCount }) : undefined,
changed: imagesChanged,
changedText: t('hero.tabs.hasChanges'),
invalid: imagesInvalid,
invalidText: t('hero.tabs.hasErrors'),
},
]}
/>
<div role="tabpanel" id="hero-panel-content" aria-labelledby="hero-tab-content" hidden={tab !== 'content'} className="space-y-8">
<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>
</div>
<div role="tabpanel" id="hero-panel-images" aria-labelledby="hero-tab-images" hidden={tab !== 'images'}>
<section
className={`space-y-3 rounded-md ${draggingFiles ? 'ring-2 ring-primary ring-offset-4' : ''}`}
onDragOver={(event) => {
if (!isFileDrag(event)) return;
event.preventDefault();
setDraggingFiles(true);
}}
onDragLeave={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDraggingFiles(false);
}}
onDrop={(event) => {
if (!isFileDrag(event)) return;
event.preventDefault();
setDraggingFiles(false);
void onFiles(event.dataTransfer.files);
}}
data-testid="hero-slides-section"
>
<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/*"
multiple
className="sr-only"
aria-label={t('hero.slides.add')}
data-testid="hero-upload"
onChange={(event) => void onFiles(event.target.files)}
/>
<Button type="button" variant="outline" disabled={uploading} onClick={() => fileInput.current?.click()} data-testid="hero-upload-button">
<ImagePlus className="mr-2 size-4" aria-hidden="true" />
{uploading ? t('hero.slides.uploading') : t('hero.slides.add')}
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">{t('hero.slides.hint')}</p>
{limits && (
<p className="text-xs text-muted-foreground" data-testid="hero-upload-limits">
{t('hero.slides.limits', { formats: limits.formats.join(', '), size: Math.round(limits.maxUploadBytes / (1024 * 1024)), megapixels: limits.maxMegapixels })}
</p>
)}
<UploadProgress items={uploads} busy={uploading} onClose={() => setUploads([])} />
{slides.fields.length === 0 && <p className="text-sm text-muted-foreground" data-testid="hero-slides-empty">{t('hero.slides.empty')}</p>}
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={onDragEnd}
accessibility={{ screenReaderInstructions: { draggable: t('hero.slides.dragInstructions') } }}
>
<SortableContext items={slides.fields.map((f) => f.id)} strategy={verticalListSortingStrategy}>
<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 (
<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 ? (
<RecutThumbnail src={thumbnail(image)} failed={image.failed} testId={`hero-slide-${index}-recut`} step={image.renderTotal ? { done: image.renderDone ?? 0, total: image.renderTotal } : null} />
) : image ? (
<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>
)}
<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`} />
<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 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>
<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="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>
</SortableSlide>
);
})}
</ol>
</SortableContext>
</DndContext>
{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>
<UnsavedChangesGuard dirty={hasUnsaved} />
{/* Full width of the content area (no gap at the sides or below), opaque, with a clear top edge and a shadow; the
bottom padding keeps clear of the home bar of a phone. */}
<div
className="sticky bottom-0 z-20 -mx-6 -mb-6 flex flex-wrap items-center justify-end gap-3 border-t bg-background px-6 pt-3 shadow-[0_-4px_8px_-4px_rgba(0,0,0,0.15)]"
style={{ paddingBottom: 'calc(0.75rem + env(safe-area-inset-bottom))' }}
data-testid="hero-save-bar"
>
<div role="status" aria-live="polite" className="min-h-5 flex-1 text-sm" data-testid="hero-unsaved-region">
{hasUnsaved && (
<span className="inline-flex items-center gap-2" data-testid="hero-unsaved">
<Badge variant="secondary">{t('hero.unsaved.badge')}</Badge>
<span className="text-muted-foreground">{t('hero.unsaved.text')}</span>
</span>
)}
</div>
<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>
<FocusDialog
image={withPendingFocus(focusImageId ? images[focusImageId] ?? null : null)}
onApply={(imageId, edit) => setFocusEdits((current) => ({ ...current, [imageId]: edit }))}
onClose={() => setFocusImageId(null)}
/>
</form>
);
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest';
import { heroFormSchema, isAllowedButtonTarget } from './hero';
// The same cases as ButtonTargetValidatorTests in src/SlpModularCms.Modules.Hero.Tests/HeroRulesTests.cs.
describe('isAllowedButtonTarget', () => {
it.each(['#contact', '#pakketten', '#a-b_c9', '/over-mij', '/', '/a/b/c?x=1&y=2', 'https://andreaslop.nl/portfolio', 'https://sub.example.com:8443/p?q=1#top'])(
'accepts %s',
(target) => expect(isAllowedButtonTarget(target)).toBe(true),
);
it.each([
'', ' ', 'contact', '#', '#1abc', '# contact', '#a b', '//evil.example/x', '/\\evil.example', '/a b', 'http://example.com', 'HTTPS://example.com',
'https://user:pw@example.com', 'https://', 'https:///path', 'javascript:alert(1)', 'JaVaScRiPt:alert(1)', 'data:text/html;base64,AAAA', 'mailto:a@b.nl',
'tel:+31612345678', 'ftp://example.com/x', '/ok"onmouseover="x', '/ok<script>', ' /leading-space', '/trailing-space ', '/tab\tx', '/new\nline',
])('rejects %j', (target) => expect(isAllowedButtonTarget(target)).toBe(false));
});
const base = {
title: 'Titel',
tagline: '',
lead: '',
display: 'single' as const,
buttons: [{ label: '', target: '' }, { label: '', target: '' }],
slides: [],
};
describe('heroFormSchema', () => {
it('accepts a minimal hero', () => expect(heroFormSchema.safeParse(base).success).toBe(true));
it('wants a title of at most 200 characters and 5 lines', () => {
expect(heroFormSchema.safeParse({ ...base, title: ' ' }).success).toBe(false);
expect(heroFormSchema.safeParse({ ...base, title: 'x'.repeat(201) }).success).toBe(false);
expect(heroFormSchema.safeParse({ ...base, title: 'a\nb\nc\nd\ne\nf' }).success).toBe(false);
expect(heroFormSchema.safeParse({ ...base, title: 'a\nb\nc\nd\ne' }).success).toBe(true);
});
it('wants an alt text unless the slide is decorative', () => {
const slide = { id: null, imageId: 'i1', alt: '', decorative: false, isActive: true };
expect(heroFormSchema.safeParse({ ...base, slides: [slide] }).success).toBe(false);
expect(heroFormSchema.safeParse({ ...base, slides: [{ ...slide, decorative: true }] }).success).toBe(true);
expect(heroFormSchema.safeParse({ ...base, slides: [{ ...slide, alt: 'Een foto' }] }).success).toBe(true);
});
it('allows any number of slides', () => {
const slides = Array.from({ length: 80 }, (_, i) => ({ id: null, imageId: `i${i}`, alt: 'foto', decorative: false, isActive: true }));
expect(heroFormSchema.safeParse({ ...base, slides }).success).toBe(true);
});
});
@@ -0,0 +1,73 @@
import { z } from 'zod';
export const TITLE_MAX = 200;
export const TITLE_MAX_LINES = 5;
export const TAGLINE_MAX = 120;
export const LEAD_MAX = 600;
export const BUTTON_LABEL_MAX = 50;
export const BUTTON_TARGET_MAX = 500;
export const ALT_MAX = 300;
/**
* Twin of the host's `ButtonTargetValidator`: a page anchor (#contact), a path of the site (/over-mij) or an absolute
* https address. Nothing else, so a button can never carry javascript:, data: or a protocol-relative address.
*/
export function isAllowedButtonTarget(target: string): boolean {
if (target === '' || target !== target.trim()) return false;
if ([...target].some((c) => /\s/.test(c) || c.charCodeAt(0) < 32 || '\\"<>`'.includes(c))) return false;
if (target.startsWith('#')) return /^#[A-Za-z][A-Za-z0-9_-]{0,99}$/.test(target);
if (target.startsWith('/')) return target.length === 1 || target[1] !== '/';
try {
const url = new URL(target);
// A host must follow the two slashes directly ("https:///path" is no address, even where a parser repairs it).
return /^https:[/][/][^/?#]/.test(target) && url.protocol === 'https:' && url.hostname !== '' && url.username === '';
} catch {
return false;
}
}
const buttonSchema = z
.object({
label: z.string().trim().max(BUTTON_LABEL_MAX, 'hero.errors.buttonLabelTooLong'),
target: z.string().trim().max(BUTTON_TARGET_MAX, 'hero.errors.buttonTargetTooLong'),
})
.superRefine((b, ctx) => {
const hasLabel = b.label !== '';
const hasTarget = b.target !== '';
if (hasLabel !== hasTarget) {
ctx.addIssue({ code: 'custom', path: [hasTarget ? 'label' : 'target'], message: 'hero.errors.buttonIncomplete' });
} else if (hasTarget && !isAllowedButtonTarget(b.target)) {
ctx.addIssue({ code: 'custom', path: ['target'], message: 'hero.errors.buttonTargetInvalid' });
}
});
const slideSchema = z
.object({
id: z.string().nullable(),
imageId: z.string().min(1),
alt: z.string().trim().max(ALT_MAX, 'hero.errors.altTooLong'),
decorative: z.boolean(),
isActive: z.boolean(),
})
.superRefine((s, ctx) => {
if (!s.decorative && s.alt === '') {
ctx.addIssue({ code: 'custom', path: ['alt'], message: 'hero.errors.altRequired' });
}
});
export const heroFormSchema = z
.object({
title: z.string().trim().min(1, 'hero.errors.titleRequired').max(TITLE_MAX, 'hero.errors.titleTooLong'),
tagline: z.string().trim().max(TAGLINE_MAX, 'hero.errors.taglineTooLong'),
lead: z.string().trim().max(LEAD_MAX, 'hero.errors.leadTooLong'),
display: z.enum(['single', 'slideshow']),
buttons: z.array(buttonSchema).length(2),
slides: z.array(slideSchema),
})
.superRefine((v, ctx) => {
if (v.title.replace(/\r\n/g, '\n').split('\n').length > TITLE_MAX_LINES) {
ctx.addIssue({ code: 'custom', path: ['title'], message: 'hero.errors.titleTooManyLines' });
}
});
export type HeroFormData = z.infer<typeof heroFormSchema>;
@@ -0,0 +1,70 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroUploadLimits } from './types';
export const HERO_KEY = ['hero'];
/** The hero as the admin edits it (also the image variants of every slide). */
export function useHero() {
return useQuery<HeroAdminDto, Error>({
queryKey: HERO_KEY,
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,
});
}
export function useSaveHero() {
const queryClient = useQueryClient();
return useMutation<HeroAdminDto, Error, HeroSaveRequest>({
mutationFn: (body) => api.put<HeroAdminDto>('/api/v1/hero', body),
onSuccess: (hero) => {
queryClient.setQueryData(HERO_KEY, hero);
},
});
}
/** Uploads one image file; the server answers with the image and its variants. */
export function useUploadHeroImage() {
return useMutation<HeroImageDto, Error, File>({
mutationFn: (file) => {
const form = new FormData();
form.append('file', file);
return api.post<HeroImageDto>('/api/v1/hero/images', form);
},
});
}
export function useDeleteHeroImage() {
return useMutation<void, Error, string>({
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 }),
});
}
/** The formats and limits an upload has to meet on this host. */
export function useHeroUploadLimits() {
return useQuery<HeroUploadLimits, Error>({
queryKey: ['hero', 'upload-limits'],
queryFn: () => api.get<HeroUploadLimits>('/api/v1/hero/images/limits'),
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,
});
@@ -0,0 +1,100 @@
export type HeroDisplay = 'single' | 'slideshow';
export interface FocusDto {
x: number;
y: number;
zoom: number;
}
export interface HeroVariantDto {
ratio: string;
width: number;
height: number;
type: string;
url: string;
}
export interface HeroImageDto {
id: string;
width: number;
height: number;
focus: FocusDto;
wideFocus: FocusDto | null;
tallFocus: FocusDto | null;
src: string;
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;
/** 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 {
label: string;
target: string;
}
export interface HeroSlideAdminDto {
id: string;
imageId: string;
alt: string;
decorative: boolean;
isActive: boolean;
sortOrder: number;
image: HeroImageDto;
}
export interface HeroAdminDto {
id: string | null;
title: string;
tagline: string | null;
lead: string | null;
display: HeroDisplay;
buttons: HeroButtonDto[];
slides: HeroSlideAdminDto[];
isLive: boolean;
updatedAt: string | null;
maxPublishedSlides: number;
}
export interface HeroSlideRequest {
id?: string | null;
imageId: string;
alt: string | null;
decorative: boolean;
isActive: boolean;
}
export interface HeroSaveRequest {
title: string;
tagline: string | null;
lead: string | null;
display: HeroDisplay;
buttons: HeroButtonDto[];
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 {
focus: FocusDto;
wide: FocusDto | null;
tall: FocusDto | null;
}
export interface HeroUploadLimits {
formats: string[];
maxUploadBytes: number;
maxMegapixels: number;
}
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckboxField } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { FieldError } from '@/components/ui/FieldError';
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
@@ -211,16 +212,12 @@ function OfferingBannerForm({
</div>
<p className="text-xs text-muted-foreground">{t('offerings.banners.scheduleHint')}</p>
<div className="flex items-center gap-2">
<input
id="banner-active"
type="checkbox"
data-testid="banner-active"
className="size-4 rounded border-input"
{...register('isActive')}
/>
<Label htmlFor="banner-active">{t('offerings.banners.activeLabel')}</Label>
</div>
<CheckboxField
id="banner-active"
data-testid="banner-active"
label={t('offerings.banners.activeLabel')}
{...register('isActive')}
/>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose} data-testid="banner-cancel">
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { Check, Pencil, Plus, Trash2, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckboxField } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { FieldError } from '@/components/ui/FieldError';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
@@ -293,28 +294,20 @@ export function OfferingForm({ initialValues, onSubmit, onCancel, isSubmitting }
{errors.ctaLabel && <FieldError message={errors.ctaLabel.message} testId="offering-cta-label-error" />}
</div>
<div className="flex items-center gap-2">
<input
id="offering-featured"
type="checkbox"
data-testid="offering-featured"
className="size-4 rounded border-input"
{...register('featured')}
/>
<Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label>
</div>
<CheckboxField
id="offering-featured"
data-testid="offering-featured"
label={t('offerings.form.featuredLabel')}
{...register('featured')}
/>
<div className="space-y-3 rounded-md border p-3" data-testid="offering-schedule">
<div className="flex items-center gap-2">
<input
id="offering-active"
type="checkbox"
data-testid="offering-active"
className="size-4 rounded border-input"
{...register('isActive')}
/>
<Label htmlFor="offering-active">{t('offerings.form.activeLabel')}</Label>
</div>
<CheckboxField
id="offering-active"
data-testid="offering-active"
label={t('offerings.form.activeLabel')}
{...register('isActive')}
/>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="offering-starts">{t('offerings.form.startsLabel')}</Label>
@@ -3,7 +3,7 @@ import { http, HttpResponse } from 'msw';
export const systemHandlers = [
http.get('*/System/capabilities', () =>
HttpResponse.json({
modules: ['Availability', 'Identity', 'Master', 'Offerings'],
modules: ['Availability', 'Identity', 'Master', 'Offerings', 'Hero'],
emailEnabled: false,
defaultLanguage: 'nl',
}),