UNPKG

containerized-state

Version:

Fast and minimal state container which can be used and shared across React or non-React components.

75 lines 2.52 kB
//#region src/constants.d.ts declare const Entity: { readonly DEFAULT: "default"; readonly COMPUTED: "computed"; }; //#endregion //#region src/types.d.ts type CallableFunction<TArgs extends any[] = [], TReturn = void> = (...args: TArgs) => TReturn; type SubscribeCallback<T> = (value: T) => Promise<void> | void; type Unsubscribe = () => void; type ComputeValue<T, P> = (value: T) => P; type EqualityCheckFunction<P> = (prev: P, next: P) => boolean; type ComputedEntity<T, P> = { type: (typeof Entity)["COMPUTED"]; cb: SubscribeCallback<P>; computeValue: ComputeValue<T, P>; isEqual?: EqualityCheckFunction<P>; }; type DefaultEntity<T> = { type: (typeof Entity)["DEFAULT"]; cb: SubscribeCallback<T>; }; type ContainerEntity<T> = DefaultEntity<T> | ComputedEntity<T, any>; type Initializer<T> = T | CallableFunction<[], T>; //#endregion //#region src/Container.d.ts declare class Container<T> { protected _value: T; protected _subscribers: Set<ContainerEntity<T>>; protected _initialValue: T; static create<T>(initializer: Initializer<T>): Container<T>; constructor(initializer: Initializer<T>); /** * A snapshot of the state. */ getValue(): T; /** * Updates the value of the state and notifies the subscribers. */ setValue(newValue: T): Promise<void>; /** * Subscribes to the changes of the container's state value * and returns the unsubscribe function. */ subscribe(cb: SubscribeCallback<T>, options?: { /** * An `AbortSignal` reference to control the unsubscibe. */ signal?: AbortSignal; }): Unsubscribe; /** * Subscribes to the changes of the container's selected state values * and returns the unsubscribe function. * * For more control over emission changes, you may provide a custom equality function. */ computedSubscribe<P>(computeValue: ComputeValue<T, P>, cb: SubscribeCallback<P>, options?: { /** * An `AbortSignal` reference to control the unsubscibe. */ signal?: AbortSignal; /** * A custom equality function to control emission changes. */ isEqual?: EqualityCheckFunction<P>; }): Unsubscribe; /** * Resets the container to its initial value. This method is asynchronous an * returns a promise that resolves when all subscriber callbacks have completed. */ reset(): Promise<void>; } //#endregion export { type ComputeValue, Container, type EqualityCheckFunction, type Initializer, type SubscribeCallback, type Unsubscribe }; //# sourceMappingURL=index.d.ts.map