|
|
|
|
|
const keyboardNavigationKeycodes = [ 9, 32, 37, 38, 39, 40 ]; |
|
|
|
|
|
|
|
|
const keyboardNavigationKeyValues = [ |
|
|
'Tab', |
|
|
' ', |
|
|
|
|
|
'Spacebar', |
|
|
'ArrowDown', |
|
|
'ArrowUp', |
|
|
'ArrowLeft', |
|
|
'ArrowRight', |
|
|
]; |
|
|
|
|
|
declare global { |
|
|
interface KeyboardEvent { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
keyIdentifier: string; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function detectKeyboardNavigation( event: KeyboardEvent ): boolean { |
|
|
let code: number | string | undefined; |
|
|
|
|
|
if ( event.key !== undefined ) { |
|
|
code = event.key; |
|
|
} else if ( event.keyIdentifier !== undefined ) { |
|
|
code = event.keyIdentifier; |
|
|
} else if ( event.keyCode !== undefined ) { |
|
|
code = event.keyCode; |
|
|
} |
|
|
|
|
|
|
|
|
if ( code === undefined ) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
if ( typeof code === 'string' ) { |
|
|
return keyboardNavigationKeyValues.indexOf( code ) !== -1; |
|
|
} |
|
|
|
|
|
return keyboardNavigationKeycodes.indexOf( code ) !== -1; |
|
|
} |
|
|
|
|
|
let keyboardNavigation = false; |
|
|
|
|
|
export default function accessibleFocus(): void { |
|
|
document.addEventListener( 'keydown', function ( event ) { |
|
|
if ( keyboardNavigation ) { |
|
|
return; |
|
|
} |
|
|
|
|
|
if ( detectKeyboardNavigation( event ) ) { |
|
|
keyboardNavigation = true; |
|
|
document.documentElement.classList.add( 'accessible-focus' ); |
|
|
} |
|
|
} ); |
|
|
document.addEventListener( 'mouseup', function () { |
|
|
if ( ! keyboardNavigation ) { |
|
|
return; |
|
|
} |
|
|
keyboardNavigation = false; |
|
|
document.documentElement.classList.remove( 'accessible-focus' ); |
|
|
} ); |
|
|
} |
|
|
|