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).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): 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 (

{t('hero.title')}

{hero && ( {hero.isLive ? t('hero.live') : t('hero.notLive')} )}

{t('hero.intro')}

{t('hero.help.heading')}
{(['title', 'tagline', 'lead', 'buttons', 'display', 'slides', 'focus'] as const).map((key) => (
{t(`hero.help.${key}.name`)}
{t(`hero.help.${key}.text`)}
))}

{t('hero.help.save')}

{isLoading &&

{t('common.loading')}

} {isError && (

{t('errors.generic')}

)} {hero && }
); } function HeroEditor({ hero }: { hero: HeroAdminDto }) { const { t } = useTranslation(); const save = useSaveHero(); const upload = useUploadHeroImage(); const [serverError, setServerError] = useState(null); const [uploads, setUploads] = useState([]); const [uploading, setUploading] = useState(false); const [draggingFiles, setDraggingFiles] = useState(false); const nextUploadKey = useRef(0); const limits = useHeroUploadLimits().data; const [localImages, setLocalImages] = useState>({}); const [focusImageId, setFocusImageId] = useState(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([]); const [recutIds, setRecutIds] = useState([]); // The slide (by position) whose photo is being chosen from the library. const [libraryFor, setLibraryFor] = useState(null); const fileInput = useRef(null); const { register, setValue, handleSubmit, control, formState: { errors, isDirty, dirtyFields }, setFocus, reset, } = useForm({ 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(() => { 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 = { ...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>({}); const wasProcessing = useRef>({}); 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) => 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(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 (
void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8" noValidate data-testid="hero-form"> setServerError(null)} /> 0 ? t('hero.tabs.busy', { count: busyCount }) : undefined, changed: imagesChanged, changedText: t('hero.tabs.hasChanges'), invalid: imagesInvalid, invalidText: t('hero.tabs.hasErrors'), }, ]} />