| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import {atom} from 'jotai'; |
| 9 | import {writeAtom} from '../jotaiUtils'; |
| 10 | import {registerCleanup} from '../utils'; |
| 11 | |
| 12 | /** Subset of KeyboardEvent. */ |
| 13 | export type KeyPress = { |
| 14 | altKey?: boolean; |
| 15 | ctrlKey?: boolean; |
| 16 | shiftKey?: boolean; |
| 17 | metaKey?: boolean; |
| 18 | isComposing?: boolean; |
| 19 | }; |
| 20 | |
| 21 | /** State of if modified keys (alt, ctrl, etc) are currently pressed. */ |
| 22 | export const keyPressAtom = atom<KeyPress>({}); |
| 23 | |
| 24 | const keyChange = (e: KeyboardEvent) => { |
| 25 | const {altKey, ctrlKey, shiftKey, metaKey, isComposing} = e; |
| 26 | writeAtom(keyPressAtom, {altKey, ctrlKey, shiftKey, metaKey, isComposing}); |
| 27 | }; |
| 28 | document.addEventListener('keydown', keyChange); |
| 29 | document.addEventListener('keyup', keyChange); |
| 30 | const onBlur = () => { |
| 31 | // reset all pressed keys when ISL is blurred, to prevent stuck key state from vscode shortcuts |
| 32 | writeAtom(keyPressAtom, {}); |
| 33 | }; |
| 34 | window.addEventListener('blur', onBlur); |
| 35 | |
| 36 | registerCleanup( |
| 37 | keyPressAtom, |
| 38 | () => { |
| 39 | document.removeEventListener('keydown', keyChange); |
| 40 | document.removeEventListener('keyup', keyChange); |
| 41 | window.removeEventListener('blur', onBlur); |
| 42 | }, |
| 43 | import.meta.hot, |
| 44 | ); |
| 45 | |
| 46 | /** Is the alt key currently held down. */ |
| 47 | export const holdingAltAtom = atom<boolean>(get => get(keyPressAtom).altKey ?? false); |
| 48 | |
| 49 | /** Is the ctrl key currently held down. */ |
| 50 | export const holdingCtrlAtom = atom<boolean>(get => get(keyPressAtom).ctrlKey ?? false); |
| 51 | |
| 52 | /** Is the meta ("Command" on macOS, or "Windows" on Windows) key currently held down. */ |
| 53 | export const holdingMetaKey = atom<boolean>(get => get(keyPressAtom).metaKey ?? false); |
| 54 | |
| 55 | /** Is the shift key currently held down. */ |
| 56 | export const holdingShiftAtom = atom<boolean>(get => get(keyPressAtom).shiftKey ?? false); |
| 57 | |