From 0fa24b21be4daa470ab16286178f89c76751812a Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Tue, 17 Sep 2024 15:00:24 +0200 Subject: [PATCH] add liveRegion.clear --- .../src/FilteredActionList/useAnnouncements.tsx | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/react/src/FilteredActionList/useAnnouncements.tsx b/packages/react/src/FilteredActionList/useAnnouncements.tsx index 597f43b779a..fc6a121a575 100644 --- a/packages/react/src/FilteredActionList/useAnnouncements.tsx +++ b/packages/react/src/FilteredActionList/useAnnouncements.tsx @@ -1,7 +1,7 @@ // Announcements for FilteredActionList (and SelectPanel) based // on https://github.com/github/multi-select-user-testing -import {announce} from '@primer/live-region-element' +import {LiveRegionElement, announce} from '@primer/live-region-element' import {useEffect, useRef} from 'react' import type {FilteredActionListProps} from './FilteredActionListEntry' @@ -41,6 +41,8 @@ export const useAnnouncements = ( listContainerRef: React.RefObject, inputRef: React.RefObject, ) => { + const liveRegion = document.querySelector('live-region') as LiveRegionElement + useEffect( function announceInitialFocus() { const focusHandler = () => { @@ -56,7 +58,7 @@ export const useAnnouncements = ( `${selected ? 'selected' : 'not selected'}`, `${index + 1} of ${items.length}`, ].join(', ') - announce(announcementText, {delayMs}) + announce(announcementText, {delayMs, from: liveRegion}) }) } @@ -64,7 +66,7 @@ export const useAnnouncements = ( inputElement?.addEventListener('focus', focusHandler) return () => inputElement?.removeEventListener('focus', focusHandler) }, - [listContainerRef, inputRef, items], + [listContainerRef, inputRef, items, liveRegion], ) const isFirstRender = useFirstRender() @@ -72,6 +74,8 @@ export const useAnnouncements = ( function announceListUpdates() { if (isFirstRender) return // ignore on first render as announceInitialFocus will also announce + liveRegion.clear() // clear previous announcements + if (items.length === 0) { announce('No matching items.', {delayMs}) return @@ -89,9 +93,9 @@ export const useAnnouncements = ( `${selected ? 'selected' : 'not selected'}`, `${index + 1} of ${items.length}`, ].join(', ') - announce(announcementText, {delayMs}) + announce(announcementText, {delayMs, from: liveRegion}) }) }, - [listContainerRef, inputRef, items, isFirstRender], + [listContainerRef, inputRef, items, isFirstRender, liveRegion], ) }