Skip to content

Commit

Permalink
don't assume live region exists
Browse files Browse the repository at this point in the history
  • Loading branch information
siddharthkp committed Sep 19, 2024
1 parent 33e8df0 commit c1aaac8
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions packages/react/src/FilteredActionList/useAnnouncements.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const useAnnouncements = (
listContainerRef: React.RefObject<HTMLUListElement>,
inputRef: React.RefObject<HTMLInputElement>,
) => {
const liveRegion = document.querySelector('live-region') as LiveRegionElement
const liveRegion = document.querySelector('live-region')

useEffect(
function announceInitialFocus() {
Expand All @@ -59,7 +59,10 @@ export const useAnnouncements = (
`${selected ? 'selected' : 'not selected'}`,
`${index + 1} of ${items.length}`,
].join(', ')
announce(announcementText, {delayMs, from: liveRegion})
announce(announcementText, {
delayMs,
from: liveRegion ? liveRegion : undefined, // announce will create a liveRegion if it doesn't find one
})
})
}

Expand All @@ -75,7 +78,7 @@ export const useAnnouncements = (
function announceListUpdates() {
if (isFirstRender) return // ignore on first render as announceInitialFocus will also announce

liveRegion.clear() // clear previous announcements
liveRegion?.clear() // clear previous announcements

if (items.length === 0) {
announce('No matching items.', {delayMs})
Expand All @@ -94,9 +97,13 @@ export const useAnnouncements = (
`${selected ? 'selected' : 'not selected'}`,
`${index + 1} of ${items.length}`,
].join(', ')
announce(announcementText, {delayMs, from: liveRegion})

announce(announcementText, {
delayMs,
from: liveRegion ? liveRegion : undefined, // announce will create a liveRegion if it doesn't find one
})
})
},
[listContainerRef, inputRef, items, isFirstRender, liveRegion],
[isFirstRender, items, listContainerRef, liveRegion],
)
}

0 comments on commit c1aaac8

Please sign in to comment.