diff --git a/bestax-mcp/data/components/Notification.json b/bestax-mcp/data/components/Notification.json index 2a419cc8d..914dcf9ed 100644 --- a/bestax-mcp/data/components/Notification.json +++ b/bestax-mcp/data/components/Notification.json @@ -34,7 +34,7 @@ "code": "\n Warning! This notification contains{' '}\n custom content.\n" } ], - "accessibility": "- **Delete button:** Includes `aria-label=\"Close notification\"` for screen readers.\n- **Keyboard:** The delete button is focusable and can be activated by keyboard.\n- **Content:** Use semantic HTML within the notification for best accessibility.\n- **Announcements:** A notification shown through `notification` announces its message: as an alert for `danger` and `warning`, and as a status otherwise.\n\n:::tip\nAlways provide clear, actionable text inside notifications.\n:::", + "accessibility": "- **Delete button:** Includes `aria-label=\"Close notification\"` for screen readers.\n- **Keyboard:** The delete button is focusable and can be activated by keyboard.\n- **Content:** Use semantic HTML within the notification for best accessibility.\n- **Announcements:** A notification shown through `notification` announces its message. `danger` and `warning` announce themselves: the message carries `role=\"alert\"` with `aria-live=\"assertive\"`, which screen readers reliably announce even though it arrives with its text. The rest are announced politely through a visually hidden `role=\"status\"` region that `NotificationContainer` keeps in the page from the moment it mounts, even with nothing showing, because a polite region that arrives already holding its text often isn't announced. A moment after one of those notifications appears, its message is written into the region, then cleared again shortly after.\n- **Testing:** A polite notification's message doesn't carry `role=\"status\"`, so `getByRole('status')` finds the container's region rather than the notification. Query the message text or `.notification` instead. A count or text [`Badge`](../components/badge.md) is a `role=\"status\"` node too, so with both on the page `getByRole('status')` matches more than one: find the badge by its accessible name, or use `getAllByRole`. While a message is in the region, the page also holds a second copy of its text, so a test that advances the clock past the announcement and then looks the message up by text can find both, and can still find the region's copy for a moment after the notification closes. Scope that query to the notification, for example with `within`.\n\n:::tip\nAlways provide clear, actionable text inside notifications.\n:::", "related": ["Delete", "useBulmaClasses"], "storybook": "https://bestax.io/storybook/?path=/story/elements-notification--default", "summary": "The `Notification` component is a Bulma-styled alert/message area for providing feedback, warnings, or information to users.", diff --git a/bulma-ui/src/elements/Notification.tsx b/bulma-ui/src/elements/Notification.tsx index 5e7b86928..4703305a5 100644 --- a/bulma-ui/src/elements/Notification.tsx +++ b/bulma-ui/src/elements/Notification.tsx @@ -1,5 +1,7 @@ import React, { useEffect, + useMemo, + useRef, useState, useCallback, useSyncExternalStore, @@ -13,6 +15,8 @@ import { } from '../helpers/useBulmaClasses'; import { warnUnstyledColor } from '../helpers/colorDeprecations'; import { groupIntoPositionStacks } from '../helpers/positionStacks'; +import { useIsHydrated } from '../helpers/useIsHydrated'; +import { StatusRegion, spokenText } from '../helpers/statusRegion'; /** * Props for the Notification component. @@ -110,7 +114,18 @@ export type NotificationPosition = * Options for showing a programmatic notification. */ export interface NotificationOptions { - /** The message to display. */ + /** + * The message to display. + * + * For a notification other than `danger` and `warning`, NotificationContainer + * announces the text the message renders, with an element's `aria-label`, + * or an image's `alt`, standing in for what's inside it, a break between + * block-level elements, and parts that are `aria-hidden`, `hidden` or + * inline-styled `display: none` left out. Other ways of naming or hiding + * content, such as `aria-labelledby`, CSS-generated content or a + * stylesheet's `display: none`, aren't followed, so a message that relies on + * them can be announced differently from what a screen reader would read. + */ message: string | React.ReactNode; /** * Bulma color modifier for the notification (renders `is-`). @@ -175,9 +190,9 @@ const getServerNotifications = () => noNotifications; // updates alone, so notifications raised before it mounted still appear. It is // replaced rather than mutated, and only when listeners are notified, because // useSyncExternalStore needs the same array back between changes. An empty -// list is `noNotifications` itself, so a container that hydrates with nothing -// to show reads the same snapshot the server did and has no reason to render -// again. +// list is `noNotifications` itself, so an empty store reads the same snapshot +// on the client as on the server, and a notify that leaves nothing showing +// when nothing was showing doesn't render the container again. let visibleNotifications: NotificationInstance[] = noNotifications; const getVisibleNotifications = () => visibleNotifications; @@ -312,17 +327,29 @@ export const notification = { }, }; +/** + * Whether a notification of this color announces itself as an alert, rather + * than politely through NotificationContainer's status region. + * + * @function isUrgentColor + * @param {NotificationOptions['color']} color - The notification's color. + * @returns {boolean} True for `danger` and `warning`. + */ +const isUrgentColor = (color: NotificationOptions['color']): boolean => + color === 'danger' || color === 'warning'; + /** * Single auto-dismissing notification item used by NotificationContainer. * * @function - * @param {{ instance: NotificationInstance; onClose: (id: string) => void }} props - Component props. + * @param {{ instance: NotificationInstance; onClose: (id: string) => void; registerMessage: (id: string, node: HTMLElement | null) => void }} props - Component props. * @returns {JSX.Element} The rendered notification item. */ const NotificationItem: React.FC<{ instance: NotificationInstance; onClose: (id: string) => void; -}> = ({ instance, onClose }) => { + registerMessage: (id: string, node: HTMLElement | null) => void; +}> = ({ instance, onClose, registerMessage }) => { const { message, color, @@ -334,12 +361,19 @@ const NotificationItem: React.FC<{ } = instance.options; const [isPaused, setIsPaused] = useState(false); - const urgent = color === 'danger' || color === 'warning'; + const urgent = isUrgentColor(color); const handleClose = useCallback(() => { onClose(instance.id); }, [onClose, instance.id]); + const messageRef = useCallback( + (node: HTMLElement | null) => { + registerMessage(instance.id, node); + }, + [registerMessage, instance.id] + ); + // Auto-close timer useEffect(() => { if (indefinite || duration === 0 || isPaused) return undefined; @@ -366,18 +400,19 @@ const NotificationItem: React.FC<{ onMouseLeave={handleMouseLeave} style={{ pointerEvents: 'auto' }} > - {/* It appears after the page has rendered, so its message announces - itself: as an alert for danger and warning, as a status otherwise. - The live region wraps only the message, not the close button that - Notification renders ahead of its children. */} + {/* Only the message is announced, not the close button Notification + renders ahead of its children. Danger and warning announce + themselves as an assertive alert, which a screen reader reliably + reads out even when it arrives with its text. The rest are announced + through the container's status region, which reads their text from + this span, so it carries no role of its own that would announce them + a second time. */} {urgent ? ( {message} ) : ( - - {message} - + {message} )} ); @@ -433,9 +468,21 @@ const notificationStackStyle = ( * container's `position`, so the container renders a stack for each position * in use. * + * It keeps a visually hidden `role="status"` live region in the page from the + * moment it mounts, even while nothing is showing, and announces every + * notification other than `danger` and `warning` through it, a moment after + * the notification appears. Those notifications carry no `role="status"` of + * their own, so `getByRole('status')` finds the region, not the notification. + * The text stays in the region briefly, even if the notification closes in + * the meantime, and while both are up the page holds two copies of it. A + * polite notification that closes before its announcement is written, a + * moment after it appears, isn't announced at all. `danger` and `warning` + * notifications announce themselves as assertive alerts. The region is hidden + * with inline styles, so it needs no stylesheet. + * * @function * @param {{ position?: NotificationPosition }} props - Container props. - * @returns {JSX.Element | null} The rendered notification container, or null if empty. + * @returns {JSX.Element | null} The rendered notification container, or null on the server and while hydrating. */ export const NotificationContainer: React.FC<{ /** @@ -453,8 +500,47 @@ export const NotificationContainer: React.FC<{ getVisibleNotifications, getServerNotifications ); + // A portal needs a document, and it has no server-rendered counterpart, so + // the server render and the hydrating one render nothing, and the container + // portals in from the render after hydration. + const isHydrated = useIsHydrated(); + + // The notifications the status region announces. Danger and warning + // announce themselves. + const politeItems = useMemo( + () => items.filter(item => !isUrgentColor(item.options.color)), + [items] + ); + + // Each polite notification's message element, so the text the region + // announces is the text on screen, whatever the message renders. + const messageNodesRef = useRef(new Map()); + const registerMessage = useCallback( + (id: string, node: HTMLElement | null) => { + if (node) { + messageNodesRef.current.set(id, node); + } else { + messageNodesRef.current.delete(id); + } + }, + [] + ); + // StatusRegion only describes polite notifications that are on screen, and + // each of those registered its message element when it mounted. The + // fallback is for a notification announced without being rendered, should + // the container ever render fewer than it announces: a plain-text message + // still says itself, and anything else is skipped. + const describe = useCallback((item: NotificationInstance) => { + const node = messageNodesRef.current.get(item.id); + /* istanbul ignore if: every polite notification on screen registers its message element when it mounts */ + if (!node) { + const { message } = item.options; + return typeof message === 'string' ? message : null; + } + return spokenText(node); + }, []); - if (typeof document === 'undefined' || items.length === 0) { + if (typeof document === 'undefined' || !isHydrated) { return null; } @@ -466,17 +552,21 @@ export const NotificationContainer: React.FC<{ ); return createPortal( - stacks.map(stack => ( -
- {stack.items.map(item => ( - - ))} -
- )), + <> + {stacks.map(stack => ( +
+ {stack.items.map(item => ( + + ))} +
+ ))} + + , document.body ); }; diff --git a/bulma-ui/src/elements/__tests__/Notification.ssr.test.tsx b/bulma-ui/src/elements/__tests__/Notification.ssr.test.tsx index e1f57e9f2..1bb348840 100644 --- a/bulma-ui/src/elements/__tests__/Notification.ssr.test.tsx +++ b/bulma-ui/src/elements/__tests__/Notification.ssr.test.tsx @@ -15,6 +15,13 @@ import { renderToStaticMarkup } from 'react-dom/server'; import { NotificationContainer, notification } from '../Notification'; describe('NotificationContainer SSR (node environment)', () => { + it('renders nothing with nothing raised, status region included', () => { + const html = renderToStaticMarkup( + React.createElement(NotificationContainer) + ); + expect(html).toBe(''); + }); + it('renders nothing, even with notifications raised', () => { notification.show({ message: 'Raised on the server', duration: 0 }); try { diff --git a/bulma-ui/src/elements/__tests__/Notification.test.tsx b/bulma-ui/src/elements/__tests__/Notification.test.tsx index a1b439ba3..2fe7d7664 100644 --- a/bulma-ui/src/elements/__tests__/Notification.test.tsx +++ b/bulma-ui/src/elements/__tests__/Notification.test.tsx @@ -10,6 +10,11 @@ import { } from '../Notification'; import { ConfigProvider } from '../../helpers/Config'; import { resetColorDeprecationWarnings } from '../../helpers/colorDeprecations'; +import { + announceDelay, + announcementLifetime, +} from '../../helpers/statusRegion'; +import { ToastContainer, toast } from '../../components/Toast'; describe('Notification Component', () => { const defaultProps: NotificationProps = { @@ -176,40 +181,380 @@ describe('Notification Programmatic API', () => { }); describe('announcements', () => { - it.each([ - ['success', 'status', 'polite'], - ['info', 'status', 'polite'], - ['warning', 'alert', 'assertive'], - ['danger', 'alert', 'assertive'], - ] as const)('a %s notification announces as %s', (color, role, live) => { - render(); + // Lets the container write what it announces. + const waitForAnnouncements = () => act(() => { - notification.show({ message: `Msg ${color}`, color, duration: 0 }); + jest.advanceTimersByTime(announceDelay); + }); + + it('keeps a status region in the page from mount, with nothing visible', () => { + const { container } = render(); + + const status = screen.getByRole('status'); + expect(status).toHaveAttribute('aria-live', 'polite'); + expect(status).toHaveStyle({ + position: 'absolute', + clip: 'rect(0px, 0px, 0px, 0px)', }); - const region = screen.getByRole(role); - expect(region).toHaveTextContent(`Msg ${color}`); - expect(region).toHaveAttribute('aria-live', live); + expect(status).toBeEmptyDOMElement(); + + // The region is all an empty container adds to the page. There's no + // alert region: alerts announce themselves. + expect( + Array.from(document.body.children).filter(el => el !== container) + ).toEqual([status]); + expect(screen.queryByRole('alert')).toBeNull(); }); - it('a notification with no color announces as a status', () => { + it.each(['success', 'info', 'primary'] as const)( + 'announces a %s notification through the status region', + color => { + render(); + act(() => { + notification.show({ message: `Msg ${color}`, color, duration: 0 }); + }); + waitForAnnouncements(); + + expect(screen.getByRole('status')).toHaveTextContent( + new RegExp(`^Msg ${color}$`) + ); + expect(screen.queryByRole('alert')).toBeNull(); + } + ); + + it('announces a notification with no color through the status region', () => { render(); act(() => { notification.show({ message: 'Plain', duration: 0 }); }); - expect(screen.getByRole('status')).toHaveTextContent('Plain'); + waitForAnnouncements(); + + expect(screen.getByRole('status')).toHaveTextContent(/^Plain$/); + }); + + it.each(['warning', 'danger'] as const)( + 'leaves a %s notification to announce itself as an alert', + color => { + render(); + act(() => { + notification.show({ message: `Msg ${color}`, color, duration: 0 }); + }); + + // The alert arrives with its text, in the notification itself. + const alert = screen.getByRole('alert'); + expect(alert).toHaveAttribute('aria-live', 'assertive'); + expect(alert).toHaveTextContent(new RegExp(`^Msg ${color}$`)); + expect(alert.closest('.notification')).not.toBeNull(); + + // And it isn't written anywhere else. + waitForAnnouncements(); + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + expect(screen.getAllByRole('alert')).toEqual([alert]); + } + ); + + it('writes only the polite ones when they appear together with an alert', () => { + render(); + act(() => { + notification.success('Saved', { duration: 0 }); + notification.warning('Almost full', { duration: 0 }); + }); + waitForAnnouncements(); + + expect(screen.getByRole('status')).toHaveTextContent(/^Saved$/); + expect(screen.getByRole('alert')).toHaveTextContent(/^Almost full$/); + }); + + it('writes the announcement into the region that was already there', () => { + render(); + const status = screen.getByRole('status'); + + act(() => { + notification.success('Saved', { duration: 0 }); + }); + // Not in the commit that shows the notification. + expect(status).toBeEmptyDOMElement(); + + waitForAnnouncements(); + expect(screen.getByRole('status')).toBe(status); + expect(status).toHaveTextContent('Saved'); }); it('announces only the message, not the close button', () => { render(); act(() => { + notification.success('Saved', { duration: 0 }); notification.danger('Something went wrong', { duration: 0 }); }); - const region = screen.getByRole('alert'); - expect(region).toHaveTextContent(/^Something went wrong$/); - expect(within(region).queryByRole('button')).toBeNull(); + waitForAnnouncements(); + + for (const [role, text] of [ + ['status', /^Saved$/], + ['alert', /^Something went wrong$/], + ] as const) { + const region = screen.getByRole(role); + expect(region).toHaveTextContent(text); + expect(within(region).queryByRole('button')).toBeNull(); + } + expect( + screen.getAllByRole('button', { name: 'Close notification' }) + ).toHaveLength(2); + }); + + it('announces the text a message renders, without its markup', () => { + render(); + act(() => { + notification.info( + <> + Draft saved + , + { duration: 0 } + ); + }); + waitForAnnouncements(); + + const region = screen.getByRole('status'); + expect(region).toHaveTextContent(/^Draft saved$/); + expect(region.querySelector('strong')).toBeNull(); + }); + + it("announces an image's alt, and leaves out what's hidden from screen readers", () => { + render(); + act(() => { + notification.success( + <> + + Upload complete + , + { duration: 0 } + ); + }); + waitForAnnouncements(); + + expect(screen.getByRole('status')).toHaveTextContent(/^Upload complete$/); + }); + + it('announces each polite notification once, through the region alone', () => { + render(); + act(() => { + notification.success('Once', { duration: 0 }); + }); + waitForAnnouncements(); + + // The notification carries no live region of its own, so the region is + // the only one in the page, and it says it once. + expect(screen.getAllByRole('status')).toEqual([ + screen.getByRole('status'), + ]); + expect(screen.queryByRole('alert')).toBeNull(); + const shown = document.querySelector('.notification')!; + expect(shown).not.toHaveAttribute('role'); + expect(shown.querySelector('[role], [aria-live]')).toBeNull(); + expect(screen.getByRole('status').children).toHaveLength(1); + const first = screen.getByRole('status').firstElementChild; + + // A later notification is added as a node of its own, and the first one + // stays as it was for the rest of its time in the region. + act(() => { + notification.info('Next', { duration: 0 }); + }); + waitForAnnouncements(); + const status = screen.getByRole('status'); + expect(Array.from(status.children, el => el.textContent)).toEqual([ + 'Once', + 'Next', + ]); + expect(status.firstElementChild).toBe(first); + }); + + it('clears an announcement after a moment, leaving the notification', () => { + render(); + act(() => { + notification.success('Stays up', { indefinite: true }); + }); + waitForAnnouncements(); + expect(screen.getByRole('status')).toHaveTextContent('Stays up'); + + act(() => { + jest.advanceTimersByTime(announcementLifetime); + }); + + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + expect(document.querySelector('.notification')).toHaveTextContent( + 'Stays up' + ); + }); + + it('announces the next queued notification when it appears', () => { + render(); + let first = ''; + act(() => { + first = notification.show({ message: 'Q1', duration: 0, queue: true }); + notification.show({ message: 'Q2', duration: 0, queue: true }); + }); + waitForAnnouncements(); + expect(screen.getByRole('status')).toHaveTextContent(/^Q1$/); + + act(() => { + notification.close(first); + }); + waitForAnnouncements(); + // Q1 closed after its announcement was written, so it keeps the rest of + // its time in the region beside Q2. + expect( + Array.from(screen.getByRole('status').children, el => el.textContent) + ).toEqual(['Q1', 'Q2']); + }); + + it('keeps an announcement for its whole lifetime after its notification closes', () => { + // The pattern the programmatic API shows: an indefinite notification + // while something runs, closed and followed by the result. + render(); + let uploading = ''; + act(() => { + uploading = notification.show({ + message: 'Uploading…', + indefinite: true, + }); + }); + waitForAnnouncements(); + act(() => { + jest.advanceTimersByTime(50); + }); + + act(() => { + notification.close(uploading); + notification.success('Saved!', { duration: 0 }); + }); + expect(screen.getByRole('status')).toHaveTextContent(/^Uploading…$/); + + waitForAnnouncements(); + expect( + Array.from(screen.getByRole('status').children, el => el.textContent) + ).toEqual(['Uploading…', 'Saved!']); + + // Each leaves when its own lifetime is up. + act(() => { + jest.advanceTimersByTime(announcementLifetime - announceDelay - 50); + }); + expect(screen.getByRole('status')).toHaveTextContent(/^Saved!$/); + }); + + it("doesn't announce a notification that closes before its announcement is due", () => { + render(); + let id = ''; + act(() => { + id = notification.success('Gone', { duration: 0 }); + }); + expect(document.querySelector('.notification')).toHaveTextContent('Gone'); + + act(() => { + notification.close(id); + }); + waitForAnnouncements(); + + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + }); + + it('keeps the lines of a block-level message apart', () => { + render(); + act(() => { + notification.info( + <> +

Upload complete

+

3 files added

+ , + { duration: 0 } + ); + }); + waitForAnnouncements(); + + expect(screen.getByRole('status')).toHaveTextContent( + /^Upload complete 3 files added$/ + ); + }); + + it('announces notifications at different positions together', () => { + render(); + act(() => { + notification.show({ message: 'Here', duration: 0 }); + notification.info('There', { position: 'bottom-left', duration: 0 }); + }); + waitForAnnouncements(); + expect( - screen.getByRole('button', { name: 'Close notification' }) - ).toBeInTheDocument(); + Array.from(screen.getByRole('status').children).map( + el => el.textContent + ) + ).toEqual(['Here', 'There']); + }); + + it('keeps its region in place while stacks come and go', () => { + render(); + const status = screen.getByRole('status'); + + act(() => { + notification.show({ message: 'Top', duration: 0 }); + notification.show({ message: 'Bottom', position: 'bottom' }); + }); + act(() => { + notification.closeAll(); + }); + + expect(screen.getByRole('status')).toBe(status); + }); + + it('hides the region with no stylesheet, whatever the class prefix', () => { + // No CSS is loaded here, Bulma's helpers included, and the region + // doesn't rely on any. + expect(document.styleSheets).toHaveLength(0); + render( + + + + ); + act(() => { + notification.success('Hidden copy', { duration: 0 }); + }); + waitForAnnouncements(); + + const status = screen.getByRole('status'); + expect(status).toHaveTextContent('Hidden copy'); + expect(status).not.toHaveAttribute('class'); + expect(status).toHaveStyle({ + position: 'absolute', + width: '1px', + height: '1px', + margin: '-1px', + overflow: 'hidden', + clip: 'rect(0px, 0px, 0px, 0px)', + 'clip-path': 'inset(50%)', + 'white-space': 'nowrap', + }); + }); + + it("leaves getByRole('alert') to a toast shown beside it", () => { + // Without an alert region of its own, a container with no danger or + // warning notification showing adds no alert to the page, so a toast's + // alert is the only one. + render( + <> + + + + ); + act(() => { + notification.success('Saved', { duration: 0 }); + toast.info('Synced', { duration: 0 }); + }); + waitForAnnouncements(); + + expect(screen.getByRole('alert')).toHaveClass('toast'); + expect(screen.getByRole('alert')).toHaveTextContent('Synced'); + + act(() => { + toast.closeAll(); + }); }); }); @@ -578,6 +923,51 @@ describe('NotificationContainer mounted after notifications are raised', () => { expect(shownMessages()).toEqual(['Strict', 'Strict later']); }); + it('announces them once the region it mounts is in the page', () => { + notification.show({ message: 'Early', duration: 0 }); + notification.warning('Early warning', { duration: 0 }); + + render(); + const status = screen.getByRole('status'); + // The region mounts empty, alongside the notifications. The warning + // arrives as an alert, holding its own text. + expect(status).toBeEmptyDOMElement(); + expect(screen.getByRole('alert')).toHaveTextContent(/^Early warning$/); + + act(() => { + jest.advanceTimersByTime(announceDelay); + }); + + expect(status).toHaveTextContent(/^Early$/); + }); + + it('keeps one status region and announces once under StrictMode', () => { + notification.show({ message: 'Strict', duration: 0 }); + render( + + + + ); + act(() => { + jest.advanceTimersByTime(announceDelay); + }); + + expect(screen.getAllByRole('status')).toHaveLength(1); + expect(screen.queryByRole('alert')).toBeNull(); + expect( + Array.from(screen.getByRole('status').children).map(el => el.textContent) + ).toEqual(['Strict']); + }); + + it('stops announcing once it unmounts', () => { + notification.show({ message: 'Unmounted', duration: 0 }); + const { unmount } = render(); + + unmount(); + + expect(jest.getTimerCount()).toBe(0); + }); + it('times each from when it appears, and drops it from the store after', () => { notification.show({ message: 'Timed', duration: 3000 }); // Time spent waiting for a container does not count against it. @@ -655,6 +1045,15 @@ describe('NotificationContainer mounted after notifications are raised', () => { expect(errorSpy).not.toHaveBeenCalled(); expect(shownMessages()).toEqual(['Before hydration']); + + // The status region arrives with it, and announces it once it's in. + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + act(() => { + jest.advanceTimersByTime(announceDelay); + }); + expect(screen.getByRole('status')).toHaveTextContent( + /^Before hydration$/ + ); } finally { // A root left mounted would add its notifications to every later test's. await act(async () => unmountRoot()); @@ -663,7 +1062,7 @@ describe('NotificationContainer mounted after notifications are raised', () => { } }); - it('renders once when it hydrates with nothing to show', async () => { + it('adds only its status region, in one render, when it hydrates with nothing to show', async () => { // Empty the way a closed notification leaves it, not only the way it // starts. const id = notification.show({ message: 'Gone', duration: 0 }); @@ -681,6 +1080,7 @@ describe('NotificationContainer mounted after notifications are raised', () => { container.innerHTML = renderToString(app); document.body.appendChild(container); + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); let unmountRoot = () => {}; try { await act(async () => { @@ -688,11 +1088,20 @@ describe('NotificationContainer mounted after notifications are raised', () => { unmountRoot = () => root.unmount(); }); - // A client snapshot that is a different array from the server's, even - // an empty one, would add an 'update' render after the mount. - expect(onRender.mock.calls.map(([, phase]) => phase)).toEqual(['mount']); + // The hydrating render matches the server's empty markup, and the one + // render after it portals the region in. + expect(errorSpy).not.toHaveBeenCalled(); + expect(onRender.mock.calls.map(([, phase]) => phase)).toEqual([ + 'mount', + 'update', + ]); + expect(container.innerHTML).toBe('
'); + expect( + Array.from(document.body.children).filter(el => el !== container) + ).toEqual([screen.getByRole('status')]); } finally { await act(async () => unmountRoot()); + errorSpy.mockRestore(); document.body.removeChild(container); } }); @@ -773,7 +1182,8 @@ describe('NotificationContainer with notifications shown at their own position', it("gives a notification at the container's own position the container's stack", () => { // What a container rendered before notifications could be placed on - // their own: one stack, fixed to the container's position. + // their own: one stack, fixed to the container's position, and then the + // status region, which says nothing until the announcements are due. const { container } = render(); act(() => { notification.show({ message: 'One', duration: 0 }); @@ -786,9 +1196,10 @@ describe('NotificationContainer with notifications shown at their own position', .map(el => el.outerHTML) ).toEqual([ '
' + - '
One
' + - '
Two
' + + '
One
' + + '
Two
' + '
', + '
', ]); }); diff --git a/bulma-ui/src/helpers/__tests__/statusRegion.styles.test.tsx b/bulma-ui/src/helpers/__tests__/statusRegion.styles.test.tsx new file mode 100644 index 000000000..f8720afdc --- /dev/null +++ b/bulma-ui/src/helpers/__tests__/statusRegion.styles.test.tsx @@ -0,0 +1,57 @@ +// The region hides itself with an inline style, so it works without any +// stylesheet. The library already hides Badge's placeholder with the +// `extras-sr-only` mixin, so this compiles that mixin and checks the two agree +// on every declaration the mixin makes, which is how a change to one shows up +// as a difference from the other. +import * as sass from 'sass'; +import path from 'path'; +import { render, screen } from '@testing-library/react'; +import { StatusRegion } from '../statusRegion'; + +const mixinCss = sass.compileString( + "@use 'mixins' as *;\n.sr-only-probe { @include extras-sr-only; }", + { + loadPaths: [path.resolve(__dirname, '../../scss')], + quietDeps: true, + logger: sass.Logger.silent, + } +).css; + +let styleEl: HTMLStyleElement; + +beforeAll(() => { + styleEl = document.createElement('style'); + styleEl.textContent = mixinCss; + document.head.appendChild(styleEl); +}); + +afterAll(() => { + styleEl.remove(); +}); + +it('hides the region with the declarations of the extras-sr-only mixin', () => { + const rule = Array.from(styleEl.sheet!.cssRules).find( + candidate => (candidate as CSSStyleRule).selectorText === '.sr-only-probe' + ) as CSSStyleRule; + const properties = Array.from( + { length: rule.style.length }, + (_, index) => rule.style[index] + ); + render( + <> +
+ null} /> + + ); + const probe = getComputedStyle(screen.getByTestId('probe')); + const region = getComputedStyle(screen.getByRole('status')); + + // The margin is the declaration that keeps the region from adding + // scrollable overflow, so it has to be among those compared. + expect(properties).toContain('margin'); + expect( + properties.map(property => [property, region.getPropertyValue(property)]) + ).toEqual( + properties.map(property => [property, probe.getPropertyValue(property)]) + ); +}); diff --git a/bulma-ui/src/helpers/__tests__/statusRegion.test.tsx b/bulma-ui/src/helpers/__tests__/statusRegion.test.tsx new file mode 100644 index 000000000..792472808 --- /dev/null +++ b/bulma-ui/src/helpers/__tests__/statusRegion.test.tsx @@ -0,0 +1,392 @@ +import { StrictMode, useState } from 'react'; +import { flushSync } from 'react-dom'; +import { render, screen, act } from '@testing-library/react'; +import { + StatusRegion, + announceDelay, + announcementLifetime, + spokenText, +} from '../statusRegion'; + +interface Item { + id: string; + text: string | null; +} + +const describeItem = (item: Item) => item.text; + +const alpha: Item = { id: 'a', text: 'Alpha' }; +const bravo: Item = { id: 'b', text: 'Bravo' }; +const charlie: Item = { id: 'c', text: 'Charlie' }; + +const region = (items: Item[]) => ( + +); + +// What the region says, one entry per announcement node. +const said = () => + Array.from(screen.getByRole('status').children).map(el => el.textContent); + +const advance = (ms: number) => + act(() => { + jest.advanceTimersByTime(ms); + }); + +describe('StatusRegion', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it('renders an empty, polite status region that reads only what is added', () => { + render(region([])); + + const status = screen.getByRole('status'); + expect(status).toHaveAttribute('aria-live', 'polite'); + expect(status).toHaveAttribute('aria-atomic', 'false'); + expect(status).not.toHaveAttribute('aria-relevant'); + expect(status).toBeEmptyDOMElement(); + }); + + it('hides itself without any stylesheet', () => { + // No CSS is loaded here, Bulma's included, so the computed style is the + // region's own. + expect(document.styleSheets).toHaveLength(0); + render(region([alpha])); + advance(announceDelay); + + const status = screen.getByRole('status'); + expect(status).not.toHaveAttribute('class'); + // The negative margin keeps the 1px box from adding scrollable overflow + // to the page. jsdom doesn't lay anything out, so this is as close as a + // test here gets to measuring that. + expect(status).toHaveStyle({ + position: 'absolute', + width: '1px', + height: '1px', + margin: '-1px', + padding: '0px', + overflow: 'hidden', + clip: 'rect(0px, 0px, 0px, 0px)', + 'clip-path': 'inset(50%)', + 'white-space': 'nowrap', + }); + expect(getComputedStyle(status).borderTopWidth).toBe('0px'); + expect(status).toHaveTextContent('Alpha'); + }); + + it('writes an announcement a moment after its item appears', () => { + const { rerender } = render(region([])); + + rerender(region([alpha])); + expect(said()).toEqual([]); + + advance(announceDelay - 1); + expect(said()).toEqual([]); + + advance(1); + expect(said()).toEqual(['Alpha']); + }); + + it('writes nothing in the commit that mounts it, then writes into the region it mounted', () => { + render(region([alpha])); + const status = screen.getByRole('status'); + expect(status).toBeEmptyDOMElement(); + + advance(announceDelay); + + expect(screen.getByRole('status')).toBe(status); + expect(said()).toEqual(['Alpha']); + }); + + it('clears an announcement once its lifetime is up', () => { + render(region([alpha])); + advance(announceDelay); + + advance(announcementLifetime - 1); + expect(said()).toEqual(['Alpha']); + + advance(1); + expect(said()).toEqual([]); + }); + + it('clears the whole lifetime in one step of the clock', () => { + // The clear is timed from when the item appears, not from a render after + // the write, so one long step runs it too. + render(region([alpha])); + + advance(announceDelay + announcementLifetime); + + expect(said()).toEqual([]); + }); + + it('keeps an announcement for its whole lifetime after its item goes', () => { + const { rerender } = render(region([alpha, bravo])); + advance(announceDelay); + expect(said()).toEqual(['Alpha', 'Bravo']); + const nodes = Array.from(screen.getByRole('status').children); + + // Alpha goes a moment after it was written, before it's had its time. + advance(50); + rerender(region([bravo])); + expect(said()).toEqual(['Alpha', 'Bravo']); + expect(Array.from(screen.getByRole('status').children)).toEqual(nodes); + + advance(announcementLifetime - 50); + expect(said()).toEqual([]); + }); + + it('writes only the waiting items still on screen when their announcements are due', () => { + const { rerender } = render(region([alpha, bravo])); + rerender(region([bravo])); + + advance(announceDelay); + + expect(said()).toEqual(['Bravo']); + }); + + it('never writes an item that goes before its announcement is due', () => { + const { rerender } = render(region([alpha])); + rerender(region([])); + + advance(announceDelay); + + expect(said()).toEqual([]); + }); + + it('announces each item once, however often it re-renders', () => { + const { rerender } = render(region([alpha])); + advance(announceDelay); + const node = screen.getByRole('status').firstElementChild; + + // A new list with the same item in it, as the store hands over on every + // change, leaves the announcement node as it is. + rerender(region([alpha])); + expect(screen.getByRole('status').firstElementChild).toBe(node); + + advance(announcementLifetime); + rerender(region([alpha])); + advance(announceDelay); + + expect(said()).toEqual([]); + }); + + it('keeps what it said for its whole lifetime while the next items wait, then adds them', () => { + const { rerender } = render(region([alpha, bravo])); + advance(announceDelay); + const written = Array.from(screen.getByRole('status').children); + + // Charlie appears while Alpha and Bravo are still being read. + advance(50); + rerender(region([alpha, bravo, charlie])); + expect(said()).toEqual(['Alpha', 'Bravo']); + + // Writing Charlie adds a node and leaves theirs as they were. + advance(announceDelay); + expect(said()).toEqual(['Alpha', 'Bravo', 'Charlie']); + expect(Array.from(screen.getByRole('status').children).slice(0, 2)).toEqual( + written + ); + + // Each leaves when its own lifetime is up. + advance(announcementLifetime - announceDelay - 50); + expect(said()).toEqual(['Charlie']); + advance(announceDelay + 50); + expect(said()).toEqual([]); + }); + + it('writes items that appear while others wait all together', () => { + const { rerender } = render(region([alpha])); + advance(announceDelay - 1); + + // Joining restarts the wait, so neither is written on the first one's + // schedule. + rerender(region([alpha, bravo])); + advance(announceDelay - 1); + expect(said()).toEqual([]); + + advance(1); + expect(said()).toEqual(['Alpha', 'Bravo']); + }); + + it('skips an item with nothing to say', () => { + const empty: Item = { id: 'e', text: '' }; + const nothing: Item = { id: 'n', text: null }; + const { rerender } = render(region([empty, nothing])); + advance(announceDelay); + expect(said()).toEqual([]); + + rerender(region([empty, nothing, alpha])); + advance(announceDelay); + expect(said()).toEqual(['Alpha']); + }); + + describe('with a timer from the batch before coming due', () => { + // Showing the new items synchronously runs their effect straight away, so + // the effect sets the new batch inside the act below, while the render + // that would cancel the old batch's write waits for the act to end. The + // old timer comes due in that gap. + let showItems: (items: Item[]) => void = () => {}; + const Harness = () => { + const [items, setItems] = useState([alpha]); + showItems = setItems; + return region(items); + }; + const showNow = (items: Item[]) => + // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the render and its effect have to happen ahead of the timer, inside the act + flushSync(() => showItems(items)); + + it("doesn't let a newer batch take down what's written while it waits", () => { + render(); + advance(announceDelay); + + act(() => { + showNow([alpha, bravo]); + jest.advanceTimersByTime(1); + }); + expect(said()).toEqual(['Alpha']); + + advance(announceDelay); + expect(said()).toEqual(['Alpha', 'Bravo']); + }); + + it("doesn't let the old clear empty the new batch", () => { + render(); + advance(announceDelay + announcementLifetime - 1); + expect(said()).toEqual(['Alpha']); + + act(() => { + showNow([alpha, bravo]); + jest.advanceTimersByTime(1); + }); + advance(announceDelay); + + expect(said()).toEqual(['Bravo']); + }); + + it("doesn't let the old write cut the new batch's wait short, or its clear cut the new batch's lifetime", () => { + render(); + advance(announceDelay - 1); + + act(() => { + showNow([alpha, bravo]); + jest.advanceTimersByTime(1); + }); + expect(said()).toEqual([]); + + advance(announceDelay); + expect(said()).toEqual(['Alpha', 'Bravo']); + + // The old write still started a clear, which comes due first and finds + // nothing of its own to take down. + advance(announcementLifetime - announceDelay); + expect(said()).toEqual(['Alpha', 'Bravo']); + advance(announceDelay); + expect(said()).toEqual([]); + }); + }); + + it('renders one region and announces once under StrictMode', () => { + render({region([alpha])}); + advance(announceDelay); + + expect(screen.getAllByRole('status')).toHaveLength(1); + expect(said()).toEqual(['Alpha']); + }); + + it('stops its timers when it unmounts', () => { + // A write still waiting. + const waiting = render(region([alpha])); + expect(jest.getTimerCount()).toBeGreaterThan(0); + waiting.unmount(); + expect(jest.getTimerCount()).toBe(0); + + // A clear still to come, which outlives the batch that started it. + const written = render(region([bravo])); + advance(announceDelay); + expect(jest.getTimerCount()).toBeGreaterThan(0); + written.unmount(); + expect(jest.getTimerCount()).toBe(0); + }); +}); + +describe('spokenText', () => { + const read = (html: string) => { + const element = document.createElement('span'); + element.innerHTML = html; + return spokenText(element); + }; + + it('reads the text, with its whitespace tidied', () => { + expect(read(' Draft\n saved ')).toBe('Draft saved'); + expect(read('Uploaded')).toBe('Uploaded'); + }); + + it.each([ + ['divs', '
Upload complete
3 files
'], + ['paragraphs', '

Upload complete

3 files

'], + ['list items', '
  • Upload complete
  • 3 files
'], + ['a line break', 'Upload complete
3 files'], + ['a heading and text', '

Upload complete

3 files'], + [ + 'table cells', + '
Upload complete3 files
', + ], + ])('keeps the text of %s apart', (_shape, html) => { + expect(read(html)).toBe('Upload complete 3 files'); + }); + + it('leaves out aria-hidden parts', () => { + expect(read(' Saved')).toBe('Saved'); + expect(read('Still read')).toBe( + 'Still read' + ); + }); + + it('leaves out hidden parts and inline display: none', () => { + expect(read('Saved')).toBe('Saved'); + expect(read('Saved debug id 42')).toBe( + 'Saved' + ); + expect(read('Still read')).toBe( + 'Still read' + ); + expect( + read('Saved debug id 42') + ).toBe('Saved'); + }); + + it('reads an element that has no inline style at all', () => { + // An element outside the HTML and SVG namespaces has no `style`. + const element = document.createElement('span'); + const note = document.createElementNS('urn:example:notes', 'note'); + note.textContent = 'kept'; + element.append('Saved, ', note); + + expect(spokenText(element)).toBe('Saved, kept'); + }); + + it('reads the text inside an svg', () => { + expect(read('Chart updated')).toBe('Chart updated'); + }); + + it("reads an element's aria-label in place of what's inside it", () => { + expect(read('💾to drafts')).toBe( + 'Saved to drafts' + ); + expect(read('Kept')).toBe('Kept'); + }); + + it("reads an image's alt", () => { + expect(read('Upload complete')).toBe('Upload complete'); + expect(read('DoneUpload')).toBe('Done Upload'); + expect(read('')).toBe(''); + }); + + it('leaves out comments', () => { + expect(read('Saved')).toBe('Saved'); + }); +}); diff --git a/bulma-ui/src/helpers/statusRegion.tsx b/bulma-ui/src/helpers/statusRegion.tsx new file mode 100644 index 000000000..ce19fef40 --- /dev/null +++ b/bulma-ui/src/helpers/statusRegion.tsx @@ -0,0 +1,357 @@ +import React, { useEffect, useRef, useState } from 'react'; + +/** + * What a status region says for one of a container's items. + */ +interface Announcement { + /** The id of the item it announces. */ + id: string; + /** The text a screen reader reads out. */ + text: string; +} + +/** + * An announcement in the region. + */ +interface WrittenAnnouncement extends Announcement { + /** The batch it was written with, which is what its clear removes. */ + batch: number; +} + +/** + * How long after an item appears its announcement is written, in ms. The wait + * lets a screen reader register a region the container has only just mounted, + * and items shown in quick succession are written, and read out, together. + */ +export const announceDelay = 100; + +/** + * How long an announcement stays in the region once written, in ms. That's + * long enough for a screen reader to pick it up. Clearing it after keeps a + * second copy of the item's text from sitting in the page, where someone + * reading through the page, or a test looking the text up, would find it + * again. + */ +export const announcementLifetime = 1000; + +/** + * What the region says, and what it's about to say. + */ +interface Announcements { + /** + * Changes whenever announcements join the wait, which restarts it. It also + * names the batch they're written with. + */ + key: number; + /** Waiting to be written, in the order their items were shown. */ + waiting: Announcement[]; + /** In the region, in the order they were written. */ + written: WrittenAnnouncement[]; +} + +const noAnnouncements: Announcement[] = []; +const nothingWritten: WrittenAnnouncement[] = []; +const noAnnouncementsYet: Announcements = { + key: 0, + waiting: noAnnouncements, + written: nothingWritten, +}; + +// Hides the region with inline styles rather than a class, so it needs no +// stylesheet, including the helper classes a modular Bulma build can leave +// out. Clipping it, rather than using `display` or `visibility`, keeps it in +// the accessibility tree. The declarations match the `extras-sr-only` mixin, +// plus `clip-path`, which replaces the deprecated `clip`. The negative margin +// pulls the 1px box back inside the page, so it doesn't add scrollable +// overflow. +const visuallyHidden: React.CSSProperties = { + position: 'absolute', + width: '1px', + height: '1px', + padding: 0, + margin: '-1px', + overflow: 'hidden', + clip: 'rect(0, 0, 0, 0)', + clipPath: 'inset(50%)', + whiteSpace: 'nowrap', + border: 0, +}; + +/** + * Works out what a status region says. Each item is announced once. Its + * announcement is written `announceDelay` after it appears, or after the last + * item to join it when several appear in quick succession, alongside whatever + * the region still says. Once written, it stays for `announcementLifetime`, + * whatever is written after it and whether or not its item goes in the + * meantime. An item that goes before its announcement is written isn't + * announced. + * + * Nothing is written in the commit that mounts the region or the item. A + * screen reader reliably announces a polite live region whose content changes + * after the region is already in the page, and not always one that arrives + * with its content. By the time `describe` runs, an item's rendered text can + * be read. + * + * @function useAnnouncements + * @param items - The items to announce, in the order they were shown. + * @param describe - The text to announce for an item, or nothing to skip it. + * It runs once the item is on screen, and it must keep its identity between + * renders (a module-level function or a `useCallback`), or every render + * re-checks the items. + * @returns The announcements to render, in the order they were written. + */ +function useAnnouncements( + items: readonly Item[], + describe: (item: Item) => string | null +): WrittenAnnouncement[] { + // The ids of the items on screen as of the last change, every one of which + // has been looked at for an announcement already. + const onScreenIdsRef = useRef(new Set()); + // Clears that haven't run yet. They outlive the batch that started them, so + // they're only stopped when the region unmounts. + const clearTimersRef = useRef(new Set>()); + const [announcements, setAnnouncements] = useState(noAnnouncementsYet); + + // Runs after the commit that puts an item on screen, which is the first + // point its rendered text can be read. + useEffect(() => { + const announced = onScreenIdsRef.current; + const appeared = items.filter(item => !announced.has(item.id)); + // Items that have gone drop out here too. Ids are never reused, so + // forgetting them can't bring an old item back. + onScreenIdsRef.current = new Set(items.map(item => item.id)); + + const next: Announcement[] = []; + for (const item of appeared) { + const text = describe(item); + if (text) next.push({ id: item.id, text }); + } + if (next.length > 0) { + // eslint-disable-next-line react-hooks/set-state-in-effect -- an item's rendered text can only be read once it's on screen + setAnnouncements(current => ({ + ...current, + key: current.key + 1, + // Announcements still waiting go out with the new ones. What's + // already written stays put. + waiting: [...current.waiting, ...next], + })); + } + }, [items, describe]); + + // The write only touches the batch it was started for: a newer batch can + // be set before the render that cancels this timer. Its clear is started + // by the write itself, so it's timed from the write without waiting on a + // render, and a newer batch arriving doesn't cut short what's written. + const { key } = announcements; + useEffect(() => { + if (key === noAnnouncementsYet.key) return undefined; + const clearTimers = clearTimersRef.current; + const write = setTimeout(() => { + // Whether an item is on screen is decided here, once. An item that + // went before its announcement was due isn't announced, and one that + // goes after keeps its announcement for the rest of its lifetime, when + // the region holds the only copy of its text rather than a second one. + const onScreen = onScreenIdsRef.current; + setAnnouncements(current => + current.key === key + ? { + ...current, + waiting: noAnnouncements, + written: [ + ...current.written, + ...current.waiting + .filter(announcement => onScreen.has(announcement.id)) + .map(announcement => ({ ...announcement, batch: key })), + ], + } + : current + ); + // eslint-disable-next-line @eslint-react/web-api-no-leaked-timeout -- it has to outlive this effect when a newer batch arrives, so the unmount effect below clears it + const clear = setTimeout(() => { + clearTimers.delete(clear); + setAnnouncements(current => { + const written = current.written.filter( + announcement => announcement.batch !== key + ); + return written.length === current.written.length + ? current + : { ...current, written }; + }); + }, announcementLifetime); + clearTimers.add(clear); + }, announceDelay); + return () => clearTimeout(write); + }, [key]); + + useEffect(() => { + const clearTimers = clearTimersRef.current; + return () => { + clearTimers.forEach(clearTimeout); + clearTimers.clear(); + }; + }, []); + + return announcements.written; +} + +/** + * Reads an element out roughly the way a screen reader would: its text, with + * an element's `aria-label`, or an image's `alt`, standing in for what's + * inside it, a break between block-level elements, and parts that are + * `aria-hidden`, `hidden` or inline-styled `display: none` left out. It isn't + * the full accessible name computation, so `aria-labelledby`, CSS-generated + * content, content hidden by a stylesheet and other ways of naming or hiding + * content aren't followed. + * + * @function spokenText + * @param element - The element to read. + * @returns Its text, with runs of whitespace collapsed and the ends trimmed. + */ +export function spokenText(element: Element): string { + return readAloud(element).replace(/\s+/g, ' ').trim(); +} + +// Elements a browser displays as blocks by default, and `br`. A screen reader +// pauses between them, so their text shouldn't run into the text beside them. +// They're known by tag rather than by computed `display`, which would depend +// on a stylesheet and on layout. +const blockLevelTags = new Set([ + 'ADDRESS', + 'ARTICLE', + 'ASIDE', + 'BLOCKQUOTE', + 'BR', + 'CAPTION', + 'DD', + 'DETAILS', + 'DIALOG', + 'DIV', + 'DL', + 'DT', + 'FIELDSET', + 'FIGCAPTION', + 'FIGURE', + 'FOOTER', + 'FORM', + 'H1', + 'H2', + 'H3', + 'H4', + 'H5', + 'H6', + 'HEADER', + 'HGROUP', + 'HR', + 'LEGEND', + 'LI', + 'MAIN', + 'MENU', + 'NAV', + 'OL', + 'P', + 'PRE', + 'SEARCH', + 'SECTION', + 'SUMMARY', + 'TABLE', + 'TBODY', + 'TD', + 'TFOOT', + 'TH', + 'THEAD', + 'TR', + 'UL', +]); + +/** + * Whether an element is left out of what a screen reader reads. + * + * @function isHidden + * @param element - The element to check. + * @returns True for `aria-hidden="true"`, the `hidden` attribute, and an + * inline `display: none`, on an HTML, SVG or any other element with an + * inline style. + */ +const isHidden = (element: Element): boolean => + element.getAttribute('aria-hidden') === 'true' || + element.hasAttribute('hidden') || + (element as Partial).style?.display === 'none'; + +/** + * The text `spokenText` reads for an element, before its whitespace is + * tidied. + * + * @function readAloud + * @param element - The element to read. + * @returns Its text. + */ +function readAloud(element: Element): string { + if (isHidden(element)) return ''; + const name = + element.getAttribute('aria-label') || + (element.tagName === 'IMG' ? element.getAttribute('alt') : null); + const text = + name || + Array.from(element.childNodes, child => { + if (child instanceof Element) return readAloud(child); + return child.nodeType === Node.TEXT_NODE ? child.textContent : ''; + }).join(''); + // A name stands in for the element's content, and a block's content stands + // apart from what's around it, so both are padded to keep them from running + // into the neighboring text. An inline run, like `Up` then + // `loaded`, still reads as one word. + return name || blockLevelTags.has(element.tagName) ? ` ${text} ` : text; +} + +/** + * Props for StatusRegion. + */ +export interface StatusRegionProps { + /** The items to announce politely, in the order they were shown. */ + items: readonly Item[]; + /** + * The text to announce for an item, or nothing to skip it, as + * `useAnnouncements` takes it. + */ + describe: (item: Item) => string | null; +} + +/** + * A visually hidden, polite `status` live region that a programmatic + * container announces its items through. The container renders it from the + * moment it mounts, whether or not it has anything to show, so the region is + * already in the page when an announcement is written into it. + * + * The announcements are this component's own state, so writing and clearing + * them re-renders the region and leaves the container's items alone. Each one + * is its own keyed node, so a re-render that leaves the announcements alone + * leaves the region's content alone too, and nothing is read out twice. + * + * @function StatusRegion + * @param props - The items to announce, and the text to announce for each. + * @returns The region. + */ +export function StatusRegion({ + items, + describe, +}: StatusRegionProps): React.ReactElement { + const announcements = useAnnouncements(items, describe); + + // `role="status"` makes a region atomic unless it says otherwise, which + // reads the whole region on every change. Each announcement is its own + // node, and only additions are relevant by default, so with atomic off a + // screen reader reads just what was written, and removing one announcement + // doesn't read out the ones still there. + return ( +
+ {announcements.map(announcement => ( +
{announcement.text}
+ ))} +
+ ); +} diff --git a/docs/docs/api/elements/notification.md b/docs/docs/api/elements/notification.md index ab89407fa..eab485de9 100644 --- a/docs/docs/api/elements/notification.md +++ b/docs/docs/api/elements/notification.md @@ -187,7 +187,8 @@ Each helper takes the message first and any other options second. - **Delete button:** Includes `aria-label="Close notification"` for screen readers. - **Keyboard:** The delete button is focusable and can be activated by keyboard. - **Content:** Use semantic HTML within the notification for best accessibility. -- **Announcements:** A notification shown through `notification` announces its message: as an alert for `danger` and `warning`, and as a status otherwise. +- **Announcements:** A notification shown through `notification` announces its message. `danger` and `warning` announce themselves: the message carries `role="alert"` with `aria-live="assertive"`, which screen readers reliably announce even though it arrives with its text. The rest are announced politely through a visually hidden `role="status"` region that `NotificationContainer` keeps in the page from the moment it mounts, even with nothing showing, because a polite region that arrives already holding its text often isn't announced. A moment after one of those notifications appears, its message is written into the region, then cleared again shortly after. +- **Testing:** A polite notification's message doesn't carry `role="status"`, so `getByRole('status')` finds the container's region rather than the notification. Query the message text or `.notification` instead. A count or text [`Badge`](../components/badge.md) is a `role="status"` node too, so with both on the page `getByRole('status')` matches more than one: find the badge by its accessible name, or use `getAllByRole`. While a message is in the region, the page also holds a second copy of its text, so a test that advances the clock past the announcement and then looks the message up by text can find both, and can still find the region's copy for a moment after the notification closes. Scope that query to the notification, for example with `within`. :::tip Always provide clear, actionable text inside notifications.