|
| 1 | +/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 | + |
| 5 | +import * as React from 'react'; |
| 6 | + |
| 7 | +// Global state for Alt key tracking |
| 8 | +let isAltPressed = false; |
| 9 | +const listeners = new Set<(pressed: boolean) => void>(); |
| 10 | + |
| 11 | +// Initialize global event listeners once |
| 12 | +if (typeof window !== 'undefined') { |
| 13 | + const handleKeyDown = (event: KeyboardEvent) => { |
| 14 | + if (event.altKey && !isAltPressed) { |
| 15 | + isAltPressed = true; |
| 16 | + listeners.forEach((listener) => listener(true)); |
| 17 | + } |
| 18 | + }; |
| 19 | + |
| 20 | + const handleKeyUp = (event: KeyboardEvent) => { |
| 21 | + if (!event.altKey && isAltPressed) { |
| 22 | + isAltPressed = false; |
| 23 | + listeners.forEach((listener) => listener(false)); |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + const handleBlur = () => { |
| 28 | + // Reset Alt state when window loses focus |
| 29 | + if (isAltPressed) { |
| 30 | + isAltPressed = false; |
| 31 | + listeners.forEach((listener) => listener(false)); |
| 32 | + } |
| 33 | + }; |
| 34 | + |
| 35 | + window.addEventListener('keydown', handleKeyDown); |
| 36 | + window.addEventListener('keyup', handleKeyUp); |
| 37 | + window.addEventListener('blur', handleBlur); |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Custom hook that tracks whether the Alt key is currently pressed. |
| 42 | + * Returns true when Alt is pressed, false otherwise. |
| 43 | + * The state is global and shared across all component instances. |
| 44 | + */ |
| 45 | +export function useAltKey(): boolean { |
| 46 | + const [altPressed, setAltPressed] = React.useState(isAltPressed); |
| 47 | + |
| 48 | + React.useEffect(() => { |
| 49 | + // Set initial state |
| 50 | + setAltPressed(isAltPressed); |
| 51 | + |
| 52 | + // Subscribe to changes |
| 53 | + const listener = (pressed: boolean) => { |
| 54 | + setAltPressed(pressed); |
| 55 | + }; |
| 56 | + listeners.add(listener); |
| 57 | + |
| 58 | + return () => { |
| 59 | + listeners.delete(listener); |
| 60 | + }; |
| 61 | + }, []); |
| 62 | + |
| 63 | + return altPressed; |
| 64 | +} |
0 commit comments