Files
slp-modular-cms/frontend/src/features/hero/pages/HeroPage.tsx
T

675 lines
37 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from 'react';
import { useQueries, useQueryClient } 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 { CheckboxField } from '@/components/ui/checkbox';
import { RadioField } from '@/components/ui/radio';
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 { LibraryPickerDialog } from '../components/LibraryPickerDialog';
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, useSetHeroImageFocus, 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): 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 })),
};
}
/** 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="-mb-6 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);
// A new crop is applied at once (no save needed): the server cuts the new variants in the background.
const setImageFocus = useSetHeroImageFocus();
// The photos of the current upload batch, for the counter "x of y processed": only the photos uploaded together, not
// every photo of the hero. A new batch starts when the previous one is finished.
const [batch, setBatch] = useState<string[]>([]);
const [recutIds, setRecutIds] = useState<string[]>([]);
// The slide (by position) whose photo is being chosen from the library.
const [libraryFor, setLibraryFor] = useState<number | null>(null);
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]);
// 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;
const contentChanged = Object.keys(dirtyFields).some((key) => key !== 'slides');
const imagesChanged = Boolean(dirtyFields.slides?.some?.(Boolean));
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;
// The counter above the form covers the current upload batch only. After a reload (no batch known) it covers the photos that
// are still being prepared. A new crop is shown on its own photo, not in this counter.
const statusImages = (batch.length > 0 ? batch.map((id) => images[id]) : slides.fields.map((f) => images[f.imageId]).filter((i) => i?.processing && !recutIds.includes(i.id))).filter(
(image): image is HeroImageDto => image !== undefined,
);
useEffect(() => {
if (!hasUnsaved) return undefined;
const warn = (event: BeforeUnloadEvent) => {
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [hasUnsaved]);
// A photo chosen from the library (or uploaded in the picker) becomes the photo of that slide: only the image id of the
// slide changes (no new data model). The photo is the same photo wherever it is used, so its crop is shared.
const queryClient = useQueryClient();
const chooseForSlide = async (index: number, imageId: string, uploaded?: HeroImageDto) => {
const current = watchedSlides[index];
if (!current) return;
try {
const image: HeroImageDto = uploaded ?? ((await queryClient.fetchQuery(heroImageQuery(imageId))) as HeroImageDto);
setLocalImages((cur) => ({ ...cur, [image.id]: image }));
if (uploaded && image.processing) setBatch((cur) => (cur.some((id) => images[id]?.processing) ? [...cur, image.id] : [image.id]));
if (image.id !== current.imageId) slides.update(index, { ...current, imageId: image.id });
setLibraryFor(null);
} catch (error) {
setServerError(serverMessage(error, t('errors.generic'), t('errors.network')));
}
};
// A new crop goes to the server at once; the page then shows the photo as processing until the new variants are ready.
const applyFocus = (imageId: string, request: HeroFocusRequest) => {
setServerError(null);
setImageFocus.mutate(
{ imageId, request },
{
onSuccess: (image) => {
setLocalImages((current) => ({ ...current, [image.id]: image }));
setRecutIds((current) => [...new Set([...current, image.id])]);
},
onError: (error) => setServerError(serverMessage(error, t('errors.generic'), t('errors.network'))),
},
);
};
// 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;
let inBatch = batch.some((id) => images[id]?.processing);
const flush = () => {
while (flushed < files.length && results[flushed] !== undefined) {
const result = results[flushed];
if (result && result !== 'failed') {
setLocalImages((current) => ({ ...current, [result.id]: result }));
const joins = inBatch;
setBatch((current) => (joins ? [...current, result.id] : [result.id]));
inBatch = true;
// 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));
// 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" noValidate data-testid="hero-form">
<ProcessingStatus images={statusImages} />
<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) => (
<RadioField key={value} value={value} data-testid={`hero-display-${value}`} label={t(`hero.display.${value}`)} {...register('display')} />
))}
</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)}
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`} />
<Button type="button" variant="outline" size="sm" onClick={() => setLibraryFor(index)} data-testid={`hero-slide-${index}-library`}>
{t('hero.library.choose')}
</Button>
</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`} />
<CheckboxField data-testid={`hero-slide-${index}-decorative`} label={t('hero.slides.decorative')} {...register(`slides.${index}.decorative` as const)} />
</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} />
{/* Flush with the bottom of the viewport and the full width of the content area, fully opaque so nothing shows
through or below it, with a clear top edge and a shadow. A sticky box measures its offset from the CONTENT
edge of the scrolling area (<main> has p-6), so "bottom: 0" would stop 24px above the screen edge and let
content show below the bar (measured in Chrome); -bottom-6 undoes that padding. The page root cancels the same
padding (-mb-6), so at the end of the page the bar is still at the very bottom and the last content is never
hidden behind it. The bottom padding clears the home bar of a phone. */}
<div
className="sticky -bottom-6 z-20 -mx-6 flex flex-wrap items-center justify-end gap-4 border-t bg-background px-6 pt-4 shadow-[0_-4px_8px_-4px_rgba(0,0,0,0.15)]"
style={{ paddingBottom: 'calc(1rem + 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={`min-w-28 ${hasUnsaved && !save.isPending ? 'ring-2 ring-primary ring-offset-2' : ''}`}
data-testid="hero-save"
>
{save.isPending ? (
<>
<Spinner className="mr-2 size-4" />
{t('hero.saving')}
</>
) : (
t('common.save')
)}
</Button>
</div>
<LibraryPickerDialog
open={libraryFor !== null}
onOpenChange={(open) => !open && setLibraryFor(null)}
currentImageId={libraryFor !== null ? (watchedSlides[libraryFor]?.imageId ?? null) : null}
onChoose={(imageId, uploaded) => libraryFor !== null && void chooseForSlide(libraryFor, imageId, uploaded)}
maxUploadBytes={limits?.maxUploadBytes ?? MAX_UPLOAD_BYTES}
limitsText={limits ? t('hero.slides.limits', { formats: limits.formats.join(', '), size: Math.round(limits.maxUploadBytes / (1024 * 1024)), megapixels: limits.maxMegapixels }) : undefined}
slideNumber={(libraryFor ?? 0) + 1}
/>
<FocusDialog
image={focusImageId ? images[focusImageId] ?? null : null}
onApply={applyFocus}
onClose={() => setFocusImageId(null)}
/>
</form>
);
}