From 0ab98dd893651cbab34225fdd84c3f59a375b79e Mon Sep 17 00:00:00 2001 From: Philipp Fritsche Date: Sun, 28 Feb 2021 11:03:43 +0100 Subject: [PATCH 1/2] fix(click): focus closest focusable --- src/__tests__/click.js | 17 +++++++++++++++++ src/click.js | 17 ++++++++++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/__tests__/click.js b/src/__tests__/click.js index 3c19daa2..8a0e784e 100644 --- a/src/__tests__/click.js +++ b/src/__tests__/click.js @@ -442,3 +442,20 @@ test('calls FocusEvents with relatedTarget', () => { element0, ) }) + +test('move focus to closest focusable element', () => { + const {element} = setup(` +
+
this is not focusable
+ +
+ `) + + document.body.focus() + userEvent.click(element.children[1]) + expect(element.children[1]).toHaveFocus() + + document.body.focus() + userEvent.click(element.children[0]) + expect(element).toHaveFocus() +}) diff --git a/src/click.js b/src/click.js index 5c40fda7..1863b65a 100644 --- a/src/click.js +++ b/src/click.js @@ -65,10 +65,11 @@ function clickElement(element, init, {clickCount}) { continueDefaultHandling && element !== element.ownerDocument.activeElement ) { - if (previousElement && !isFocusable(element)) { + const closestFocusable = findClosest(element, isFocusable) + if (previousElement && !closestFocusable) { blur(previousElement, init) - } else { - focus(element, init) + } else if (closestFocusable) { + focus(closestFocusable, init) } } } @@ -84,6 +85,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) { From b6593681677842b5d12877ae09bf35ca1f37416d Mon Sep 17 00:00:00 2001 From: Philipp Fritsche Date: Sun, 28 Feb 2021 12:00:18 +0100 Subject: [PATCH 2/2] refactor: remove redundant check --- src/click.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/click.js b/src/click.js index 1863b65a..e8fe535f 100644 --- a/src/click.js +++ b/src/click.js @@ -61,10 +61,7 @@ function clickElement(element, init, {clickCount}) { element, getMouseEventOptions('mousedown', init, clickCount), ) - if ( - continueDefaultHandling && - element !== element.ownerDocument.activeElement - ) { + if (continueDefaultHandling) { const closestFocusable = findClosest(element, isFocusable) if (previousElement && !closestFocusable) { blur(previousElement, init)