1 import { PropsWithChildren, useCallback, useMemo, useState } from "react"
2
3 import { useShortcuts } from "./hooks"
4 import { KeybindContext } from "./keybind-context"
5 import { KeybindContextState, Shortcut } from "./types"
6 import {
7 findFirstPlatformMatch,
8 findShortcutIndex,
9 getShortcutKeys,
10 getShortcutWithDefaultValues,
11 } from "./utils"
12
13 type KeybindProviderProps = PropsWithChildren<{
14 shortcuts: Shortcut[]
15 debounce?: number
16 }>
17
18 export const KeybindProvider = ({
19 shortcuts,
20 debounce = 500,
21 children,
22 }: KeybindProviderProps) => {
23 const [storeShortcuts, setStoreCommands] = useState(
24 shortcuts.map((shr) => getShortcutWithDefaultValues(shr))
25 )
26 const registerShortcut = useCallback(
27 (shortcut: Shortcut) => {
28 setStoreCommands((prevShortcuts) => {
29 const idx = findShortcutIndex(shortcuts, getShortcutKeys(shortcut))
30
31 const newShortcuts = [...prevShortcuts]
32
33 if (idx > -1) {
34 newShortcuts[idx] = getShortcutWithDefaultValues(shortcut)
35 return prevShortcuts
36 }
37
38 return [...prevShortcuts, getShortcutWithDefaultValues(shortcut)]
39 })
40 },
41 [shortcuts]
42 )
43
44 const getKeysByPlatform = useCallback((command: Shortcut) => {
45 return findFirstPlatformMatch(command.keys)
46 }, [])
47
48 useShortcuts({ shortcuts: storeShortcuts, debounce })
49
50 const commandsContext = useMemo<KeybindContextState>(
51 () => ({
52 shortcuts: storeShortcuts,
53 registerShortcut,
54 getKeysByPlatform,
55 }),
56 [storeShortcuts, registerShortcut, getKeysByPlatform]
57 )
58
59 return (
60 <KeybindContext.Provider value={commandsContext}>
61 {children}
62 </KeybindContext.Provider>
63 )
64 }