From 34ae16c90226ca8b295141e691333e17809bb059 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 08:41:31 +0100 Subject: [PATCH] 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 --- .../src/features/hero/components/HeroTabs.tsx | 106 ++++++++++++++++++ .../src/features/hero/pages/HeroPage.test.tsx | 103 +++++++++++++++++ frontend/src/features/hero/pages/HeroPage.tsx | 96 +++++++++++++++- frontend/src/i18n/locales/en/translation.json | 10 +- frontend/src/i18n/locales/nl/translation.json | 10 +- 5 files changed, 319 insertions(+), 6 deletions(-) create mode 100644 frontend/src/features/hero/components/HeroTabs.tsx diff --git a/frontend/src/features/hero/components/HeroTabs.tsx b/frontend/src/features/hero/components/HeroTabs.tsx new file mode 100644 index 0000000..86ec1b4 --- /dev/null +++ b/frontend/src/features/hero/components/HeroTabs.tsx @@ -0,0 +1,106 @@ +import { useRef, type KeyboardEvent, type ReactNode } from 'react'; + +export interface HeroTab { + id: Id; + label: ReactNode; + /** Short note after the label, for example "2 busy". */ + note?: string; + /** There are unsaved changes in this tab: a dot and a text for screen readers. */ + changed?: boolean; + changedText?: string; + /** This tab holds a field with an error: a red mark and a text for screen readers. */ + invalid?: boolean; + invalidText?: string; +} + +interface HeroTabsProps { + label: string; + tabs: HeroTab[]; + selected: Id; + onSelect: (id: Id) => void; + idPrefix: string; +} + +/** + * Accessible tabs (role tablist, tab, tabpanel): the arrow keys move between the tabs (and select, "automatic activation"), + * Home and End go to the first and the last, only the selected tab is in the tab order. The panels themselves are rendered + * by the page, with id="{idPrefix}-panel-{id}" and aria-labelledby="{idPrefix}-tab-{id}". + */ +export function HeroTabs({ label, tabs, selected, onSelect, idPrefix }: HeroTabsProps) { + const refs = useRef>({}); + + const move = (index: number) => { + const next = tabs[(index + tabs.length) % tabs.length]; + onSelect(next.id); + refs.current[next.id]?.focus(); + }; + + const onKeyDown = (event: KeyboardEvent, index: number) => { + switch (event.key) { + case 'ArrowRight': + case 'ArrowDown': + event.preventDefault(); + move(index + 1); + break; + case 'ArrowLeft': + case 'ArrowUp': + event.preventDefault(); + move(index - 1); + break; + case 'Home': + event.preventDefault(); + move(0); + break; + case 'End': + event.preventDefault(); + move(tabs.length - 1); + break; + default: + } + }; + + return ( +
+ {tabs.map((tab, index) => { + const active = tab.id === selected; + return ( + + ); + })} +
+ ); +} diff --git a/frontend/src/features/hero/pages/HeroPage.test.tsx b/frontend/src/features/hero/pages/HeroPage.test.tsx index 59df94e..710f339 100644 --- a/frontend/src/features/hero/pages/HeroPage.test.tsx +++ b/frontend/src/features/hero/pages/HeroPage.test.tsx @@ -13,6 +13,7 @@ const T = { timeout: 10000 }; beforeEach(() => { _resetSetupStatusCache(); resetMockHero(); + window.sessionStorage.clear(); }); async function openPage() { @@ -632,6 +633,7 @@ describe('Order by dragging, wording and calm waiting', () => { }); it('speaks plain language: a plain Description field inside a titled slide, no alt text, and a short guide per part', async () => { + window.sessionStorage.setItem('cms-hero-tab', 'images'); setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] }); await openPage(); @@ -648,6 +650,7 @@ describe('Order by dragging, wording and calm waiting', () => { }); it('numbers the slides by their current order, also after the order changed', async () => { + window.sessionStorage.setItem('cms-hero-tab', 'images'); setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] }); await openPage(); @@ -1068,3 +1071,103 @@ describe('The Save button', () => { expect(screen.getByTestId('hero-save')).toBeEnabled(); }); }); + +describe('Tabs Content and Images', () => { + beforeEach(() => { + resetMockHero(); + }); + + it('has accessible tabs: tablist, tab, tabpanel, the arrow keys, Home and End', async () => { + await openPage(); + + const tablist = screen.getByRole('tablist'); + const [content, images] = within(tablist).getAllByRole('tab'); + expect(content).toHaveAttribute('aria-selected', 'true'); + expect(content).toHaveAttribute('tabindex', '0'); + expect(images).toHaveAttribute('aria-selected', 'false'); + expect(images).toHaveAttribute('tabindex', '-1'); + expect(screen.getByRole('tabpanel')).toHaveAttribute('aria-labelledby', content.id); + expect(screen.getByTestId('hero-title-input')).toBeVisible(); + + content.focus(); + await userEvent.keyboard('{ArrowRight}'); + expect(images).toHaveAttribute('aria-selected', 'true'); + expect(images).toHaveFocus(); + expect(screen.getByRole('tabpanel')).toHaveAttribute('aria-labelledby', images.id); + expect(screen.getByTestId('hero-slides-empty')).toBeVisible(); + expect(screen.getByTestId('hero-title-input')).not.toBeVisible(); + + await userEvent.keyboard('{ArrowRight}'); + expect(content).toHaveAttribute('aria-selected', 'true'); + await userEvent.keyboard('{End}'); + expect(images).toHaveAttribute('aria-selected', 'true'); + await userEvent.keyboard('{Home}'); + expect(content).toHaveAttribute('aria-selected', 'true'); + }); + + it('keeps a change when switching tabs, shows a dot on the tab with changes, and saves both tabs with one button', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] }); + await openPage(); + await userEvent.type(screen.getByTestId('hero-title-input'), 'x'); + expect(screen.getByTestId('hero-tab-content-changed')).toBeInTheDocument(); + expect(screen.queryByTestId('hero-tab-images-changed')).not.toBeInTheDocument(); + + await userEvent.click(screen.getByTestId('hero-tab-images')); + expect(screen.getByTestId('hero-unsaved')).toBeInTheDocument(); + await userEvent.type(screen.getByTestId('hero-slide-0-alt'), '!'); + expect(screen.getByTestId('hero-tab-images-changed')).toBeInTheDocument(); + await userEvent.click(screen.getByTestId('hero-tab-content')); + expect(screen.getByTestId('hero-title-input')).toHaveValue('Tx'); + + await userEvent.click(screen.getByTestId('hero-save')); + + await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1)); + expect(getSavedHeroRequests()[0].title).toBe('Tx'); + expect(getSavedHeroRequests()[0].slides[0].alt).toBe('Foto 1!'); + }); + + it('remembers the chosen tab for the session', async () => { + const first = await openPage(); + expect(first).toBeInTheDocument(); + await userEvent.click(screen.getByTestId('hero-tab-images')); + + expect(window.sessionStorage.getItem('cms-hero-tab')).toBe('images'); + }); + + it('opens on the remembered tab', async () => { + window.sessionStorage.setItem('cms-hero-tab', 'images'); + + await openPage(); + + expect(screen.getByTestId('hero-tab-images')).toHaveAttribute('aria-selected', 'true'); + }); + + it('shows how many photos are busy on the Images tab', 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(); + + expect(await screen.findByTestId('hero-tab-images', {}, T)).toHaveTextContent(/1 bezig|1 busy/); + }); + + it('jumps to the tab of the first error, marks it, and puts the cursor in that field', async () => { + setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1, { alt: '' })] }); + await openPage(); + await userEvent.type(screen.getByTestId('hero-lead'), 'x'); + + await userEvent.click(screen.getByTestId('hero-save')); + + await waitFor(() => expect(screen.getByTestId('hero-tab-images')).toHaveAttribute('aria-selected', 'true')); + expect(screen.getByTestId('hero-tab-images-invalid')).toBeInTheDocument(); + await waitFor(() => expect(screen.getByTestId('hero-slide-0-alt')).toHaveFocus()); + }); + + it('has a full-width, opaque save bar', async () => { + await openPage(); + + const bar = screen.getByTestId('hero-save-bar'); + expect(bar).toHaveClass('-mx-6', 'bg-background', 'border-t'); + expect(bar.className).not.toMatch(/bg-background\//); + }); +}); diff --git a/frontend/src/features/hero/pages/HeroPage.tsx b/frontend/src/features/hero/pages/HeroPage.tsx index 5ab80ad..b81943a 100644 --- a/frontend/src/features/hero/pages/HeroPage.tsx +++ b/frontend/src/features/hero/pages/HeroPage.tsx @@ -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({ resolver: zodResolver(heroFormSchema), mode: 'onTouched', defaultValues: toForm(hero) }); + } = 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. @@ -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 ( -
+ void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8 pb-4" noValidate data-testid="hero-form"> images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} /> setServerError(null)} /> + 0 ? t('hero.tabs.busy', { count: busyCount }) : undefined, + changed: imagesChanged, + changedText: t('hero.tabs.hasChanges'), + invalid: imagesInvalid, + invalidText: t('hero.tabs.hasErrors'), + }, + ]} + /> + + + + -
+ {/* 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. */} +
{hasUnsaved && ( diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index d98c892..763aefb 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -764,6 +764,14 @@ "stay": "Stay", "discard": "Discard changes" }, - "saving": "Saving…" + "saving": "Saving…", + "tabs": { + "label": "Hero sections", + "content": "Content", + "images": "Images", + "busy": "{{count}} busy", + "hasChanges": "unsaved changes", + "hasErrors": "has errors" + } } } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index 529be0a..b42cb57 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -764,6 +764,14 @@ "stay": "Blijven", "discard": "Wijzigingen weggooien" }, - "saving": "Bezig met opslaan…" + "saving": "Bezig met opslaan…", + "tabs": { + "label": "Onderdelen van de hero", + "content": "Inhoud", + "images": "Afbeeldingen", + "busy": "{{count}} bezig", + "hasChanges": "niet-opgeslagen wijzigingen", + "hasErrors": "bevat fouten" + } } }