Hotkeys with Effector made easy
- Easy-to-use, no need to implement by yourself
- Supports both Windows/MacOS style hotkeys
- Doesn't break if using with SSR
npm i effector-hotkey
import { hotkey } from 'effector-hotkey';
const copyPressed = hotkey({ key: 'Ctrl+C' });
sample({
clock: copyPressed,
source: $formData,
target: saveFx,
});
import { hotkey } from 'effector-hotkey';
const spaceDown = hotkey({ key: 'Space', type: 'keydown' });
const spaceUp = hotkey({ key: 'Space', type: 'keyup' });
const spacePress = hotkey({ key: 'Space', type: 'keypress' });
import { hotkey } from 'effector-hotkey';
const copyPressed = hotkey('Ctrl+C');
const spaceDown = hotkey('Space', 'keydown');
import { hotkey } from 'effector-hotkey';
import { createStore } from 'effector';
const $isConfirmModalOpened = createStore(true);
hotkey({
key: 'Y',
filter: $isConfirmModalOpened,
target: removeFx,
});
hotkey({
key: 'N',
filter: $isConfirmModalOpened,
target: closeModal,
});
If you want to just trigger something instead of listening to event, you can use target
prop:
import { sample } from 'effector';
import { hotkey } from 'effector-hotkey';
hotkey({
key: 'Ctrl+C',
target: copyTextFx,
});
// <=>
sample({
clock: hotkey('Ctrl+C'),
target: copyTextFx,
});
You can use internal wrappers for native events as well
import { keyup, keydown, keypress } from 'effector-hotkey';
keyup.watch(console.log); // KeyboardEvent
You can also use pre-made stores to track if Shift
/Ctrl
/Alt
buttons are held
Simple use-case: display hotkeys in UI while holding Ctrl
import { useStore } from 'effector-react';
import { hotkey, $isCtrlDown } from 'effector-hotkey';
const SubmitButton = () => {
const isCtrlDown = useStore($isCtrlDown);
return (
<Button onClick={savePressed}>{isCtrlDown ? 'Ctrl+S' : 'Save'}</Button>
);
};
const savePressed = createEvent<MouseEvent>();
sample({
clock: [savePressed, hotkey('Ctrl+S')],
target: saveFx,
});