import { useEffect, useMemo, useRef, useState } from 'react'; import { useFieldArray, useForm, useWatch } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { useTranslation } from 'react-i18next'; import { toast } from 'sonner'; import { ArrowDown, ArrowUp, Crosshair, ImagePlus, Trash2 } from 'lucide-react'; import { 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 { PhotoPlaceholder, ProcessingStatus } from '../components/ProcessingStatus'; import { SortableSlide } from '../components/SortableSlide'; import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard'; import { UploadProgress, type UploadItem } from '../components/UploadProgress'; import { mediaUrl } from '../lib/media'; import { fromLocalInput, heroFormSchema, toLocalInput, type HeroFormData } from '../schemas/hero'; import { 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, isActive: hero.isActive, startsAt: toLocalInput(hero.startsAt), endsAt: toLocalInput(hero.endsAt), slides: hero.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.alt, decorative: s.decorative, isActive: s.isActive })), }; } function toRequest(values: HeroFormData, focusEdits: Record): HeroSaveRequest { return { title: values.title, tagline: values.tagline || null, lead: values.lead || null, display: values.display, buttons: values.buttons.filter((b) => b.label !== '' && b.target !== ''), isActive: values.isActive, startsAt: fromLocalInput(values.startsAt), endsAt: fromLocalInput(values.endsAt), slides: values.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.decorative ? null : s.alt, decorative: s.decorative, isActive: s.isActive })), 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).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', 'schedule'] 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 && } {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); // 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>({}); const fileInput = useRef(null); const { register, handleSubmit, control, formState: { errors, isDirty }, reset, } = useForm({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', defaultValues: toForm(hero) }); const slides = useFieldArray({ control, name: 'slides' }); const watchedSlides = useWatch({ control, name: 'slides' }) ?? []; // The images of the saved hero (always current: a change of focus refreshes them) plus the ones uploaded in this session. const images = useMemo(() => { const map: Record = { ...localImages }; for (const s of hero.slides) map[s.imageId] = s.image; return map; }, [hero.slides, localImages]); // 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; 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) => 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; const flush = () => { while (flushed < files.length && results[flushed] !== undefined) { const result = results[flushed]; if (result && result !== 'failed') { setLocalImages((current) => ({ ...current, [result.id]: result })); 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 err = (message?: string) => (message ? t(message) : undefined); const heroErrors = errors; return (
setServerError(null)} />