state.ts51 lines · main
| 1 | import { LOCAL_STORAGE_KEYS } from 'common' |
| 2 | import { useCallback } from 'react' |
| 3 | |
| 4 | import type { ShortcutId } from './registry' |
| 5 | import { DisabledShortcuts } from './types' |
| 6 | import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage' |
| 7 | |
| 8 | const STORAGE_KEY = LOCAL_STORAGE_KEYS.SHORTCUT_STORAGE_KEY |
| 9 | |
| 10 | const DEFAULT_DISABLED: DisabledShortcuts = {} |
| 11 | |
| 12 | export 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 | } |