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

Allow keyboard accessible sorting #12

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
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
47 changes: 47 additions & 0 deletions __tests__/sort-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,53 @@ describe('sort.sort', function () {
expect(sorted).toEqual(testColumnIndex);
});

it('triggers sorting on enter key', function () {
const testColumnIndex = 0;
let sorted;
const _sorter = sort({
onSort(columnIndex) {
sorted = columnIndex;
}
});
const result = _sorter('testValue', {
columnIndex: testColumnIndex
});

result.onKeyDown({ keyCode: 13 });

expect(sorted).toEqual(testColumnIndex);
});

it('does not triggers sorting on enter key if disableKeyboard=true', function () {
const testColumnIndex = 0;
const _sorter = sort({
disableKeyboard: true,
onSort() {}
});
const result = _sorter('testValue', {
columnIndex: testColumnIndex
});

expect(result.onKeyDown).toBeUndefined();
});

it('does not trigger sorting on other keyDown events', function () {
const testColumnIndex = 0;
let sorted;
const _sorter = sort({
onSort(columnIndex) {
sorted = columnIndex;
}
});
const result = _sorter('testValue', {
columnIndex: testColumnIndex
});

result.onKeyDown({ keyCode: 32 });

expect(sorted).toBeFalsy();
});

it('allows strategy to be customized', function () {
const testProperty = 'foobar';
const sortDirection = 'asc';
Expand Down
10 changes: 8 additions & 2 deletions src/sort.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const sort = ({
event = 'onClick',
getSortingColumns = () => [],
onSort = () => {},
strategy = defaultStrategy
strategy = defaultStrategy,
disableKeyboard = false
} = {}) => (_value, extra, { className, ...props } = {}) => {
const sortingColumns = getSortingColumns();
const field = extra[strategy.fieldName];
Expand All @@ -16,10 +17,15 @@ const sort = ({
headerClass = `sort sort-${sortingColumns[field].direction}`;
}

const keyboardEventHandler = disableKeyboard ? {} : {
onKeyDown: (e) => { if (e.keyCode === 13) { onSort(field); } }
};

return {
...props,
className: classNames(className, headerClass),
[event]: () => onSort(field)
[event]: () => onSort(field),
...keyboardEventHandler
};
};

Expand Down
Loading