@tanstack/solid-pacer 0.9.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/async-batcher/createAsyncBatcher.cjs +1 -1
- package/dist/cjs/async-batcher/createAsyncBatcher.cjs.map +1 -1
- package/dist/cjs/async-batcher/createAsyncBatcher.d.cts +54 -6
- package/dist/cjs/async-debouncer/createAsyncDebouncer.cjs +1 -1
- package/dist/cjs/async-debouncer/createAsyncDebouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer/createAsyncDebouncer.d.cts +50 -8
- package/dist/cjs/async-queuer/createAsyncQueuer.cjs +1 -1
- package/dist/cjs/async-queuer/createAsyncQueuer.cjs.map +1 -1
- package/dist/cjs/async-queuer/createAsyncQueuer.d.cts +55 -6
- package/dist/cjs/async-rate-limiter/createAsyncRateLimiter.cjs +1 -1
- package/dist/cjs/async-rate-limiter/createAsyncRateLimiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter/createAsyncRateLimiter.d.cts +59 -9
- package/dist/cjs/async-throttler/createAsyncThrottler.cjs +1 -1
- package/dist/cjs/async-throttler/createAsyncThrottler.cjs.map +1 -1
- package/dist/cjs/async-throttler/createAsyncThrottler.d.cts +54 -9
- package/dist/cjs/batcher/createBatcher.cjs +1 -1
- package/dist/cjs/batcher/createBatcher.cjs.map +1 -1
- package/dist/cjs/batcher/createBatcher.d.cts +46 -9
- package/dist/cjs/debouncer/createDebouncedSignal.cjs.map +1 -1
- package/dist/cjs/debouncer/createDebouncedSignal.d.cts +36 -4
- package/dist/cjs/debouncer/createDebouncedValue.cjs.map +1 -1
- package/dist/cjs/debouncer/createDebouncedValue.d.cts +30 -2
- package/dist/cjs/debouncer/createDebouncer.cjs +1 -1
- package/dist/cjs/debouncer/createDebouncer.cjs.map +1 -1
- package/dist/cjs/debouncer/createDebouncer.d.cts +56 -10
- package/dist/cjs/queuer/createQueuer.cjs +1 -1
- package/dist/cjs/queuer/createQueuer.cjs.map +1 -1
- package/dist/cjs/queuer/createQueuer.d.cts +46 -12
- package/dist/cjs/rate-limiter/createRateLimitedSignal.cjs.map +1 -1
- package/dist/cjs/rate-limiter/createRateLimitedSignal.d.cts +30 -3
- package/dist/cjs/rate-limiter/createRateLimitedValue.cjs.map +1 -1
- package/dist/cjs/rate-limiter/createRateLimitedValue.d.cts +32 -2
- package/dist/cjs/rate-limiter/createRateLimiter.cjs +1 -1
- package/dist/cjs/rate-limiter/createRateLimiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter/createRateLimiter.d.cts +50 -8
- package/dist/cjs/throttler/createThrottledSignal.cjs.map +1 -1
- package/dist/cjs/throttler/createThrottledSignal.d.cts +34 -6
- package/dist/cjs/throttler/createThrottledValue.cjs.map +1 -1
- package/dist/cjs/throttler/createThrottledValue.d.cts +33 -2
- package/dist/cjs/throttler/createThrottler.cjs +1 -1
- package/dist/cjs/throttler/createThrottler.cjs.map +1 -1
- package/dist/cjs/throttler/createThrottler.d.cts +56 -12
- package/dist/esm/async-batcher/createAsyncBatcher.d.ts +54 -6
- package/dist/esm/async-batcher/createAsyncBatcher.js +1 -1
- package/dist/esm/async-batcher/createAsyncBatcher.js.map +1 -1
- package/dist/esm/async-debouncer/createAsyncDebouncer.d.ts +50 -8
- package/dist/esm/async-debouncer/createAsyncDebouncer.js +1 -1
- package/dist/esm/async-debouncer/createAsyncDebouncer.js.map +1 -1
- package/dist/esm/async-queuer/createAsyncQueuer.d.ts +55 -6
- package/dist/esm/async-queuer/createAsyncQueuer.js +1 -1
- package/dist/esm/async-queuer/createAsyncQueuer.js.map +1 -1
- package/dist/esm/async-rate-limiter/createAsyncRateLimiter.d.ts +59 -9
- package/dist/esm/async-rate-limiter/createAsyncRateLimiter.js +1 -1
- package/dist/esm/async-rate-limiter/createAsyncRateLimiter.js.map +1 -1
- package/dist/esm/async-throttler/createAsyncThrottler.d.ts +54 -9
- package/dist/esm/async-throttler/createAsyncThrottler.js +1 -1
- package/dist/esm/async-throttler/createAsyncThrottler.js.map +1 -1
- package/dist/esm/batcher/createBatcher.d.ts +46 -9
- package/dist/esm/batcher/createBatcher.js +1 -1
- package/dist/esm/batcher/createBatcher.js.map +1 -1
- package/dist/esm/debouncer/createDebouncedSignal.d.ts +36 -4
- package/dist/esm/debouncer/createDebouncedSignal.js.map +1 -1
- package/dist/esm/debouncer/createDebouncedValue.d.ts +30 -2
- package/dist/esm/debouncer/createDebouncedValue.js.map +1 -1
- package/dist/esm/debouncer/createDebouncer.d.ts +56 -10
- package/dist/esm/debouncer/createDebouncer.js +1 -1
- package/dist/esm/debouncer/createDebouncer.js.map +1 -1
- package/dist/esm/queuer/createQueuer.d.ts +46 -12
- package/dist/esm/queuer/createQueuer.js +1 -1
- package/dist/esm/queuer/createQueuer.js.map +1 -1
- package/dist/esm/rate-limiter/createRateLimitedSignal.d.ts +30 -3
- package/dist/esm/rate-limiter/createRateLimitedSignal.js.map +1 -1
- package/dist/esm/rate-limiter/createRateLimitedValue.d.ts +32 -2
- package/dist/esm/rate-limiter/createRateLimitedValue.js.map +1 -1
- package/dist/esm/rate-limiter/createRateLimiter.d.ts +50 -8
- package/dist/esm/rate-limiter/createRateLimiter.js +1 -1
- package/dist/esm/rate-limiter/createRateLimiter.js.map +1 -1
- package/dist/esm/throttler/createThrottledSignal.d.ts +34 -6
- package/dist/esm/throttler/createThrottledSignal.js.map +1 -1
- package/dist/esm/throttler/createThrottledValue.d.ts +33 -2
- package/dist/esm/throttler/createThrottledValue.js.map +1 -1
- package/dist/esm/throttler/createThrottler.d.ts +56 -12
- package/dist/esm/throttler/createThrottler.js +1 -1
- package/dist/esm/throttler/createThrottler.js.map +1 -1
- package/package.json +2 -2
- package/src/async-batcher/createAsyncBatcher.ts +58 -14
- package/src/async-debouncer/createAsyncDebouncer.ts +53 -10
- package/src/async-queuer/createAsyncQueuer.ts +58 -8
- package/src/async-rate-limiter/createAsyncRateLimiter.ts +61 -10
- package/src/async-throttler/createAsyncThrottler.ts +56 -10
- package/src/batcher/createBatcher.ts +48 -10
- package/src/debouncer/createDebouncedSignal.ts +36 -7
- package/src/debouncer/createDebouncedValue.ts +30 -5
- package/src/debouncer/createDebouncer.ts +58 -17
- package/src/queuer/createQueuer.ts +48 -14
- package/src/rate-limiter/createRateLimitedSignal.ts +30 -3
- package/src/rate-limiter/createRateLimitedValue.ts +32 -2
- package/src/rate-limiter/createRateLimiter.ts +53 -16
- package/src/throttler/createThrottledSignal.ts +34 -9
- package/src/throttler/createThrottledValue.ts +33 -5
- package/src/throttler/createThrottler.ts +58 -19
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncRateLimiter.js","sources":["../../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected =
|
|
1
|
+
{"version":3,"file":"createAsyncRateLimiter.js","sources":["../../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `currentWindowStart`: Timestamp when the current window started\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Opt-in to re-render when rate limit and execution state changes (optimized for UI feedback)\n * const rateLimiter = createAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { limit: 10, window: 60000 },\n * (state) => ({\n * remainingInWindow: state.remainingInWindow,\n * isExecuting: state.isExecuting,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const rateLimiter = createAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (info) => console.log(`Rate limit exceeded: ${info.nextValidTime - Date.now()}ms until next window`)\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { remainingInWindow, isExecuting } = rateLimiter.state();\n * ```\n */\nexport function createAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncRateLimiter<TFn, TSelected> {\n const asyncRateLimiter = new AsyncRateLimiter<TFn>(fn, initialOptions)\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n return {\n ...asyncRateLimiter,\n state,\n } as SolidAsyncRateLimiter<TFn, TSelected>\n}\n"],"names":[],"mappings":";;AAgIO,SAAS,uBAId,IACA,gBACA,WAA6D,OAC1D,CAAA,IACoC;AACvC,QAAM,mBAAmB,IAAI,iBAAsB,IAAI,cAAc;AAErE,QAAM,QAAQ,SAAS,iBAAiB,OAAO,QAAQ;AAEvD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
import { AsyncThrottler, AsyncThrottlerOptions, AsyncThrottlerState } from '@tanstack/pacer/async-throttler';
|
|
2
|
+
import { Store } from '@tanstack/solid-store';
|
|
2
3
|
import { Accessor } from 'solid-js';
|
|
3
4
|
import { AnyAsyncFunction } from '@tanstack/pacer/types';
|
|
4
|
-
export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected =
|
|
5
|
+
export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncThrottler<TFn>, 'store'> {
|
|
5
6
|
/**
|
|
6
|
-
* Reactive state that will be updated
|
|
7
|
+
* Reactive state that will be updated when the throttler state changes
|
|
7
8
|
*
|
|
8
9
|
* Use this instead of `throttler.store.state`
|
|
9
10
|
*/
|
|
10
11
|
readonly state: Accessor<Readonly<TSelected>>;
|
|
12
|
+
/**
|
|
13
|
+
* @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.
|
|
14
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
|
|
15
|
+
* Although, you can make the state reactive by using the `useStore` in your own usage.
|
|
16
|
+
*/
|
|
17
|
+
readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
|
|
11
18
|
}
|
|
12
19
|
/**
|
|
13
20
|
* A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.
|
|
@@ -30,9 +37,34 @@ export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = A
|
|
|
30
37
|
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
31
38
|
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
32
39
|
*
|
|
40
|
+
* ## State Management and Selector
|
|
41
|
+
*
|
|
42
|
+
* The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
|
|
43
|
+
* to specify which state changes will trigger a re-render, optimizing performance by preventing
|
|
44
|
+
* unnecessary re-renders when irrelevant state changes occur.
|
|
45
|
+
*
|
|
46
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
47
|
+
* tracking by providing a selector function. This prevents unnecessary re-renders and gives you
|
|
48
|
+
* full control over when your component updates. Only when you provide a selector will the
|
|
49
|
+
* component re-render when the selected state values change.
|
|
50
|
+
*
|
|
51
|
+
* Available state properties:
|
|
52
|
+
* - `canLeadingExecute`: Whether the throttler can execute on the leading edge
|
|
53
|
+
* - `canTrailingExecute`: Whether the throttler can execute on the trailing edge
|
|
54
|
+
* - `executionCount`: Number of function executions that have been completed
|
|
55
|
+
* - `hasError`: Whether the last execution resulted in an error
|
|
56
|
+
* - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
|
|
57
|
+
* - `isExecuting`: Whether an async function execution is currently in progress
|
|
58
|
+
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
59
|
+
* - `lastError`: The error from the most recent failed execution (if any)
|
|
60
|
+
* - `lastExecutionTime`: Timestamp of the last execution
|
|
61
|
+
* - `lastResult`: The result from the most recent successful execution
|
|
62
|
+
* - `nextExecutionTime`: Timestamp of the next allowed execution
|
|
63
|
+
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')
|
|
64
|
+
*
|
|
33
65
|
* @example
|
|
34
66
|
* ```tsx
|
|
35
|
-
* //
|
|
67
|
+
* // Default behavior - no reactive state subscriptions
|
|
36
68
|
* const { maybeExecute } = createAsyncThrottler(
|
|
37
69
|
* async (id: string) => {
|
|
38
70
|
* const data = await api.fetchData(id);
|
|
@@ -41,12 +73,21 @@ export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = A
|
|
|
41
73
|
* { wait: 1000 }
|
|
42
74
|
* );
|
|
43
75
|
*
|
|
44
|
-
* //
|
|
45
|
-
* const
|
|
46
|
-
* const { maybeExecute } = createAsyncThrottler(
|
|
76
|
+
* // Opt-in to re-render when isPending or isExecuting changes (optimized for loading states)
|
|
77
|
+
* const throttler = createAsyncThrottler(
|
|
47
78
|
* async (query) => {
|
|
48
79
|
* const result = await searchAPI(query);
|
|
49
|
-
*
|
|
80
|
+
* return result;
|
|
81
|
+
* },
|
|
82
|
+
* { wait: 2000 },
|
|
83
|
+
* (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })
|
|
84
|
+
* );
|
|
85
|
+
*
|
|
86
|
+
* // Opt-in to re-render when error state changes (optimized for error handling)
|
|
87
|
+
* const throttler = createAsyncThrottler(
|
|
88
|
+
* async (query) => {
|
|
89
|
+
* const result = await searchAPI(query);
|
|
90
|
+
* return result;
|
|
50
91
|
* },
|
|
51
92
|
* {
|
|
52
93
|
* wait: 2000,
|
|
@@ -55,8 +96,12 @@ export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = A
|
|
|
55
96
|
* onError: (error) => {
|
|
56
97
|
* console.error('API call failed:', error);
|
|
57
98
|
* }
|
|
58
|
-
* }
|
|
99
|
+
* },
|
|
100
|
+
* (state) => ({ hasError: state.hasError, lastError: state.lastError })
|
|
59
101
|
* );
|
|
102
|
+
*
|
|
103
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
104
|
+
* const { isPending, isExecuting } = throttler.state();
|
|
60
105
|
* ```
|
|
61
106
|
*/
|
|
62
|
-
export declare function createAsyncThrottler<TFn extends AnyAsyncFunction, TSelected =
|
|
107
|
+
export declare function createAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): SolidAsyncThrottler<TFn, TSelected>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { AsyncThrottler } from "@tanstack/pacer/async-throttler";
|
|
2
2
|
import { useStore } from "@tanstack/solid-store";
|
|
3
|
-
function createAsyncThrottler(fn, initialOptions, selector) {
|
|
3
|
+
function createAsyncThrottler(fn, initialOptions, selector = () => ({})) {
|
|
4
4
|
const asyncThrottler = new AsyncThrottler(fn, initialOptions);
|
|
5
5
|
const state = useStore(asyncThrottler.store, selector);
|
|
6
6
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncThrottler.js","sources":["../../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected =
|
|
1
|
+
{"version":3,"file":"createAsyncThrottler.js","sources":["../../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to re-render when isPending or isExecuting changes (optimized for loading states)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { wait: 2000 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = throttler.state();\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"names":[],"mappings":";;AAoHO,SAAS,qBAId,IACA,gBACA,WAA2D,OACxD,CAAA,IACkC;AACrC,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AAE5D,QAAM,QAAQ,SAAS,eAAe,OAAO,QAAQ;AAErD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
import { Batcher, BatcherOptions, BatcherState } from '@tanstack/pacer/batcher';
|
|
2
|
+
import { Store } from '@tanstack/solid-store';
|
|
2
3
|
import { Accessor } from 'solid-js';
|
|
3
|
-
export interface SolidBatcher<TValue, TSelected =
|
|
4
|
+
export interface SolidBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 'store'> {
|
|
4
5
|
/**
|
|
5
6
|
* Reactive state that will be updated when the batcher state changes
|
|
6
7
|
*
|
|
7
8
|
* Use this instead of `batcher.store.state`
|
|
8
9
|
*/
|
|
9
10
|
readonly state: Accessor<Readonly<TSelected>>;
|
|
11
|
+
/**
|
|
12
|
+
* @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.
|
|
13
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
|
|
14
|
+
* Although, you can make the state reactive by using the `useStore` in your own usage.
|
|
15
|
+
*/
|
|
16
|
+
readonly store: Store<Readonly<BatcherState<TValue>>>;
|
|
10
17
|
}
|
|
11
18
|
/**
|
|
12
19
|
* Creates a Solid-compatible Batcher instance for managing batches of items, exposing Solid signals for all stateful properties.
|
|
@@ -23,8 +30,26 @@ export interface SolidBatcher<TValue, TSelected = BatcherState<TValue>> extends
|
|
|
23
30
|
* - Time-based batching (process after X milliseconds)
|
|
24
31
|
* - Custom batch processing logic via getShouldExecute
|
|
25
32
|
*
|
|
33
|
+
* ## State Management and Selector
|
|
34
|
+
*
|
|
35
|
+
* The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
|
|
36
|
+
* to specify which state changes will trigger a re-render, optimizing performance by preventing
|
|
37
|
+
* unnecessary re-renders when irrelevant state changes occur.
|
|
38
|
+
*
|
|
39
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
40
|
+
* tracking by providing a selector function. This prevents unnecessary re-renders and gives you
|
|
41
|
+
* full control over when your component updates. Only when you provide a selector will the
|
|
42
|
+
* component re-render when the selected state values change.
|
|
43
|
+
*
|
|
44
|
+
* Available state properties:
|
|
45
|
+
* - `executionCount`: Number of batch executions that have been completed
|
|
46
|
+
* - `isRunning`: Whether the batcher is currently running (not stopped)
|
|
47
|
+
* - `items`: Array of items currently queued for batching
|
|
48
|
+
* - `totalItemsProcessed`: Total number of individual items that have been processed across all batches
|
|
49
|
+
*
|
|
26
50
|
* Example usage:
|
|
27
51
|
* ```tsx
|
|
52
|
+
* // Default behavior - no reactive state subscriptions
|
|
28
53
|
* const batcher = createBatcher(
|
|
29
54
|
* (items) => {
|
|
30
55
|
* // Process batch of items
|
|
@@ -38,6 +63,23 @@ export interface SolidBatcher<TValue, TSelected = BatcherState<TValue>> extends
|
|
|
38
63
|
* }
|
|
39
64
|
* );
|
|
40
65
|
*
|
|
66
|
+
* // Opt-in to re-render when items or isRunning changes (optimized for UI updates)
|
|
67
|
+
* const batcher = createBatcher(
|
|
68
|
+
* (items) => console.log('Processing batch:', items),
|
|
69
|
+
* { maxSize: 5, wait: 2000 },
|
|
70
|
+
* (state) => ({ items: state.items, isRunning: state.isRunning })
|
|
71
|
+
* );
|
|
72
|
+
*
|
|
73
|
+
* // Opt-in to re-render when execution metrics change (optimized for tracking progress)
|
|
74
|
+
* const batcher = createBatcher(
|
|
75
|
+
* (items) => console.log('Processing batch:', items),
|
|
76
|
+
* { maxSize: 5, wait: 2000 },
|
|
77
|
+
* (state) => ({
|
|
78
|
+
* executionCount: state.executionCount,
|
|
79
|
+
* totalItemsProcessed: state.totalItemsProcessed
|
|
80
|
+
* })
|
|
81
|
+
* );
|
|
82
|
+
*
|
|
41
83
|
* // Add items to batch
|
|
42
84
|
* batcher.addItem('task1');
|
|
43
85
|
* batcher.addItem('task2');
|
|
@@ -46,13 +88,8 @@ export interface SolidBatcher<TValue, TSelected = BatcherState<TValue>> extends
|
|
|
46
88
|
* batcher.stop(); // Pause processing
|
|
47
89
|
* batcher.start(); // Resume processing
|
|
48
90
|
*
|
|
49
|
-
* // Access
|
|
50
|
-
*
|
|
51
|
-
* console.log('Size:', batcher.size());
|
|
52
|
-
* console.log('Is empty:', batcher.isEmpty());
|
|
53
|
-
* console.log('Is running:', batcher.isRunning());
|
|
54
|
-
* console.log('Batch count:', batcher.executionCount());
|
|
55
|
-
* console.log('Item count:', batcher.totalItemsProcessed());
|
|
91
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
92
|
+
* const { items, isRunning } = batcher.state();
|
|
56
93
|
* ```
|
|
57
94
|
*/
|
|
58
|
-
export declare function createBatcher<TValue, TSelected =
|
|
95
|
+
export declare function createBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => void, initialOptions?: BatcherOptions<TValue>, selector?: (state: BatcherState<TValue>) => TSelected): SolidBatcher<TValue, TSelected>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Batcher } from "@tanstack/pacer/batcher";
|
|
2
2
|
import { useStore } from "@tanstack/solid-store";
|
|
3
|
-
function createBatcher(fn, initialOptions = {}, selector) {
|
|
3
|
+
function createBatcher(fn, initialOptions = {}, selector = () => ({})) {
|
|
4
4
|
const batcher = new Batcher(fn, initialOptions);
|
|
5
5
|
const state = useStore(batcher.store, selector);
|
|
6
6
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createBatcher.js","sources":["../../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcher<TValue, TSelected =
|
|
1
|
+
{"version":3,"file":"createBatcher.js","sources":["../../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcher<TValue, TSelected = {}>\n extends Omit<Batcher<TValue>, 'store'> {\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<BatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Batcher instance for managing batches of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Batch processing of items using the provided `fn` function\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `executionCount`: Number of batch executions that have been completed\n * - `isRunning`: Whether the batcher is currently running (not stopped)\n * - `items`: Array of items currently queued for batching\n * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = createBatcher(\n * (items) => {\n * // Process batch of items\n * console.log('Processing batch:', items);\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed'),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Opt-in to re-render when items or isRunning changes (optimized for UI updates)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for tracking progress)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Add items to batch\n * batcher.addItem('task1');\n * batcher.addItem('task2');\n *\n * // Control the batcher\n * batcher.stop(); // Pause processing\n * batcher.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = batcher.state();\n * ```\n */\nexport function createBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidBatcher<TValue, TSelected> {\n const batcher = new Batcher(fn, initialOptions)\n\n const state = useStore(batcher.store, selector)\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"names":[],"mappings":";;AAmGO,SAAS,cACd,IACA,iBAAyC,CAAA,GACzC,WAAuD,OACpD,CAAA,IAC8B;AACjC,QAAM,UAAU,IAAI,QAAQ,IAAI,cAAc;AAE9C,QAAM,QAAQ,SAAS,QAAQ,OAAO,QAAQ;AAC9C,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"}
|
|
@@ -15,21 +15,53 @@ import { DebouncerOptions, DebouncerState } from '@tanstack/pacer/debouncer';
|
|
|
15
15
|
* - A function to update the debounced value
|
|
16
16
|
* - The debouncer instance with additional control methods and state signals
|
|
17
17
|
*
|
|
18
|
+
* ## State Management and Selector
|
|
19
|
+
*
|
|
20
|
+
* The hook uses TanStack Store for reactive state management via the underlying debouncer instance.
|
|
21
|
+
* The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,
|
|
22
|
+
* optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur.
|
|
23
|
+
*
|
|
24
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
25
|
+
* tracking by providing a selector function. This prevents unnecessary reactive updates and gives you
|
|
26
|
+
* full control over when your component subscribes to state changes. Only when you provide a selector will
|
|
27
|
+
* the reactive system track the selected state values.
|
|
28
|
+
*
|
|
29
|
+
* Available debouncer state properties:
|
|
30
|
+
* - `canLeadingExecute`: Whether the debouncer can execute on the leading edge
|
|
31
|
+
* - `executionCount`: Number of function executions that have been completed
|
|
32
|
+
* - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution
|
|
33
|
+
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
34
|
+
* - `status`: Current execution status ('disabled' | 'idle' | 'pending')
|
|
35
|
+
*
|
|
18
36
|
* @example
|
|
19
37
|
* ```tsx
|
|
20
|
-
* //
|
|
38
|
+
* // Default behavior - no reactive state subscriptions
|
|
21
39
|
* const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {
|
|
22
40
|
* wait: 500 // Wait 500ms after last keystroke
|
|
23
41
|
* });
|
|
24
42
|
*
|
|
43
|
+
* // Opt-in to reactive updates when pending state changes (optimized for loading indicators)
|
|
44
|
+
* const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(
|
|
45
|
+
* '',
|
|
46
|
+
* { wait: 500 },
|
|
47
|
+
* (state) => ({ isPending: state.isPending })
|
|
48
|
+
* );
|
|
49
|
+
*
|
|
50
|
+
* // Opt-in to reactive updates when execution count changes (optimized for tracking executions)
|
|
51
|
+
* const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(
|
|
52
|
+
* '',
|
|
53
|
+
* { wait: 500 },
|
|
54
|
+
* (state) => ({ executionCount: state.executionCount })
|
|
55
|
+
* );
|
|
56
|
+
*
|
|
25
57
|
* // Update value - will be debounced
|
|
26
58
|
* const handleChange = (e) => {
|
|
27
59
|
* setSearchTerm(e.target.value);
|
|
28
60
|
* };
|
|
29
61
|
*
|
|
30
62
|
* // Access debouncer state via signals
|
|
31
|
-
* console.log('Executions:', debouncer.
|
|
32
|
-
* console.log('Is pending:', debouncer.
|
|
63
|
+
* console.log('Executions:', debouncer.state().executionCount);
|
|
64
|
+
* console.log('Is pending:', debouncer.state().isPending);
|
|
33
65
|
*
|
|
34
66
|
* // In onExecute callback, use get* methods
|
|
35
67
|
* const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {
|
|
@@ -40,7 +72,7 @@ import { DebouncerOptions, DebouncerState } from '@tanstack/pacer/debouncer';
|
|
|
40
72
|
* });
|
|
41
73
|
* ```
|
|
42
74
|
*/
|
|
43
|
-
export declare function createDebouncedSignal<TValue, TSelected =
|
|
75
|
+
export declare function createDebouncedSignal<TValue, TSelected = {}>(value: TValue, initialOptions: DebouncerOptions<Setter<TValue>>, selector?: (state: DebouncerState<Setter<TValue>>) => TSelected): [
|
|
44
76
|
Accessor<TValue>,
|
|
45
77
|
Setter<TValue>,
|
|
46
78
|
SolidDebouncer<Setter<TValue>, TSelected>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createDebouncedSignal.js","sources":["../../../src/debouncer/createDebouncedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createDebouncer } from './createDebouncer'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced state value, combining Solid's createSignal with debouncing functionality.\n * This hook provides both the current debounced value and methods to update it.\n *\n * The state value is only updated after the specified wait time has elapsed since the last update attempt.\n * If another update is attempted before the wait time expires, the timer resets and starts waiting again.\n * This is useful for handling frequent state updates that should be throttled, like search input values\n * or window resize dimensions.\n *\n * The hook returns a tuple containing:\n * - The current debounced value accessor\n * - A function to update the debounced value\n * - The debouncer instance with additional control methods and state signals\n *\n * @example\n * ```tsx\n * //
|
|
1
|
+
{"version":3,"file":"createDebouncedSignal.js","sources":["../../../src/debouncer/createDebouncedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createDebouncer } from './createDebouncer'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced state value, combining Solid's createSignal with debouncing functionality.\n * This hook provides both the current debounced value and methods to update it.\n *\n * The state value is only updated after the specified wait time has elapsed since the last update attempt.\n * If another update is attempted before the wait time expires, the timer resets and starts waiting again.\n * This is useful for handling frequent state updates that should be throttled, like search input values\n * or window resize dimensions.\n *\n * The hook returns a tuple containing:\n * - The current debounced value accessor\n * - A function to update the debounced value\n * - The debouncer instance with additional control methods and state signals\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying debouncer instance.\n * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available debouncer state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500 // Wait 500ms after last keystroke\n * });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(\n * '',\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to reactive updates when execution count changes (optimized for tracking executions)\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(\n * '',\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Update value - will be debounced\n * const handleChange = (e) => {\n * setSearchTerm(e.target.value);\n * };\n *\n * // Access debouncer state via signals\n * console.log('Executions:', debouncer.state().executionCount);\n * console.log('Is pending:', debouncer.state().isPending);\n *\n * // In onExecute callback, use get* methods\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500,\n * onExecute: (debouncer) => {\n * console.log('Total executions:', debouncer.getExecutionCount());\n * }\n * });\n * ```\n */\nexport function createDebouncedSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: DebouncerOptions<Setter<TValue>>,\n selector?: (state: DebouncerState<Setter<TValue>>) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidDebouncer<Setter<TValue>, TSelected>,\n] {\n const [debouncedValue, setDebouncedValue] = createSignal<TValue>(value)\n\n const debouncer = createDebouncer(setDebouncedValue, initialOptions, selector)\n\n return [debouncedValue, debouncer.maybeExecute as Setter<TValue>, debouncer]\n}\n"],"names":[],"mappings":";;AAgFO,SAAS,sBACd,OACA,gBACA,UAKA;AACA,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,aAAqB,KAAK;AAEtE,QAAM,YAAY,gBAAgB,mBAAmB,gBAAgB,QAAQ;AAE7E,SAAO,CAAC,gBAAgB,UAAU,cAAgC,SAAS;AAC7E;"}
|
|
@@ -18,21 +18,49 @@ import { DebouncerOptions, DebouncerState } from '@tanstack/pacer/debouncer';
|
|
|
18
18
|
* - An Accessor that provides the current debounced value
|
|
19
19
|
* - The debouncer instance with control methods
|
|
20
20
|
*
|
|
21
|
+
* ## State Management and Selector
|
|
22
|
+
*
|
|
23
|
+
* The hook uses TanStack Store for reactive state management via the underlying debouncer instance.
|
|
24
|
+
* The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,
|
|
25
|
+
* optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur.
|
|
26
|
+
*
|
|
27
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
28
|
+
* tracking by providing a selector function. This prevents unnecessary reactive updates and gives you
|
|
29
|
+
* full control over when your component subscribes to state changes. Only when you provide a selector will
|
|
30
|
+
* the reactive system track the selected state values.
|
|
31
|
+
*
|
|
32
|
+
* Available debouncer state properties:
|
|
33
|
+
* - `canLeadingExecute`: Whether the debouncer can execute on the leading edge
|
|
34
|
+
* - `executionCount`: Number of function executions that have been completed
|
|
35
|
+
* - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution
|
|
36
|
+
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
37
|
+
* - `status`: Current execution status ('disabled' | 'idle' | 'pending')
|
|
38
|
+
*
|
|
21
39
|
* @example
|
|
22
40
|
* ```tsx
|
|
23
|
-
* //
|
|
41
|
+
* // Default behavior - no reactive state subscriptions
|
|
24
42
|
* const [searchQuery, setSearchQuery] = createSignal('');
|
|
25
43
|
* const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, {
|
|
26
44
|
* wait: 500 // Wait 500ms after last change
|
|
27
45
|
* });
|
|
28
46
|
*
|
|
47
|
+
* // Opt-in to reactive updates when pending state changes (optimized for loading indicators)
|
|
48
|
+
* const [debouncedQuery, debouncer] = createDebouncedValue(
|
|
49
|
+
* searchQuery,
|
|
50
|
+
* { wait: 500 },
|
|
51
|
+
* (state) => ({ isPending: state.isPending })
|
|
52
|
+
* );
|
|
53
|
+
*
|
|
29
54
|
* // debouncedQuery will update 500ms after searchQuery stops changing
|
|
30
55
|
* createEffect(() => {
|
|
31
56
|
* fetchSearchResults(debouncedQuery());
|
|
32
57
|
* });
|
|
33
58
|
*
|
|
59
|
+
* // Access debouncer state via signals
|
|
60
|
+
* console.log('Is pending:', debouncer.state().isPending);
|
|
61
|
+
*
|
|
34
62
|
* // Control the debouncer
|
|
35
63
|
* debouncer.cancel(); // Cancel any pending updates
|
|
36
64
|
* ```
|
|
37
65
|
*/
|
|
38
|
-
export declare function createDebouncedValue<TValue, TSelected =
|
|
66
|
+
export declare function createDebouncedValue<TValue, TSelected = {}>(value: Accessor<TValue>, initialOptions: DebouncerOptions<Setter<TValue>>, selector?: (state: DebouncerState<Setter<TValue>>) => TSelected): [Accessor<TValue>, SolidDebouncer<Setter<TValue>, TSelected>];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createDebouncedValue.js","sources":["../../../src/debouncer/createDebouncedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createDebouncedSignal } from './createDebouncedSignal'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced value that updates only after a specified delay.\n * Unlike createDebouncedSignal, this hook automatically tracks changes to the input value\n * and updates the debounced value accordingly.\n *\n * The debounced value will only update after the specified wait time has elapsed since\n * the last change to the input value. If the input value changes again before the wait\n * time expires, the timer resets and starts waiting again.\n *\n * This is useful for deriving debounced values from props or state that change frequently,\n * like search queries or form inputs, where you want to limit how often downstream effects\n * or calculations occur.\n *\n * The hook returns a tuple containing:\n * - An Accessor that provides the current debounced value\n * - The debouncer instance with control methods\n *\n * @example\n * ```tsx\n * //
|
|
1
|
+
{"version":3,"file":"createDebouncedValue.js","sources":["../../../src/debouncer/createDebouncedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createDebouncedSignal } from './createDebouncedSignal'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced value that updates only after a specified delay.\n * Unlike createDebouncedSignal, this hook automatically tracks changes to the input value\n * and updates the debounced value accordingly.\n *\n * The debounced value will only update after the specified wait time has elapsed since\n * the last change to the input value. If the input value changes again before the wait\n * time expires, the timer resets and starts waiting again.\n *\n * This is useful for deriving debounced values from props or state that change frequently,\n * like search queries or form inputs, where you want to limit how often downstream effects\n * or calculations occur.\n *\n * The hook returns a tuple containing:\n * - An Accessor that provides the current debounced value\n * - The debouncer instance with control methods\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying debouncer instance.\n * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available debouncer state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [searchQuery, setSearchQuery] = createSignal('');\n * const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, {\n * wait: 500 // Wait 500ms after last change\n * });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [debouncedQuery, debouncer] = createDebouncedValue(\n * searchQuery,\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // debouncedQuery will update 500ms after searchQuery stops changing\n * createEffect(() => {\n * fetchSearchResults(debouncedQuery());\n * });\n *\n * // Access debouncer state via signals\n * console.log('Is pending:', debouncer.state().isPending);\n *\n * // Control the debouncer\n * debouncer.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createDebouncedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: DebouncerOptions<Setter<TValue>>,\n selector?: (state: DebouncerState<Setter<TValue>>) => TSelected,\n): [Accessor<TValue>, SolidDebouncer<Setter<TValue>, TSelected>] {\n const [debouncedValue, setDebouncedValue, debouncer] = createDebouncedSignal(\n value(),\n initialOptions,\n selector,\n )\n\n createEffect(() => {\n setDebouncedValue(value() as any)\n })\n\n return [debouncedValue, debouncer]\n}\n"],"names":[],"mappings":";;AAuEO,SAAS,qBACd,OACA,gBACA,UAC+D;AAC/D,QAAM,CAAC,gBAAgB,mBAAmB,SAAS,IAAI;AAAA,IACrD,MAAA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,eAAa,MAAM;AACjB,sBAAkB,OAAc;AAAA,EAAA,CACjC;AAED,SAAO,CAAC,gBAAgB,SAAS;AACnC;"}
|
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
import { Debouncer, DebouncerOptions, DebouncerState } from '@tanstack/pacer/debouncer';
|
|
2
|
+
import { Store } from '@tanstack/solid-store';
|
|
2
3
|
import { Accessor } from 'solid-js';
|
|
3
4
|
import { AnyFunction } from '@tanstack/pacer/types';
|
|
4
|
-
export interface SolidDebouncer<TFn extends AnyFunction, TSelected =
|
|
5
|
+
export interface SolidDebouncer<TFn extends AnyFunction, TSelected = {}> extends Omit<Debouncer<TFn>, 'store'> {
|
|
5
6
|
/**
|
|
6
7
|
* Reactive state that will be updated when the debouncer state changes
|
|
7
8
|
*
|
|
8
9
|
* Use this instead of `debouncer.store.state`
|
|
9
10
|
*/
|
|
10
11
|
readonly state: Accessor<Readonly<TSelected>>;
|
|
12
|
+
/**
|
|
13
|
+
* @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.
|
|
14
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
|
|
15
|
+
* Although, you can make the state reactive by using the `useStore` in your own usage.
|
|
16
|
+
*/
|
|
17
|
+
readonly store: Store<Readonly<DebouncerState<TFn>>>;
|
|
11
18
|
}
|
|
12
19
|
/**
|
|
13
20
|
* A Solid hook that creates and manages a Debouncer instance.
|
|
@@ -24,12 +31,55 @@ export interface SolidDebouncer<TFn extends AnyFunction, TSelected = DebouncerSt
|
|
|
24
31
|
* since the last call. If the function is called again before the wait time expires, the
|
|
25
32
|
* timer resets and starts waiting again.
|
|
26
33
|
*
|
|
34
|
+
* ## State Management and Selector
|
|
35
|
+
*
|
|
36
|
+
* The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
|
|
37
|
+
* to specify which state changes will trigger a re-render, optimizing performance by preventing
|
|
38
|
+
* unnecessary re-renders when irrelevant state changes occur.
|
|
39
|
+
*
|
|
40
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
41
|
+
* tracking by providing a selector function. This prevents unnecessary re-renders and gives you
|
|
42
|
+
* full control over when your component updates. Only when you provide a selector will the
|
|
43
|
+
* component re-render when the selected state values change.
|
|
44
|
+
*
|
|
45
|
+
* Available state properties:
|
|
46
|
+
* - `canLeadingExecute`: Whether the debouncer can execute on the leading edge
|
|
47
|
+
* - `executionCount`: Number of function executions that have been completed
|
|
48
|
+
* - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution
|
|
49
|
+
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
50
|
+
* - `status`: Current execution status ('disabled' | 'idle' | 'pending')
|
|
51
|
+
*
|
|
27
52
|
* @example
|
|
28
53
|
* ```tsx
|
|
29
|
-
* //
|
|
54
|
+
* // Default behavior - no reactive state subscriptions
|
|
55
|
+
* const debouncer = createDebouncer(
|
|
56
|
+
* (query: string) => fetchSearchResults(query),
|
|
57
|
+
* { wait: 500 }
|
|
58
|
+
* );
|
|
59
|
+
*
|
|
60
|
+
* // Opt-in to re-render when isPending changes (optimized for loading states)
|
|
30
61
|
* const debouncer = createDebouncer(
|
|
31
62
|
* (query: string) => fetchSearchResults(query),
|
|
32
|
-
* { wait: 500 }
|
|
63
|
+
* { wait: 500 },
|
|
64
|
+
* (state) => ({ isPending: state.isPending })
|
|
65
|
+
* );
|
|
66
|
+
*
|
|
67
|
+
* // Opt-in to re-render when executionCount changes (optimized for tracking execution)
|
|
68
|
+
* const debouncer = createDebouncer(
|
|
69
|
+
* (query: string) => fetchSearchResults(query),
|
|
70
|
+
* { wait: 500 },
|
|
71
|
+
* (state) => ({ executionCount: state.executionCount })
|
|
72
|
+
* );
|
|
73
|
+
*
|
|
74
|
+
* // Multiple state properties - re-render when any of these change
|
|
75
|
+
* const debouncer = createDebouncer(
|
|
76
|
+
* (query: string) => fetchSearchResults(query),
|
|
77
|
+
* { wait: 500 },
|
|
78
|
+
* (state) => ({
|
|
79
|
+
* isPending: state.isPending,
|
|
80
|
+
* executionCount: state.executionCount,
|
|
81
|
+
* status: state.status
|
|
82
|
+
* })
|
|
33
83
|
* );
|
|
34
84
|
*
|
|
35
85
|
* // In an event handler
|
|
@@ -37,12 +87,8 @@ export interface SolidDebouncer<TFn extends AnyFunction, TSelected = DebouncerSt
|
|
|
37
87
|
* debouncer.maybeExecute(e.target.value);
|
|
38
88
|
* };
|
|
39
89
|
*
|
|
40
|
-
* // Access
|
|
41
|
-
*
|
|
42
|
-
* console.log('Is pending:', debouncer.isPending());
|
|
43
|
-
*
|
|
44
|
-
* // Update options
|
|
45
|
-
* debouncer.setOptions({ wait: 1000 });
|
|
90
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
91
|
+
* const { isPending } = debouncer.state();
|
|
46
92
|
* ```
|
|
47
93
|
*/
|
|
48
|
-
export declare function createDebouncer<TFn extends AnyFunction, TSelected =
|
|
94
|
+
export declare function createDebouncer<TFn extends AnyFunction, TSelected = {}>(fn: TFn, initialOptions: DebouncerOptions<TFn>, selector?: (state: DebouncerState<TFn>) => TSelected): SolidDebouncer<TFn, TSelected>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Debouncer } from "@tanstack/pacer/debouncer";
|
|
2
2
|
import { createEffect, onCleanup } from "solid-js";
|
|
3
3
|
import { useStore } from "@tanstack/solid-store";
|
|
4
|
-
function createDebouncer(fn, initialOptions, selector) {
|
|
4
|
+
function createDebouncer(fn, initialOptions, selector = () => ({})) {
|
|
5
5
|
const asyncDebouncer = new Debouncer(fn, initialOptions);
|
|
6
6
|
const state = useStore(asyncDebouncer.store, selector);
|
|
7
7
|
createEffect(() => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createDebouncer.js","sources":["../../../src/debouncer/createDebouncer.ts"],"sourcesContent":["import { Debouncer } from '@tanstack/pacer/debouncer'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\nexport interface SolidDebouncer
|
|
1
|
+
{"version":3,"file":"createDebouncer.js","sources":["../../../src/debouncer/createDebouncer.ts"],"sourcesContent":["import { Debouncer } from '@tanstack/pacer/debouncer'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\nexport interface SolidDebouncer<TFn extends AnyFunction, TSelected = {}>\n extends Omit<Debouncer<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<DebouncerState<TFn>>>\n}\n\n/**\n * A Solid hook that creates and manages a Debouncer instance.\n *\n * This is a lower-level hook that provides direct access to the Debouncer's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (createSignal, Redux, Zustand, etc.).\n *\n * This hook provides debouncing functionality to limit how often a function can be called,\n * waiting for a specified delay before executing the latest call. This is useful for handling\n * frequent events like window resizing, scroll events, or real-time search inputs.\n *\n * The debouncer will only execute the function after the specified wait time has elapsed\n * since the last call. If the function is called again before the wait time expires, the\n * timer resets and starts waiting again.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 }\n * );\n *\n * // Opt-in to re-render when isPending changes (optimized for loading states)\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to re-render when executionCount changes (optimized for tracking execution)\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - re-render when any of these change\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * status: state.status\n * })\n * );\n *\n * // In an event handler\n * const handleChange = (e) => {\n * debouncer.maybeExecute(e.target.value);\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending } = debouncer.state();\n * ```\n */\nexport function createDebouncer<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidDebouncer<TFn, TSelected> {\n const asyncDebouncer = new Debouncer<TFn>(fn, initialOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;;AAsGO,SAAS,gBACd,IACA,gBACA,WAAsD,OAAO,CAAA,IAC7B;AAChC,QAAM,iBAAiB,IAAI,UAAe,IAAI,cAAc;AAE5D,QAAM,QAAQ,SAAS,eAAe,OAAO,QAAQ;AAErD,eAAa,MAAM;AACjB,cAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"}
|