Skip to content

Commit 7c1c90b

Browse files
DataTable: refine selection announcement state
1 parent c36e341 commit 7c1c90b

3 files changed

Lines changed: 79 additions & 21 deletions

File tree

‎packages/react/src/DataTable/DataTable.docs.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@
155155
{
156156
"name": "getSelectionAnnouncement",
157157
"type": "(context: DataTableSelectionAnnouncementContext) => string",
158-
"description": "Localize the live announcement after the selected row count changes. Receives selectedCount and whether bulk actions are available."
158+
"description": "Localize the live announcement after the selected row count changes. Receives selectedCount and whether the active bulk-action renderer returned content."
159159
},
160160
{
161161
"name": "bulkActionsProps",

‎packages/react/src/DataTable/DataTable.tsx‎

Lines changed: 40 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {useEffect, useId, useRef, type ReactElement, type ReactNode, type RefObject} from 'react'
1+
import {Children, useEffect, useId, useRef, type ReactElement, type ReactNode, type RefObject} from 'react'
22
import type {Column} from './column'
33
import {useTable} from './useTable'
44
import type {SortDirection} from './sorting'
@@ -237,6 +237,14 @@ function DataTableImplementation<Data extends UniqueRow>({
237237
const {headers, bodies, actions, selection, gridTemplateColumns} = table
238238
const hasBulkActions = Boolean(rowSelection && renderBulkActions)
239239
const bulkActionsActive = hasBulkActions && selection.selectedCount > 0
240+
const renderedBulkActions = bulkActionsActive
241+
? renderBulkActions?.({
242+
selectedRows: new Set(selection.selectedRows),
243+
selectedCount: selection.selectedCount,
244+
clearSelection: actions.clearSelection,
245+
})
246+
: null
247+
const bulkActionsAvailable = Children.toArray(renderedBulkActions).length > 0
240248

241249
const renderRow = (row: (typeof bodies)[number]['rows'][number]) => (
242250
<TableRow key={`${typeof row.selectionId}:${row.selectionId}`}>
@@ -269,35 +277,56 @@ function DataTableImplementation<Data extends UniqueRow>({
269277
const selectionAnnouncement = rowSelection
270278
? getSelectionAnnouncement({
271279
selectedCount: selection.selectedCount,
272-
bulkActionsAvailable: hasBulkActions,
280+
bulkActionsAvailable,
273281
})
274282
: null
275283
const selectedCountForAnnouncement = rowSelection ? selection.selectedCount : null
276284
const previousSelectedCount = useRef(selectedCountForAnnouncement)
285+
const previousSelectionAnnouncement = useRef<string | null>(null)
286+
const pendingSelectionAnnouncement = useRef<ReturnType<typeof announce> | null>(null)
277287
useEffect(() => {
278288
const previous = previousSelectedCount.current
279289
previousSelectedCount.current = selectedCountForAnnouncement
280-
if (
281-
previous === null ||
282-
selectedCountForAnnouncement === null ||
283-
previous === selectedCountForAnnouncement ||
284-
selectionAnnouncement === null
285-
) {
290+
// eslint-disable-next-line react-you-might-not-need-an-effect/no-event-handler
291+
if (selectedCountForAnnouncement === null) {
292+
pendingSelectionAnnouncement.current?.cancel()
293+
pendingSelectionAnnouncement.current = null
294+
previousSelectionAnnouncement.current = null
295+
return
296+
}
297+
// eslint-disable-next-line react-you-might-not-need-an-effect/no-event-handler
298+
if (previous === null || previous === selectedCountForAnnouncement || selectionAnnouncement === null) {
286299
return
287300
}
288301

289302
const table = tableRef.current
290303
if (!table || !isVisible(table)) {
304+
pendingSelectionAnnouncement.current?.cancel()
305+
pendingSelectionAnnouncement.current = null
306+
previousSelectionAnnouncement.current = null
291307
return
292308
}
293309

294-
const announcement = announce(selectionAnnouncement, {
310+
// eslint-disable-next-line react-you-might-not-need-an-effect/no-event-handler
311+
if (previousSelectionAnnouncement.current === selectionAnnouncement) {
312+
return
313+
}
314+
315+
pendingSelectionAnnouncement.current?.cancel()
316+
previousSelectionAnnouncement.current = selectionAnnouncement
317+
318+
pendingSelectionAnnouncement.current = announce(selectionAnnouncement, {
295319
politeness: 'polite',
296320
delayMs: 150,
297321
from: table,
298322
})
299-
return () => announcement.cancel()
300323
}, [selectedCountForAnnouncement, selectionAnnouncement])
324+
useEffect(
325+
() => () => {
326+
pendingSelectionAnnouncement.current?.cancel()
327+
},
328+
[],
329+
)
301330

302331
return (
303332
<Table
@@ -405,13 +434,7 @@ function DataTableImplementation<Data extends UniqueRow>({
405434
}
406435
}}
407436
>
408-
{bulkActionsActive
409-
? renderBulkActions?.({
410-
selectedRows: new Set(selection.selectedRows),
411-
selectedCount: selection.selectedCount,
412-
clearSelection: actions.clearSelection,
413-
})
414-
: null}
437+
{renderedBulkActions}
415438
</TableBulkActions>
416439
</TableSelectionAnnouncementContext.Provider>
417440
</VisuallyHidden>

‎packages/react/src/DataTable/__tests__/DataTableSelection.test.tsx‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -771,9 +771,11 @@ describe('DataTable selection announcements', () => {
771771
bulkActionsAvailable: withBulkActions,
772772
})
773773
await browserUserEvent.click(alpha)
774-
await expect
775-
.poll(() => getLiveRegion().getMessage('polite'))
776-
.toBe(`0 chosen; bulk actions: ${withBulkActions ? 'yes' : 'no'}`)
774+
await expect.poll(() => getLiveRegion().getMessage('polite')).toBe('0 chosen; bulk actions: no')
775+
expect(getSelectionAnnouncement).toHaveBeenLastCalledWith({
776+
selectedCount: 0,
777+
bulkActionsAvailable: false,
778+
})
777779
})
778780
})
779781

@@ -794,6 +796,39 @@ describe('DataTable selection announcements', () => {
794796
.toBe('1 row selected, additional bulk actions available')
795797
})
796798

799+
it('does not repeat the same custom announcement for different counts', async () => {
800+
vi.useFakeTimers()
801+
const announce = vi.spyOn(getLiveRegion(), 'announce')
802+
const example = (ids: Array<number>) => (
803+
<DataTable
804+
data={data}
805+
columns={columns}
806+
rowSelection
807+
selectedRows={new Set(ids)}
808+
getSelectionAnnouncement={() => 'Selection changed'}
809+
/>
810+
)
811+
const {rerender} = render(example([]))
812+
rerender(example([1]))
813+
await act(async () => vi.advanceTimersByTime(100))
814+
expect(getLiveRegion().getMessage('polite')).toBe('')
815+
expect(announce).toHaveBeenCalledTimes(1)
816+
rerender(example([1, 2]))
817+
await act(async () => vi.advanceTimersByTime(49))
818+
expect(getLiveRegion().getMessage('polite')).toBe('')
819+
await act(async () => vi.advanceTimersByTime(1))
820+
expect(getLiveRegion().getMessage('polite')).toBe('Selection changed')
821+
expect(announce).toHaveBeenCalledTimes(1)
822+
})
823+
824+
it('reports bulk actions only when the renderer returns content', async () => {
825+
const renderBulkActions = vi.fn(() => null)
826+
render(<DataTable data={data} columns={columns} rowSelection renderBulkActions={renderBulkActions} />)
827+
await browserUserEvent.click(page.getByRole('checkbox', {name: 'Select Alpha', exact: true}))
828+
await expect.poll(() => getLiveRegion().getMessage('polite')).toBe('1 row selected')
829+
expect(renderBulkActions).toHaveBeenCalledTimes(1)
830+
})
831+
797832
it('keeps selection silent when enabled and does not repeat it when adding a toolbar', async () => {
798833
vi.useFakeTimers()
799834
const announce = vi.spyOn(getLiveRegion(), 'announce')

0 commit comments

Comments
 (0)