addons/isl/src/atoms/keyboardAtoms.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import {atom} from 'jotai';
b69ab319import {writeAtom} from '../jotaiUtils';
b69ab3110import {registerCleanup} from '../utils';
b69ab3111
b69ab3112/** Subset of KeyboardEvent. */
b69ab3113export type KeyPress = {
b69ab3114 altKey?: boolean;
b69ab3115 ctrlKey?: boolean;
b69ab3116 shiftKey?: boolean;
b69ab3117 metaKey?: boolean;
b69ab3118 isComposing?: boolean;
b69ab3119};
b69ab3120
b69ab3121/** State of if modified keys (alt, ctrl, etc) are currently pressed. */
b69ab3122export const keyPressAtom = atom<KeyPress>({});
b69ab3123
b69ab3124const keyChange = (e: KeyboardEvent) => {
b69ab3125 const {altKey, ctrlKey, shiftKey, metaKey, isComposing} = e;
b69ab3126 writeAtom(keyPressAtom, {altKey, ctrlKey, shiftKey, metaKey, isComposing});
b69ab3127};
b69ab3128document.addEventListener('keydown', keyChange);
b69ab3129document.addEventListener('keyup', keyChange);
b69ab3130const onBlur = () => {
b69ab3131 // reset all pressed keys when ISL is blurred, to prevent stuck key state from vscode shortcuts
b69ab3132 writeAtom(keyPressAtom, {});
b69ab3133};
b69ab3134window.addEventListener('blur', onBlur);
b69ab3135
b69ab3136registerCleanup(
b69ab3137 keyPressAtom,
b69ab3138 () => {
b69ab3139 document.removeEventListener('keydown', keyChange);
b69ab3140 document.removeEventListener('keyup', keyChange);
b69ab3141 window.removeEventListener('blur', onBlur);
b69ab3142 },
b69ab3143 import.meta.hot,
b69ab3144);
b69ab3145
b69ab3146/** Is the alt key currently held down. */
b69ab3147export const holdingAltAtom = atom<boolean>(get => get(keyPressAtom).altKey ?? false);
b69ab3148
b69ab3149/** Is the ctrl key currently held down. */
b69ab3150export const holdingCtrlAtom = atom<boolean>(get => get(keyPressAtom).ctrlKey ?? false);
b69ab3151
b69ab3152/** Is the meta ("Command" on macOS, or "Windows" on Windows) key currently held down. */
b69ab3153export const holdingMetaKey = atom<boolean>(get => get(keyPressAtom).metaKey ?? false);
b69ab3154
b69ab3155/** Is the shift key currently held down. */
b69ab3156export const holdingShiftAtom = atom<boolean>(get => get(keyPressAtom).shiftKey ?? false);