2024-01-01 04:55:11 +00:00
|
|
|
import { atom } from 'nanostores';
|
2023-12-28 13:03:21 +00:00
|
|
|
import { useCallback, useEffect } from 'react';
|
|
|
|
|
2024-01-01 04:55:11 +00:00
|
|
|
export const $shift = atom(false);
|
|
|
|
export const $ctrl = atom(false);
|
|
|
|
export const $meta = atom(false);
|
|
|
|
export const $alt = atom(false);
|
2023-12-28 13:03:21 +00:00
|
|
|
|
|
|
|
const $subscribers = atom(0);
|
|
|
|
|
|
|
|
const listener = (e: KeyboardEvent) => {
|
2024-01-01 04:55:11 +00:00
|
|
|
$shift.set(e.shiftKey);
|
|
|
|
$ctrl.set(e.ctrlKey);
|
|
|
|
$alt.set(e.altKey);
|
|
|
|
$meta.set(e.metaKey);
|
2023-12-28 13:03:21 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const useGlobalModifiersInit = () => {
|
|
|
|
useEffect(() => {
|
|
|
|
$subscribers.set($subscribers.get() + 1);
|
|
|
|
|
|
|
|
if ($subscribers.get() === 1) {
|
|
|
|
window.addEventListener('keydown', listener);
|
|
|
|
window.addEventListener('keyup', listener);
|
|
|
|
}
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
$subscribers.set(Math.max($subscribers.get() - 1, 0));
|
|
|
|
if ($subscribers.get() > 0) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
window.removeEventListener('keydown', listener);
|
|
|
|
window.removeEventListener('keyup', listener);
|
|
|
|
};
|
|
|
|
}, []);
|
|
|
|
};
|
|
|
|
|
|
|
|
export const useGlobalModifiersSetters = () => {
|
|
|
|
const setShift = useCallback((shift: boolean) => {
|
2024-01-01 04:55:11 +00:00
|
|
|
$shift.set(shift);
|
2023-12-28 13:03:21 +00:00
|
|
|
}, []);
|
2024-01-01 04:55:11 +00:00
|
|
|
const setCtrl = useCallback((ctrl: boolean) => {
|
|
|
|
$ctrl.set(ctrl);
|
2023-12-28 13:03:21 +00:00
|
|
|
}, []);
|
2024-01-01 04:55:11 +00:00
|
|
|
const setAlt = useCallback((alt: boolean) => {
|
|
|
|
$alt.set(alt);
|
2023-12-28 13:03:21 +00:00
|
|
|
}, []);
|
2024-01-01 04:55:11 +00:00
|
|
|
const setMeta = useCallback((meta: boolean) => {
|
|
|
|
$meta.set(meta);
|
2023-12-28 13:03:21 +00:00
|
|
|
}, []);
|
|
|
|
return { setShift, setCtrl, setAlt, setMeta };
|
|
|
|
};
|