state.ts51 lines · main
1import { LOCAL_STORAGE_KEYS } from 'common'
2import { useCallback } from 'react'
3
4import type { ShortcutId } from './registry'
5import { DisabledShortcuts } from './types'
6import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
7
8const STORAGE_KEY = LOCAL_STORAGE_KEYS.SHORTCUT_STORAGE_KEY
9
10const DEFAULT_DISABLED: DisabledShortcuts = {}
11
12export function useShortcutPreferences() {
13 const [disabled, setDisabled] = useLocalStorageQuery<DisabledShortcuts>(
14 STORAGE_KEY,
15 DEFAULT_DISABLED
16 )
17
18 const setShortcutEnabled = useCallback(
19 (id: ShortcutId, enabled: boolean) => {
20 setDisabled((prev) => {
21 if (enabled) {
22 const { [id]: _removed, ...rest } = prev
23 return rest
24 }
25 return { ...prev, [id]: true }
26 })
27 },
28 [setDisabled]
29 )
30
31 const resetShortcut = useCallback(
32 (id: ShortcutId) => {
33 setDisabled((prev) => {
34 const { [id]: _removed, ...rest } = prev
35 return rest
36 })
37 },
38 [setDisabled]
39 )
40
41 const resetAllShortcuts = useCallback(() => {
42 setDisabled(DEFAULT_DISABLED)
43 }, [setDisabled])
44
45 return {
46 disabled,
47 setShortcutEnabled,
48 resetShortcut,
49 resetAllShortcuts,
50 }
51}