Skip to content

Commit

Permalink
fix(utils): update focus visible to remove keydown approach
Browse files Browse the repository at this point in the history
  • Loading branch information
brandyscarney committed Jan 7, 2025
1 parent 3cb9e13 commit d4230a8
Showing 1 changed file with 7 additions and 34 deletions.
41 changes: 7 additions & 34 deletions core/src/utils/focus-visible.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,5 @@
const ION_FOCUSED = 'ion-focused';
const ION_FOCUSABLE = 'ion-focusable';
const FOCUS_KEYS = [
'Tab',
'ArrowDown',
'Space',
'Escape',
' ',
'Shift',
'Enter',
'ArrowLeft',
'ArrowRight',
'ArrowUp',
'Home',
'End',
];

export interface FocusVisibleUtility {
destroy: () => void;
Expand All @@ -22,7 +8,6 @@ export interface FocusVisibleUtility {

export const startFocusVisible = (rootEl?: HTMLElement): FocusVisibleUtility => {
let currentFocus: Element[] = [];
let keyboardMode = true;

const ref = rootEl ? rootEl.shadowRoot! : document;
const root = rootEl ? rootEl : document.body;
Expand All @@ -32,43 +17,31 @@ export const startFocusVisible = (rootEl?: HTMLElement): FocusVisibleUtility =>
elements.forEach((el) => el.classList.add(ION_FOCUSED));
currentFocus = elements;
};

const pointerDown = () => {
keyboardMode = false;
setFocus([]);
};

const onKeydown = (ev: Event) => {
keyboardMode = FOCUS_KEYS.includes((ev as KeyboardEvent).key);
if (!keyboardMode) {
setFocus([]);
}
};
const onFocusin = (ev: Event) => {
if (keyboardMode && ev.composedPath !== undefined) {
const toFocus = ev.composedPath().filter((el: any) => {
// TODO(FW-2832): type
if (el.classList) {
return el.classList.contains(ION_FOCUSABLE);
}
return false;
}) as Element[];
setFocus(toFocus);
}
const toFocus = ev.composedPath().filter((el): el is HTMLElement => {
return el instanceof HTMLElement && el.classList.contains(ION_FOCUSABLE);
});

setFocus(toFocus);
};

const onFocusout = () => {
if (ref.activeElement === root) {
setFocus([]);
}
};

ref.addEventListener('keydown', onKeydown);
ref.addEventListener('focusin', onFocusin);
ref.addEventListener('focusout', onFocusout);
ref.addEventListener('touchstart', pointerDown, { passive: true });
ref.addEventListener('mousedown', pointerDown);

const destroy = () => {
ref.removeEventListener('keydown', onKeydown);
ref.removeEventListener('focusin', onFocusin);
ref.removeEventListener('focusout', onFocusout);
ref.removeEventListener('touchstart', pointerDown);
Expand Down

0 comments on commit d4230a8

Please sign in to comment.