Skip to content

Commit

Permalink
perf(tab): avert visibility check on irrelevant elements (#967)
Browse files Browse the repository at this point in the history
Check visibility only on elements which are next/previous in tab order and thus considered a potential target.

Co-authored-by: Philipp Fritsche <ph.fritsche@gmail.com>
  • Loading branch information
camchenry and ph-fritsche committed Jun 17, 2022
1 parent 9dd3985 commit d2d8a39
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
30 changes: 20 additions & 10 deletions src/utils/focus/getTabDestination.ts
Expand Up @@ -10,14 +10,11 @@ export function getTabDestination(activeElement: Element, shift: boolean) {
const enabledElements = Array.from(focusableElements).filter(
el =>
el === activeElement ||
(el.getAttribute('tabindex') !== '-1' &&
!isDisabled(el) &&
// Hidden elements are not tabable
isVisible(el)),
!(Number(el.getAttribute('tabindex')) < 0 || isDisabled(el)),
)

if (activeElement.getAttribute('tabindex') !== '-1') {
// tabindex has no effect if the active element has tabindex="-1"
// tabindex has no effect if the active element has negative tabindex
if (Number(activeElement.getAttribute('tabindex')) >= 0) {
enabledElements.sort((a, b) => {
const i = Number(a.getAttribute('tabindex'))
const j = Number(b.getAttribute('tabindex'))
Expand Down Expand Up @@ -73,9 +70,22 @@ export function getTabDestination(activeElement: Element, shift: boolean) {
prunedElements.push(el)
})

const currentIndex = prunedElements.findIndex(el => el === activeElement)
for (let index = prunedElements.findIndex(el => el === activeElement); ; ) {
index += shift ? -1 : 1

const nextIndex = shift ? currentIndex - 1 : currentIndex + 1
const defaultIndex = shift ? prunedElements.length - 1 : 0
return prunedElements[nextIndex] || prunedElements[defaultIndex]
// loop at overflow
if (index === prunedElements.length) {
index = 0
} else if (index === -1) {
index = prunedElements.length - 1
}

if (
prunedElements[index] === activeElement ||
prunedElements[index] === document.body ||
isVisible(prunedElements[index])
) {
return prunedElements[index]
}
}
}
8 changes: 5 additions & 3 deletions tests/utils/focus/getTabDestination.ts
Expand Up @@ -46,12 +46,13 @@ test('get next focusable element in tab order', () => {
const {
elements: [elA, elB, elC, elD, elE, elF],
} = setup(`
<input id="a" tabIndex="2"/>
<input id="a" tabIndex="2">
<input id="b" tabIndex="0">
<input id="c" tabIndex="-1"/>
<input id="c" tabIndex="-1">
<input id="d" tabIndex="0">
<input id="e" tabIndex="1">
<input id="f" />
<input id="f">
<input id="g" tabIndex="-999">
`)

assertTabOrder([elE, elA, elB, elD, elF])
Expand All @@ -72,6 +73,7 @@ test('exclude hidden elements', () => {
} = setup(`
<input/>
<input type="hidden"/>
<input hidden />
<input style="visibility: hidden"/>
<input style="display: none"/>
`)
Expand Down

0 comments on commit d2d8a39

Please sign in to comment.