Skip to content

Commit

Permalink
feat: add relative focusing API
Browse files Browse the repository at this point in the history
  • Loading branch information
theKashey committed Aug 16, 2020
1 parent 5bc1498 commit 3086116
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { setFocus } from './setFocus';
import * as constants from './constants';
import getAllAffectedNodes from './utils/all-affected';
import { getFocusabledIn } from './focusables';
import { focusNextElement, focusPrevElement } from './sibling';

export {
tabHook,
Expand All @@ -15,6 +16,8 @@ export {
getFocusabledIn,
constants,
getAllAffectedNodes,
focusNextElement,
focusPrevElement,
};

export default setFocus;
48 changes: 48 additions & 0 deletions src/sibling.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { getTabbableNodes } from './utils/DOMutils';
import { isNotAGuard } from './utils/is';

const getRelativeFocusable = (element, scope) => {
if (!element || !scope || !scope.contains(element)) {
return {};
}
const focusables = getTabbableNodes([scope]);
const current = focusables.indexOf(element);
if (current === -1) {
return {};
}

return {
prev: focusables[current - 1],
next: focusables[current + 1],
first: focusables[0],
last: focusables[focusables.length - 1],
};
};

/**
* focuses next element in the tab-order
* @param baseElement
* @param scope
* @param cycle
*/
export const focusNextElement = (baseElement, { scope = document.body, cycle = true }) => {
const { next, first } = getRelativeFocusable(baseElement, scope);
const node = next || (cycle && first);
if (node) {
node.focus();
}
};

/**
* focuses prev element in the tab order
* @param baseElement
* @param parent
* @param cycle
*/
export const focusPrevElement = (baseElement, { parent = document.body, cycle = true }) => {
const { prev, last } = getRelativeFocusable(baseElement, parent);
const node = prev || (cycle && last);
if (node) {
node.focus();
}
};

0 comments on commit 3086116

Please sign in to comment.