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:
@@ -0,0 +1,106 @@
|
||||
import { useRef, type KeyboardEvent, type ReactNode } from 'react';
|
||||
|
||||
export interface HeroTab<Id extends string> {
|
||||
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<Id extends string> {
|
||||
label: string;
|
||||
tabs: HeroTab<Id>[];
|
||||
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 <c>id="{idPrefix}-panel-{id}"</c> and <c>aria-labelledby="{idPrefix}-tab-{id}"</c>.
|
||||
*/
|
||||
export function HeroTabs<Id extends string>({ label, tabs, selected, onSelect, idPrefix }: HeroTabsProps<Id>) {
|
||||
const refs = useRef<Record<string, HTMLButtonElement | null>>({});
|
||||
|
||||
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 (
|
||||
<div role="tablist" aria-label={label} className="flex gap-1 border-b" data-testid="hero-tabs">
|
||||
{tabs.map((tab, index) => {
|
||||
const active = tab.id === selected;
|
||||
return (
|
||||
<button
|
||||
key={tab.id}
|
||||
ref={(element) => {
|
||||
refs.current[tab.id] = element;
|
||||
}}
|
||||
type="button"
|
||||
role="tab"
|
||||
id={`${idPrefix}-tab-${tab.id}`}
|
||||
aria-selected={active}
|
||||
aria-controls={`${idPrefix}-panel-${tab.id}`}
|
||||
tabIndex={active ? 0 : -1}
|
||||
onClick={() => onSelect(tab.id)}
|
||||
onKeyDown={(event) => onKeyDown(event, index)}
|
||||
className={`-mb-px inline-flex items-center gap-2 rounded-t-md border-b-2 px-4 py-2 text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${
|
||||
active ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
data-testid={`hero-tab-${tab.id}`}
|
||||
>
|
||||
{tab.label}
|
||||
{tab.note && <span className="text-xs font-normal text-muted-foreground">({tab.note})</span>}
|
||||
{tab.changed && (
|
||||
<>
|
||||
<span className="size-2 rounded-full bg-amber-500" aria-hidden="true" data-testid={`hero-tab-${tab.id}-changed`} />
|
||||
<span className="sr-only">{tab.changedText}</span>
|
||||
</>
|
||||
)}
|
||||
{tab.invalid && (
|
||||
<>
|
||||
<span className="inline-flex size-4 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-destructive-foreground" aria-hidden="true" data-testid={`hero-tab-${tab.id}-invalid`}>
|
||||
!
|
||||
</span>
|
||||
<span className="sr-only">{tab.invalidText}</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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\//);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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">
|
||||
|
||||
Reference in New Issue
Block a user