// Generated by dts-bundle-generator v9.5.1 import React$1 from 'react'; import { FC } from 'react'; import { Get } from 'type-fest'; /** * Helper function to create a setState function that adds the given amount * @param baseAmount A base amount to add * e.g. use baseAmount = 1 to create an incrementer function and baseAmount = -1 for a decremeter function * @return A function suitable for store.connect(path, ) * @example * const store = new Store({ score: 0, highScore: 1000 }); * const maybeUpdateHighScore = newScore => { * if (newScore > store.getStateAt('highScore')) { * store.setStateAt('highScore', newScore); * } * }; * const eatEnemy = store.connect('score', adder(10), maybeUpdateHighScore); * * const levelUp = store.connect('score', adder(100), newScore => { * maybeUpdateHighScore(newScore); * window.postMessage({ type: 'LEVEL_UP', data: newScore }); * }); */ export function adder(baseAmount?: number): (amount?: number) => (old: number) => number; /** * Build an action function that appends the given item(s) to an array * @return A function suitable for store.connect(path, ) * @example * const store = new Store({ primes: [2, 3, 5, 7] }); * const appendPrime = store.connect('primes', appender()); * appendPrime(11); * // => primes is now set to [2, 3, 5, 7, 11] * appendPrime(13, 17); * // => primes is now set to [2, 3, 5, 7, 11, 13, 17] */ export function appender(): (...newItems: Item[]) => (old: T) => T extends Item[] ? Item[] : T; /** * Given a list of actions, run them all, i.e. parallel * @param actions The array of action functions to run in parallel * @return A function to run the actions, returning the result of the first action that returns a value */ export declare function composeActions(actions: Function[]): (...args: any[]) => any; /** * Given a list of actions, pipe results of action to the next action, i.e. in series * @param actions The array of action functions to pipe together * @return A function to run the actions */ export declare function pipeActions(actions: Function[]): (result: any) => any; /** * Build an action function that cycles through the given values * @return A function suitable for store.connect(path, ) * @example * * const store = new Store({ visibility: 'visible' }); * const toggleVisibility = store.connect('visibility', cycler(['visible', 'hidden'])); * toggleVisibility(); * // => state "visibility" toggles between "visible" and "hidden" * * const store = new Store({ alignment: 'left' }); * const cyclePosition = store.connect('visibility', cycler(['left', 'center', 'right])); * cyclePosition(); * // => state "alignment" cycles through "left", "center", and "right", wrapping from "right" to "left" if applicable */ export function cycler(values: PossibleValue[]): () => (old: PossibleValue) => PossibleValue; /** * Helper function to send a fetch() request and add the response to the state * @param url The url to fetch data from * @param init The initialization options for fetch * @param extractor A function that receives the response object and returns new state * It defaults to the function `res => res.json()` * @return A function suitable for a store action * @example * const store = new Store({ products: [] }); * const loadProducts = store.connect( * 'products', * fetcher( * '/api/products', * { headers: { Authorization: `Bearer ${token}` } }, * ) * ); * * // Or using a function to generate the url * const searchProducts = store.connect( * 'products', * fetcher( * (criteria) => '/api/products?' + new URLSearchParams(criteria).toString(), * { headers: { Authorization: `Bearer ${token}` } } * ) * ); * searchProducts({ category: 'shoes', size: '10' }); * // `store.getStateAt('products')` now contains search results * * // Or using a function to generate the initialization options * const addToCart = store.connect( * 'cart', * fetcher( * '/api/cart', * (productId) => ({ body: { productId }, method: 'POST' }) * ) * ); * // assuming `POST /api/cart` returns the new cart contents, * // `store.getStateAt('cart')` now contains those cart contents */ export declare function fetcher(url: string | URL | ((...args: any[]) => string | URL), init?: RequestInit | ((...args: any[]) => RequestInit), extractor?: (response: Response) => any): (...args: any[]) => () => Promise; /** * Build a setState function that runs a map function against an array value * @return A function suitable for store.connect(path, ) * * @example * const store = new Store({ prices: [10, 20, 30] }); * const applyDiscount = store.connect('prices', price => price * 0.9); * applyDiscount(); * // => "prices" now equals [9, 18, 27] */ export function mapper(mapFn: (item: Item) => any): () => (items: Item[]) => any[]; /** * Build a setState function that merges the given object with the target object * @return A function suitable for store.connect(path, ) * @example * * const store = new Store({ user: { name: 'John', age: 30 } }); * const patchUser = store.connect('user', merger()); * patchUser({ age: 31 }); * // => "user" is now set to { name: 'John', age: 31 } */ export function merger(): (withValues: Partial) => (old: StateShape) => StateShape; /** * Build an action function that removes the given item(s) from an array * @return A function suitable for store.connect(path, ) * @example * const store = new Store({ primes: [2, 3, 5, 7, 11] }); * const removePrime = store.connect('primes', remover()); * removePrime(3); * // => primes is now set to [2, 5, 7, 11] * removePrime(5, 7); * // => primes is now set to [2, 11] */ export function remover(): (...itemsToRemove: Item[]) => (old: Item[]) => Item[]; /** * Build a setState function that replaces a particular array item * @return A function suitable for store.connect(path, ) * @example * const store = new Store({ cart: ['apple', 'banana', 'orange'] }); * const replaceItem = store.connect('cart', replacer()); * replaceItem('banana', 'pear'); * // => cart is now set to ['apple', 'pear', 'orange'] */ export function replacer(): (itemToReplace: Item, newItem: Item | ((oldItem: Item) => Item)) => (old: Item[]) => Item[]; /** * Helper function to create a setState function that directly sets one value * @return A function suitable for store.connect(path, ) * @example * const store = new Store({ name: 'Bob' }); * const setName = store.connect('name', setter()); * setName('Alice'); * // => store state is now { name: 'Alice' } * * // Note that the following two lines are equivalent: * const setName = store.connect('name', setter()); * const setName = newName => store.setStateAt('name', newName); */ export declare function setter(): (newValueOrFunction: ShapeAtPath | ((old: ShapeAtPath) => ShapeAtPath)) => ShapeAtPath | ((old: ShapeAtPath) => ShapeAtPath); export type AnyInputEvent = { target: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement; }; /** * Run setter and then flush pending state changes * using a DOM event object to set value to evt.target.value * @return A function suitable for an input's handler for onChange/onBlur/onKeyUp etc. * @example * // In /stores/search.ts * import { Store, setterInput, useStoreSelector } from 'react-thermals'; * const store = new Store({ criteria: { term: '', category: undefined } }); * export const setTerm = store.connect('criteria.term', setterInput()); * export const setCategory = store.connect('criteria.category', setterInput()); * export function useCriteria() { * return useStoreSelector(store, 'criteria'); * } * // In /components/SearchForm.tsx * import { setTerm, setCategory, useCriteria } from '../stores/search'; * export default function SearchForm() { * const { term, category } = useCriteria(); * return ( *
* * *
* ); * } */ export declare function setterInput(): (evt: AnyInputEvent) => string; /** * Helper function to create a setState function that directly toggles one value * @return A function suitable for store.connect(path, fn) */ export function toggler(): () => (old: boolean) => boolean; declare class SimpleEmitter { #private; /** * Add an event listener * @param type The event name * @param handler The function to be called when the event fires * @return The emitter instance */ on: (type: EventName, handler: EventHandlerType) => this; /** * Check if the given event name has any handlers * @param type The event name * @return True if there are any handlers registered */ hasSubscriber: (type: KnownEventNames) => number | undefined; /** * Remove an event listener * @param type The event name * @param handler The function registered with "on()" or "once()" * @return The emitter instance */ off: (type: EventName, handler: EventHandlerType) => this; /** * Add an event listener that should fire once and only once * @param type The event name * @param handler The function to be called when the event fires * @return The emitter instance */ once: (type: EventName, handler: EventHandlerType) => this; /** * Trigger handlers attached to the given event with the given data * @param type The event name * @param data The data to pass to evt.data */ emit: (type: EventName, data?: EventDataType) => EventType; } export type KnownEventNames = "BeforeInitialize" | "AfterInitialize" | "BeforeFirstUse" | "AfterFirstUse" | "AfterFirstMount" | "AfterMount" | "AfterUnmount" | "AfterLastUnmount" | "AfterReset" | "AfterUpdate" | "SetterRejection" | "*"; export type EventDataType = EventName extends "BeforeInitialize" | "AfterInitialize" | "BeforeFirstUse" | "AfterFirstUse" ? StateType : EventName extends "AfterMount" | "AfterUnmount" ? number : EventName extends "AfterUpdate" ? { prev: StateType; next: StateType; } : EventName extends "SetterRejection" ? Error : undefined; export type EventType = { target: SimpleEmitter | Store; type: EventName; data: EventDataType; }; export type EventHandlerType = (evt: EventType) => void; export type Spreadable = Iterable | Partial; export type StoreConfigType = { autoReset?: boolean; id?: string; }; export type SetStateOptionsType = { bypassRender?: boolean; bypassMiddleware?: boolean; bypassEvent?: boolean; bypassAll?: boolean; }; export interface MiddlewareContextInterface { prev: StateType; next: StateType; store: Store; } export type MiddlewareType = (context: MiddlewareContextInterface, next: Function) => void; export type PluginFunctionType = (store: Store) => any; export type SetterType = { handler: React$1.Dispatch; mapState?: (fullState: StateType) => SelectedState; equalityFn?: (prev: SelectedState, next: SelectedState) => boolean; }; export type PlainObjectType = Record; export type StateAtType = Get; export type FunctionStateType = ((oldState: StateType) => StateType) | ((oldState: StateType) => Promise); export type SettableStateType = StateType | Promise | FunctionStateType; export type FunctionMergeableStateType = ((oldState: StateType) => Spreadable) | ((oldState: StateType) => Promise>); export type MergeableStateType = Spreadable | Promise> | FunctionMergeableStateType; export type FunctionStateAtType = (oldState: StateAtType) => StateAtType; export type SettableStateAtPathType = StateAtType | Promise> | FunctionStateAtType | ((oldState: StateAtType) => Promise>); export type MergeableStateAtPathType = Spreadable> | Promise>> | ((oldState: StateAtType) => Spreadable>) | ((oldState: StateAtType) => Promise>>); export type StateMapperType = ((fullState: StateType) => Mapped) | string; export type StateMapperOrMappersType = undefined | null | StateMapperType | StateMapperType[]; export declare class Store extends SimpleEmitter { #private; protected _middlewares: MiddlewareType[]; protected _setters: SetterType[]; protected _state: StateType; protected _waitingQueue: SettableStateType[]; protected _isWaiting: boolean; /** * A string to identify the store by */ id: string; /** * Values to attach that may be used by other stores */ locals: PlainObjectType; /** * Create a new store with the given state and actions * @param initialState The store's initial state; it can be of any type * @param options * @property options.autoReset True to reset state after all components unmount * @property options.id An identifier that could be used by plugins or event listeners */ constructor(initialState?: StateType, { autoReset, id }?: StoreConfigType); /** * Connect a component to the store so that when relevant state changes, * we can tell the component to re-render * @param setState A setState function from React.useState() * @note private but used by useStoreSelector() */ attachComponent: (setState: SetterType) => void; /** * Disconnect a component from the store * @param setState The setState function used to subscribe * @note private but used by useStoreSelector() */ detachComponent: (setState: SetterType) => void; /** * Return the initial state of the store */ getInitialState: () => StateType; /** * Return the initial state of the store at the given path * @param path Path string such as "cart" or "cart.total" */ getInitialStateAt: (path: Path) => StateAtType; /** * Return the current state of the store * @return The current state */ getState: () => StateType; /** * Return the current state of the store at the given path * @param path Path string such as "cart" or "cart.total" */ getStateAt: (path: Path) => StateAtType; /** * Reset a store to its initial condition and initial state values, * and notifies all consumer components * @param options Options to allow bypassing render, middleware, event, all * @return This store * @chainable */ reset: (options?: SetStateOptionsType) => this; /** * Reset the store to its initial state values * and notifies all consumer components * @param options Options to allow bypassing render, middleware, event, all * @chainable */ resetState: (options?: SetStateOptionsType) => this; /** * Reset the store at the given path to its initial state values * and notifies all consumer components * @param path The path to the value to reset * @param options Options to allow bypassing render, middleware, event, all * @chainable */ resetStateAt: (path: string, options?: SetStateOptionsType) => this; /** * Return a promise that will resolve once the store gets a new state * @return Resolves with the new state value */ nextState: () => Promise; /** * Bind an action updater function to operate on the given path in the store * @param path The path to the value the updater will operate * @param updater The function to bind * @param [callback] After state is updated, callback receives new state at path * @example * const store = new Store({ favorites: 0 }); * const increment = old => old + 1; * const incrementFavs = store.connect('favorites', increment); * // Also supports a callback that receives the new state * const incrementFavsAndSave = store.connect('favorites', increment, newCount => { * fetch('/favs', { method: 'PUT', body: newCount }); * window.postMessage({ type: 'FAVS_UPDATED', data: newCount }); * }); */ connect: (path: Path, updater: (...args: any) => SettableStateAtPathType, callback?: (finalState: StateAtType) => void) => (...args: any[]) => void; /** * Bind a list of (possibly async) action updater functions to operate on the given path in the store * Each updater will receive the return value of the previous updater * @param path The path to the value the updater will operate * @param updaters The functions to run in sequence * @returns a function that returns a Promise with the final value * const store = new Store({ emails: [] }); * const addEmail = appender(); * const lower = newEmails => newEmails.map(email => email.toLowerCase()); * const addAndLower = store.chain('emails', [addEmail, lower]); */ chain: (path: Path, updaters: Array>) => ((...args: any) => Promise>); /** * Return the number of components that "use" this store data */ getUsedCount: () => number; /** * Return true if any component has ever used this store */ hasInitialized: () => boolean; /** * Return the number of *mounted* components that "use" this store */ getMountCount: () => number; /** * Register a plugin * @param initializer The function the plugin uses to configure and attach itself * @return The return value of the plugin initializer function */ plugin: (initializer: PluginFunctionType) => any; /** * Get the array of plugin initializer functions */ getPlugins: () => PluginFunctionType[]; /** * Register a middleware function * @param middlewares The middleware function to register * @return This store */ use: (...middlewares: MiddlewareType[]) => this; /** * Run all the registered middleware * @private * @param context Object with prev, next, isAsync, store * @param callback The function to call when all middlewares have called "next()" */ protected _runMiddlewares: (context: MiddlewareContextInterface, callback: Function) => void; protected _updateState: (newState: StateType, options?: SetStateOptionsType) => void; /** * Schedule state to be updated in the next batch of updates * @param newStateOrUpdater The new value or function that will return the new value * @param options Options to allow bypassing render, middleware, event, all * @return This store * @chainable */ setState: (newStateOrUpdater: SettableStateType, options?: SetStateOptionsType) => this; /** * Schedule a value to be updated in the next batch of updates at the given path inside the state * @param path The path to the value * @param newStateOrUpdater The new value or a function that receives "oldState" as a first parameter * @param options Options to allow bypassing render, middleware, event, all * @return This store * @chainable */ setStateAt: (path: Path, newStateOrUpdater: SettableStateAtPathType, options?: SetStateOptionsType) => this; /** * Set state but bypass all middleware and rendering * @param newStateOrUpdater The new value or a function that receives "oldState" as a first parameter */ initState: (newStateOrUpdater: SettableStateType) => this; /** * Set state at the given path but bypass all middleware and rendering * @param path The path to the value * @param newStateOrUpdater The new value or a function that receives "oldState" as a first parameter */ initStateAt: (path: Path, newStateOrUpdater: SettableStateAtPathType) => this; /** * Get a function that can update state at a path containing a * * @param arrayOfState An array of items * @param updater A function that will map one item to a new one * @private */ protected _getMapUpdater: (arrayOfState: T[], updater: (old: T) => T) => Function | Promise; /** * Merge state into an Object or Array * @param newStateOrUpdater The new value or function that will return the new value * @param options Options to allow bypassing render, middleware, event, all * @return This store * @chainable */ mergeState: (newStateOrUpdater: MergeableStateType, options?: SetStateOptionsType) => this; /** * Merge state at the given path into an Object or Array * @param path The path to the value to merge * @param newStateOrUpdater The new value or function that will return the new value * @param options Options to allow bypassing render, middleware, event, all * @return This store * @chainable */ mergeStateAt: (path: Path, newStateOrUpdater: MergeableStateAtPathType, options?: SetStateOptionsType) => this; /** * Tell connected components to re-render if applicable * @param prev The previous state value * @param next The new state value * @param options Specifies how changes should be broadcast */ protected _notifyComponents: (prev: StateType, next: StateType, options: SetStateOptionsType) => void; /** * Get a function that will tell connected components to re-render * @param prev The previous state value * @param next The next state value */ protected _getComponentUpdater: (prev: StateType, next: StateType) => (setter: SetterType) => void; subscribe: Function; undo: Function; redo: Function; jump: Function; jumpTo: Function; getHistory: Function; } export declare class SyncStore extends Store { /** * Set state synchronously — no promise handling, no waiting queue. * @param newStateOrUpdater The new value or a function that receives current state * @param options Options to allow bypassing render, middleware, event, all * @return This store * @chainable */ setState: (newStateOrUpdater: SettableStateType, options?: SetStateOptionsType) => this; /** * Map state at a wildcard path — sync only, no Promise.all. * @param arrayOfState An array of items * @param updater A function that maps one item to a new one * @private */ protected _getMapUpdater: (arrayOfState: T[], updater: (old: T) => T) => Function; /** * Notify components and emit AfterUpdate synchronously (no microtask delay). * @param prev The previous state value * @param next The new state value * @param options Specifies how changes should be broadcast */ protected _notifyComponents: (prev: StateType, next: StateType, options: SetStateOptionsType) => void; /** * Return the current state as an immediately resolved promise. * In a SyncStore, state is always up-to-date synchronously. * @return A promise that resolves with the current state */ nextState: () => Promise; } /** * Hook to request updated values any time a relevant portion of state changes * @param store - A store created with createStore() * @param [mapState] - Function that returns a slice of data * @param [equalityFn] - Custom equality function that checks if state has change * @return The selected state */ export function useStoreSelector(store: Store, mapState?: StateMapperOrMappersType, equalityFn?: ((prev: SelectedState, next: SelectedState) => boolean) | undefined): any; /** * Hook to request state values any time state changes * @param store An instance of Store * @return The entire state value that will rerender the host Component * when the state value changes */ export function useStoreState(store: Store): StateType; /** * Deep updater takes a path plus a transformer and returns a function * that will take in an object and return a copy of that object * with that transform applied to the value at "path" * @param fullState The entire state * @param path Path string such as "cart" or "cart.total" to the desired state * @param newValue New value or a function to update the value at that given path * @return */ export function replacePath(fullState: StateType, path: Path, newValue: StateAtType | FunctionStateAtType): StateType; export declare const selectPath: Function; /** * Copy a value shallowly * @param value Any value, but often an object * @return A copy of the value */ export function shallowCopy(value: any): any; /** * Create a copy of the given value, shallowly overriding properties * @param value The value to copy * @param overrides Override values to extend the copy * @return The composite value */ export function shallowOverride(value: any, overrides: any): any; /** * Deep updater takes a path plus a transformer and returns a function * that will take in an object and return a copy of that object * with that transform applied to the value at "path" * @param path Path string such as "cart" or "cart.total" * @param transform Transform function(s) to update the value at the given path * @return */ export function updatePath(path: string, transform?: undefined | ((old: T, ...args: any[]) => T)): (object: any, ...callTimeArgs: any[]) => any; export type LoggerDataType = { storeId: string; eventType: KnownEventNames; event: EventType; }; export type LoggerConfigType = { eventTypes?: KnownEventNames[]; logHandler?: (message: LoggerDataType) => void; }; /** * Plugin a logger that will emit all store events to the console * @param eventTypes * @param logHandler The function that will actually log */ export function consoleLogger({ eventTypes, logHandler, }?: LoggerConfigType): (store: Store) => void; export function observable(): (store: Store) => void; export type ParseType = (serialized: string) => any; export type StringifyType = (value: any) => string; export type PersistStateConfig = { key?: string; path?: string; storage?: { getItem: (key: string) => any; setItem: (key: string, item: any) => void; }; parse?: ParseType; stringify?: StringifyType; }; /** * * @param key The key under which to persist in localStorage/sessionStorage (defaults to store id) * @param [path=@] The path to the part of state you want to persist * @param [storage=localStorage] localStorage/sessionStorage or compatible * @param [parse=JSON.parse] The deserialization function * @param [stringify=JSON.stringify] The serialization function * * @example * Persist whole state in localStorage under "preferences" * store.plugin({ key: 'preferences' }); * * @example * Persist state under "auth.user" path in localStorage under "user" * store.plugin({ key: 'user', path: 'auth.user' }); * * @example * Persist state under "auth.user" path in sessionStorage under "user" * store.plugin({ key: 'user', path: 'auth.user', storage: sessionStorage }); * */ export function persistState({ key, path, storage, parse, stringify, }: PersistStateConfig): (store: Store) => void; export type Setter = (newValue: T | ((old: T) => T)) => void; export type Getter = () => T; export type ReadonlySignal = { Value: React$1.FC; get: Getter; peek: Getter; store: SyncStore; }; export type Signal = ReadonlySignal & { set: Setter; }; /** Returned by createComputed — writable only internally, exposes dispose(). */ export type ComputedSignal = ReadonlySignal & { dispose: () => void; }; /** * Defer all signal writes inside fn until the outermost batch exits. * Effects and computeds only see fully-committed state when they run, * preventing partial-update reads. Nested batch() calls are supported. */ export declare function batch(fn: () => void): void; export declare function createSignal(defaultValue: T | (() => T)): Signal; export type ComputedCallback = () => T; export declare function createComputed(compute: ComputedCallback, options?: { equals?: (a: T, b: T) => boolean; }): ComputedSignal; /** * Run a callback immediately and re-run it whenever any signal it reads changes. * The callback may return a teardown function called before each re-run and on dispose. * Returns a dispose function that cleans up all subscriptions. */ export declare function effect(callback: () => (() => void) | void): () => void; /** * Read signals inside a callback without registering them as dependencies. * Calls are re-entrant; throws if signal.set() is called inside. */ export declare function untrack(callback: () => T): T; /** * Subscribe a React component to a signal and return its current value. * Re-renders whenever the signal changes. Unlike , this works * for non-primitive values and enables conditional rendering based on signal state. */ export declare function useSignalValue(signal: ReadonlySignal): T; /** * Creates a reactive root that manages the lifecycle of computeds and effects. * Call the provided dispose function to clean up all reactive subscriptions * created within the callback. */ export declare function createRoot(fn: (dispose: () => void) => T): T; export type SchemaType = "string" | "string[]" | "number" | "number[]" | "Date" | "Date[]" | "boolean" | "boolean[]"; export type CastableSchema = Record; export type SyncUrlConfig = { fields?: String[]; schema?: CastableSchema; replace?: boolean; parse?: Function; stringify?: Function; }; export function syncUrl({ fields: givenFields, schema: givenSchema, replace, parse, stringify, }?: SyncUrlConfig): (store: Store) => void; export function undo({ maxSize }?: { maxSize?: number | undefined; }): (store: Store) => void; export {};