/*
* Copyright 2022 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {
act,
fireEvent,
installPointerEvent,
mockClickDefault,
pointerMap,
render,
setupIntersectionObserverMock,
triggerLongPress,
within
} from '@react-spectrum/test-utils-internal';
import {Button} from '../src/Button';
import {
Cell,
Column,
ColumnResizer,
ResizableTableContainer,
Row,
Table,
TableBody,
TableFooter,
TableHeader,
TableLoadMoreItem,
useTableOptions
} from '../src/Table';
import {Checkbox, CheckboxButton, CheckboxField} from '../src/Checkbox';
import {Collection} from 'react-aria/Collection';
import {composeStories} from '@storybook/react';
import {DataTransfer, DragEvent} from 'react-aria/test/dnd/mocks';
import {Dialog, DialogTrigger} from '../src/Dialog';
import {DropIndicator, useDragAndDrop} from '../src/useDragAndDrop';
import {Label} from '../src/Label';
import {Modal} from '../src/Modal';
import React, {useMemo, useState} from 'react';
import {resizingTests} from 'react-aria/test/table/tableResizingTests.tsx';
import {setInteractionModality} from 'react-aria/private/interactions/useFocusVisible';
import * as stories from '../stories/Table.stories';
import {TableLayout} from '../src/TableLayout';
import {Tag, TagGroup, TagList} from '../src/TagGroup';
import {User} from '@react-aria/test-utils';
import userEvent from '@testing-library/user-event';
import {Virtualizer} from '../src/Virtualizer';
let {
DndTableExample,
RenderEmptyStateStory: EmptyLoadingTable,
TableLoadingBodyWrapperStory: LoadingMoreTable,
TableCellColSpanWithVariousSpansExample: TableCellColSpan,
TableWithSuspense
} = composeStories(stories);
const mockCollectionUpdate = jest.fn();
jest.mock('react', () => {
const actual = jest.requireActual('react');
const useSyncExternalStore = (subscribe, ...args) => {
const fn = actual.useCallback(
onStoreChange => {
subscribe(() => {
mockCollectionUpdate();
onStoreChange();
});
},
[subscribe]
);
return actual.useSyncExternalStore(fn, ...args);
};
return actual.use ? {...actual, useSyncExternalStore} : actual;
});
function MyColumn(props) {
return (
{({allowsSorting, sortDirection}) => (
<>
{props.children}
{allowsSorting && (
{sortDirection === 'ascending' ? '▲' : '▼'}
)}
{props.allowsResizing && }
>
)}
);
}
function MyTableHeader({columns, children, ...otherProps}) {
let {selectionBehavior, selectionMode, allowsDragging} = useTableOptions();
return (
{allowsDragging && }
{selectionBehavior === 'toggle' && (
{selectionMode === 'multiple' && }
)}
{children}
);
}
function MyRow({id, columns, children, checkboxComponent, ...otherProps}) {
let {selectionBehavior, allowsDragging} = useTableOptions();
return (
{allowsDragging && (
)}
{selectionBehavior === 'toggle' && (
)}
{children}
);
}
function MyCheckbox({comp}) {
if (comp === 'CheckboxField') {
return (
);
}
return (
{({isIndeterminate}) => (
);
let items = getAllByRole('row');
expect(items[2]).toHaveAttribute('aria-disabled', 'true');
await user.tab();
expect(document.activeElement).toBe(items[1]);
await user.keyboard('{ArrowDown}');
expect(document.activeElement).toBe(items[3]);
});
it('should support onAction on items', async () => {
let onAction = jest.fn();
let {getByRole} = render(
FooBarBazFoo 1Bar 1Baz 1Foo 2Bar 2Baz 2
);
let tableTester = testUtilUser.createTester('Table', {root: getByRole('grid')});
await tableTester.triggerRowAction({row: 0});
expect(onAction).toHaveBeenCalled();
});
it('should support sorting', async () => {
let onSortChange = jest.fn();
let {getByRole} = renderTable({
tableProps: {sortDescriptor: {column: 'name', direction: 'ascending'}, onSortChange},
columnProps: {allowsSorting: true}
});
let tableTester = testUtilUser.createTester('Table', {root: getByRole('grid')});
let columns = tableTester.getColumns();
expect(columns[0]).toHaveAttribute('aria-sort', 'ascending');
expect(columns[0]).toHaveTextContent('▲');
expect(columns[1]).toHaveAttribute('aria-sort', 'none');
expect(columns[1]).not.toHaveTextContent('▲');
expect(columns[2]).toHaveAttribute('aria-sort', 'none');
expect(columns[2]).not.toHaveTextContent('▲');
await tableTester.toggleSort({column: 0});
expect(onSortChange).toHaveBeenCalledTimes(1);
expect(onSortChange).toHaveBeenCalledWith({column: 'name', direction: 'descending'});
});
it('should support empty state', () => {
let {getAllByRole, getByRole} = render(
NameTypeDate Modified 'No results'}>{[]}
);
let body = getAllByRole('rowgroup')[1];
expect(body).toHaveAttribute('data-empty', 'true');
let cell = getByRole('rowheader');
expect(cell).toHaveTextContent('No results');
});
it('supports removing rows', async () => {
let {rerender, getByRole} = render();
let tableTester = testUtilUser.createTester('Table', {root: getByRole('grid')});
await user.tab();
await user.keyboard('{ArrowDown}');
await user.keyboard('{ArrowRight}');
let gridRows = tableTester.getRows();
expect(gridRows).toHaveLength(4);
let cell = within(gridRows[1]).getAllByRole('rowheader')[0];
expect(cell).toHaveTextContent('Program Files');
expect(document.activeElement).toBe(cell);
rerender();
gridRows = tableTester.getRows();
expect(gridRows).toHaveLength(3);
cell = within(gridRows[1]).getAllByRole('rowheader')[0];
expect(cell).toHaveTextContent('bootmgr');
expect(document.activeElement).toBe(cell);
});
it('does not hang restoring focus when no focusable row remains', async () => {
let {rerender, getByRole} = render();
let tableTester = testUtilUser.createTester('Table', {root: getByRole('grid')});
await user.tab();
await user.keyboard('{ArrowDown}');
await user.keyboard('{ArrowRight}');
let gridRows = tableTester.getRows();
let cell = within(gridRows[1]).getAllByRole('rowheader')[0];
expect(cell).toHaveTextContent('Program Files');
expect(document.activeElement).toBe(cell);
// Remove the focused row and disable every remaining row. Restoring focus
// previously infinite-looped (the search bounced between the focused index
// and the end and never terminated when no focusable row existed).
let remaining = [rows[0], ...rows.slice(2)];
rerender(
r.id)}}
tableBodyProps={{items: remaining}}
/>
);
// Completes without hanging; focus left the now-removed row.
gridRows = tableTester.getRows();
expect(gridRows).toHaveLength(3);
expect(document.activeElement).not.toBe(cell);
});
it('should support refs', () => {
let tableRef = React.createRef();
let headerRef = React.createRef();
let columnRef = React.createRef();
let bodyRef = React.createRef();
let rowRef = React.createRef();
let cellRef = React.createRef();
render(
Name
TypeFooBar
);
expect(tableRef.current).toBeInstanceOf(HTMLTableElement);
expect(headerRef.current).toBeInstanceOf(HTMLTableSectionElement);
expect(columnRef.current).toBeInstanceOf(HTMLTableCellElement);
expect(bodyRef.current).toBeInstanceOf(HTMLTableSectionElement);
expect(rowRef.current).toBeInstanceOf(HTMLTableRowElement);
expect(cellRef.current).toBeInstanceOf(HTMLTableCellElement);
});
it('should support row render function and not call it with state', () => {
let renderRow = jest.fn(() => {});
render(
);
// React 19 only calls render function once, vs twice in React 18, 17 and 16.
// Every call should be the same, so just loop over them.
expect(renderRow.mock.calls.length).toBeGreaterThanOrEqual(1);
renderRow.mock.calls.forEach(call => {
expect(call[0]).toBe(columns[0]);
});
renderRow.mockReset();
// We do not currently call the renderProps function on any of these changes
// let rowElems = getAllByRole('row');
// let cells = getAllByRole('rowheader');
// act(() => rowElems[1].focus());
// expect(cells[0]).toHaveTextContent('Games focused');
});
it('should support cell render props', () => {
let {getAllByRole} = render(
);
let rowElements = getAllByRole('row');
await user.tab();
expect(document.activeElement).toBe(rowElements[1]);
// Rapid repeated keystrokes cycle through matching rows and wrap around.
await user.keyboard('a');
expect(document.activeElement).toBe(rowElements[2]);
await user.keyboard('a');
expect(document.activeElement).toBe(rowElements[3]);
await user.keyboard('a');
expect(document.activeElement).toBe(rowElements[1]);
// After timeout, typing the same character again still advances to the next match.
act(() => {
jest.runAllTimers();
});
await user.keyboard('a');
expect(document.activeElement).toBe(rowElements[2]);
// Multi-character search still matches across the table.
act(() => {
jest.runAllTimers();
});
await user.keyboard('av');
expect(document.activeElement).toBe(rowElements[3]);
// Typing a multi-character search whose only match is before the focused row wraps around.
act(() => {
jest.runAllTimers();
});
await user.keyboard('app');
expect(document.activeElement).toBe(rowElements[1]);
// Typing a non-matching character leaves focus unchanged.
act(() => {
jest.runAllTimers();
});
await user.keyboard('z');
expect(document.activeElement).toBe(rowElements[1]);
// Typing a character that only matches the currently focused row keeps focus on that row.
await user.keyboard('b');
expect(document.activeElement).toBe(rowElements[4]);
await user.keyboard('b');
expect(document.activeElement).toBe(rowElements[4]);
});
it('should preserve cell focus when cycling and wrapping via repeated character typeahead', async () => {
let items = [
{id: 1, name: 'Apple', date: '6/7/2020', type: 'File'},
{id: 2, name: 'Apricot', date: '4/7/2021', type: 'File'},
{id: 3, name: 'Banana', date: '1/18/2016', type: 'File'}
];
let {getAllByRole} = render(
);
}
it('Column resizer accepts data attributes', () => {
let {getAllByTestId} = render();
let resizers = getAllByTestId('resizer');
expect(resizers).toHaveLength(5);
});
});
it('should support overriding table style', () => {
let {getByRole} = render(
FooBarBazFoo 1Bar 1Baz 1Foo 2Bar 2Baz 2
);
let table = getByRole('grid');
expect(table).toHaveAttribute('style', expect.stringContaining('width: 200px'));
});
describe('links', function () {
describe.each(['mouse', 'keyboard'])('%s', type => {
let trigger = async (item, key = 'Enter') => {
if (type === 'mouse') {
await user.click(item);
} else {
fireEvent.keyDown(item, {key});
fireEvent.keyUp(item, {key});
}
};
it('should support links with selectionMode="none"', async function () {
let {getAllByRole} = render(
FooBarBazFoo 1Bar 1Baz 1Foo 2Bar 2Baz 2
);
let items = getAllByRole('row').slice(1);
for (let item of items) {
expect(item.tagName).not.toBe('A');
expect(item).toHaveAttribute('data-href');
}
let onClick = mockClickDefault();
await trigger(items[0]);
expect(onClick).toHaveBeenCalledTimes(1);
expect(onClick.mock.calls[0][0].target).toBeInstanceOf(HTMLAnchorElement);
expect(onClick.mock.calls[0][0].target.href).toBe('https://google.com/');
});
it.each(['single', 'multiple'])(
'should support links with selectionBehavior="toggle" selectionMode="%s"',
async function (selectionMode) {
let {getAllByRole} = render(
FooBarBazFoo 1Bar 1Baz 1Foo 2Bar 2Baz 2
);
let items = getAllByRole('row').slice(1);
for (let item of items) {
expect(item.tagName).not.toBe('A');
expect(item).toHaveAttribute('data-href');
}
let onClick = mockClickDefault();
await trigger(items[0]);
expect(onClick).toHaveBeenCalledTimes(1);
expect(onClick.mock.calls[0][0].target).toBeInstanceOf(HTMLAnchorElement);
expect(onClick.mock.calls[0][0].target.href).toBe('https://google.com/');
await user.click(within(items[0]).getByRole('checkbox'));
expect(items[0]).toHaveAttribute('aria-selected', 'true');
await trigger(items[1], ' ');
expect(onClick).toHaveBeenCalledTimes(1);
expect(items[1]).toHaveAttribute('aria-selected', 'true');
}
);
it.each(['single', 'multiple'])(
'should support links with selectionBehavior="replace" selectionMode="%s"',
async function (selectionMode) {
let {getAllByRole} = render(
FooBarBazFoo 1Bar 1Baz 1Foo 2Bar 2Baz 2
);
let items = getAllByRole('row').slice(1);
for (let item of items) {
expect(item.tagName).not.toBe('A');
expect(item).toHaveAttribute('data-href');
}
let onClick = mockClickDefault({once: true});
if (type === 'mouse') {
await user.click(items[0]);
} else {
fireEvent.keyDown(items[0], {key: ' '});
fireEvent.keyUp(items[0], {key: ' '});
}
expect(onClick).not.toHaveBeenCalled();
expect(items[0]).toHaveAttribute('aria-selected', 'true');
if (type === 'mouse') {
await user.dblClick(items[0], {pointerType: 'mouse'});
} else {
fireEvent.keyDown(items[0], {key: 'Enter'});
fireEvent.keyUp(items[0], {key: 'Enter'});
}
expect(onClick).toHaveBeenCalledTimes(1);
expect(onClick.mock.calls[0][0].target).toBeInstanceOf(HTMLAnchorElement);
expect(onClick.mock.calls[0][0].target.href).toBe('https://google.com/');
}
);
});
});
describe('error state', () => {
let consoleWarnSpy = jest.fn();
let consoleWarn = console.warn;
let consoleError = console.error;
beforeEach(() => {
console.warn = consoleWarnSpy;
console.error = jest.fn();
});
afterEach(() => {
console.warn = consoleWarn;
console.error = consoleError;
jest.clearAllMocks();
});
afterAll(() => {
jest.restoreAllMocks();
});
it('should throw a warning if the rows are rendered staticly without ids but the cells are rendered dynamically', () => {
function StaticRowDynamicCell() {
let columns = [
{name: 'Name', id: 'name', isRowHeader: true},
{name: 'Type', id: 'type'},
{name: 'Date Modified', id: 'date'}
];
return (
);
}
expect(() => render()).toThrow(
'No id detected for the Row element. The Row element requires a id to be provided to it when the cells are rendered dynamically.'
);
});
it('should throw an error if two rows share an id', () => {
function DuplicateRowIds() {
return (
);
}
expect(() => render()).toThrow(
'Duplicate key "1" found in collection. Every item in a collection must have a unique key.'
);
});
});
describe('load more spinner', () => {
let clientHeight, scrollHeight;
let DndTable = stories.DndTable;
let initialItems = [
{id: '1', type: 'file', name: 'Adobe Photoshop'},
{id: '2', type: 'file', name: 'Adobe XD'}
];
beforeAll(function () {
scrollHeight = jest
.spyOn(window.HTMLElement.prototype, 'scrollHeight', 'get')
.mockImplementation(() => 200);
clientHeight = jest
.spyOn(window.HTMLElement.prototype, 'clientHeight', 'get')
.mockImplementation(function () {
if (this.getAttribute('role') === 'grid') {
return 200;
}
return 40;
});
});
afterAll(function () {
clientHeight.mockReset();
scrollHeight.mockReset();
});
it('should render the load more element with the expected attributes', () => {
let {getAllByRole} = render();
let rows = getAllByRole('row');
expect(rows).toHaveLength(7);
let loader = rows[6];
let cell = within(loader).getByRole('rowheader');
expect(cell).toHaveAttribute('colspan', '3');
let spinner = within(cell).getByRole('progressbar');
expect(spinner).toHaveAttribute('aria-label', 'loading');
let sentinel = rows[5];
expect(sentinel).toHaveAttribute('inert');
});
it('should still render the sentinel, but not render the spinner if it isnt loading', () => {
let {getAllByRole, queryByRole} = render();
let rows = getAllByRole('row');
expect(rows).toHaveLength(6);
let sentinel = rows[5];
expect(sentinel).toHaveAttribute('inert');
let spinner = queryByRole('progressbar');
expect(spinner).toBeFalsy();
});
it('should not focus the load more row when using ArrowDown', async () => {
let {getAllByRole} = render();
let rows = getAllByRole('row');
let loader = rows[6];
let spinner = within(loader).getByRole('progressbar');
expect(spinner).toHaveAttribute('aria-label', 'loading');
await user.tab();
expect(document.activeElement).toBe(rows[1]);
await user.keyboard('{ArrowDown}');
await user.keyboard('{ArrowDown}');
await user.keyboard('{ArrowDown}');
expect(document.activeElement).toBe(rows[4]);
await user.keyboard('{ArrowDown}');
expect(document.activeElement).toBe(rows[4]);
// Check that it didn't shift the focusedkey to the loader key even if DOM focus didn't shift to the loader
await user.keyboard('{ArrowUp}');
expect(document.activeElement).toBe(rows[3]);
});
it('should not focus the load more row when using End', async () => {
let {getAllByRole} = render();
let rows = getAllByRole('row');
let loader = rows[6];
let spinner = within(loader).getByRole('progressbar');
expect(spinner).toHaveAttribute('aria-label', 'loading');
await user.tab();
expect(document.activeElement).toBe(rows[1]);
await user.keyboard('{End}');
expect(document.activeElement).toBe(rows[4]);
// Check that it didn't shift the focusedkey to the loader key even if DOM focus didn't shift to the loader
await user.keyboard('{ArrowUp}');
expect(document.activeElement).toBe(rows[3]);
});
it('should not focus the load more row when using PageDown', async () => {
let {getAllByRole} = render();
let rows = getAllByRole('row');
let loader = rows[6];
let spinner = within(loader).getByRole('progressbar');
expect(spinner).toHaveAttribute('aria-label', 'loading');
await user.tab();
expect(document.activeElement).toBe(rows[1]);
await user.keyboard('{PageDown}');
expect(document.activeElement).toBe(rows[4]);
// Check that it didn't shift the focusedkey to the loader key even if DOM focus didn't shift to the loader
await user.keyboard('{ArrowUp}');
expect(document.activeElement).toBe(rows[3]);
// Check that the same when cell is focused
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(within(rows[3]).getByRole('rowheader'));
await user.keyboard('{ArrowUp}');
expect(document.activeElement).toBe(within(rows[2]).getByRole('rowheader'));
await user.keyboard('{PageDown}');
expect(document.activeElement).toBe(within(rows[4]).getByRole('rowheader'));
});
it('should disable the select all checkbox and column focusablity when the table is empty and loading', async () => {
let {getByRole, getAllByRole} = render();
let table = getByRole('grid');
await user.tab();
expect(document.activeElement).toBe(table);
let column = getAllByRole('columnheader')[0];
expect(within(column).getByRole('checkbox', {hidden: true})).toBeDisabled();
});
it('should not render no results state and the loader at the same time', () => {
let {getAllByRole, rerender} = render();
let rows = getAllByRole('row');
let loader = rows[1];
let body = getAllByRole('rowgroup')[1];
expect(rows).toHaveLength(2);
expect(body).toHaveAttribute('data-empty', 'true');
let spinner = within(loader).getByRole('progressbar');
expect(spinner).toHaveAttribute('aria-label', 'loading');
rerender();
rows = getAllByRole('row');
expect(rows).toHaveLength(2);
expect(body).toHaveAttribute('data-empty', 'true');
expect(rows[1]).toHaveTextContent('No results');
});
it('should not include the loader in the selection when selecting all/deselecting all', async () => {
let onSelectionChange = jest.fn();
let {getAllByRole} = render(
);
let rows = getAllByRole('row');
expect(rows).toHaveLength(5);
let loader = rows[4];
let spinner = within(loader).getByRole('progressbar');
expect(spinner).toHaveAttribute('aria-label', 'loading');
let selectAll = getAllByRole('checkbox')[0];
expect(selectAll).toHaveAttribute('aria-label', 'Select All');
await user.click(selectAll);
expect(onSelectionChange).toHaveBeenLastCalledWith('all');
let checkbox = getAllByRole('checkbox')[2];
await user.click(checkbox);
expect(new Set(onSelectionChange.mock.calls[1][0])).toEqual(new Set(['1']));
});
it('should not crash when dragging over the loader', async () => {
let {getAllByRole} = render(
);
let rows = getAllByRole('row');
expect(rows).toHaveLength(5);
expect(rows[1]).toHaveTextContent('Adobe Photoshop');
let loader = rows[4];
let spinner = within(loader).getByRole('progressbar');
expect(spinner).toHaveAttribute('aria-label', 'loading');
let dragButton = getAllByRole('button')[0];
expect(dragButton).toHaveAttribute('aria-label', 'Drag Adobe Photoshop');
await user.tab();
await user.keyboard('{Right}');
expect(document.activeElement).toBe(dragButton);
await user.keyboard('{Enter}');
act(() => jest.runAllTimers());
rows = getAllByRole('row');
// There should be 4 rows aka the drag indicator rows (1 for before the first row, between the two rows, and after the last row) + the original dragged row
expect(rows).toHaveLength(4);
expect(within(rows[0]).getByRole('button')).toHaveAttribute(
'aria-label',
'Insert before Adobe Photoshop'
);
await user.keyboard('{Escape}');
act(() => jest.runAllTimers());
rows = getAllByRole('row');
let dragCell = within(rows[1]).getAllByRole('rowheader')[0];
let dataTransfer = new DataTransfer();
fireEvent.pointerDown(dragCell, {
pointerType: 'mouse',
button: 0,
pointerId: 1,
clientX: 0,
clientY: 0
});
fireEvent(dragCell, new DragEvent('dragstart', {dataTransfer, clientX: 0, clientY: 0}));
let dropTarget = rows[2];
fireEvent.pointerMove(dragCell, {
pointerType: 'mouse',
button: 0,
pointerId: 1,
clientX: 1,
clientY: 1
});
fireEvent(dragCell, new DragEvent('drag', {dataTransfer, clientX: 1, clientY: 1}));
fireEvent(dropTarget, new DragEvent('dragover', {dataTransfer, clientX: 1, clientY: 80}));
fireEvent.pointerUp(dragCell, {
pointerType: 'mouse',
button: 0,
pointerId: 1,
clientX: 1,
clientY: 1
});
fireEvent(dropTarget, new DragEvent('drop', {dataTransfer, clientX: 1, clientY: 80}));
fireEvent(dragCell, new DragEvent('dragend', {dataTransfer, clientX: 1, clientY: 1}));
act(() => jest.runAllTimers());
rows = getAllByRole('row');
expect(rows[2]).toHaveTextContent('Adobe Photoshop');
});
});
describe('async loading', function () {
let onLoadMore = jest.fn();
let items = [];
for (let i = 1; i <= 10; i++) {
items.push({id: i, foo: 'Foo ' + i, bar: 'Bar ' + i});
}
function LoadMoreTable({onLoadMore, isLoading, items}) {
return (
);
}
afterEach(() => {
onLoadMore.mockRestore();
});
it('should render the loading element when loading', async () => {
let tree = render();
let tableTester = testUtilUser.createTester('Table', {root: tree.getByRole('grid')});
let rows = tableTester.getRows();
expect(rows).toHaveLength(12);
let loaderRow = rows[11];
expect(loaderRow).toHaveTextContent('spinner');
let sentinel = within(loaderRow.parentElement).getByTestId('loadMoreSentinel');
expect(sentinel.closest('[inert]')).toBeTruthy();
});
it('should render the sentinel but not the loading indicator when not loading', async () => {
let tree = render();
let tableTester = testUtilUser.createTester('Table', {root: tree.getByRole('grid')});
let rows = tableTester.getRows();
expect(rows).toHaveLength(11);
expect(tree.queryByText('spinner')).toBeFalsy();
expect(tree.getByTestId('loadMoreSentinel')).toBeInTheDocument();
});
it('should properly render the renderEmptyState if table is empty', async () => {
let tree = render();
let tableTester = testUtilUser.createTester('Table', {root: tree.getByRole('grid')});
let rows = tableTester.getRows();
expect(rows).toHaveLength(2);
expect(rows[1]).toHaveTextContent('No results');
expect(tree.queryByText('spinner')).toBeFalsy();
expect(tree.getByTestId('loadMoreSentinel')).toBeInTheDocument();
let body = tableTester.getRowGroups()[1];
expect(body).toHaveAttribute('data-empty', 'true');
let selectAll = tree.getAllByRole('checkbox')[0];
expect(selectAll).toBeDisabled();
// Even if the table is empty, providing isLoading will render the loader
tree.rerender();
rows = tableTester.getRows();
expect(rows).toHaveLength(3);
expect(rows[2]).toHaveTextContent('No results');
expect(tree.queryByText('spinner')).toBeTruthy();
expect(tree.getByTestId('loadMoreSentinel')).toBeInTheDocument();
body = tableTester.getRowGroups()[1];
expect(body).toHaveAttribute('data-empty', 'true');
selectAll = tree.getAllByRole('checkbox')[0];
expect(selectAll).toBeDisabled();
});
it('should fire onLoadMore when intersecting with the sentinel', function () {
let observe = jest.fn();
let observer = setupIntersectionObserverMock({
observe
});
let tree = render();
expect(onLoadMore).toHaveBeenCalledTimes(0);
let sentinel = tree.getByTestId('loadMoreSentinel');
expect(observe).toHaveBeenLastCalledWith(sentinel);
expect(sentinel.nodeName).toBe('DIV');
expect(sentinel.parentElement.nodeName).toBe('TD');
expect(sentinel.parentElement.parentElement.nodeName).toBe('TR');
expect(onLoadMore).toHaveBeenCalledTimes(0);
act(() => {
observer.instance.triggerCallback([{isIntersecting: true}]);
});
act(() => {
jest.runAllTimers();
});
expect(onLoadMore).toHaveBeenCalledTimes(1);
});
it('should only fire loadMore when intersection is detected regardless of loading state', function () {
let observe = jest.fn();
let observer = setupIntersectionObserverMock({
observe
});
let tree = render();
let sentinel = tree.getByTestId('loadMoreSentinel');
expect(observe).toHaveBeenLastCalledWith(sentinel);
expect(onLoadMore).toHaveBeenCalledTimes(0);
observe.mockClear();
act(() => {
observer.instance.triggerCallback([{isIntersecting: true}]);
});
expect(onLoadMore).toHaveBeenCalledTimes(1);
tree.rerender();
expect(observe).toHaveBeenLastCalledWith(sentinel);
expect(onLoadMore).toHaveBeenCalledTimes(1);
act(() => {
observer.instance.triggerCallback([{isIntersecting: true}]);
});
expect(onLoadMore).toHaveBeenCalledTimes(2);
});
it("should automatically fire onLoadMore if there aren't enough items to fill the Table", function () {
let observer = setupIntersectionObserverMock();
jest.spyOn(window.HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(() => 100);
jest.spyOn(window.HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(() => 100);
let tree = render();
tree.rerender();
act(() => {
observer.instance.triggerCallback([{isIntersecting: true}]);
});
expect(onLoadMore).toHaveBeenCalledTimes(1);
});
// TODO: this test doesn't work due to the TableBody not being rendered immediately, hence scrollRef.current is undef when
// we try to attach it via useEvent
// This could be remedied perhaps by moving the useLoadOnScroll call to TableBody internally and passing down the scrollRef and other load props via context from body.
// That would guarentee that the ref for the table body is defined at the time the hook renders. Stashed this change locally, to be discussed.
it.skip('accepts a user defined scrollRef', function () {
jest.spyOn(window.HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(() => 100);
jest.spyOn(window.HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(() => 25);
let LoadMoreTableBodyScroll = ({onLoadMore, isLoading, scrollOffset, items}) => {
let scrollRef = React.useRef();
return (
FooBar
{item => (
{item.foo}{item.bar}
)}
);
};
let tree = render();
let table = tree.getByRole('grid');
expect(onLoadMore).toHaveBeenCalledTimes(0);
table.scrollTop = 76;
fireEvent.scroll(table);
act(() => {
jest.runAllTimers();
});
expect(onLoadMore).toHaveBeenCalledTimes(0);
let scrollView = tree.getAllByRole('rowgroup')[1];
scrollView.scrollTop = 76;
fireEvent.scroll(scrollView);
act(() => {
jest.runAllTimers();
});
expect(onLoadMore).toHaveBeenCalledTimes(1);
});
describe('virtualized', () => {
let items = [];
for (let i = 1; i <= 50; i++) {
items.push({id: i, foo: 'Foo ' + i, bar: 'Bar ' + i});
}
let clientWidth, clientHeight;
beforeAll(() => {
clientWidth = jest
.spyOn(window.HTMLElement.prototype, 'clientWidth', 'get')
.mockImplementation(() => 100);
clientHeight = jest
.spyOn(window.HTMLElement.prototype, 'clientHeight', 'get')
.mockImplementation(() => 100);
});
beforeEach(() => {
act(() => {
jest.runAllTimers();
});
});
afterAll(function () {
clientWidth.mockReset();
clientHeight.mockReset();
});
let VirtualizedTableLoad = props => {
let {items, loadingState, onLoadMore} = props;
return (
);
let tableTester = testUtilUser.createTester('Table', {root});
let groups = tableTester.getRowGroups();
expect(groups).toHaveLength(5);
expect(groups[0].tagName).toBe('THEAD');
expect(groups[1].tagName).toBe('TBODY');
expect(groups[2].tagName).toBe('TBODY');
expect(groups[3].tagName).toBe('TBODY');
expect(tableTester.getRows()).toHaveLength(11);
expect(tableTester.getRows({element: groups[1]})).toHaveLength(3);
expect(tableTester.getRows({element: groups[2]})).toHaveLength(3);
expect(tableTester.getRows({element: groups[3]})).toHaveLength(4);
await user.tab();
for (let row of tableTester.getRows()) {
expect(document.activeElement).toBe(row);
await user.keyboard('{ArrowDown}');
}
for (let row of tableTester.getRows().toReversed().slice(1)) {
await user.keyboard('{ArrowUp}');
expect(document.activeElement).toBe(row);
}
expect(tableTester.getFooterRows()).toHaveLength(1);
expect(tableTester.getFooterRows()[0]).toHaveTextContent('Blah');
});
describe("keyboardNavigationBehavior='tab' and textfields in row", () => {
it('Tab from a focused cell moves focus to the first tabbable child', async () => {
let {getByRole} = render();
let tableTester = testUtilUser.createTester('Table', {
root: getByRole('grid', {name: 'Tab mode table'})
});
let row = tableTester.getRows()[0];
let cells = tableTester.getCells({element: row});
await user.tab();
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(cells[cells.length - 1]);
await user.tab();
expect(document.activeElement).toBe(getByRole('textbox', {name: 'Games notes'}));
});
it('Tab from a cell with no tabbable children or from the last child in a cell exits the table', async () => {
let {getAllByRole, getByRole} = render(
);
let tableTester = testUtilUser.createTester('Table', {
root: getByRole('grid', {name: 'Tab mode table'})
});
let rowheader = tableTester.getRowHeaders()[0];
let row = tableTester.getRows()[0];
let cells = tableTester.getCells({element: row});
await user.tab();
await user.tab();
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(rowheader);
await user.tab();
let buttons = getAllByRole('button');
expect(document.activeElement).toBe(buttons[2]);
await user.tab({shift: true});
await user.keyboard('{ArrowLeft}');
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(cells[cells.length - 1]);
await user.tab();
expect(document.activeElement).toBe(getByRole('textbox', {name: 'Games notes'}));
await user.tab();
expect(document.activeElement).toBe(getByRole('button', {name: 'Button next to input'}));
await user.tab();
expect(document.activeElement).toBe(buttons[2]);
});
it('Shift+Tab from a child returns focus to the cell', async () => {
let {getByRole} = render();
let tableTester = testUtilUser.createTester('Table', {
root: getByRole('grid', {name: 'Tab mode table'})
});
let row = tableTester.getRows()[0];
let cells = tableTester.getCells({element: row});
await user.tab();
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(cells[cells.length - 1]);
await user.tab();
expect(document.activeElement).toBe(getByRole('textbox', {name: 'Games notes'}));
await user.tab({shift: true});
expect(document.activeElement).toBe(cells[cells.length - 1]);
});
it('should not navigate to next cell when arrow keys are pressed while a text input child has focus', async () => {
let {getByRole} = render();
let tableTester = testUtilUser.createTester('Table', {
root: getByRole('grid', {name: 'Tab mode table'})
});
let row = tableTester.getRows()[0];
let cells = tableTester.getCells({element: row});
await user.tab();
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(cells[cells.length - 1]);
await user.tab();
let input = getByRole('textbox', {name: 'Games notes'});
expect(document.activeElement).toBe(input);
await user.keyboard('{ArrowDown}');
expect(document.activeElement).toBe(input);
await user.keyboard('{ArrowUp}');
expect(document.activeElement).toBe(input);
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(input);
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(input);
});
it('should not trigger typeahead when typing in a text input child', async () => {
let {getByRole} = render();
let tableTester = testUtilUser.createTester('Table', {
root: getByRole('grid', {name: 'Tab mode table'})
});
let row = tableTester.getRows()[0];
let cells = tableTester.getCells({element: row});
await user.tab();
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(cells[cells.length - 1]);
await user.tab();
let input = getByRole('textbox', {name: 'Games notes'});
expect(document.activeElement).toBe(input);
await user.type(input, 'Games');
expect(input).toHaveValue('Games');
expect(document.activeElement).toBe(input);
});
it('should not trigger selection when pressing Space or Enter in a text input child', async () => {
let {getByRole} = render(
);
let tableTester = testUtilUser.createTester('Table', {
root: getByRole('grid', {name: 'Tab mode table'})
});
let row = tableTester.getRows()[0];
let cells = tableTester.getCells({element: row});
await user.tab();
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(cells[cells.length - 1]);
await user.tab();
let input = getByRole('textbox', {name: 'Games notes'});
expect(document.activeElement).toBe(input);
await user.keyboard(' ');
expect(input).toHaveValue(' ');
expect(onSelectionChange).not.toHaveBeenCalled();
await user.keyboard('{Enter}');
expect(onSelectionChange).not.toHaveBeenCalled();
});
it('should not trigger selection when clicking on a tabbable child element', async () => {
let {getByRole} = render(
);
let input = getByRole('textbox', {name: 'Games notes'});
await user.click(input);
expect(document.activeElement).toBe(input);
expect(onSelectionChange).not.toHaveBeenCalled();
});
it('should not trigger row selection when clicking a TagGroup tag nested inside a cell', async () => {
let {getByRole} = render(
);
// click on actual grid cell since that mimics what would happen in browser
// note that grid cell is not tabbable nor has the data-collection/etc attributes since those
// are on a wrapping div
let tagGrid = getByRole('grid', {name: 'Games tags'});
let tagInnerCell = within(tagGrid).getAllByRole('gridcell')[0];
await user.click(tagInnerCell);
expect(onSelectionChange).not.toHaveBeenCalled();
});
it('should still trigger selection when clicking on a row with no tabbable children ', async () => {
let {getByRole} = render(
);
let tableTester = testUtilUser.createTester('Table', {
root: getByRole('grid', {name: 'Tab mode table'})
});
let row = tableTester.getRows()[0];
await user.click(row);
expect(onSelectionChange).toHaveBeenCalledTimes(1);
expect(new Set(onSelectionChange.mock.calls[0][0])).toEqual(new Set(['1']));
});
describe("focusMode='child'", () => {
it('arrow navigating to a focusMode="child" cell focuses the child directly', async () => {
let {getByRole} = render();
await user.tab();
// ArrowLeft navigation uses childFocusStrategy='last', so focuses the last child (button)
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(getByRole('button', {name: 'Button next to input'}));
});
it('allowsArrowNavigation allows arrow key row navigation when focused on child', async () => {
let {getByRole} = render(
);
await user.tab();
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(getByRole('button', {name: 'Button next to input'}));
await user.keyboard('{ArrowDown}');
expect(document.activeElement).toBe(getByRole('textbox', {name: 'Program Files notes'}));
});
it('Shift+Tab from a focusMode="child" child skips the cell and does not return to it', async () => {
let {getByRole} = render();
let button = getByRole('button', {name: 'Button next to input'});
let input = getByRole('textbox', {name: 'Games notes'});
await user.tab();
await user.keyboard('{ArrowLeft}');
act(() => jest.runAllTimers());
expect(document.activeElement).toBe(button);
await user.tab({shift: true});
expect(document.activeElement).toBe(input);
await user.tab({shift: true});
expect(document.activeElement).toBe(document.body);
});
});
});
describe('cells with focusable children in arrow navigation mode', () => {
it('default focusMode: ArrowRight crosses from last child to first child of next cell, ArrowLeft reverses', async () => {
let {getByRole} = render();
await user.tab();
// Tab → row, ArrowRight×2 → col2 first child (col1 is text-only, focuses cell then crosses)
await user.keyboard('{ArrowRight}');
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(getByRole('button', {name: 'R1C2 first'}));
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(getByRole('button', {name: 'R1C2 last'}));
// ArrowRight from last child crosses into first child of next cell
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(getByRole('button', {name: 'R1C3 first'}));
// ArrowLeft from first child crosses back to last child of previous cell
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(getByRole('button', {name: 'R1C2 last'}));
});
describe("focusMode='cell'", () => {
it('arrow navigation with focusMode="cell": cell element stays focused on navigate, arrows enter/exit children within cell', async () => {
// walker.previousNode() from first child returns cell root → stays on same cell
// (contrast with default focusMode="child" which crosses to prev cell's last child)
let {getByRole, getAllByRole} = render();
let rows = getAllByRole('row');
let col2Cell = within(rows[1]).getAllByRole('gridcell')[0];
let col3Cell = within(rows[1]).getAllByRole('gridcell')[1];
await user.tab();
// ArrowRight×2: row → col1 (text-only, focuses cell) → col2Cell (focusMode='cell' stays on cell element)
await user.keyboard('{ArrowRight}');
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(col2Cell);
// ArrowRight from cell element enters first child
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(getByRole('button', {name: 'R1C2 first'}));
// ArrowRight within cell advances to next child
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(getByRole('button', {name: 'R1C2 last'}));
// ArrowLeft within cell retreats to previous child
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(getByRole('button', {name: 'R1C2 first'}));
// ArrowLeft from first child returns to same cell element (not previous cell's last child)
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(col2Cell);
// Navigate forward to reach col3: col2Cell → first → last → col3Cell
await user.keyboard('{ArrowRight}');
await user.keyboard('{ArrowRight}');
// ArrowRight from last child of col2 enters next cell element (not its first child)
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(col3Cell);
// ArrowRight from col3Cell enters its first child
await user.keyboard('{ArrowRight}');
expect(document.activeElement).toBe(getByRole('button', {name: 'R1C3 first'}));
// ArrowLeft from first child of col3 returns to col3Cell (same cell, not col2)
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(col3Cell);
// ArrowLeft from cell element moves to previous cell element
await user.keyboard('{ArrowLeft}');
expect(document.activeElement).toBe(col2Cell);
});
});
});
});
function HidingColumnsExample({dynamic = false}) {
const [hideColumns, setHideColumns] = React.useState(false);
const label = hideColumns ? 'Show Columns' : 'Hide Columns';
return (
<>
{dynamic ? (
) : (
)}
>
);
}
function StockTableExampleDynamic({hideColumns}) {
return (
Symbol
Name
{!hideColumns && Market Cap}
{!hideColumns && Sector}
Industry
{item => (
${item.symbol}{item.name}
{!hideColumns && {item.marketCap}}
{!hideColumns && {item.sector}}
{item.industry}
)}
);
}
function StockTableExampleStatic({hideColumns}) {
return (
Symbol
Name
{!hideColumns && Market Cap}
{!hideColumns && Sector}
Industry
{stocks.map(item => (
${item.symbol}{item.name}
{!hideColumns && {item.marketCap}}
{!hideColumns && {item.sector}}
{item.industry}
))}