seitu
Version:
73 lines • 2.82 kB
text/typescript
import { i as Subscribable, r as ServerReadable, s as Writable, t as Clearable } from "../../index-B0IeflOl.mjs";
import { i as StandardSchemaV1, n as ValidationSchemaObjectErrorProps } from "../../validate-C_H-c0gq.mjs";
import { t as Simplify } from "../../index-BGgVNdXS.mjs";
//#region src/web/web-storage/index.d.ts
type WebStorageInput = Record<string, StandardSchemaV1<unknown, unknown>>;
type WebStorageOutput<S extends WebStorageInput> = Simplify<{ [K in keyof S]: StandardSchemaV1.InferOutput<S[K]>; }>;
interface WebStorageOptions<S extends WebStorageInput> {
schemas: S;
defaultValues: WebStorageOutput<S>;
type: 'localStorage' | 'sessionStorage';
keyTransform?: (key: keyof S) => string;
onValidationError?: (props: ValidationSchemaObjectErrorProps<WebStorageOutput<S>>) => void | StandardSchemaV1.InferOutput<S[keyof S]>;
}
interface WebStorage<O extends Record<string, unknown>> extends Subscribable<O>, ServerReadable<O>, Writable<Partial<O>, O>, Clearable {
'~': {
getDefaultValue: <K extends keyof O>(key: K) => O[K];
getSchema: (key: keyof O) => StandardSchemaV1<unknown>;
transformKey: (key: keyof O) => string;
type: 'localStorage' | 'sessionStorage';
} & Subscribable<O>['~'];
}
/**
* Reactive handle for `localStorage` or `sessionStorage`. On the server, `get()`
* and the SSR snapshot are `defaultValues`.
*
* @example Vanilla
* ```ts twoslash title="session-storage.ts"
* import { createWebStorage } from 'seitu/web'
* import * as z from 'zod'
*
* const sessionStorage = createWebStorage({
* type: 'sessionStorage',
* schemas: {
* token: z.string().nullable(),
* preferences: z.object({ theme: z.enum(['light', 'dark']) }),
* },
* defaultValues: { token: null, preferences: { theme: 'light' } },
* })
*
* sessionStorage.get()
* sessionStorage.set({ token: 'abc' })
* sessionStorage.get() // { token: 'abc', preferences: { theme: 'light' } }
* sessionStorage.subscribe(console.log)
* ```
*
* @example React
* ```tsx twoslash title="page.tsx"
* 'use client'
*
* import { createWebStorage } from 'seitu/web'
* import { useSubscription } from 'seitu/react'
* import * as z from 'zod'
*
* const sessionStorage = createWebStorage({
* type: 'sessionStorage',
* schemas: { count: z.number(), name: z.string() },
* defaultValues: { count: 0, name: '' },
* })
*
* export default function Page() {
* const value = useSubscription(sessionStorage)
* return (
* <div>
* <span>{value.count}</span>
* <span>{value.name}</span>
* </div>
* )
* }
* ```
*/
declare function createWebStorage<S extends WebStorageInput>(options: WebStorageOptions<S>): WebStorage<WebStorageOutput<S>>;
//#endregion
export { WebStorage, WebStorageInput, WebStorageOptions, WebStorageOutput, createWebStorage };