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

fix(click): focus closest focusable (#566) #567

Merged
merged 2 commits into from
Feb 28, 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
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) {
ph-fritsche marked this conversation as resolved.
Show resolved Hide resolved
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