Skip to content

Commit

Permalink
fix(click): focus closest focusable (#566) (#567)
Browse files Browse the repository at this point in the history
* fix(click): focus closest focusable

* refactor: remove redundant check
  • Loading branch information
ph-fritsche authored Feb 28, 2021
1 parent 7a5c51e commit 73c2323
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
17 changes: 17 additions & 0 deletions src/__tests__/click.js
Original file line number Diff line number Diff line change
Expand Up @@ -442,3 +442,20 @@ test('calls FocusEvents with relatedTarget', () => {
element0,
)
})

test('move focus to closest focusable element', () => {
const {element} = setup(`
<div tabIndex="0">
<div>this is not focusable</div>
<button>this is focusable</button>
</div>
`)

document.body.focus()
userEvent.click(element.children[1])
expect(element.children[1]).toHaveFocus()

document.body.focus()
userEvent.click(element.children[0])
expect(element).toHaveFocus()
})
22 changes: 15 additions & 7 deletions src/click.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,12 @@ function clickElement(element, init, {clickCount}) {
element,
getMouseEventOptions('mousedown', init, clickCount),
)
if (
continueDefaultHandling &&
element !== element.ownerDocument.activeElement
) {
if (previousElement && !isFocusable(element)) {
if (continueDefaultHandling) {
const closestFocusable = findClosest(element, isFocusable)
if (previousElement && !closestFocusable) {
blur(previousElement, init)
} else {
focus(element, init)
} else if (closestFocusable) {
focus(closestFocusable, init)
}
}
}
Expand All @@ -84,6 +82,16 @@ function clickElement(element, init, {clickCount}) {
}
}

function findClosest(el, callback) {
do {
if (callback(el)) {
return el
}
el = el.parentElement
} while (el && el !== document.body)
return undefined
}

function click(element, init, {skipHover = false, clickCount = 0} = {}) {
if (!skipHover) hover(element, init)
switch (element.tagName) {
Expand Down

0 comments on commit 73c2323

Please sign in to comment.