UNPKG

@chayns-components/core

Version:

A set of beautiful React components for developing your own applications with chayns.

57 lines (54 loc) 2.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useKeyboardFocusHighlighting = void 0; var _react = require("react"); var _ColorSchemeProvider = require("../components/color-scheme-provider/ColorSchemeProvider"); /* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return */ const KEYBOARD_NAVIGATION_KEYS = new Set(['Tab', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Enter', ' ', 'Spacebar', 'Escape', 'Home', 'End', 'PageUp', 'PageDown']); /** * Tracks whether focus highlighting should be visible for keyboard navigation. * Keyboard mode is enabled via Tab and reset by mouse interaction. */ const useKeyboardFocusHighlighting = isEnabledProp => { const colorScheme = (0, _react.useContext)(_ColorSchemeProvider.ColorSchemeContext); const contextIsEnabled = (colorScheme === null || colorScheme === void 0 ? void 0 : colorScheme.shouldEnableKeyboardHighlighting) === true; const isEnabled = isEnabledProp ?? contextIsEnabled; const [isKeyboardNavigation, setIsKeyboardNavigation] = (0, _react.useState)(false); (0, _react.useEffect)(() => { const canListen = isEnabled && typeof window !== 'undefined'; const enableKeyboardNavigation = () => { setIsKeyboardNavigation(true); }; const handleKeyDown = event => { if (event.ctrlKey || event.altKey || event.metaKey) { return; } if (!KEYBOARD_NAVIGATION_KEYS.has(event.key)) { return; } enableKeyboardNavigation(); }; const disableKeyboardNavigation = () => { setIsKeyboardNavigation(current => current ? false : current); }; if (canListen) { window.addEventListener('keydown', handleKeyDown); window.addEventListener('mousedown', disableKeyboardNavigation); window.addEventListener('mousemove', disableKeyboardNavigation); } else { setIsKeyboardNavigation(false); } return () => { if (canListen) { window.removeEventListener('keydown', handleKeyDown); window.removeEventListener('mousedown', disableKeyboardNavigation); window.removeEventListener('mousemove', disableKeyboardNavigation); } }; }, [isEnabled]); return Boolean(isEnabled && isKeyboardNavigation); }; exports.useKeyboardFocusHighlighting = useKeyboardFocusHighlighting; //# sourceMappingURL=useKeyboardFocusHighlighting.js.map