Configurable biome colors in preview

- add Store context
- add useLocalStorage
- color utils
This commit is contained in:
Misode
2022-05-14 19:39:48 +02:00
parent 114164c740
commit 2ebba08d4b
9 changed files with 125 additions and 24 deletions

View File

@@ -4,6 +4,7 @@ export * from './useAsyncFn'
export * from './useCanvas'
export * from './useFocus'
export * from './useHash'
export * from './useLocalStorage'
export * from './useMediaQuery'
export * from './useModel'
export * from './useSearchParam'

View File

@@ -0,0 +1,35 @@
import { useCallback, useState } from 'preact/hooks'
type Result<T> = [T, (value: T | null | undefined) => void]
export function useLocalStorage<T = string>(key: string, defaultValue: T): Result<T>
export function useLocalStorage<T>(key: string, defaultValue: T, parse: (s: string) => T, stringify: (e: T) => string): Result<T>
export function useLocalStorage<T>(key: string, defaultValue: T, parse?: (s: string) => T, stringify?: (e: T) => string): Result<T> {
const getter = useCallback(() => {
const raw = localStorage.getItem(key)
if (raw === null) {
return defaultValue
} else if (parse === undefined) {
return raw as unknown as T
} else {
return parse(raw)
}
}, [])
const [state, setState] = useState(getter())
const setter = useCallback((value: T | null | undefined) => {
if (value == null) {
localStorage.removeItem(key)
setState(defaultValue)
} else if (stringify !== undefined) {
localStorage.setItem(key, stringify(value))
setState(value)
} else {
localStorage.setItem(key, value as unknown as string)
setState(value)
}
}, [])
return [state, setter]
}