fix(a11y): announce singular calendar and search counts

Preserve the real result count and localized date. Zero and multiple entries keep the existing translations. The Bokmål search noun has the same form in both cases.

Verified from f6143b9c with 37 component tests and six isolated Chromium/SQLite journeys on ports 4397/5397. New zero/one/two checks reproduced three singular failures before the fix. Next static export, TypeScript and scoped lint passed.

(cherry picked from commit 86d2305e64)
This commit is contained in:
cesnimda
2026-11-20 19:30:45 +01:00
parent 8b9aa1dafe
commit ac64d2ee22
7 changed files with 52 additions and 3 deletions
+1 -1
View File
@@ -232,7 +232,7 @@ for (const sample of [desktop, { language: 'nb', theme: 'dark', width: 390, heig
await expect(original.locator('xpath=..').locator('time')).toHaveAttribute('datetime', items.find(item => item.jobApplicationId === row.id)!.recordedAt);
await keyboard(page, page.getByRole('button', { name: t.calendarMonth, exact: true }));
const date = await page.evaluate(language => new Intl.DateTimeFormat(language === 'nb' ? 'nb-NO' : 'en-GB', { dateStyle: 'medium', timeZone: 'UTC' }).format(new Date('2026-10-16T12:00:00Z')), sample.language);
const dayName = text(t.calendarDayEvents, { date, count: 1 });
const dayName = text(t.calendarDayEvent, { date, count: 1 });
await keyboard(page, agenda.getByRole('button', { name: dayName, exact: true }));
await expect(original).toBeVisible();
await capture(page, info, sample, 'connected-status-scheduled-month');
@@ -200,7 +200,13 @@ for (const mode of ["light", "dark"] as const) for (const language of ["en", "nb
await page.keyboard.press("Escape");
await expect(trigger).toBeFocused();
await page.keyboard.press("Control+k");
const announcement = dialog.locator('[aria-live="polite"]');
await input.fill("no-such-workshop-729");
await expect(announcement).toHaveText(t.searchResultsCount.replace("{count}", "0"));
await input.fill("plattformutvikler");
await expect(announcement).toHaveText(t.searchResultCount.replace("{count}", "1"));
await input.fill("Nordlys");
await expect(announcement).toHaveText(t.searchResultsCount.replace("{count}", "2"));
const job = dialog.getByRole("button", { name: /Nordlys.*Tilgjengelig/ });
await expect(job).toBeVisible();
await job.focus();
@@ -45,6 +45,24 @@ test('month toggle persists only view preference and selecting a day keeps linke
expect(await screen.findByRole('table', { name: translations.en.calendarMonth })).toBeVisible();
});
test.each([
['en', 'en-GB', '0 recorded dates', '1 recorded date', '2 recorded dates'],
['nb', 'nb-NO', '0 registrerte datoer', '1 registrert dato', '2 registrerte datoer'],
] as const)('month day names announce the date and its recorded count in %s', async (language, locale, zero, one, two) => {
localStorage.setItem('uiLanguage', language);
const nextDay = { ...row, date: `${month}-16`, recordedAt: `${month}-16T12:00:00` };
get.mockResolvedValue({ data: [row, nextDay, { ...nextDay, jobApplicationId: 43, kind: 'follow-up' }] });
mount();
await screen.findAllByRole('link', { name: /Recorded teacher role/ });
fireEvent.click(screen.getByRole('button', { name: translations[language].calendarMonth }));
const table = within(screen.getByRole('table'));
const formatter = new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone: 'UTC' });
for (const [day, expected] of [['14', zero], ['15', one], ['16', two]]) {
const date = formatter.format(new Date(`${month}-${day}T12:00:00Z`));
expect(table.getByText(day, { selector: 'button' })).toHaveAccessibleName(`${date}, ${expected}`);
}
});
test('locale changes translate controls without repeating the read or translating source text', async () => {
mount(); await screen.findByRole('link', { name: /Recorded teacher role/ });
act(() => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: 'nb' })));
@@ -41,6 +41,10 @@ export default function CalendarAgenda({ refreshToken = 0 }: { refreshToken?: nu
return new Map([...result.entries()].sort(([a], [b]) => Number(a < today) - Number(b < today) || a.localeCompare(b)));
}, [resource.data, today]);
const changeMonth = (value: string) => { if (/^[1-9]\d{3}-(0[1-9]|1[0-2])$/.test(value) && Number(value.slice(0, 4)) <= 9998) { setMonth(value); setSelectedDate(null); } };
const dayLabel = (date: string) => {
const count = byDay.get(date)?.length ?? 0;
return t(count === 1 ? 'calendarDayEvent' : 'calendarDayEvents', { date: formatDate(date), count });
};
const offsetMonth = (offset: number) => changeMonth(monthValue(new Date(year, monthNumber - 1 + offset, 1)));
const firstWeekday = (calendarDate(from)!.getUTCDay() + 6) % 7;
const cells = Array.from({ length: Math.ceil((firstWeekday + days) / 7) * 7 }, (_, index) => {
@@ -71,7 +75,7 @@ export default function CalendarAgenda({ refreshToken = 0 }: { refreshToken?: nu
{!resource.loading && !resource.refreshing && !resource.error && <Stack spacing={2}>
{view === 'month' && <Table size="small" aria-label={t('calendarMonth')} sx={{ tableLayout: 'fixed', '& th, & td': { p: 0.25, textAlign: 'center', verticalAlign: 'top' } }}>
<TableHead><TableRow>{Array.from({ length: 7 }, (_, index) => <TableCell component="th" scope="col" key={index} abbr={new Intl.DateTimeFormat(locale, { weekday: 'long', timeZone: 'UTC' }).format(new Date(Date.UTC(2026, 10, 2 + index)))}>{new Intl.DateTimeFormat(locale, { weekday: 'narrow', timeZone: 'UTC' }).format(new Date(Date.UTC(2026, 10, 2 + index)))}</TableCell>)}</TableRow></TableHead>
<TableBody>{Array.from({ length: cells.length / 7 }, (_, week) => <TableRow key={week}>{cells.slice(week * 7, week * 7 + 7).map((date, day) => <TableCell key={day}>{date && <Button size="small" aria-pressed={selectedDate === date} aria-label={t('calendarDayEvents', { date: formatDate(date), count: byDay.get(date)?.length ?? 0 })} onClick={() => setSelectedDate(date)} variant={selectedDate === date ? 'contained' : 'text'} sx={{ minWidth: 0, width: '100%', minHeight: 44, px: 0, flexDirection: 'column' }}>{new Intl.NumberFormat(locale).format(Number(date.slice(-2)))}{byDay.has(date) && <Box component="span" aria-hidden="true" sx={{ width: 5, height: 5, bgcolor: 'currentColor', borderRadius: '50%' }} />}</Button>}</TableCell>)}</TableRow>)}</TableBody>
<TableBody>{Array.from({ length: cells.length / 7 }, (_, week) => <TableRow key={week}>{cells.slice(week * 7, week * 7 + 7).map((date, day) => <TableCell key={day}>{date && <Button size="small" aria-pressed={selectedDate === date} aria-label={dayLabel(date)} onClick={() => setSelectedDate(date)} variant={selectedDate === date ? 'contained' : 'text'} sx={{ minWidth: 0, width: '100%', minHeight: 44, px: 0, flexDirection: 'column' }}>{new Intl.NumberFormat(locale).format(Number(date.slice(-2)))}{byDay.has(date) && <Box component="span" aria-hidden="true" sx={{ width: 5, height: 5, bgcolor: 'currentColor', borderRadius: '50%' }} />}</Button>}</TableCell>)}</TableRow>)}</TableBody>
</Table>}
{view === 'agenda' ? [...byDay].map(([date, items]) => eventList(date, items)) : selectedDate ? (byDay.has(selectedDate) ? eventList(selectedDate, byDay.get(selectedDate)!) : <Typography>{t('calendarDayEmpty')}</Typography>) : <Typography>{t('calendarSelectDay')}</Typography>}
{!resource.data.length && <Typography color="text.secondary">{t('calendarAgendaEmpty')}</Typography>}
@@ -168,7 +168,7 @@ export default function QuickCommandDialog({ open, onClose, onNavigate, onOpenAd
</Box>
<Box aria-live="polite" sx={{ position: "absolute", width: 1, height: 1, overflow: "hidden", clipPath: "inset(50%)" }}>
{searchState === "loading" ? t("loading") : searchState === "ready" ? t("searchResultsCount", { count: allItems.length }) : ""}
{searchState === "loading" ? t("loading") : searchState === "ready" ? t(allItems.length === 1 ? "searchResultCount" : "searchResultsCount", { count: allItems.length }) : ""}
{activeIndex >= 0 ? ` ${allItems[activeIndex]?.label ?? ""}` : ""}
</Box>
{searchState === "error" ? <Alert severity="error" sx={{ mt: 1 }} action={<Button color="inherit" size="small" onClick={() => setSearchAttempt((value) => value + 1)}>{t("retry")}</Button>}>{t("searchLoadFailed")}</Alert> : null}
+4
View File
@@ -39,6 +39,7 @@ export const translations = {
calendarSelectedMonth: "Selected month",
calendarAgendaFailed: "Could not load recorded calendar dates.",
calendarAgendaEmpty: "No recorded deadlines or follow-up dates in this month.",
calendarDayEvent: "{date}, {count} recorded date",
calendarDayEvents: "{date}, {count} recorded dates",
calendarDayEmpty: "No recorded dates on this day.",
calendarSelectDay: "Select a day to see linked applications.",
@@ -533,6 +534,7 @@ export const translations = {
commandJobs: "Jobs",
commandCompanies: "Companies",
searchLoadFailed: "Search could not be loaded.",
searchResultCount: "{count} result available.",
searchResultsCount: "{count} results available.",
goToDashboard: "Go to dashboard",
analyticsOverview: "Analytics overview",
@@ -3285,6 +3287,7 @@ export const translations = {
calendarSelectedMonth: "Valgt måned",
calendarAgendaFailed: "Kunne ikke laste registrerte kalenderdatoer.",
calendarAgendaEmpty: "Ingen registrerte søknadsfrister eller oppfølgingsdatoer denne måneden.",
calendarDayEvent: "{date}, {count} registrert dato",
calendarDayEvents: "{date}, {count} registrerte datoer",
calendarDayEmpty: "Ingen registrerte datoer denne dagen.",
calendarSelectDay: "Velg en dag for å se tilknyttede søknader.",
@@ -3779,6 +3782,7 @@ export const translations = {
commandJobs: "Jobber",
commandCompanies: "Selskaper",
searchLoadFailed: "Søket kunne ikke lastes.",
searchResultCount: "{count} treff tilgjengelig.",
searchResultsCount: "{count} treff tilgjengelig.",
goToDashboard: "Gå til dashboard",
analyticsOverview: "Analyseoversikt",
@@ -60,6 +60,23 @@ test("[P5-00 PRES-E07] command and empty results use valid list semantics", asyn
expect(mockedApi.post).not.toHaveBeenCalled();
});
test.each([
["en", 0, "0 results available."],
["en", 1, "1 result available."],
["en", 2, "2 results available."],
["nb", 0, "0 treff tilgjengelig."],
["nb", 1, "1 treff tilgjengelig."],
["nb", 2, "2 treff tilgjengelig."],
] as const)("quick search announces %s result count %i in the live region", async (language, count, expected) => {
localStorage.setItem("uiLanguage", language);
const jobs = Array.from({ length: count }, (_, index) => ({ id: index + 1, jobTitle: "Radar technician", company: { name: "Workshop" } }));
mockedApi.get.mockImplementation((url: string) => Promise.resolve({ data: url === "/companies" ? [] : { items: jobs } }) as never);
render(<I18nProvider><QuickCommandDialog open onClose={jest.fn()} onNavigate={jest.fn()} onOpenAddJob={jest.fn()} /></I18nProvider>);
fireEvent.change(screen.getByRole("textbox"), { target: { value: "radar" } });
expect(await screen.findByText(expected, { selector: '[aria-live="polite"]' })).toBeInTheDocument();
expect(screen.queryAllByRole("listitem")).toHaveLength(count);
});
test("[P5-02 PRES-E07] search failure is distinct from no matches and Retry recovers", async () => {
mockedApi.get.mockRejectedValueOnce(new Error("offline"));
render(<I18nProvider><QuickCommandDialog open onClose={jest.fn()} onNavigate={jest.fn()} onOpenAddJob={jest.fn()} /></I18nProvider>);