mirror of
https://github.com/misode/misode.github.io.git
synced 2026-04-25 08:06:51 +00:00
Configurable biome colors in preview
- add Store context - add useLocalStorage - color utils
This commit is contained in:
@@ -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'
|
||||
|
||||
35
src/app/hooks/useLocalStorage.ts
Normal file
35
src/app/hooks/useLocalStorage.ts
Normal 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]
|
||||
}
|
||||
Reference in New Issue
Block a user