Skip to content

Commit 85206b2

Browse files
committed
fix: make focus management lazy, on focus of toolbar.
This allows toolbars to be in an initially hidden state, and only when they are visible and focus moves to them does the focus management kick in.
1 parent 715efc8 commit 85206b2

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

index.js

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const buttonSelectors = [
1515
'md-mention',
1616
'md-ref'
1717
]
18-
function getButtons(toolbar: Element): Element[] {
18+
function getButtons(toolbar: Element): HTMLElement[] {
1919
const els = []
2020
for (const button of toolbar.querySelectorAll(buttonSelectors.join(', '))) {
2121
// Skip buttons that are hidden, either via `hidden` attribute or CSS:
@@ -251,11 +251,8 @@ class MarkdownToolbarElement extends HTMLElement {
251251
this.field.addEventListener('keydown', fn)
252252
shortcutListeners.set(this, fn)
253253
}
254-
let tabindex = '0'
255-
for (const button of getButtons(this)) {
256-
button.setAttribute('tabindex', tabindex)
257-
if (tabindex === '0') tabindex = '-1'
258-
}
254+
this.setAttribute('tabindex', '0')
255+
this.addEventListener('focus', onToolbarFocus)
259256
}
260257

261258
disconnectedCallback() {
@@ -275,6 +272,19 @@ class MarkdownToolbarElement extends HTMLElement {
275272
}
276273
}
277274

275+
function onToolbarFocus({target}: FocusEvent) {
276+
if (!(target instanceof Element)) return
277+
let tabindex = '0'
278+
target.removeAttribute('tabindex')
279+
for (const button of getButtons(target)) {
280+
button.setAttribute('tabindex', tabindex)
281+
if (tabindex === '0') {
282+
button.focus()
283+
tabindex = '-1'
284+
}
285+
}
286+
}
287+
278288
function focusKeydown(event: KeyboardEvent) {
279289
const key = event.key
280290
if (key !== 'ArrowRight' && key !== 'ArrowLeft' && key !== 'Home' && key !== 'End') return
@@ -296,9 +306,7 @@ function focusKeydown(event: KeyboardEvent) {
296306
buttons[i].setAttribute('tabindex', i === n ? '0' : '-1')
297307
}
298308

299-
if (buttons[n] instanceof HTMLElement) {
300-
buttons[n].focus()
301-
}
309+
buttons[n].focus()
302310
}
303311

304312
const shortcutListeners = new WeakMap()

test/test.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,10 @@ describe('markdown-toolbar-element', function() {
113113
return [...document.querySelectorAll(`markdown-toolbar [tabindex="${index}"]`)]
114114
}
115115

116+
beforeEach(() => {
117+
document.querySelector('markdown-toolbar').focus()
118+
})
119+
116120
it('moves focus to next button when ArrowRight is pressed', function() {
117121
focusFirstButton()
118122
pushKeyOnFocussedButton('ArrowRight')

0 commit comments

Comments
 (0)