Hero-admin: meerdere foto's tegelijk, slepen, niet-opgeslagen waarschuwing, begrijpelijke teksten, rustige wachtanimatie

- Meerdere bestanden kiezen of slepen (2 tegelijk, per bestand voortgang en reden bij falen, volgorde van kiezen), uploadlimiet standaard 100 per uur
- Volgorde ook met slepen (greepje, toetsenbord), pijltjes blijven
- Waarschuwing bij niet-opgeslagen wijzigingen (badge, beforeunload, bevestiging bij navigeren, vergelijking met laatst opgeslagen stand)
- Teksten zonder vakjargon, uitleg per onderdeel, formaten en limieten van de host (GET /hero/images/limits)
- Shimmer (CSS, reduced-motion) op foto's die nog verwerkt worden

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 21:56:10 +01:00
co-authored by Claude Sonnet 5.5
parent 49302c3228
commit 9d647bb049
20 changed files with 900 additions and 98 deletions
@@ -66,3 +66,24 @@ export function ProcessingStatus({ hero }: { hero: HeroAdminDto }) {
</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 }: { failed: boolean; testId: string }) {
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>
</div>
);
}
@@ -0,0 +1,45 @@
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;
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, 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' : ''}`}
data-testid={`hero-slide-${index}`}
data-dragging={isDragging ? '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="outline" 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>
);
}
@@ -112,6 +112,10 @@ export const heroHandlers = [
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.post(`${API_BASE}/api/v1/hero/images/:id/retry`, ({ params }) => {
retried.push(String(params.id));
return new HttpResponse(null, { status: 204 });
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from '@/mocks/server';
@@ -142,9 +142,9 @@ describe('Hero page', () => {
});
it.each([
['javascript:alert(1)', 'hero-button-0-target-error', /Kies een #anker|Choose an #anchor/],
['//evil.example', 'hero-button-0-target-error', /Kies een #anker|Choose an #anchor/],
['http://example.com', 'hero-button-0-target-error', /Kies een #anker|Choose an #anchor/],
['javascript:alert(1)', 'hero-button-0-target-error', /Kies een onderdeel van de pagina|Choose a part of the page/],
['//evil.example', 'hero-button-0-target-error', /Kies een onderdeel van de pagina|Choose a part of the page/],
['http://example.com', 'hero-button-0-target-error', /Kies een onderdeel van de pagina|Choose a part of the page/],
])('rejects the button target %s', async (target, errorId, message) => {
await openPage();
await userEvent.type(screen.getByTestId('hero-title-input'), 'Titel');
@@ -407,3 +407,261 @@ describe('Upload problems', () => {
expect(await screen.findByTestId('hero-upload-error')).toHaveTextContent(/te veel uploads|Too many uploads/);
});
});
describe('Unsaved changes', () => {
beforeEach(() => {
resetMockHero();
});
const withSlides = () => setMockHero({ ...emptyHero(), id: 'h1', title: 'Titel', isLive: true, updatedAt: '2026-11-16T12:00:00Z', slides: [slide(1), slide(2)] });
it('shows a notice as soon as something changed, and removes it when the change is undone', async () => {
withSlides();
await openPage();
expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument();
const title = screen.getByTestId('hero-title-input');
await userEvent.type(title, 'X');
expect(await screen.findByTestId('hero-unsaved')).toHaveTextContent(/Niet-opgeslagen wijzigingen|Unsaved changes/);
await userEvent.type(title, '{backspace}');
await waitFor(() => expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument());
});
it('counts a reordered, removed, decorative or switched-off slide as a change', async () => {
withSlides();
await openPage();
await userEvent.click(screen.getByTestId('hero-slide-1-up'));
expect(await screen.findByTestId('hero-unsaved')).toBeInTheDocument();
await userEvent.click(screen.getByTestId('hero-slide-1-up'));
await waitFor(() => expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument());
await userEvent.click(screen.getByTestId('hero-slide-0-active'));
expect(await screen.findByTestId('hero-unsaved')).toBeInTheDocument();
});
it('is gone after a successful save, and comes back for the next change', async () => {
withSlides();
await openPage();
await userEvent.type(screen.getByTestId('hero-title-input'), '!');
expect(await screen.findByTestId('hero-unsaved')).toBeInTheDocument();
await userEvent.click(screen.getByTestId('hero-save'));
await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1));
await waitFor(() => expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument());
await userEvent.type(screen.getByTestId('hero-title-input'), '?');
expect(await screen.findByTestId('hero-unsaved')).toBeInTheDocument();
});
it('asks the browser to warn when the tab is closed, only while there are unsaved changes', async () => {
withSlides();
await openPage();
const clean = new Event('beforeunload', { cancelable: true });
window.dispatchEvent(clean);
expect(clean.defaultPrevented).toBe(false);
await userEvent.type(screen.getByTestId('hero-title-input'), 'X');
await screen.findByTestId('hero-unsaved');
const dirty = new Event('beforeunload', { cancelable: true });
window.dispatchEvent(dirty);
expect(dirty.defaultPrevented).toBe(true);
});
it('asks before leaving through the menu: stay keeps the page and the changes, discard leaves', async () => {
withSlides();
await openPage();
await userEvent.type(screen.getByTestId('hero-title-input'), 'X');
await screen.findByTestId('hero-unsaved');
await userEvent.click(screen.getByTestId('nav-dashboard'));
expect(await screen.findByTestId('hero-leave-dialog', {}, T)).toBeInTheDocument();
await userEvent.click(screen.getByTestId('hero-leave-stay'));
await waitFor(() => expect(screen.queryByTestId('hero-leave-dialog')).not.toBeInTheDocument());
expect(screen.getByTestId('hero-title-input')).toHaveValue('TitelX');
await userEvent.click(screen.getByTestId('nav-dashboard'));
await userEvent.click(await screen.findByTestId('hero-leave-discard', {}, T));
await waitFor(() => expect(screen.queryByTestId('hero-form')).not.toBeInTheDocument(), T);
});
it('leaves without a question when nothing changed', async () => {
withSlides();
await openPage();
await userEvent.click(screen.getByTestId('nav-dashboard'));
await waitFor(() => expect(screen.queryByTestId('hero-form')).not.toBeInTheDocument(), T);
expect(screen.queryByTestId('hero-leave-dialog')).not.toBeInTheDocument();
});
it('does not count photos that are still being prepared, and keeps the notice through the background refresh', async () => {
const waiting = { ...slide(1), image: { ...slide(1).image, variants: [], src: '', processing: true } };
setMockHero({ ...emptyHero(), id: 'h1', title: 'Titel', slides: [waiting] });
await openPage();
await screen.findByTestId('hero-slide-0-processing', {}, T);
expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument();
await userEvent.type(screen.getByTestId('hero-title-input'), 'X');
setMockHero({ ...emptyHero(), id: 'h1', title: 'Titel', slides: [slide(1)] });
await waitFor(() => expect(screen.queryByTestId('hero-slide-0-processing')).not.toBeInTheDocument(), { timeout: 12000 });
expect(screen.getByTestId('hero-unsaved')).toBeInTheDocument();
expect(screen.getByTestId('hero-title-input')).toHaveValue('TitelX');
}, 20000);
});
describe('Several photos at once', () => {
beforeEach(() => {
resetMockHero();
});
const jpg = (name: string) => new File(['x'], name, { type: 'image/jpeg' });
it('adds every chosen photo at the end of the list, in the order they were chosen', async () => {
await openPage();
await userEvent.upload(screen.getByTestId('hero-upload'), [jpg('a.jpg'), jpg('b.jpg'), jpg('c.jpg')]);
await waitFor(() => expect(screen.getAllByTestId(/^hero-slide-\d+$/)).toHaveLength(3), T);
expect(screen.getByTestId('hero-upload-summary')).toHaveTextContent(/3 van 3|3 of 3/);
expect(screen.getByTestId('hero-upload-item-0') ?? screen.getByTestId('hero-upload-list')).toBeInTheDocument();
});
it('goes on with the other photos when one is refused, and says why for that one', async () => {
await openPage();
const big = jpg('groot.jpg');
Object.defineProperty(big, 'size', { value: 11 * 1024 * 1024 });
const pdf = new File(['x'], 'brief.pdf', { type: 'application/pdf' });
// The file chooser would filter on type; here the files arrive as they do on a drop.
fireEvent.change(screen.getByTestId('hero-upload'), { target: { files: [jpg('a.jpg'), big, pdf, jpg('d.jpg')] } });
await waitFor(() => expect(screen.getAllByTestId(/^hero-slide-\d+$/)).toHaveLength(2), T);
const errors = screen.getAllByTestId('hero-upload-error');
expect(errors).toHaveLength(2);
expect(errors[0]).toHaveTextContent(/maximaal 10 MB|at most 10 MB/);
expect(errors[1]).toHaveTextContent(/geen afbeelding|not an image/);
expect(screen.getByTestId('hero-upload-summary')).toHaveTextContent(/2 van 4|2 of 4/);
});
it('never has more than two uploads running at the same time', async () => {
await openPage();
let running = 0;
let most = 0;
server.use(
http.post(`${API_BASE}/api/v1/hero/images`, async () => {
running += 1;
most = Math.max(most, running);
await new Promise((resolve) => setTimeout(resolve, 60));
running -= 1;
return HttpResponse.json(
{ id: crypto.randomUUID(), width: 1600, height: 1067, focus: { x: 0.5, y: 0.5, zoom: 1 }, wideFocus: null, tallFocus: null, src: '', variants: [], processing: true, failed: false },
{ status: 201 },
);
}),
);
await userEvent.upload(screen.getByTestId('hero-upload'), [jpg('1.jpg'), jpg('2.jpg'), jpg('3.jpg'), jpg('4.jpg'), jpg('5.jpg')]);
await waitFor(() => expect(screen.getAllByTestId(/^hero-slide-\d+$/)).toHaveLength(5), T);
expect(most).toBe(2);
});
it('accepts photos that are dropped on the list', async () => {
await openPage();
const section = screen.getByTestId('hero-slides-section');
fireEvent.drop(section, { dataTransfer: { types: ['Files'], files: [jpg('a.jpg'), jpg('b.jpg')] } });
await waitFor(() => expect(screen.getAllByTestId(/^hero-slide-\d+$/)).toHaveLength(2), T);
});
it('lists the formats and limits the host gives, in plain words', async () => {
await openPage();
const limits = await screen.findByTestId('hero-upload-limits', {}, T);
expect(limits).toHaveTextContent('JPEG, PNG, GIF, BMP, TIFF, WebP, AVIF');
expect(limits).toHaveTextContent(/10 MB/);
expect(limits).toHaveTextContent(/64 megapixel/);
});
});
describe('Order by dragging, wording and calm waiting', () => {
beforeEach(() => {
resetMockHero();
});
it('gives every row a handle with an understandable name, next to the arrows', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
await openPage();
const handle = screen.getByTestId('hero-slide-1-drag');
expect(handle).toHaveAccessibleName(/Verplaats afbeelding 2|Move image 2/);
expect(screen.getByTestId('hero-slide-1-up')).toBeInTheDocument();
});
it('moves a row with the keyboard on the handle, and the new order goes live only on save', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
await openPage();
// jsdom has no layout: give the rows a position so the sorting can see where they are.
const rects = new Map<Element, DOMRect>();
['hero-slide-0', 'hero-slide-1'].forEach((id, i) => {
const rect = { x: 0, y: i * 100, top: i * 100, bottom: i * 100 + 90, left: 0, right: 500, width: 500, height: 90, toJSON: () => ({}) } as DOMRect;
rects.set(screen.getByTestId(id), rect);
});
const original = Element.prototype.getBoundingClientRect;
Element.prototype.getBoundingClientRect = function (this: Element) {
return rects.get(this) ?? original.call(this);
};
try {
const handle = screen.getByTestId('hero-slide-1-drag');
handle.focus();
await userEvent.keyboard(' ');
await userEvent.keyboard('{ArrowUp}');
await userEvent.keyboard(' ');
await waitFor(() => expect(screen.getByTestId('hero-slide-0-alt')).toHaveValue('Foto 2'));
expect(getSavedHeroRequests()).toHaveLength(0);
expect(await screen.findByTestId('hero-unsaved')).toBeInTheDocument();
} finally {
Element.prototype.getBoundingClientRect = original;
}
});
it('speaks plain language: no alt text, decoration with an explanation, and a short guide per part', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
await openPage();
expect(screen.getByLabelText(/Beschrijving afbeelding 1$|Description of image 1$/)).toBeInTheDocument();
const row = within(screen.getByTestId('hero-slide-0'));
expect(row.getByText(/Alleen versiering|Decoration only/)).toBeInTheDocument();
expect(row.getByText(/niets toevoegt aan de inhoud|adds nothing to the content/)).toBeInTheDocument();
expect(screen.queryByText(/alt-tekst|alt text/i)).not.toBeInTheDocument();
const help = screen.getByTestId('hero-help');
expect(help).toHaveTextContent(/#contact/);
expect(help).toHaveTextContent(/\/privacy/);
expect(help).toHaveTextContent(/Planning|Schedule/);
});
it('keeps the waiting placeholder mounted through the background refresh, so its animation keeps running', async () => {
const waiting = { ...slide(1), image: { ...slide(1).image, variants: [], src: '', processing: true } };
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [waiting, slide(2)] });
await openPage();
const before = await screen.findByTestId('hero-slide-0-processing', {}, T);
expect(before).toHaveClass('hero-shimmer');
expect(before).toHaveAttribute('role', 'status');
expect(before).toHaveAttribute('aria-busy', 'true');
// The server still has the photo in the works when the page asks again after 5 seconds.
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', updatedAt: '2026-11-16T12:05:00Z', slides: [{ ...waiting }, slide(2)] });
await new Promise((resolve) => setTimeout(resolve, 6000));
expect(screen.getByTestId('hero-slide-0-processing')).toBe(before);
}, 20000);
});
+172 -41
View File
@@ -4,6 +4,8 @@ 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';
@@ -12,10 +14,13 @@ 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 { ProcessingStatus, Spinner } from '../components/ProcessingStatus';
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, useSaveHero, useUploadHeroImage } from '../services/hooks';
import { useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks';
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from '../services/types';
const textareaClass =
@@ -106,6 +111,18 @@ export function HeroPage() {
)}
</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', 'schedule'] 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 && (
@@ -125,7 +142,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
const save = useSaveHero();
const upload = useUploadHeroImage();
const [serverError, setServerError] = useState<string | null>(null);
const [uploadError, setUploadError] = 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.
@@ -137,6 +158,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
handleSubmit,
control,
formState: { errors, isDirty },
reset,
} = useForm<HeroFormData>({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', defaultValues: toForm(hero) });
const slides = useFieldArray({ control, name: 'slides' });
const watchedSlides = useWatch({ control, name: 'slides' }) ?? [];
@@ -148,15 +170,23 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
return map;
}, [hero.slides, localImages]);
const hasPendingFocus = Object.keys(focusEdits).length > 0;
// 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 (!isDirty && !hasPendingFocus) return undefined;
if (!hasUnsaved) return undefined;
const warn = (event: BeforeUnloadEvent) => {
event.preventDefault();
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [isDirty, hasPendingFocus]);
}, [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 => {
@@ -164,32 +194,94 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
return image && edit ? { ...image, focus: edit.focus, wideFocus: edit.wide, tallFocus: edit.tall } : image;
};
const onUpload = async (files: FileList | null) => {
const file = files?.[0];
if (!file) return;
setUploadError(null);
// The host (and the proxy in front of it) refuse bigger files; say so without sending the whole file first.
if (file.size > MAX_UPLOAD_BYTES) {
setUploadError(t('hero.upload.tooLarge', { max: MAX_UPLOAD_BYTES / (1024 * 1024) }));
if (fileInput.current) fileInput.current.value = '';
return;
}
// 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 }));
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 {
const image = await upload.mutateAsync(file);
setLocalImages((current) => ({ ...current, [image.id]: image }));
slides.append({ id: null, imageId: image.id, alt: '', decorative: false, isActive: true }, { shouldFocus: false });
} catch (error) {
setUploadError(uploadMessage(error, t));
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 {
await save.mutateAsync(toRequest(values, focusEdits));
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')));
@@ -272,7 +364,24 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
<p className="text-xs text-muted-foreground">{t('hero.schedule.hint')}</p>
</section>
<section className="space-y-3">
<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>
@@ -281,35 +390,42 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
id="hero-upload"
type="file"
accept="image/*"
multiple
className="sr-only"
aria-label={t('hero.slides.add')}
data-testid="hero-upload"
onChange={(event) => void onUpload(event.target.files)}
onChange={(event) => void onFiles(event.target.files)}
/>
<Button type="button" variant="outline" disabled={upload.isPending} onClick={() => fileInput.current?.click()} data-testid="hero-upload-button">
<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" />
{upload.isPending ? t('hero.slides.uploading') : t('hero.slides.add')}
{uploading ? t('hero.slides.uploading') : t('hero.slides.add')}
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">{t('hero.slides.hint')}</p>
{uploadError && <p className="text-sm text-destructive" role="alert" data-testid="hero-upload-error">{uploadError}</p>}
{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 (
<li key={field.id} className="flex flex-wrap items-start gap-3 rounded-md border p-3" data-testid={`hero-slide-${index}`}>
<SortableSlide key={field.id} id={field.id} index={index}>
{image && image.variants.length === 0 ? (
<div
className={`flex h-20 w-28 flex-col items-center justify-center gap-1 rounded p-1 text-center text-xs ${image.failed ? 'bg-destructive/10 text-destructive' : 'bg-muted'}`}
title={t('hero.slides.processingHint')}
data-testid={`hero-slide-${index}-processing`}
>
{image.failed ? null : <Spinner />}
{image.failed ? t('hero.slides.failed') : t('hero.slides.processing')}
</div>
<PhotoPlaceholder failed={image.failed} testId={`hero-slide-${index}-processing`} />
) : image ? (
<img src={thumbnail(image)} alt="" className="h-20 w-28 rounded object-cover" />
) : (
@@ -317,7 +433,8 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
)}
<div className="min-w-[12rem] flex-1 space-y-2">
<Label htmlFor={`hero-slide-${index}-alt`}>{t('hero.slides.alt', { n: index + 1 })}</Label>
<Input id={`hero-slide-${index}-alt`} maxLength={300} disabled={decorative} data-testid={`hero-slide-${index}-alt`} {...register(`slides.${index}.alt` as const)} />
<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`} />
{focusEdits[field.imageId] && (
<p className="text-xs font-medium" data-testid={`hero-slide-${index}-focus-pending`}>{t('hero.slides.focusPending')}</p>
@@ -325,7 +442,10 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
<div className="flex flex-wrap gap-4 text-sm">
<label className="flex items-center gap-2">
<input type="checkbox" className="size-4 rounded border-input" data-testid={`hero-slide-${index}-decorative`} {...register(`slides.${index}.decorative` as const)} />
{t('hero.slides.decorative')}
<span>
{t('hero.slides.decorative')}
<span className="block text-xs text-muted-foreground">{t('hero.slides.decorativeHint')}</span>
</span>
</label>
<label className="flex items-center gap-2">
<input type="checkbox" className="size-4 rounded border-input" data-testid={`hero-slide-${index}-active`} {...register(`slides.${index}.isActive` as const)} />
@@ -347,10 +467,12 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
<Trash2 className="size-4" aria-hidden="true" />
</Button>
</div>
</li>
</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 })}
@@ -358,8 +480,17 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
)}
</section>
<div className="flex justify-end">
<Button type="submit" disabled={save.isPending} data-testid="hero-save">
<UnsavedChangesGuard dirty={hasUnsaved} />
<div className="sticky bottom-0 z-20 -mx-1 flex flex-wrap items-center justify-end gap-3 border-t bg-background/95 px-1 py-3 backdrop-blur">
<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} className={hasUnsaved ? 'ring-2 ring-primary ring-offset-2' : undefined} data-testid="hero-save">
{save.isPending ? '…' : t('common.save')}
</Button>
</div>
+10 -1
View File
@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest } from './types';
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroUploadLimits } from './types';
export const HERO_KEY = ['hero'];
@@ -49,3 +49,12 @@ export function useRetryHeroImage() {
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,
});
}
@@ -91,3 +91,9 @@ export interface HeroFocusRequest {
wide: FocusDto | null;
tall: FocusDto | null;
}
export interface HeroUploadLimits {
formats: string[];
maxUploadBytes: number;
maxMegapixels: number;
}