Hero-admin: tabbladen Inhoud en Afbeeldingen (toegankelijk, onthouden, fout- en wijzigingsmarkering, sprong naar eerste fout) en strakke opslaanbalk over de volle breedte

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 08:41:31 +01:00
co-authored by Claude Sonnet 5.5
parent 555ab10e14
commit 34ae16c902
5 changed files with 319 additions and 6 deletions
+92 -4
View File
@@ -19,6 +19,7 @@ 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';
@@ -154,12 +155,48 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
setValue,
handleSubmit,
control,
formState: { errors, isDirty },
formState: { errors, isDirty, dirtyFields },
setFocus,
reset,
} = useForm<HeroFormData>({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', defaultValues: toForm(hero) });
} = 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.
@@ -213,6 +250,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
// The form is compared with the last saved state (react-hook-form keeps it), so a change that is undone no longer counts.
// Photos still being prepared on the server and the background refresh are not changes of the administrator.
const hasUnsaved = isDirty || hasPendingFocus;
const contentChanged = Object.keys(dirtyFields).some((key) => key !== 'slides');
const imagesChanged = Boolean(dirtyFields.slides?.some?.(Boolean)) || hasPendingFocus;
const contentInvalid = Object.keys(errors).some((key) => key !== 'slides');
const imagesInvalid = Boolean(errors.slides);
const busyCount = slides.fields.filter((f) => images[f.imageId]?.processing).length;
useEffect(() => {
if (!hasUnsaved) return undefined;
const warn = (event: BeforeUnloadEvent) => {
@@ -324,14 +366,50 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
}
};
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={handleSubmit(onSubmit)} className="space-y-8" noValidate data-testid="hero-form">
<form onSubmit={(event) => void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8 pb-4" noValidate data-testid="hero-form">
<ProcessingStatus images={slides.fields.map((f) => images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} />
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
<HeroTabs
idPrefix="hero"
label={t('hero.tabs.label')}
selected={tab}
onSelect={setTab}
tabs={[
{ id: 'content', label: t('hero.tabs.content'), changed: contentChanged, changedText: t('hero.tabs.hasChanges'), invalid: contentInvalid, invalidText: t('hero.tabs.hasErrors') },
{
id: 'images',
label: t('hero.tabs.images'),
note: busyCount > 0 ? t('hero.tabs.busy', { count: busyCount }) : undefined,
changed: imagesChanged,
changedText: t('hero.tabs.hasChanges'),
invalid: imagesInvalid,
invalidText: t('hero.tabs.hasErrors'),
},
]}
/>
<div role="tabpanel" id="hero-panel-content" aria-labelledby="hero-tab-content" hidden={tab !== 'content'} className="space-y-8">
<section className="space-y-4">
<div className="space-y-2">
<Label htmlFor="hero-title-input">{t('hero.fields.title')}</Label>
@@ -381,6 +459,9 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
))}
</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) => {
@@ -501,9 +582,16 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
</p>
)}
</section>
</div>
<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">
{/* Full width of the content area (no gap at the sides or below), opaque, with a clear top edge and a shadow; the
bottom padding keeps clear of the home bar of a phone. */}
<div
className="sticky bottom-0 z-20 -mx-6 -mb-6 flex flex-wrap items-center justify-end gap-3 border-t bg-background px-6 pt-3 shadow-[0_-4px_8px_-4px_rgba(0,0,0,0.15)]"
style={{ paddingBottom: 'calc(0.75rem + env(safe-area-inset-bottom))' }}
data-testid="hero-save-bar"
>
<div role="status" aria-live="polite" className="min-h-5 flex-1 text-sm" data-testid="hero-unsaved-region">
{hasUnsaved && (
<span className="inline-flex items-center gap-2" data-testid="hero-unsaved">