Direct answer
All three problems have a markup-level fix, and the fixes are small. Clickable divs become <button type="button">, so the browser supplies the role, the Tab stop and the Enter and Space keys. Icon-only buttons get an accessible name (the label that assistive technology and the browser's accessibility tree expose for a control) from aria-label or from visually hidden text, with the decorative icon marked aria-hidden="true". A panel that takes focus from the page becomes a <dialog> opened with showModal(), which moves focus into the panel, makes the rest of the page inert so that Tab and Shift+Tab cannot land on anything behind the panel (inert: the browser ignores clicks and focus there and hides it from assistive technology), closes on Escape and, in the engines tested below, hands focus back to the trigger. All of it is visible to a keyboard user only if a :focus-visible outline replaces the library's outline: none reset.
The three problems, side by side
| Problem | Before (what the user gets) | Markup fix | After (what the user gets) |
|---|
| Clickable div | Tab skips it; Enter and Space do nothing; no role is set on it, so it is not a button | <button type="button">Save</button> | Tab reaches it; Enter and Space each click it once |
| Icon-only button | The accessibility tree holds a button whose name is the empty string, so the control has no name | aria-label="Close" on the button plus aria-hidden="true" on the <svg>, or <span class="visually-hidden">Search</span> | The tree holds buttons named "Close" and "Search" |
| Panel steals focus | The open trigger is hidden while focused, document.activeElement falls to <body>, and the next Tab lands somewhere the user did not choose | <dialog> and one showModal() call | Focus moves into the dialog, six Tab presses never reach the page behind, Escape closes it and focus is back on the trigger |
Fix 1: clickable divs
A div has no role and no tab stop. tabindex="0" and role="button" plus key handlers can imitate a button, but a native <button> does the same with no script, so in a library the right fix is to render a <button> and keep the old class for the look. Add type="button" so it does not submit an enclosing form by accident. Before and after for a keyboard user: in the test, three Tab presses visit the icon button, the open button and the repaired Save button, and never the div; Enter and Space on the repaired button give 2 clicks while the same keys aimed at the div give 0. That zero is only meaningful if the check can fail, so a mutation swaps the div for a <button> with the same id and expects 2 clicks, which the run shows (divAsButtonClicks: 2).
Fix 2: icon-only buttons
What the user gets: a screen reader builds what it says from the control's role and name. The unfixed icon button has the role button and an empty name, so there is a control to reach but nothing that says what it does; MDN describes aria-label on an icon-only button as essential for screen reader users to understand its function ("Close" in its example). The clickable div has no role, only its text content, so it reads like plain text and not as something to activate. After the fixes the buttons carry the names "Close" and "Search" and the role button, and the repaired Save is a button named "Save". The exact spoken wording differs between screen readers.
An <svg> with no text contributes no name, and a button's name is computed from its content, so the button is exposed with an empty name. Two fixes work, and both are exercised:
aria-label="Close" on the <button>: the name is exactly the string you give it. Mark the inner icon aria-hidden="true" (which hides it from assistive technology) and focusable="false" (which keeps the SVG itself from becoming a Tab stop where a browser would make it one) so it is not double-counted.
- Visually hidden text: a
<span class="visually-hidden">Search</span> inside the button. The CSS reads as follows: position: absolute takes the span out of the layout so it takes no space; width and height of 1px shrink its box; overflow: hidden and clip-path: inset(50%) (a clip that cuts 50% from every side, leaving nothing visible) hide anything beyond that; white-space: nowrap keeps the text on one line so it is not wrapped into a tall column. The test reads the box as 1x1, so the text is invisible but still in the accessibility tree.
Fix 3: focus that vanishes when a panel opens
The faulty library code hides the trigger and shows the panel without moving focus. Focus sits on an element that is now display: none, so document.activeElement reverts to <body> and the keyboard user loses their place. Where the next Tab goes then depends on the engine (in the run below Chromium and Firefox continue from the old position, to the panel's button, and WebKit starts from the top of the page).
The fix is markup plus one line of script: the browser feature does the focus management, so do not hand-roll a focus trap. Walking the unfixed panel with the Tab key shows the failure: the first Tab reaches the icon button, the second reaches "Open filters", Enter hides that button and shows the panel, and focus drops to <body>. The next Tab then goes to the panel's Done button (b-close) in Chromium and Firefox, or back to the first icon button in WebKit, and a keyboard user who expected to start inside the panel has to find it. The clickable div is never visited at all.
html
<dialog id="a-panel" aria-labelledby="a-title"> ... </dialog>
<script>document.getElementById('a-open').addEventListener('click', () => document.getElementById('a-panel').showModal());</script>
MDN documents the pieces (inert means the browser ignores clicks and focus on that part of the page and hides it from assistive technology): "Modal dialog boxes block interaction with other UI elements, making the rest of the page inert", "By default, a dialog invoked by the showModal() method can be dismissed by pressing the Esc key", and "focus is set on the first nested focusable element" (use autofocus to choose a better target). In the run, the first focusable element in the dialog was the checkbox, since it comes first in the source. That is also the reason to put the heading and controls in a deliberate order. The run also shows focus returning to the opener after Escape in all three engines.
Focus style for all three
The library's button:focus { outline: none; } reset is why users cannot see focus, and replacing it is part of every fix above. The test replaces it with :is(button, a, input):focus-visible { outline: 3px solid ...; } (:is() matches an element that matches any selector in its list; :focus-visible matches when the browser decides an indicator is useful, such as for keyboard focus) and checks that the computed outline after Tab is 3px solid; with the rule deleted it is none.
The page and the test
html
<!-- library.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Component library fixes</title>
<style>
button:focus, [role="button"]:focus { outline: none; } /* the library's reset */
:is(button, a, input):focus-visible { outline: 3px solid #f59e0b; outline-offset: 2px; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.icon { width: 1.25rem; height: 1.25rem; }
</style>
</head>
<body>
<h1>Before</h1>
<div id="b-div" class="action">Save</div>
<button id="b-icon" type="button"><svg class="icon" viewBox="0 0 20 20"><path d="M4 4l12 12M16 4L4 16" stroke="currentColor" fill="none"/></svg></button>
<button id="b-open" type="button">Open filters</button>
<div id="b-panel" hidden><h2>Filters</h2><button id="b-close" type="button">Done</button></div>
<h1>After</h1>
<button id="a-btn" type="button">Save</button>
<button id="a-label" type="button" aria-label="Close"><svg class="icon" viewBox="0 0 20 20" aria-hidden="true" focusable="false"><path d="M4 4l12 12M16 4L4 16" stroke="currentColor" fill="none"/></svg></button>
<button id="a-text" type="button"><svg class="icon" viewBox="0 0 20 20" aria-hidden="true" focusable="false"><circle cx="8" cy="8" r="5" stroke="currentColor" fill="none"/></svg><span class="visually-hidden">Search</span></button>
<button id="a-open" type="button">Open filters</button>
<dialog id="a-panel" aria-labelledby="a-title">
<h2 id="a-title">Filters</h2>
<label><input id="a-stock" type="checkbox"> In stock only</label>
<button id="a-done" type="button" aria-label="Close filters"><svg class="icon" viewBox="0 0 20 20" aria-hidden="true" focusable="false"><path d="M4 4l12 12M16 4L4 16" stroke="currentColor" fill="none"/></svg></button>
</dialog>
<p><a id="bg" href="#end">Link behind the panel</a></p>
<span id="end"></span>
<script>
window.n = { bDiv: 0, aBtn: 0 };
document.getElementById('b-div').addEventListener('click', () => window.n.bDiv++);
document.getElementById('a-btn').addEventListener('click', () => window.n.aBtn++);
// Before: the trigger is hidden and the panel shown, and focus is not moved anywhere.
document.getElementById('b-open').addEventListener('click', () => {
document.getElementById('b-open').hidden = true;
document.getElementById('b-panel').hidden = false;
});
// After: showModal() is the one line of JS; focus, an inert page behind the panel, Escape and focus return come from <dialog>.
document.getElementById('a-open').addEventListener('click', () => document.getElementById('a-panel').showModal());
document.getElementById('a-done').addEventListener('click', () => document.getElementById('a-panel').close());
</script>
</body>
</html>
The test runs in Chromium, Firefox and WebKit (Playwright's WebKit build; this is not Safari). It asserts the Tab stops, the click counts, the accessible names read from the accessibility tree (exactly one empty name, which is the unfixed icon button, plus "Close" and "Search"), the visually hidden box size, where focus goes before and after, that six Tab presses never reach the link behind the dialog, that Escape returns focus to the opener, and the outline. Three mutations (deliberately changing the markup to prove a check can fail) show the checks do work: replacing the div with a <button> makes the div check see 2 clicks instead of 0, deleting aria-label="Close" makes a second empty name appear (the string occurs once, because the dialog's button says Close filters; the test throws if that stops being true), and deleting the focus rule gives outline none.
js
// library-test.mjs
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
const html = readFileSync('library.html', 'utf8');
let failures = 0;
const check = (ok, msg) => { if (!ok) { failures++; console.log(' FAIL', msg); } };
const active = (page) => page.evaluate(() => document.activeElement.id || document.activeElement.tagName);
// Accessible name of every button in the accessibility tree, in document order.
const buttons = async (page) => {
const out = [];
(function walk(n) { if (n.role === 'button') out.push(n.name); (n.children || []).forEach(walk); })(await page.accessibility.snapshot({ interestingOnly: false }));
return out;
};
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const b = await type.launch();
const page = await b.newPage();
await page.setContent(html);
const result = {};
// 1. Clickable div versus button: keyboard reach and activation.
const tabStops = [];
for (let i = 0; i < 3; i++) { await page.keyboard.press('Tab'); tabStops.push(await active(page)); }
result.tabStops = tabStops.join('>');
check(!tabStops.includes('b-div') && tabStops[0] === 'b-icon', `${name} tab stops ${result.tabStops}`);
await page.focus('#a-btn');
await page.keyboard.press('Enter'); await page.keyboard.press(' ');
result.buttonClicks = await page.evaluate(() => window.n.aBtn);
// Try the same two keys on the div: blur whatever has focus, ask for focus on the div, press Enter and Space.
const divKeyboardClicks = async () => {
await page.evaluate(() => document.activeElement.blur());
await page.focus('#b-div');
await page.keyboard.press('Enter'); await page.keyboard.press(' ');
return page.evaluate(() => window.n.bDiv);
};
result.divClicks = await divKeyboardClicks();
check(result.buttonClicks === 2 && result.divClicks === 0, `${name} clicks`);
// 2. Icon-only buttons: names in the accessibility tree.
const names = await buttons(page);
result.names = JSON.stringify(names);
check(names.filter((n) => n === '').length === 1 && names.includes('Close') && names.includes('Search') && names.length === 6, `${name} names ${result.names}`);
const hidden = await page.$eval('#a-text .visually-hidden', (el) => { const r = el.getBoundingClientRect(); return `${r.width}x${r.height}`; });
result.visuallyHiddenBox = hidden;
check(hidden === '1x1', `${name} visually-hidden box ${hidden}`);
// 3a. Before: the trigger is hidden while it holds focus, so focus falls back to the body (where the next Tab goes is engine-dependent).
await page.focus('#b-open'); await page.keyboard.press('Enter');
// WebKit reports the hidden trigger as focused for one frame, so wait for focus to settle on the body.
await page.waitForFunction(() => document.activeElement === document.body);
result.beforeFocus = await active(page);
await page.keyboard.press('Tab');
result.tabAfterLoss = await active(page);
check(result.beforeFocus === 'BODY', `${name} before focus ${result.beforeFocus}`);
// 3b. After: showModal moves focus into the dialog, makes the page behind it unreachable by Tab, Escape closes it and returns focus to the trigger.
await page.focus('#a-open'); await page.keyboard.press('Enter');
result.afterFocus = await active(page);
check(await page.evaluate(() => !!document.activeElement.closest('dialog')), `${name} focus not in dialog`);
let leaked = false;
for (let i = 0; i < 6; i++) { await page.keyboard.press('Tab'); if (await active(page) === 'bg') leaked = true; }
result.tabLeaksToBackground = leaked;
check(!leaked, `${name} Tab reached background link`);
await page.keyboard.press('Escape');
await page.waitForFunction(() => !document.getElementById('a-panel').open);
result.afterEscape = await active(page);
check(result.afterEscape === 'a-open', `${name} focus after Escape ${result.afterEscape}`);
// 4. Focus indicator: visible on keyboard focus, from the :focus-visible rule.
await page.focus('#a-open'); await page.keyboard.press('Shift+Tab'); await page.keyboard.press('Tab');
result.outline = await page.$eval('#a-open', (el) => getComputedStyle(el).outlineWidth + ' ' + getComputedStyle(el).outlineStyle);
check(result.outline === '3px solid', `${name} outline ${result.outline}`);
// 5. Mutations: delete aria-label (name goes empty); delete the :focus-visible rule (outline goes none).
const noLabel = html.replace(' aria-label="Close"', '');
if (html.split(' aria-label="Close"').length !== 2) throw new Error('aria-label="Close" is not unique');
await page.setContent(noLabel);
const mutNames = await buttons(page);
check(mutNames.filter((n) => n === '').length === 2, `${name} mutation names ${JSON.stringify(mutNames)}`);
const noRule = html.replace(/ :is\(button[^\n]*\n/, '');
if (noRule === html) throw new Error('focus rule not removed');
// Mutation: make the div a real button (same id, so the same counter) and the div check must now see 2 clicks.
await page.setContent(html.replace('<div id="b-div" class="action">Save</div>', '<button id="b-div" type="button">Save</button>'));
const mutDivClicks = await divKeyboardClicks();
check(mutDivClicks === 2, `${name} mutation div-as-button should give 2 clicks, got ${mutDivClicks}`);
result.divAsButtonClicks = mutDivClicks;
await page.setContent(noRule);
await page.focus('#a-open'); await page.keyboard.press('Shift+Tab'); await page.keyboard.press('Tab');
result.outlineWithoutRule = await page.$eval('#a-open', (el) => getComputedStyle(el).outlineStyle);
check(result.outlineWithoutRule === 'none', `${name} mutation outline`);
console.log(name, JSON.stringify(result));
await b.close();
}
console.log(failures === 0 ? 'ALL CHECKS PASSED' : `${failures} FAILURES`);
process.exit(failures ? 1 : 0);
Output (the script above run in the Playwright 1.48.2 image; the lines were identical across repeated runs). The keys are the measurements: tabStops is where three Tab presses land, names is the name of every button in the accessibility tree (the single "" is the unfixed icon button), beforeFocus and tabAfterLoss are the focus owner after the unfixed panel opens and after one more Tab, afterFocus is where showModal() puts focus, and afterEscape is where focus returns:
text
chromium {"tabStops":"b-icon>b-open>a-btn","buttonClicks":2,"divClicks":0,"names":"[\"\",\"Open filters\",\"Save\",\"Close\",\"Search\",\"Open filters\"]","visuallyHiddenBox":"1x1","beforeFocus":"BODY","tabAfterLoss":"b-close","afterFocus":"a-stock","tabLeaksToBackground":false,"afterEscape":"a-open","outline":"3px solid","divAsButtonClicks":2,"outlineWithoutRule":"none"}
firefox {"tabStops":"b-icon>b-open>a-btn","buttonClicks":2,"divClicks":0,"names":"[\"\",\"Open filters\",\"Save\",\"Close\",\"Search\",\"Open filters\"]","visuallyHiddenBox":"1x1","beforeFocus":"BODY","tabAfterLoss":"b-close","afterFocus":"a-stock","tabLeaksToBackground":false,"afterEscape":"a-open","outline":"3px solid","divAsButtonClicks":2,"outlineWithoutRule":"none"}
webkit {"tabStops":"b-icon>b-open>a-btn","buttonClicks":2,"divClicks":0,"names":"[\"\",\"Open filters\",\"Save\",\"Close\",\"Search\",\"Open filters\"]","visuallyHiddenBox":"1x1","beforeFocus":"BODY","tabAfterLoss":"b-icon","afterFocus":"a-stock","tabLeaksToBackground":false,"afterEscape":"a-open","outline":"3px solid","divAsButtonClicks":2,"outlineWithoutRule":"none"}
ALL CHECKS PASSED
Trade-offs and pitfalls
aria-label replaces visible text. Put it on controls with no visible text. On a button that already shows "Close", aria-label adds a second source of text that can drift from the visible words; use it for icon-only controls.
- A
<dialog> is the markup answer, not the whole component. The JavaScript step is just the showModal() call and, if the app removes or re-renders the trigger, restoring focus to a sensible element yourself, since focus return is only helpful when the opener still exists. Widget-level focus management belongs to the component's own code.
- Native
<dialog> is not a closed loop. The specification only makes the rest of the document inert, so the dialog's controls are the only page content Tab can reach, but the browser's own interface (address bar, toolbar) sits outside the document. In a normal window, Tab past the last control can move focus there instead of wrapping to the first control; the W3C ARIA Authoring Practices discussion of this (w3c/aria-practices issue 1772) records that native dialogs do not wrap. The headless browsers used in the test have no such interface, so the test can show only that the page behind is unreachable (six Tab presses never reach the link), not that focus cycles. Do not claim a closed loop unless you have written one and tested it in a headed browser.
- Do not suppress the Escape default with a key handler that swallows it, or keyboard users lose the way out.
- Library rollout. Fix these three in the shared component so every consumer inherits the repair, and add the Playwright checks above to the component's test suite so a change that removes a label or reintroduces
outline: none fails.
Running the code
bash
mkdir demo && cd demo && echo '{"type":"module"}' > package.json
# save library.html and library-test.mjs from above into this folder
docker run --rm -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'npm i playwright@1.48.2 && node library-test.mjs'