Skip to content

Commit

Permalink
Fix nested autofocus with multiple targets
Browse files Browse the repository at this point in the history
Fixes an issue where the wrong element would be focused only when autofocus was nested inside a target and multiple elements were targeted at the same time
  • Loading branch information
imacrayon committed Aug 17, 2024
1 parent 54f1bd9 commit fb5b7c1
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@imacrayon/alpine-ajax",
"description": "An Alpine.js plugin for building server-powered frontends.",
"version": "0.8.1",
"version": "0.8.2",
"license": "MIT",
"author": "Christian Taylor",
"homepage": "https://alpine-ajax.js.org",
Expand Down
11 changes: 5 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -455,15 +455,14 @@ async function render(response, el, targets, history, focus) {
if (merged) {
merged.dataset.source = response.url
merged.removeAttribute('aria-busy')
let focusables = ['[x-autofocus]', '[autofocus]']
focusables.some(selector => {
if (focused) return true
let selectors = ['[x-autofocus]', '[autofocus]']
while (!focused && selectors.length) {
let selector = selectors.shift()
if (merged.matches(selector)) {
focused = focusOn(merged)
}

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

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

test('first listed target is focused when multiple nested [autofocus] are merged',
html`<div id="replace2"><a href="#" autofocus>Second</a></div><div id="replace1"><a href="#" autofocus>First</a></div><form x-init x-target="replace1 replace2" method="post"><button></button></form>`,
({ intercept, get, wait }) => {
intercept('POST', '/tests', {
statusCode: 200,
body: '<div id="replace2"><a href="#" autofocus>Second Replaced</a></div><div id="replace1"><a href="#" autofocus>First Replaced</a></div>'
}).as('response')
get('button').click()
wait('@response').then(() => {
get('#replace1 a').should('have.focus')
})
}
)

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 }) => {
Expand Down

0 comments on commit fb5b7c1

Please sign in to comment.