Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DataGrid] Fix shift+space keyboard regression to select row #897

Merged
merged 8 commits into from
Jan 22, 2021
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const useKeyboard = (gridRootRef: React.RefObject<HTMLDivElement>, apiRef
);

const navigateCells = React.useCallback(
(code: string, isCtrlPressed: boolean) => {
(key: string, isCtrlPressed: boolean) => {
const cellEl = findParentElementFromClassName(
document.activeElement as HTMLDivElement,
CELL_CSS_CLASS,
Expand All @@ -90,13 +90,13 @@ export const useKeyboard = (gridRootRef: React.RefObject<HTMLDivElement>, apiRef
: totalRowCount;

let nextCellIndexes: CellIndexCoordinates;
if (isArrowKeys(code)) {
nextCellIndexes = getNextCellIndexes(code, {
if (isArrowKeys(key)) {
nextCellIndexes = getNextCellIndexes(key, {
colIndex: currentColIndex,
rowIndex: currentRowIndex,
});
} else if (isHomeOrEndKeys(code)) {
const colIdx = code === 'Home' ? 0 : colCount - 1;
} else if (isHomeOrEndKeys(key)) {
const colIdx = key === 'Home' ? 0 : colCount - 1;

if (!isCtrlPressed) {
// we go to the current row, first col, or last col!
Expand All @@ -111,10 +111,10 @@ export const useKeyboard = (gridRootRef: React.RefObject<HTMLDivElement>, apiRef
}
nextCellIndexes = { colIndex: colIdx, rowIndex };
}
} else if (isPageKeys(code) || isSpaceKey(code)) {
} else if (isPageKeys(key) || isSpaceKey(key)) {
const nextRowIndex =
currentRowIndex +
(code.indexOf('Down') > -1 || isSpaceKey(code)
(key.indexOf('Down') > -1 || isSpaceKey(key)
? containerSizes!.viewportPageSize
: -1 * containerSizes!.viewportPageSize);
nextCellIndexes = { colIndex: currentColIndex, rowIndex: nextRowIndex };
Expand Down Expand Up @@ -167,7 +167,7 @@ export const useKeyboard = (gridRootRef: React.RefObject<HTMLDivElement>, apiRef
}, [apiRef]);

const expandSelection = React.useCallback(
(code: string) => {
(key: string) => {
const rowEl = findParentElementFromClassName(
document.activeElement as HTMLDivElement,
ROW_CSS_CLASS,
Expand All @@ -190,7 +190,7 @@ export const useKeyboard = (gridRootRef: React.RefObject<HTMLDivElement>, apiRef
selectionFromRowIndex = selectedRowsIndex[diffWithCurrentIndex.indexOf(minIndex)];
}

const nextCellIndexes = navigateCells(code, false);
const nextCellIndexes = navigateCells(key, false);
// We select the rows in between
const rowIds = Array(Math.abs(nextCellIndexes.rowIndex - selectionFromRowIndex) + 1)
.fill(
Expand Down
11 changes: 7 additions & 4 deletions packages/grid/_modules_/grid/utils/domUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@ export function findParentElementFromClassName(elem: Element, className: string)
return elem.closest(`.${className}`);
}

export function isCell(elem: Element | null): boolean {
return elem != null && findParentElementFromClassName(elem, CELL_CSS_CLASS) !== null;
}

export function isCellRoot(elem: Element | null): boolean {
return elem != null && elem.classList.contains(CELL_CSS_CLASS);
}

export function isCell(elem: Element | null): boolean {
return (
elem != null &&
(isCellRoot(elem) || findParentElementFromClassName(elem, CELL_CSS_CLASS) !== null)
);
}

export function isHeaderTitleContainer(elem: Element): boolean {
return elem && findParentElementFromClassName(elem, HEADER_CELL_TITLE_CSS_CLASS) !== null;
}
Expand Down
16 changes: 8 additions & 8 deletions packages/grid/_modules_/grid/utils/keyboardUtils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
export const MULTIPLE_SELECTION_KEYS = ['Meta', 'Control'];
export const isMultipleKey = (code: string): boolean => MULTIPLE_SELECTION_KEYS.indexOf(code) > -1;
export const isTabKey = (code: string): boolean => code === 'Tab';
export const isSpaceKey = (code: string): boolean => code === 'Space';
Copy link
Member

@oliviertassinari oliviertassinari Jan 22, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It took me some time to find where was the fix in the diff, spotted. Space => ' ' :)

export const isArrowKeys = (code: string): boolean => code.indexOf('Arrow') === 0;
export const isHomeOrEndKeys = (code: string): boolean => code === 'Home' || code === 'End';
export const isPageKeys = (code: string): boolean => code.indexOf('Page') === 0;
export const isMultipleKey = (key: string): boolean => MULTIPLE_SELECTION_KEYS.indexOf(key) > -1;
dtassone marked this conversation as resolved.
Show resolved Hide resolved
export const isTabKey = (key: string): boolean => key === 'Tab';
export const isSpaceKey = (key: string): boolean => key === ' ';
export const isArrowKeys = (key: string): boolean => key.indexOf('Arrow') === 0;
export const isHomeOrEndKeys = (key: string): boolean => key === 'Home' || key === 'End';
export const isPageKeys = (key: string): boolean => key.indexOf('Page') === 0;

export const isNavigationKey = (code: string) =>
isHomeOrEndKeys(code) || isArrowKeys(code) || isPageKeys(code) || isSpaceKey(code);
export const isNavigationKey = (key: string) =>
isHomeOrEndKeys(key) || isArrowKeys(key) || isPageKeys(key) || isSpaceKey(key);
37 changes: 26 additions & 11 deletions packages/grid/data-grid/src/tests/keyboard.DataGrid.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@ import {
} from 'test/utils';
import { spy } from 'sinon';
import { expect } from 'chai';
import { getActiveCell } from 'test/utils/helperFn';
import { getActiveCell, getCell, getRow } from 'test/utils/helperFn';
import { DataGrid } from '@material-ui/data-grid';
import { useData } from 'packages/storybook/src/hooks/useData';
import { Columns } from 'packages/grid/_modules_/grid/models/colDef/colDef';

const SPACE_KEY = { key: ' ', code: 'Space', shiftKey: false };
const SHIFT_SPACE_KEY = { ...SPACE_KEY, shiftKey: true };

describe('<DataGrid /> - Keyboard', () => {
// TODO v5: replace with createClientRender
const render = createClientRenderStrictMode();
Expand Down Expand Up @@ -117,9 +120,7 @@ describe('<DataGrid /> - Keyboard', () => {
<DataGrid rows={rows} columns={columns} />
</div>,
);
const firstCell = document.querySelector(
'[role="cell"][data-rowindex="0"][aria-colindex="0"]',
) as HTMLElement;
const firstCell = getCell(0, 0);
firstCell.focus();
fireEvent.keyDown(firstCell, { key: 'ArrowRight' });
expect(handleKeyDown.returnValues).to.deep.equal([true]);
Expand All @@ -140,8 +141,7 @@ describe('<DataGrid /> - Keyboard', () => {
/* eslint-disable material-ui/disallow-active-element-as-key-event-target */
it('cell navigation with arrows', () => {
render(<KeyboardTest />);
// @ts-ignore
document.querySelector('[role="cell"][data-rowindex="0"][aria-colindex="0"]').focus();
getCell(0, 0).focus();
expect(getActiveCell()).to.equal('0-0');
fireEvent.keyDown(document.activeElement!, { key: 'ArrowRight' });
expect(getActiveCell()).to.equal('0-1');
Expand All @@ -153,17 +153,32 @@ describe('<DataGrid /> - Keyboard', () => {
expect(getActiveCell()).to.equal('0-0');
});

it('Shift + Space should select a row', () => {
render(<KeyboardTest />);
getCell(0, 0).focus();
expect(getActiveCell()).to.equal('0-0');
fireEvent.keyDown(document.activeElement!, SHIFT_SPACE_KEY);
const row = getRow(0);
const isSelected = row.classList.contains('Mui-selected');
expect(isSelected).to.equal(true);
});

it('Space only should go to the bottom of the page', () => {
render(<KeyboardTest />);
getCell(0, 0).focus();
expect(getActiveCell()).to.equal('0-0');
fireEvent.keyDown(document.activeElement!, SPACE_KEY);
expect(getActiveCell()).to.equal('3-0');
});

it('Home / End navigation', async () => {
render(<KeyboardTest />);
// @ts-ignore
document.querySelector('[role="cell"][data-rowindex="1"][aria-colindex="1"]').focus();
getCell(1, 1).focus();
expect(getActiveCell()).to.equal('1-1');
fireEvent.keyDown(document.activeElement!, { key: 'Home' });
expect(getActiveCell()).to.equal('1-0');
fireEvent.keyDown(document.activeElement!, { key: 'End' });
await waitFor(() =>
document.querySelector('[role="cell"][data-rowindex="1"][aria-colindex="19"]'),
);
await waitFor(() => getCell(1, 19));
expect(getActiveCell()).to.equal('1-19');
});
/* eslint-enable material-ui/disallow-active-element-as-key-event-target */
Expand Down
18 changes: 18 additions & 0 deletions test/utils/helperFn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,21 @@ export function getColumnHeaders() {
(node) => node!.textContent,
);
}

export function getCell(rowIndex: number, colIndex: number): HTMLElement {
oliviertassinari marked this conversation as resolved.
Show resolved Hide resolved
const cell = document.querySelector(
`[role="cell"][data-rowindex="${rowIndex}"][aria-colindex="${colIndex}"]`,
);
if (cell == null) {
throw new Error(`Cell ${rowIndex} ${colIndex} not found`);
}
return cell as HTMLElement;
}

export function getRow(rowIndex: number): HTMLElement {
const row = document.querySelector(`[role="row"][data-rowindex="${rowIndex}"]`);
if (row == null) {
throw new Error(`Row ${rowIndex} not found`);
}
return row as HTMLElement;
}