-
Notifications
You must be signed in to change notification settings - Fork 287
/
io.tsx
49 lines (47 loc) · 1.39 KB
/
io.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { createContainer } from 'unstated-next';
import { useState, useEffect } from 'react';
export enum KeyboardActions {
Delete = 'Delete',
Undo = 'Undo',
Redo = 'Redo',
Save = 'Save',
}
const useIOStateContainer = createContainer(() => {
const [actions, setActions] = useState<Partial<Record<KeyboardActions, Function>>>({});
const on = (action: KeyboardActions) => {
actions[action]?.();
};
useEffect(() => {
const handleKeyboard = (event: KeyboardEvent) => {
// if (DOM.panLock) return;
const ctrl = event.ctrlKey || event.metaKey;
if (event.key === 'm') {
}
if (event.key === 'Delete') {
on(KeyboardActions.Delete);
}
if (event.key === 'Backspace') {
on(KeyboardActions.Delete);
}
if (event.key === 'z' && ctrl && !event.shiftKey) {
on(KeyboardActions.Undo);
}
if (event.key === 'z' && ctrl && event.shiftKey) {
on(KeyboardActions.Redo);
}
if (event.key === 's' && ctrl) {
event.preventDefault();
on(KeyboardActions.Save);
}
};
document.addEventListener('keydown', handleKeyboard);
return () => {
document.removeEventListener('keydown', handleKeyboard);
};
}, [actions]);
return {
setActions,
};
});
export const useIOState = useIOStateContainer.useContainer;
export const IOStateProvider = useIOStateContainer.Provider;