UNPKG

use-keybinds

Version:

Lightweight keybind library for React

1 lines 2.73 kB
{"version":3,"sources":["../src/useKeybindsList.tsx","../src/KeybindsProvider.tsx"],"sourcesContent":["import { useContext } from \"react\";\r\nimport { KeybindsContext } from \"./KeybindsProvider\";\r\n\r\nconst useKeybindsList = <Slug extends string>() => {\r\n const { keybinds } = useContext(KeybindsContext);\r\n\r\n const getKeybind = (slug: Slug) => keybinds[slug];\r\n\r\n return {\r\n getKeybind,\r\n keybinds,\r\n };\r\n};\r\n\r\nexport default useKeybindsList;\r\n","import React, { createContext, useMemo } from \"react\";\r\nimport { createKeybindCombinationString } from \"./utils\";\r\nimport type { ReactNode } from \"react\";\r\nimport type { Keybind, KeybindCombination, Keybinds } from \"./types\";\r\n\r\nexport const KeybindsContext = createContext<{\r\n keybinds: Keybinds<string>;\r\n combinationsToKeybindKey: Record<string, string>;\r\n}>({\r\n keybinds: {},\r\n combinationsToKeybindKey: {},\r\n});\r\n\r\ninterface KeybindsProviderProps<Slug extends string> {\r\n children: ReactNode;\r\n keybinds: Keybinds<Slug>;\r\n}\r\n\r\nconst KeybindsProvider = <Slug extends string>(props: KeybindsProviderProps<Slug>) => {\r\n const { children, keybinds = {} } = props;\r\n\r\n const combinationsToKeybindKey = useMemo<Record<string, Slug>>(() => {\r\n return Object.entries(keybinds).reduce((result, entry) => {\r\n const key = entry[0] as string;\r\n const keybind: Keybind = entry[1] as Keybind;\r\n\r\n const combinations: KeybindCombination[] = Array.isArray(keybind.keybind[0])\r\n ? (keybind.keybind as KeybindCombination[])\r\n : [keybind.keybind as KeybindCombination];\r\n\r\n const combinationStrings = combinations.reduce((result, combination) => {\r\n const combinationString = createKeybindCombinationString(\r\n combination,\r\n keybind.isSequential,\r\n );\r\n return { ...result, [combinationString]: key };\r\n }, {});\r\n\r\n return { ...result, ...combinationStrings };\r\n }, {});\r\n }, [keybinds]);\r\n\r\n return (\r\n <KeybindsContext.Provider value={{ keybinds, combinationsToKeybindKey }}>\r\n {children}\r\n </KeybindsContext.Provider>\r\n );\r\n};\r\n\r\nexport default KeybindsProvider;\r\n"],"mappings":";AAAA,OAAS,cAAAA,MAAkB,QCA3B,OAAOC,GAAS,iBAAAC,EAAe,WAAAC,MAAe,QAKvC,IAAMC,EAAkBC,EAG5B,CACD,SAAU,CAAC,EACX,yBAA0B,CAAC,CAC7B,CAAC,EDRD,IAAMC,EAAkB,IAA2B,CACjD,GAAM,CAAE,SAAAC,CAAS,EAAIC,EAAWC,CAAe,EAI/C,MAAO,CACL,WAHkBC,GAAeH,EAASG,CAAI,EAI9C,SAAAH,CACF,CACF,EAEOI,EAAQL","names":["useContext","React","createContext","useMemo","KeybindsContext","createContext","useKeybindsList","keybinds","useContext","KeybindsContext","slug","useKeybindsList_default"]}