| 1 |
export function focusElement(elementOrSelector: string | HTMLElement) { |
| 2 |
let el: HTMLElement | null; |
| 3 |
if (typeof elementOrSelector === 'string') { |
| 4 |
el = document.querySelector<HTMLElement>(elementOrSelector); |
| 5 |
} else { |
| 6 |
el = elementOrSelector; |
| 7 |
} |
| 8 |
|
| 9 |
if (!(el instanceof HTMLElement)) return; |
| 10 |
|
| 11 |
// Apply a tabindex attribute to allow focusing non-focusable elements |
| 12 |
const tabindex = el.getAttribute('tabindex'); |
| 13 |
el.setAttribute('tabindex', '-1'); |
| 14 |
el.focus({ preventScroll: true }); |
| 15 |
if (tabindex !== null) { |
| 16 |
el.setAttribute('tabindex', tabindex); |
| 17 |
} else { |
| 18 |
// Removing the tabindex will reset screen reader position, so we'll keep it |
| 19 |
// el.removeAttribute('tabindex'); |
| 20 |
} |
| 21 |
} |
| 22 |
|
| 23 |
export function focusAutofocusElement(): boolean { |
| 24 |
const autofocusEl = getAutofocusElement(); |
| 25 |
if (!autofocusEl) return false; |
| 26 |
|
| 27 |
if (autofocusEl !== document.activeElement) { |
| 28 |
// Only focus if not already focused |
| 29 |
// No preventScroll flag here, as probably intended with autofocus |
| 30 |
autofocusEl.focus(); |
| 31 |
} |
| 32 |
return true; |
| 33 |
} |
| 34 |
|
| 35 |
export function getAutofocusElement(): HTMLElement | undefined { |
| 36 |
const focusEl = document.querySelector<HTMLElement>('body [autofocus]'); |
| 37 |
if (focusEl && !focusEl.closest('[inert], [aria-disabled], [aria-hidden="true"]')) { |
| 38 |
return focusEl; |
| 39 |
} |
| 40 |
} |