Skip to content

Commit

Permalink
feat(hooks): reset modifiers on window blur
Browse files Browse the repository at this point in the history
  • Loading branch information
psychedelicious committed Sep 10, 2024
1 parent beb7d62 commit b6e2e4b
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions lib/hooks/use-global-modifiers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { useStore } from '@nanostores/react';
import { atom } from 'nanostores';
import { useEffect } from 'react';

import { useAssertSingleton } from './use-assert-singleton';

/**
* A `nanostores` atom that represents the current state of the shift key.
* If true, the shift key is currently pressed.
Expand All @@ -23,30 +25,37 @@ export const $meta = atom(false);
*/
export const $alt = atom(false);

const $isInitialized = atom(0);

const listener = (e: KeyboardEvent) => {
$shift.set(e.shiftKey);
$ctrl.set(e.ctrlKey);
$alt.set(e.altKey);
$meta.set(e.metaKey);
};

const reset = () => {
$shift.set(false);
$ctrl.set(false);
$alt.set(false);
$meta.set(false);
};

const symbol = Symbol('useGlobalModifiersInit');

/**
* Initializes the global modifiers state. This hook is a singleton.
*/
export const useGlobalModifiersInit = () => {
useEffect(() => {
if ($isInitialized.get()) {
return;
}
useAssertSingleton(symbol);

useEffect(() => {
window.addEventListener('keydown', listener);
window.addEventListener('keyup', listener);
window.addEventListener('blur', reset);

return () => {
window.removeEventListener('keydown', listener);
window.removeEventListener('keyup', listener);
window.removeEventListener('blur', reset);
};
}, []);
};
Expand Down

0 comments on commit b6e2e4b

Please sign in to comment.