Skip to content

Commit

Permalink
Skip hidden [autofocus] and [x-autofocus] elements
Browse files Browse the repository at this point in the history
  • Loading branch information
imacrayon committed Mar 7, 2024
1 parent 24075e7 commit 073900a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
24 changes: 13 additions & 11 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -372,16 +372,15 @@ async function render(request, targets, el, config) {
if (merged) {
merged.dataset.source = response.url
merged.removeAttribute('aria-busy')
if (!focused) {
['[x-autofocus]', '[autofocus]'].forEach(selector => {
if (focused) return
let autofocus = merged.matches(selector) ? merged : merged.querySelector(selector)
if (autofocus) {
focusOn(autofocus)
focused = true
}
})
}
let focusables = ['[x-autofocus]', '[autofocus]']
focusables.some(selector => {
if (focused) return true
if (merged.matches(selector)) {
focused = focusOn(merged)
}

return focused || Array.from(merged.querySelectorAll(selector)).some(focusable => focusOn(focusable))
})
}

dispatch(merged, 'ajax:merged')
Expand Down Expand Up @@ -453,11 +452,14 @@ async function merge(strategy, from, to) {
}

function focusOn(el) {
if (!el) return
if (!el) return false
if (!el.getClientRects().length) return false
setTimeout(() => {
if (!el.hasAttribute('tabindex')) el.setAttribute('tabindex', '0')
el.focus()
}, 0)

return true
}

function updateHistory(strategy, url) {
Expand Down
14 changes: 14 additions & 0 deletions tests/focus.cy.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,20 @@ test('first listed target is focused when multiple [autofocus] are merged',
}
)

test('hidden [autofocus] elements are ignored',
html`<form x-init x-target id="replace" method="post"><button>First</button><a href="#">Second</a></form>`,
({ intercept, get, wait }) => {
intercept('POST', '/tests', {
statusCode: 200,
body: '<form x-init x-target id="replace" method="post"><button hidden autofocus>First</button><a href="#" autofocus>Second</a></form>'
}).as('response')
get('button').focus().click()
wait('@response').then(() => {
get('a').should('have.focus')
})
}
)

test('[x-autofocus] overrides [autofocus]',
html`<form x-init x-target id="replace" method="post"><button>First</button><a href="#">Second</a></form>`,
({ intercept, get, wait }) => {
Expand Down

0 comments on commit 073900a

Please sign in to comment.