diff --git a/src/core/snapshot.ts b/src/core/snapshot.ts index f46977da5..414d4afc8 100644 --- a/src/core/snapshot.ts +++ b/src/core/snapshot.ts @@ -26,7 +26,14 @@ export class Snapshot { } get firstAutofocusableElement() { - return this.element.querySelector("[autofocus]") + const inertDisabledOrHidden = "[inert], :disabled, [hidden], details:not([open]), dialog:not([open])" + + for (const element of this.element.querySelectorAll("[autofocus]")) { + if (element.closest(inertDisabledOrHidden) == null) return element + else continue + } + + return null } get permanentElements() { diff --git a/src/tests/fixtures/autofocus-inert.html b/src/tests/fixtures/autofocus-inert.html new file mode 100644 index 000000000..50204fcff --- /dev/null +++ b/src/tests/fixtures/autofocus-inert.html @@ -0,0 +1,28 @@ + + + + + Autofocus + + + + +

Autofocus With Inert Elements

+ + + +
+ +
+ +
+ +
+ +
+ +
+ + diff --git a/src/tests/fixtures/autofocus.html b/src/tests/fixtures/autofocus.html index dfb1354b8..a0d55fa0d 100644 --- a/src/tests/fixtures/autofocus.html +++ b/src/tests/fixtures/autofocus.html @@ -12,6 +12,7 @@

Autofocus

+ autofocus-inert.html link Outer #frame link to frames/form.html diff --git a/src/tests/functional/autofocus_tests.ts b/src/tests/functional/autofocus_tests.ts index 03deea684..06fa68e46 100644 --- a/src/tests/functional/autofocus_tests.ts +++ b/src/tests/functional/autofocus_tests.ts @@ -47,6 +47,36 @@ test("test navigating a frame with a descendant link autofocuses [autofocus]:fir ) }) +test("test autofocus visible [autofocus] element on visit with inert elements", async ({ page }) => { + await page.click("#autofocus-inert-link") + await nextBeat() + + assert.notOk( + await hasSelector(page, "#dialog-autofocus-element:focus"), + "autofocus element is ignored in a closed dialog" + ) + assert.notOk( + await hasSelector(page, "#details-autofocus-element:focus"), + "autofocus element is ignored in a closed details" + ) + assert.notOk( + await hasSelector(page, "#hidden-autofocus-element:focus"), + "autofocus element is ignored in a hidden div" + ) + assert.notOk( + await hasSelector(page, "#inert-autofocus-element:focus"), + "autofocus element is ignored in an inert div" + ) + assert.notOk( + await hasSelector(page, "#disabled-autofocus-element:focus"), + "autofocus element is ignored when disabled" + ) + assert.ok( + await hasSelector(page, "#visible-autofocus-element:focus"), + "focuses the visible [autofocus] element on the page" + ) +}) + test("test navigating a frame with a link targeting the frame autofocuses [autofocus]:first-of-type", async ({ page, }) => {