state.ts 1.2 KB

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