zustand-duck
Version:
Simple reducer writing and cross-process state sharing.
58 lines (57 loc) • 2.13 kB
TypeScript
import type { StateCreator, StoreApi, StoreMutatorIdentifier } from 'zustand/vanilla';
export type ActionKeyToPayload = {
[A: string]: any[];
};
export type Reducers<S, KTP extends ActionKeyToPayload> = {
[A in keyof KTP]: (state: S, ...args: KTP[A]) => S;
};
export type Actions<KTP extends ActionKeyToPayload> = {
[A in keyof KTP]: (...args: KTP[A]) => KTP[A];
};
export type AsyncActions<KTP extends ActionKeyToPayload> = {
[A in keyof KTP]: (...args: KTP[A]) => Promise<KTP[A]> | KTP[A];
};
export type ActionRewrite<P extends any[] = any[]> = (data: {
action: string;
payload: P;
}, origin: (...args: P) => P) => Promise<P> | P;
export type DuckOptions<S, KTP extends ActionKeyToPayload> = {
/**
*
*/
name?: string;
/**
* Initial state
*/
state: S;
reducers: Reducers<S, KTP>;
/**
* Optional initialization function that determines the ready time
*/
initialize?: (api: CustomStoreApi<S, KTP>, resolve: (value: any) => void) => void;
/**
* Action rewrite
*/
actionRewrite?: ActionRewrite;
};
type CustomStoreApiMethods<S, KTP extends ActionKeyToPayload> = {
actions: AsyncActions<KTP & {
reset: [];
}>;
originActions: Actions<KTP & {
reset: [];
}>;
ready: () => Promise<CustomStoreApi<S, KTP>>;
wait: (condition: (state: S) => boolean) => Promise<CustomStoreApi<S, KTP>>;
onAction: <K extends (keyof KTP | 'reset')>(action: K, listener: (...args: KTP[K]) => void) => () => void;
};
export type CustomStoreApi<S, KTP extends ActionKeyToPayload> = StoreApi<S> & CustomStoreApiMethods<S, KTP>;
type WithDuck<S, KTP> = S extends StoreApi<infer T> ? S & (KTP extends ActionKeyToPayload ? CustomStoreApiMethods<T, KTP> : never) : never;
declare module 'zustand/vanilla' {
interface StoreMutators<S, A> {
'zustand/duck': WithDuck<S, A>;
}
}
export type Duck = <T, A extends ActionKeyToPayload, Cms extends [StoreMutatorIdentifier, unknown][] = []>(options: DuckOptions<T, A>) => StateCreator<T, Cms, [['zustand/duck', A]]>;
export declare const duck: Duck;
export {};