Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shortcutModifierState.ts

96 lines2.5 KB

1import { create } from "zustand";
2​
3export interface ShortcutModifierState {
4 metaKey: boolean;
5 ctrlKey: boolean;
6 altKey: boolean;
7 shiftKey: boolean;
8}
9​
10const EMPTY_SHORTCUT_MODIFIER_STATE: ShortcutModifierState = {
11 metaKey: false,
12 ctrlKey: false,
13 altKey: false,
14 shiftKey: false,
15};
16​
17export function areShortcutModifierStatesEqual(
18 left: ShortcutModifierState,
19 right: ShortcutModifierState,
20): boolean {
21 return (
22 left.metaKey === right.metaKey &&
23 left.ctrlKey === right.ctrlKey &&
24 left.altKey === right.altKey &&
25 left.shiftKey === right.shiftKey
26 );
28​
29const useShortcutModifierStateStore = create<{
30 state: ShortcutModifierState;
31 setState: (state: ShortcutModifierState) => void;
32 clear: () => void;
33}>((set) => ({
34 state: EMPTY_SHORTCUT_MODIFIER_STATE,
35 setState: (state) =>
36 set((current) => (areShortcutModifierStatesEqual(current.state, state) ? current : { state })),
37 clear: () =>
38 set((current) =>
39 areShortcutModifierStatesEqual(current.state, EMPTY_SHORTCUT_MODIFIER_STATE)
40 ? current
41 : { state: EMPTY_SHORTCUT_MODIFIER_STATE },
42 ),
43}));
44​
45export function useShortcutModifierState(): ShortcutModifierState {
46 return useShortcutModifierStateStore((store) => store.state);
48​
49function normalizeModifierKey(key: string): keyof ShortcutModifierState | null {
50 switch (key) {
51 case "Meta":
52 case "OS":
53 case "Command":
54 return "metaKey";
55 case "Control":
56 return "ctrlKey";
57 case "Alt":
58 case "Option":
59 return "altKey";
60 case "Shift":
61 return "shiftKey";
62 default:
63 return null;
64 }
66​
67export function syncShortcutModifierStateFromKeyboardEvent(event: KeyboardEvent): void {
68 const normalizedModifierKey = normalizeModifierKey(event.key);
69 if (normalizedModifierKey) {
70 const currentState = useShortcutModifierStateStore.getState().state;
71 useShortcutModifierStateStore.getState().setState({
72 ...currentState,
73 [normalizedModifierKey]: event.type === "keydown",
74 });
75 return;
76 }
77​
78 useShortcutModifierStateStore.getState().setState({
79 metaKey: event.metaKey,
80 ctrlKey: event.ctrlKey,
81 altKey: event.altKey,
82 shiftKey: event.shiftKey,
83 });
85​
86export function setShortcutModifierState(state: ShortcutModifierState): void {
87 useShortcutModifierStateStore.getState().setState(state);
89​
90export function clearShortcutModifierState(): void {
91 useShortcutModifierStateStore.getState().clear();
93​
94export function readShortcutModifierState(): ShortcutModifierState {
95 return useShortcutModifierStateStore.getState().state;