1.8 KB57 lines
Blame
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
8import {atom} from 'jotai';
9import {writeAtom} from '../jotaiUtils';
10import {registerCleanup} from '../utils';
11
12/** Subset of KeyboardEvent. */
13export 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. */
22export const keyPressAtom = atom<KeyPress>({});
23
24const keyChange = (e: KeyboardEvent) => {
25 const {altKey, ctrlKey, shiftKey, metaKey, isComposing} = e;
26 writeAtom(keyPressAtom, {altKey, ctrlKey, shiftKey, metaKey, isComposing});
27};
28document.addEventListener('keydown', keyChange);
29document.addEventListener('keyup', keyChange);
30const onBlur = () => {
31 // reset all pressed keys when ISL is blurred, to prevent stuck key state from vscode shortcuts
32 writeAtom(keyPressAtom, {});
33};
34window.addEventListener('blur', onBlur);
35
36registerCleanup(
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. */
47export const holdingAltAtom = atom<boolean>(get => get(keyPressAtom).altKey ?? false);
48
49/** Is the ctrl key currently held down. */
50export 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. */
53export const holdingMetaKey = atom<boolean>(get => get(keyPressAtom).metaKey ?? false);
54
55/** Is the shift key currently held down. */
56export const holdingShiftAtom = atom<boolean>(get => get(keyPressAtom).shiftKey ?? false);
57