Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/select-panel-announcement-debounce.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/react': patch
---

SelectPanel: Debounce screen reader announcements for list updates so rapid keystrokes while filtering don't queue up duplicate messages
258 changes: 257 additions & 1 deletion packages/react/src/FilteredActionList/useAnnouncements.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {act, renderHook} from '@testing-library/react'
import {announce} from '@primer/live-region-element'
import {beforeEach, describe, expect, it, vi} from 'vitest'
import {StrictMode} from 'react'
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
import {useAnnouncements} from './useAnnouncements'

vi.mock('@primer/live-region-element', () => ({
Expand All @@ -12,6 +13,12 @@ describe('useAnnouncements', () => {
vi.mocked(announce).mockClear()
})

afterEach(() => {
// Tests using fake timers restore real timers themselves, but make sure
// a failure can never leak fake timers into the next test.
vi.useRealTimers()
})

it('includes the input label in the initial focus announcement', async () => {
const input = document.createElement('input')
input.setAttribute('aria-label', 'Filter fields')
Expand Down Expand Up @@ -156,4 +163,253 @@ describe('useAnnouncements', () => {

await expect.poll(() => announce).toHaveBeenCalledWith("Nothing found. There's nothing here.", {delayMs: 500})
})

it('debounces list update announcements while the filter value changes rapidly', () => {
const {rerender} = renderHook(
({filterValue, items}) =>
useAnnouncements(
items,
{current: null},
{current: null},
true,
false,
undefined,
'roving-tabindex',
filterValue,
),
{
initialProps: {
filterValue: '',
items: [{id: 'start-date', text: 'Start date', selected: false}],
},
},
)

vi.useFakeTimers()

// First update schedules an announcement for one item; it must not
// fire before the 250ms debounce window elapses.
rerender({
filterValue: 's',
items: [{id: 'start-date', text: 'Start date', selected: false}],
})
act(() => {
vi.advanceTimersByTime(100)
})
expect(announce).not.toHaveBeenCalled()

// A second update inside the window replaces the pending
// announcement; the first text must never be announced.
rerender({
filterValue: 'st',
items: [
{id: 'start-date', text: 'Start date', selected: false},
{id: 'end-date', text: 'End date', selected: false},
],
})
act(() => {
vi.advanceTimersByTime(100)
})
expect(announce).not.toHaveBeenCalled()

// A third update replaces it again; advancing past the deadline from
// the last update fires exactly once, with the latest text.
rerender({
filterValue: 'sta',
items: [
{id: 'start-date', text: 'Start date', selected: false},
{id: 'end-date', text: 'End date', selected: false},
{id: 'due-date', text: 'Due date', selected: false},
],
})
act(() => {
vi.advanceTimersByTime(200)
})
expect(announce).not.toHaveBeenCalled()
act(() => {
vi.advanceTimersByTime(100)
})
expect(announce).toHaveBeenCalledTimes(1)
expect(announce).toHaveBeenCalledWith('3 items available, 0 selected.', {delayMs: 500, from: undefined})

vi.useRealTimers()
})

it('still announces list updates after StrictMode replays effects on mount', () => {
vi.useFakeTimers()
const {rerender} = renderHook(
({filterValue}) =>
useAnnouncements(
[{id: 'start-date', text: 'Start date', selected: false}],
{current: null},
{current: null},
true,
false,
undefined,
'roving-tabindex',
filterValue,
),
{
initialProps: {filterValue: ''},
wrapper: ({children}: {children: React.ReactNode}) => <StrictMode>{children}</StrictMode>,
},
)

// With the previous memoized debouncer, StrictMode's mount cleanup
// permanently disabled it, so this update was never announced.
rerender({filterValue: 's'})
act(() => {
vi.advanceTimersByTime(300)
})
expect(announce).toHaveBeenCalledTimes(1)
expect(announce).toHaveBeenCalledWith('1 item available, 0 selected.', {delayMs: 500, from: undefined})

vi.useRealTimers()
})

it.each([100, 250])('cancels list-update delivery when unmounted after %i ms', async elapsed => {
const {announce: announceToLiveRegion} = await vi.importActual<{announce: typeof announce}>(
'@primer/live-region-element',
)
const liveRegion = document.createElement('live-region')
document.body.append(liveRegion)
vi.mocked(announce).mockImplementation(announceToLiveRegion)
vi.useFakeTimers()

try {
const {rerender, unmount} = renderHook(
({filterValue}) =>
useAnnouncements(
[{text: 'Start date'}],
{current: null},
{current: null},
true,
false,
undefined,
'roving-tabindex',
filterValue,
),
{initialProps: {filterValue: ''}},
)

rerender({filterValue: 's'})
await act(() => vi.advanceTimersByTimeAsync(elapsed))
expect(announce).toHaveBeenCalledTimes(elapsed === 250 ? 1 : 0)
unmount()
await act(() => vi.advanceTimersByTimeAsync(1000))
expect(liveRegion.getMessage('polite')).toBe('')
} finally {
vi.mocked(announce).mockReset()
liveRegion.remove()
}
})

it('cancels a queued list update when announcements are disabled without a content change', () => {
vi.useFakeTimers()
const {rerender} = renderHook(
({enabled, filterValue}) =>
useAnnouncements(
[{text: 'Start date'}],
{current: null},
{current: null},
enabled,
false,
undefined,
'roving-tabindex',
filterValue,
),
{initialProps: {enabled: true, filterValue: ''}},
)

rerender({enabled: true, filterValue: 's'})
act(() => vi.advanceTimersByTime(100))
rerender({enabled: false, filterValue: 's'})
act(() => vi.advanceTimersByTime(1000))
expect(announce).not.toHaveBeenCalled()

rerender({enabled: true, filterValue: 'st'})
act(() => vi.advanceTimersByTime(250))
expect(announce).toHaveBeenCalledTimes(1)
})

it('announces current focus once after the final active-descendant list update', () => {
vi.useFakeTimers({toFake: ['requestAnimationFrame', 'cancelAnimationFrame', 'setTimeout', 'clearTimeout']})
const list = document.createElement('ul')
const start = document.createElement('li')
start.setAttribute('role', 'option')
start.setAttribute('data-is-active-descendant', 'true')
start.textContent = 'Start date'
const end = document.createElement('li')
end.setAttribute('role', 'option')
end.textContent = 'End date'
list.append(start, end)

const {rerender} = renderHook(
({filterValue}) =>
useAnnouncements(
[{text: 'Start date'}, {text: 'End date', selected: true}],
{current: list},
{current: null},
true,
false,
undefined,
'active-descendant',
filterValue,
),
{initialProps: {filterValue: ''}},
)

rerender({filterValue: 's'})
act(() => vi.advanceTimersToNextFrame())
act(() => vi.advanceTimersByTime(100))
rerender({filterValue: 'st'})
rerender({filterValue: 'sta'})
act(() => vi.advanceTimersToNextFrame())

start.removeAttribute('data-is-active-descendant')
end.setAttribute('data-is-active-descendant', 'true')
act(() => vi.advanceTimersByTime(249))
expect(announce).not.toHaveBeenCalled()
act(() => vi.advanceTimersByTime(1))
expect(announce).toHaveBeenCalledExactlyOnceWith('List updated, Focused item: End date, selected, 2 of 2', {
delayMs: 500,
from: undefined,
})
})

it('cancels a queued empty-result announcement when a new query starts loading', () => {
vi.useFakeTimers()
const message = {title: 'Nothing found', description: "There's nothing here."}
const {rerender} = renderHook(
({loading, filterValue}) =>
useAnnouncements(
[],
{current: null},
{current: null},
true,
loading,
message,
'active-descendant',
filterValue,
),
{initialProps: {loading: false, filterValue: ''}},
)

// Queue the empty-result announcement.
rerender({loading: false, filterValue: 'zero'})
act(() => {
vi.advanceTimersByTime(100)
})
expect(announce).not.toHaveBeenCalled()

// A new query starts loading before the window elapses; the stale
// "Nothing found" message must not be announced.
rerender({loading: true, filterValue: 'zero'})
act(() => {
vi.advanceTimersByTime(300)
})
expect(announce).not.toHaveBeenCalled()

vi.useRealTimers()
})
})
76 changes: 52 additions & 24 deletions packages/react/src/FilteredActionList/useAnnouncements.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {ItemInput} from '../SelectPanel'

// we add a delay so that it does not interrupt default screen reader announcement and queues after it
const delayMs = 500
const listUpdateDelayMs = 250

const getInputLabel = (input: HTMLInputElement | null) => {
if (!input) return
Expand Down Expand Up @@ -93,6 +94,14 @@ export const useAnnouncements = (
[enabled],
)

const pendingListAnnouncement = useRef<(() => void) | null>(null)
const cancelPendingListAnnouncement = useCallback(() => {
pendingListAnnouncement.current?.()
pendingListAnnouncement.current = null
}, [])

useEffect(() => cancelPendingListAnnouncement, [cancelPendingListAnnouncement, enabled, usingRovingTabindex])

const onInputFocus = useCallback(() => {
if (usingRovingTabindex) {
const announcementText = `${items.length} item${items.length > 1 ? 's' : ''} available, ${selectedItems} selected.`
Expand Down Expand Up @@ -129,45 +138,64 @@ export const useAnnouncements = (
if (previousAnnouncementState.current === announcementState) return
previousAnnouncementState.current = announcementState

cancelPendingListAnnouncement()
// eslint-disable-next-line react-you-might-not-need-an-effect/no-event-handler -- Updates can come from props, independently of input events.
if (!enabled) return

liveRegion?.clear() // clear previous announcements

let frameId: number | undefined
let timeoutId: number | undefined
let delivery: ReturnType<typeof announce>
pendingListAnnouncement.current = () => {
if (frameId !== undefined) window.cancelAnimationFrame(frameId)
if (timeoutId !== undefined) window.clearTimeout(timeoutId)
delivery?.cancel()
}

const schedule = (getText: () => string | undefined, options: Parameters<typeof liveRegionAnnounce>[1]) => {
timeoutId = window.setTimeout(() => {
const text = getText()
if (text !== undefined) delivery = announce(text, options)
}, listUpdateDelayMs)
}

// eslint-disable-next-line react-you-might-not-need-an-effect/no-event-handler
if (items.length === 0 && !loading) {
announce(`${message?.title}. ${message?.description}`, {delayMs})
schedule(() => `${message?.title}. ${message?.description}`, {delayMs})
return
}

const options = {delayMs, from: liveRegion ?? undefined}
if (usingRovingTabindex) {
const announcementText = `${items.length} item${items.length > 1 ? 's' : ''} available, ${selectedItems} selected.`

announce(announcementText, {
delayMs,
from: liveRegion ? liveRegion : undefined,
})
schedule(
() => `${items.length} item${items.length > 1 ? 's' : ''} available, ${selectedItems} selected.`,
options,
)
} else {
// give @primer/behaviors a moment to update active-descendant
window.requestAnimationFrame(() => {
const activeItem = getItemWithActiveDescendant(listContainerRef, items)
if (!activeItem) return
const {index, text, selected} = activeItem

const announcementText = [
`List updated`,
`Focused item: ${text}`,
`${selected ? 'selected' : 'not selected'}`,
`${index + 1} of ${items.length}`,
].join(', ')

announce(announcementText, {
delayMs,
from: liveRegion ? liveRegion : undefined, // announce will create a liveRegion if it doesn't find one
})
// Give @primer/behaviors a frame to update active-descendant, then
// read focus when the delay ends so intervening navigation is included.
frameId = window.requestAnimationFrame(() => {
schedule(() => {
const activeItem = getItemWithActiveDescendant(listContainerRef, items)
if (!activeItem) return
const {index, text, selected} = activeItem

return [
'List updated',
`Focused item: ${text}`,
selected ? 'selected' : 'not selected',
`${index + 1} of ${items.length}`,
].join(', ')
}, options)
})
}
},
[
announce,
announcementState,
cancelPendingListAnnouncement,
enabled,
items,
listContainerRef,
liveRegion,
Expand Down
Loading