UNPKG

dreamstate

Version:

Store management library based on react context and observers

284 lines (268 loc) 13.6 kB
import { T as TAnyObject, a as TAnyValue, b as TQueryType, c as TSignalType, I as IRegistry, d as IScopeContext, e as IContextManagerConstructor } from './lib.js'; export { C as ContextManager, i as ManagerInstanceMap, j as ManagerMap, k as OptionalQueryResponse, l as PartialTransformer, f as ProviderProps, m as QueryRequest, n as QueryResponse, h as Signal, g as SignalEvent, o as createProvider } from './lib.js'; import { ReactNode, ReactElement } from 'react'; /** * Error codes describing various issues related to Dreamstate usage. * These error codes are used to categorize different types of errors. * * @enum {string} */ declare enum EDreamstateErrorCode { UNEXPECTED_ERROR = "UNEXPECTED_ERROR", RESTRICTED_OPERATION = "RESTRICTED_OPERATION", INSTANCE_DISPOSED_LIFECYCLE = "INSTANCE_DISPOSED_LIFECYCLE", INSTANCE_DISPOSED_SCOPE = "INSTANCE_DISPOSED_SCOPE", OUT_OF_SCOPE = "OUT_OF_SCOPE", INCORRECT_PARAMETER = "INCORRECT_PARAMETER", INCORRECT_SIGNAL_LISTENER = "INCORRECT_SIGNAL_LISTENER", INCORRECT_SIGNAL_TYPE = "INCORRECT_SIGNAL_TYPE", INCORRECT_QUERY_PROVIDER = "INCORRECT_QUERY_PROVIDER", INCORRECT_QUERY_TYPE = "INCORRECT_QUERY_TYPE", TARGET_CONTEXT_MANAGER_EXPECTED = "TARGET_CONTEXT_MANAGER_EXPECTED" } /** * Represents a loadable store entry that manages transactional transitions for state updates. * Provides methods to represent the state of the entry as loading, ready, failed, or updated. */ interface ILoadable<T, E = Error> { /** * The value associated with the loadable state, or null if no value is available. */ readonly value: T | null; /** * A flag indicating whether the loadable state is in a loading state. */ readonly isLoading: boolean; /** * The error associated with the loadable state, or null if no error occurred. */ readonly error: E | null; /** * @param value Optional value to be associated with the ready state. * @returns a new loadable state as ready with an optional value. */ asReady(value?: T): ILoadable<T, E>; /** * @param value The new value to be associated with the updated state. * @param isLoading Optional flag indicating whether the state is loading. * @param error Optional error associated with the updated state. * @returns a new loadable state as updated with a new value, and optionally an updated loading state and error. */ asUpdated(value: T, isLoading?: boolean, error?: E | null): ILoadable<T, E>; /** * @param value Optional value to be associated with the loading state. * @returns a new loadable state as loading with an optional value. */ asLoading(value?: T): ILoadable<T, E>; /** * @param error The error that caused the failure. * @param value Optional value associated with the failed state. * @returns a new loadable state as failed with an error and an optional value. */ asFailed(error: E, value?: T): ILoadable<T, E>; } /** * Represents a base for a nested store that allows merging state. * Provides a method for merging state into the nested store. */ interface INestedBase<T> { /** * Merges a partial state into the current nested state. * * @param state The partial state to be merged. * @returns The merged state. */ asMerged(state: Partial<T>): TNested<T>; } /** * Represents a nested type that combines a base type with additional methods for merging state. */ type TNested<T> = T & INestedBase<T>; /** * Represents a computed field base with selectors and optional memoization and diff functionality. * Used for defining computed fields with custom selection logic and caching. */ interface IComputedBase<T extends TAnyObject, C extends TAnyObject> { /** * A selector function that extracts the computed value from the context. * * @param context The context from which the value is computed. */ readonly __selector__: (context: C) => T; /** * An optional memoization function to optimize the computed value calculation. * * @param context The context used to compute the memoized value. */ readonly __memo__?: (context: C) => Array<TAnyValue>; /** * An optional diff array used to track differences in the computed value. */ readonly __diff__?: Array<TAnyValue>; } /** * A computed type that combines the base computed functionality with the specific type of the computed value. */ type TComputed<T extends TAnyObject, C extends TAnyObject = TAnyValue> = T & IComputedBase<T, C>; /** * Decorator factory that modifies the method descriptor to bind the method to the prototype instance. * This ensures that the method retains the correct `this` context when invoked. * * All credits: 'https://www.npmjs.com/package/autobind-decorator'. * Modified to support proposal syntax. * * @returns {MethodDecorator} A method decorator that binds the method to the instance prototype. */ declare function Bind(): MethodDecorator; /** * A custom error class that contains generic error information for Dreamstate-related issues. * * This class extends the native `Error` class and is used to represent errors specific * to the Dreamstate library, providing more structured error handling. */ declare class DreamstateError extends Error { /** * Name or error class to help differentiate error class in minified environments. */ readonly name: string; /** * Error code describing the issue. */ readonly code: EDreamstateErrorCode; /** * Error message describing the issue. */ readonly message: string; constructor(code?: EDreamstateErrorCode, detail?: string); } /** * Class method decorator factory that marks the decorated method as a handler for specified query types. * * This decorator ensures that the decorated method will be invoked when a query of the specified type(s) * is triggered within the current scope. It supports handling a single query type or an array of query types. * The supported query types include `string`, `number`, and `symbol`. * * @param {TQueryType | Array<TQueryType>} queryType - The query type or an array of query types * that the decorated method will handle. * @returns {MethodDecorator} A method decorator that attaches the query handler functionality to the method. */ declare function OnQuery(queryType: TQueryType): MethodDecorator; /** * Class method decorator factory that marks the decorated method as a handler for specified signal types. * * This decorator ensures that the decorated method is invoked when a signal of the specified type(s) * is emitted within the current scope. It supports handling a single signal type or an array of signal types. * * Supported signal types include: `string`, `number`, and `symbol`. * * @param {(TSignalType | Array<TSignalType>)} signalType - The signal type or an array of signal types * that the decorated method will handle. * @returns {MethodDecorator} A method decorator that attaches the handler functionality to the method. */ declare function OnSignal(signalType: Array<TSignalType> | TSignalType): MethodDecorator; interface IScopeProviderProps { children?: ReactNode; } /** * Provides an isolated scope for signaling and context managers. * * The `ScopeProvider` component wraps its children within a dedicated scope, ensuring that signals * and context managers operate independently from other parts of the React tree. This isolation * helps prevent interference between different parts of the application and maintains the integrity * of context data and signal handling. * * @param {IScopeProviderProps} props - The properties for the scope provider, including the children * to be rendered within the isolated scope. * @returns {ReactElement} A React element representing the scope provider. */ declare function ScopeProvider(props: IScopeProviderProps): ReactElement; declare namespace ScopeProvider { var displayName: string; } /** * Creates an actions store, which is an object containing readonly method links representing actions. * The intention is to provide a container that is visually and programmatically distinguishable as * a storage of actions. * * Every call to 'setContext' will perform a comparison of the current 'context' before updating, * excluding the actions object, as it is expected to be immutable and consistent. * * @template T The type of actions object. * @param {T} actions - An object containing a set of mutation operations (actions). * @returns {Readonly<T>} An instance of an ActionsStore class containing the supplied actions. */ declare function createActions<T extends TAnyObject>(actions: T): Readonly<T>; /** * Creates a computed value that will be re-calculated after each context update. * The computed value is recalculated only when its dependencies, as determined by the memo function, * are updated. * * @template T The type of the computed value. * @template C The type of the context the computed value depends on. * @param {Function} selector A generic selector function that returns computed values on update. * @param {Function} memo An optional memo checker function that returns an array of dependencies, * indicating whether the computed value should be updated. * @returns {TComputed<T, C>} A computed value object that will be updated based on context changes. */ declare function createComputed<T extends TAnyObject, C extends TAnyObject>(selector: (context: C) => T, memo?: (context: C) => Array<TAnyValue>): TComputed<T, C>; /** * Creates a loadable value, which is useful when the context value has error/loading states. * The loadable value can represent different states: loading, ready, or error. * * @template T The type of the value being loaded. * @template E The type of the error (defaults to `Error`). * @param {T | null} [value] The initial value or `null` if not yet loaded. * @param {boolean} [isLoading] A flag indicating whether the value is in a loading state. * @param {E | null} [error] The error if the value failed to load, or `null` if no error. * @returns {ILoadable<T, E>} A loadable value utility representing the current state of the value. */ declare function createLoadable<T, E extends Error = Error>(value?: T | null, isLoading?: boolean, error?: E | null): ILoadable<T, E>; /** * Creates a nested sub-state for deeper shallow checking, useful when the context contains nested objects * that need to be checked separately during updates. * * As an example: * - `{ first: 'first', second: { one: 1, two: 2 } }` - `first` and `second` will be checked, * while `one` and `two` will be ignored. * - `{ first: 'first', second: createNested({ one: 1, two: 2 }) }` - `first`, `one`, and `two` * will be checked during updates. * * @template T The type of the nested object. * @param {T} initialValue The initial value of the nested store object. * @returns {TNested<T>} An instance of a nested store containing the initial state, marked for deeper shallow checking. */ declare function createNested<T extends TAnyObject>(initialValue: T): TNested<T>; /** * Initializes the core scope context for managing stores, signals, and queries in the VDOM tree. * This function sets up the scope that is responsible for handling state and interactions within * the context of React's virtual DOM. * * @param {IRegistry} [registry] - Optional registry object to initialize. * @returns {IScopeContext} Mutable scope with a set of methods and registry stores for the React VDOM tree. */ declare function createScope(registry?: IRegistry): IScopeContext; /** * Custom hook that wraps `useContext` to provide scoped context data with optional update * optimization via a dependency selector. It returns the context from the specified manager * class and limits re-renders to changes in selected dependencies. * * @template T - The type of the context state. * @template D - The type of the context manager constructor. * @param {D} ManagerClass - The manager class whose instance context is returned. * @param {(context: D["prototype"]["context"]) => TAnyValue[]} dependenciesSelector - An optional function * that receives the current context and returns an array of dependencies. The component re-renders * only if values in this array change. Without it, the component updates on every context change. * @returns {D["prototype"]["context"]} The context data provided by the manager within the current * dreamstate scope. */ declare function useManager<T extends TAnyObject, D extends IContextManagerConstructor<T>>(ManagerClass: D, dependenciesSelector?: (context: D["prototype"]["context"]) => Array<TAnyValue>): D["prototype"]["context"]; /** * Custom hook that retrieves the current scope context. * This hook provides access to the current scope in the React tree. It returns a bundle of * functions and data that allow for processing data, signals and queries within that scope. * * @returns {IScopeContext} The current scope context in the React tree. */ declare function useScope(): IScopeContext; export { Bind, IContextManagerConstructor as ContextManagerConstructor, DreamstateError, EDreamstateErrorCode as DreamstateErrorCode, OnQuery, OnSignal, TQueryType as QueryType, IScopeContext as ScopeContext, ScopeProvider, TSignalType as SignalType, createActions, createComputed, createLoadable, createNested, createScope, useManager, useScope }; export type { TComputed as Computed, ILoadable as Loadable, TNested as Nested };