@tanstack/pacer 0.21.1 → 0.23.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/README.md +21 -6
- package/dist/async-batcher.d.ts +11 -14
- package/dist/async-batcher.js +186 -132
- package/dist/async-debouncer.d.ts +10 -13
- package/dist/async-debouncer.js +187 -146
- package/dist/async-queuer.d.ts +12 -14
- package/dist/async-queuer.js +384 -259
- package/dist/async-rate-limiter.d.ts +9 -12
- package/dist/async-rate-limiter.js +198 -147
- package/dist/async-retryer.d.ts +10 -10
- package/dist/async-retryer.js +209 -188
- package/dist/async-throttler.d.ts +10 -13
- package/dist/async-throttler.js +215 -161
- package/dist/batcher.d.ts +5 -8
- package/dist/batcher.js +107 -87
- package/dist/debouncer.d.ts +6 -9
- package/dist/debouncer.js +99 -86
- package/dist/event-client.d.ts +8 -11
- package/dist/event-client.js +1 -2
- package/dist/index.js +1 -1
- package/dist/queuer.d.ts +8 -10
- package/dist/queuer.js +277 -207
- package/dist/rate-limiter.d.ts +6 -9
- package/dist/rate-limiter.js +127 -109
- package/dist/throttler.d.ts +6 -9
- package/dist/throttler.js +127 -90
- package/dist/types.d.ts +4 -6
- package/dist/utils.d.ts +3 -6
- package/dist/utils.js +1 -2
- package/package.json +23 -70
- package/dist/async-batcher.cjs +0 -337
- package/dist/async-batcher.cjs.map +0 -1
- package/dist/async-batcher.d.cts +0 -344
- package/dist/async-batcher.js.map +0 -1
- package/dist/async-debouncer.cjs +0 -330
- package/dist/async-debouncer.cjs.map +0 -1
- package/dist/async-debouncer.d.cts +0 -300
- package/dist/async-debouncer.js.map +0 -1
- package/dist/async-queuer.cjs +0 -484
- package/dist/async-queuer.cjs.map +0 -1
- package/dist/async-queuer.d.cts +0 -440
- package/dist/async-queuer.js.map +0 -1
- package/dist/async-rate-limiter.cjs +0 -373
- package/dist/async-rate-limiter.cjs.map +0 -1
- package/dist/async-rate-limiter.d.cts +0 -357
- package/dist/async-rate-limiter.js.map +0 -1
- package/dist/async-retryer.cjs +0 -374
- package/dist/async-retryer.cjs.map +0 -1
- package/dist/async-retryer.d.cts +0 -319
- package/dist/async-retryer.js.map +0 -1
- package/dist/async-throttler.cjs +0 -347
- package/dist/async-throttler.cjs.map +0 -1
- package/dist/async-throttler.d.cts +0 -320
- package/dist/async-throttler.js.map +0 -1
- package/dist/batcher.cjs +0 -200
- package/dist/batcher.cjs.map +0 -1
- package/dist/batcher.d.cts +0 -180
- package/dist/batcher.js.map +0 -1
- package/dist/debouncer.cjs +0 -203
- package/dist/debouncer.cjs.map +0 -1
- package/dist/debouncer.d.cts +0 -167
- package/dist/debouncer.js.map +0 -1
- package/dist/event-client.cjs +0 -64
- package/dist/event-client.cjs.map +0 -1
- package/dist/event-client.d.cts +0 -66
- package/dist/event-client.js.map +0 -1
- package/dist/index.cjs +0 -52
- package/dist/index.d.cts +0 -15
- package/dist/queuer.cjs +0 -401
- package/dist/queuer.cjs.map +0 -1
- package/dist/queuer.d.cts +0 -345
- package/dist/queuer.js.map +0 -1
- package/dist/rate-limiter.cjs +0 -263
- package/dist/rate-limiter.cjs.map +0 -1
- package/dist/rate-limiter.d.cts +0 -215
- package/dist/rate-limiter.js.map +0 -1
- package/dist/throttler.cjs +0 -215
- package/dist/throttler.cjs.map +0 -1
- package/dist/throttler.d.cts +0 -207
- package/dist/throttler.js.map +0 -1
- package/dist/types.cjs +0 -0
- package/dist/types.d.cts +0 -13
- package/dist/utils.cjs +0 -14
- package/dist/utils.cjs.map +0 -1
- package/dist/utils.d.cts +0 -8
- package/dist/utils.js.map +0 -1
- package/src/async-batcher.ts +0 -594
- package/src/async-debouncer.ts +0 -565
- package/src/async-queuer.ts +0 -925
- package/src/async-rate-limiter.ts +0 -647
- package/src/async-retryer.ts +0 -684
- package/src/async-throttler.ts +0 -633
- package/src/batcher.ts +0 -329
- package/src/debouncer.ts +0 -334
- package/src/event-client.ts +0 -129
- package/src/index.ts +0 -24
- package/src/queuer.ts +0 -740
- package/src/rate-limiter.ts +0 -429
- package/src/throttler.ts +0 -380
- package/src/types.ts +0 -12
- package/src/utils.ts +0 -12
package/dist/batcher.d.cts
DELETED
|
@@ -1,180 +0,0 @@
|
|
|
1
|
-
import { OptionalKeys } from "./types.cjs";
|
|
2
|
-
import { Store } from "@tanstack/store";
|
|
3
|
-
|
|
4
|
-
//#region src/batcher.d.ts
|
|
5
|
-
interface BatcherState<TValue> {
|
|
6
|
-
/**
|
|
7
|
-
* Number of batch executions that have been completed
|
|
8
|
-
*/
|
|
9
|
-
executionCount: number;
|
|
10
|
-
/**
|
|
11
|
-
* Whether the batcher has no items to process (items array is empty)
|
|
12
|
-
*/
|
|
13
|
-
isEmpty: boolean;
|
|
14
|
-
/**
|
|
15
|
-
* Whether the batcher is waiting for the timeout to trigger batch processing
|
|
16
|
-
*/
|
|
17
|
-
isPending: boolean;
|
|
18
|
-
/**
|
|
19
|
-
* Array of items currently queued for batch processing
|
|
20
|
-
*/
|
|
21
|
-
items: Array<TValue>;
|
|
22
|
-
/**
|
|
23
|
-
* Number of items currently in the batch queue
|
|
24
|
-
*/
|
|
25
|
-
size: number;
|
|
26
|
-
/**
|
|
27
|
-
* Current processing status - 'idle' when not processing, 'pending' when waiting for timeout
|
|
28
|
-
*/
|
|
29
|
-
status: 'idle' | 'pending';
|
|
30
|
-
/**
|
|
31
|
-
* Total number of items that have been processed across all batches
|
|
32
|
-
*/
|
|
33
|
-
totalItemsProcessed: number;
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Options for configuring a Batcher instance
|
|
37
|
-
*/
|
|
38
|
-
interface BatcherOptions<TValue> {
|
|
39
|
-
/**
|
|
40
|
-
* Custom function to determine if a batch should be processed
|
|
41
|
-
* Return true to process the batch immediately
|
|
42
|
-
*/
|
|
43
|
-
getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean;
|
|
44
|
-
/**
|
|
45
|
-
* Initial state for the batcher
|
|
46
|
-
*/
|
|
47
|
-
initialState?: Partial<BatcherState<TValue>>;
|
|
48
|
-
/**
|
|
49
|
-
* Optional key to identify this batcher instance.
|
|
50
|
-
* If provided, the batcher will be identified by this key in the devtools and PacerProvider if applicable.
|
|
51
|
-
*/
|
|
52
|
-
key?: string;
|
|
53
|
-
/**
|
|
54
|
-
* Maximum number of items in a batch
|
|
55
|
-
* @default Infinity
|
|
56
|
-
*/
|
|
57
|
-
maxSize?: number;
|
|
58
|
-
/**
|
|
59
|
-
* Callback fired after a batch is processed
|
|
60
|
-
*/
|
|
61
|
-
onExecute?: (batch: Array<TValue>, batcher: Batcher<TValue>) => void;
|
|
62
|
-
/**
|
|
63
|
-
* Callback fired after items are added to the batcher
|
|
64
|
-
*/
|
|
65
|
-
onItemsChange?: (batcher: Batcher<TValue>) => void;
|
|
66
|
-
/**
|
|
67
|
-
* Whether the batcher should start processing immediately
|
|
68
|
-
* @default true
|
|
69
|
-
*/
|
|
70
|
-
started?: boolean;
|
|
71
|
-
/**
|
|
72
|
-
* Maximum time in milliseconds to wait before processing a batch.
|
|
73
|
-
* If the wait duration has elapsed, the batch will be processed.
|
|
74
|
-
* If not provided, the batch will not be triggered by a timeout.
|
|
75
|
-
* @default Infinity
|
|
76
|
-
*/
|
|
77
|
-
wait?: number | ((batcher: Batcher<TValue>) => number);
|
|
78
|
-
}
|
|
79
|
-
type BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<Required<BatcherOptions<TValue>>, 'initialState' | 'onExecute' | 'onItemsChange' | 'key'>;
|
|
80
|
-
/**
|
|
81
|
-
* A class that collects items and processes them in batches.
|
|
82
|
-
*
|
|
83
|
-
* Batching is a technique for grouping multiple operations together to be processed as a single unit.
|
|
84
|
-
* This synchronous version is lighter weight and often all you need - upgrade to AsyncBatcher when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
|
|
85
|
-
*
|
|
86
|
-
* The Batcher provides a flexible way to implement batching with configurable:
|
|
87
|
-
* - Maximum batch size (number of items per batch)
|
|
88
|
-
* - Time-based batching (process after X milliseconds)
|
|
89
|
-
* - Custom batch processing logic via getShouldExecute
|
|
90
|
-
* - Event callbacks for monitoring batch operations
|
|
91
|
-
*
|
|
92
|
-
* State Management:
|
|
93
|
-
* - Uses TanStack Store for reactive state management
|
|
94
|
-
* - Use `initialState` to provide initial state values when creating the batcher
|
|
95
|
-
* - Use `onExecute` callback to react to batch execution and implement custom logic
|
|
96
|
-
* - Use `onItemsChange` callback to react to items being added or removed from the batcher
|
|
97
|
-
* - The state includes batch execution count, total items processed, items, and running status
|
|
98
|
-
* - State can be accessed via `batcher.store.state` when using the class directly
|
|
99
|
-
* - When using framework adapters (React/Solid), state is accessed from `batcher.state`
|
|
100
|
-
*
|
|
101
|
-
* @example
|
|
102
|
-
* ```ts
|
|
103
|
-
* const batcher = new Batcher<number>(
|
|
104
|
-
* (items) => console.log('Processing batch:', items),
|
|
105
|
-
* {
|
|
106
|
-
* maxSize: 5,
|
|
107
|
-
* wait: 2000,
|
|
108
|
-
* onExecute: (batch, batcher) => console.log('Batch executed:', batch)
|
|
109
|
-
* }
|
|
110
|
-
* );
|
|
111
|
-
*
|
|
112
|
-
* batcher.addItem(1);
|
|
113
|
-
* batcher.addItem(2);
|
|
114
|
-
* // After 2 seconds or when 5 items are added, whichever comes first,
|
|
115
|
-
* // the batch will be processed
|
|
116
|
-
* // batcher.flush() // manually trigger a batch
|
|
117
|
-
* ```
|
|
118
|
-
*/
|
|
119
|
-
declare class Batcher<TValue> {
|
|
120
|
-
#private;
|
|
121
|
-
fn: (items: Array<TValue>) => void;
|
|
122
|
-
readonly store: Store<Readonly<BatcherState<TValue>>>;
|
|
123
|
-
key: string | undefined;
|
|
124
|
-
options: BatcherOptionsWithOptionalCallbacks<TValue>;
|
|
125
|
-
constructor(fn: (items: Array<TValue>) => void, initialOptions: BatcherOptions<TValue>);
|
|
126
|
-
/**
|
|
127
|
-
* Updates the batcher options
|
|
128
|
-
*/
|
|
129
|
-
setOptions: (newOptions: Partial<BatcherOptions<TValue>>) => void;
|
|
130
|
-
/**
|
|
131
|
-
* Adds an item to the batcher
|
|
132
|
-
* If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
|
|
133
|
-
*/
|
|
134
|
-
addItem: (item: TValue) => void;
|
|
135
|
-
/**
|
|
136
|
-
* Processes the current batch of items immediately
|
|
137
|
-
*/
|
|
138
|
-
flush: () => void;
|
|
139
|
-
/**
|
|
140
|
-
* Returns a copy of all items in the batcher
|
|
141
|
-
*/
|
|
142
|
-
peekAllItems: () => Array<TValue>;
|
|
143
|
-
/**
|
|
144
|
-
* Removes all items from the batcher
|
|
145
|
-
*/
|
|
146
|
-
clear: () => void;
|
|
147
|
-
/**
|
|
148
|
-
* Cancels any pending execution that was scheduled.
|
|
149
|
-
* Does NOT clear out the items.
|
|
150
|
-
*/
|
|
151
|
-
cancel: () => void;
|
|
152
|
-
/**
|
|
153
|
-
* Resets the batcher state to its default values
|
|
154
|
-
*/
|
|
155
|
-
reset: () => void;
|
|
156
|
-
}
|
|
157
|
-
/**
|
|
158
|
-
* Creates a batcher that processes items in batches.
|
|
159
|
-
*
|
|
160
|
-
* This synchronous version is lighter weight and often all you need - upgrade to asyncBatch when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
|
|
161
|
-
*
|
|
162
|
-
* @example
|
|
163
|
-
* ```ts
|
|
164
|
-
* const batchItems = batch<number>(
|
|
165
|
-
* (items) => console.log('Processing:', items),
|
|
166
|
-
* {
|
|
167
|
-
* maxSize: 3,
|
|
168
|
-
* onExecute: (batch, batcher) => console.log('Batch executed:', batch)
|
|
169
|
-
* }
|
|
170
|
-
* );
|
|
171
|
-
*
|
|
172
|
-
* batchItems(1);
|
|
173
|
-
* batchItems(2);
|
|
174
|
-
* batchItems(3); // Triggers batch processing
|
|
175
|
-
* ```
|
|
176
|
-
*/
|
|
177
|
-
declare function batch<TValue>(fn: (items: Array<TValue>) => void, options: BatcherOptions<TValue>): (item: TValue) => void;
|
|
178
|
-
//#endregion
|
|
179
|
-
export { Batcher, BatcherOptions, BatcherState, batch };
|
|
180
|
-
//# sourceMappingURL=batcher.d.cts.map
|
package/dist/batcher.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"batcher.js","names":["#setState","#execute","#clearTimeout","#timeoutId","#getWait"],"sources":["../src/batcher.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { OptionalKeys } from './types'\n\nexport interface BatcherState<TValue> {\n /**\n * Number of batch executions that have been completed\n */\n executionCount: number\n /**\n * Whether the batcher has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the batcher is waiting for the timeout to trigger batch processing\n */\n isPending: boolean\n /**\n * Array of items currently queued for batch processing\n */\n items: Array<TValue>\n /**\n * Number of items currently in the batch queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout\n */\n status: 'idle' | 'pending'\n /**\n * Total number of items that have been processed across all batches\n */\n totalItemsProcessed: number\n}\n\nfunction getDefaultBatcherState<TValue>(): BatcherState<TValue> {\n return {\n executionCount: 0,\n isEmpty: true,\n isPending: false,\n totalItemsProcessed: 0,\n items: [],\n size: 0,\n status: 'idle',\n }\n}\n\n/**\n * Options for configuring a Batcher instance\n */\nexport interface BatcherOptions<TValue> {\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean\n /**\n * Initial state for the batcher\n */\n initialState?: Partial<BatcherState<TValue>>\n /**\n * Optional key to identify this batcher instance.\n * If provided, the batcher will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Callback fired after a batch is processed\n */\n onExecute?: (batch: Array<TValue>, batcher: Batcher<TValue>) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: Batcher<TValue>) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\n */\n started?: boolean\n /**\n * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number | ((batcher: Batcher<TValue>) => number)\n}\n\ntype BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<BatcherOptions<TValue>>,\n 'initialState' | 'onExecute' | 'onItemsChange' | 'key'\n>\n\nconst defaultOptions: BatcherOptionsWithOptionalCallbacks<any> = {\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches.\n *\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncBatcher when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The Batcher provides a flexible way to implement batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the batcher\n * - Use `onExecute` callback to react to batch execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the batcher\n * - The state includes batch execution count, total items processed, items, and running status\n * - State can be accessed via `batcher.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `batcher.state`\n *\n * @example\n * ```ts\n * const batcher = new Batcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batch, batcher) => console.log('Batch executed:', batch)\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed\n * // batcher.flush() // manually trigger a batch\n * ```\n */\nexport class Batcher<TValue> {\n readonly store: Store<Readonly<BatcherState<TValue>>> = new Store(\n getDefaultBatcherState<TValue>(),\n )\n key: string | undefined\n options: BatcherOptionsWithOptionalCallbacks<TValue>\n #timeoutId: ReturnType<typeof setTimeout> | null = null\n\n constructor(\n public fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Batcher', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<BatcherState<TValue>>,\n )\n this.setOptions(\n event.payload.options as Partial<BatcherOptions<TValue>>,\n )\n })\n }\n }\n\n /**\n * Updates the batcher options\n */\n setOptions = (newOptions: Partial<BatcherOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<BatcherState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending, items } = combinedState\n const size = items.length\n const isEmpty = size === 0\n return {\n ...combinedState,\n isEmpty,\n size,\n status: isPending ? 'pending' : 'idle',\n }\n })\n emitChange('Batcher', this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Adds an item to the batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n */\n addItem = (item: TValue): void => {\n this.#setState({\n items: [...this.store.state.items, item],\n isPending: this.options.wait !== Infinity,\n })\n this.options.onItemsChange?.(this)\n\n const shouldProcess =\n this.store.state.items.length >= this.options.maxSize ||\n this.options.getShouldExecute(this.store.state.items, this)\n\n if (shouldProcess) {\n this.#execute()\n } else if (this.options.wait !== Infinity) {\n this.#clearTimeout() // clear any pending timeout to replace it with a new one\n this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait())\n }\n }\n\n /**\n * Processes the current batch of items.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches batchSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n */\n #execute = (): void => {\n if (this.store.state.items.length === 0) {\n return\n }\n\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this.clear() // Clear items before processing to prevent race conditions\n this.options.onItemsChange?.(this) // Call onItemsChange to notify listeners that the items have changed\n\n this.fn(batch) // EXECUTE\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n totalItemsProcessed: this.store.state.totalItemsProcessed + batch.length,\n })\n this.options.onExecute?.(batch, this)\n }\n\n /**\n * Processes the current batch of items immediately\n */\n flush = (): void => {\n this.#clearTimeout() // clear any pending timeout\n this.#execute() // execute immediately\n }\n\n /**\n * Returns a copy of all items in the batcher\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Removes all items from the batcher\n */\n clear = (): void => {\n this.#setState({ items: [], isPending: false })\n }\n\n /**\n * Cancels any pending execution that was scheduled.\n * Does NOT clear out the items.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({ isPending: false })\n }\n\n /**\n * Resets the batcher state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultBatcherState<TValue>())\n this.options.onItemsChange?.(this)\n }\n}\n\n/**\n * Creates a batcher that processes items in batches.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncBatch when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * @example\n * ```ts\n * const batchItems = batch<number>(\n * (items) => console.log('Processing:', items),\n * {\n * maxSize: 3,\n * onExecute: (batch, batcher) => console.log('Batch executed:', batch)\n * }\n * );\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function batch<TValue>(\n fn: (items: Array<TValue>) => void,\n options: BatcherOptions<TValue>,\n) {\n const batcher = new Batcher<TValue>(fn, options)\n return batcher.addItem\n}\n"],"mappings":";;;;;A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_utils = require('./utils.cjs');
|
|
3
|
-
const require_event_client = require('./event-client.cjs');
|
|
4
|
-
let _tanstack_store = require("@tanstack/store");
|
|
5
|
-
|
|
6
|
-
//#region src/debouncer.ts
|
|
7
|
-
function getDefaultDebouncerState() {
|
|
8
|
-
return {
|
|
9
|
-
canLeadingExecute: true,
|
|
10
|
-
executionCount: 0,
|
|
11
|
-
isPending: false,
|
|
12
|
-
lastArgs: void 0,
|
|
13
|
-
status: "idle",
|
|
14
|
-
maybeExecuteCount: 0
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.
|
|
19
|
-
*/
|
|
20
|
-
function debouncerOptions(options) {
|
|
21
|
-
return options;
|
|
22
|
-
}
|
|
23
|
-
const defaultOptions = {
|
|
24
|
-
enabled: true,
|
|
25
|
-
leading: false,
|
|
26
|
-
trailing: true,
|
|
27
|
-
wait: 0
|
|
28
|
-
};
|
|
29
|
-
/**
|
|
30
|
-
* A class that creates a debounced function.
|
|
31
|
-
*
|
|
32
|
-
* Debouncing ensures that a function is only executed after a certain amount of time has passed
|
|
33
|
-
* since its last invocation. This is useful for handling frequent events like window resizing,
|
|
34
|
-
* scroll events, or input changes where you want to limit the rate of execution.
|
|
35
|
-
* This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
|
|
36
|
-
*
|
|
37
|
-
* The debounced function can be configured to execute either at the start of the delay period
|
|
38
|
-
* (leading edge) or at the end (trailing edge, default). Each new call during the wait period
|
|
39
|
-
* will reset the timer.
|
|
40
|
-
*
|
|
41
|
-
* State Management:
|
|
42
|
-
* - Uses TanStack Store for reactive state management
|
|
43
|
-
* - Use `initialState` to provide initial state values when creating the debouncer
|
|
44
|
-
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
45
|
-
* - The state includes canLeadingExecute, execution count, and isPending status
|
|
46
|
-
* - State can be accessed via `debouncer.store.state` when using the class directly
|
|
47
|
-
* - When using framework adapters (React/Solid), state is accessed from `debouncer.state`
|
|
48
|
-
*
|
|
49
|
-
* @example
|
|
50
|
-
* ```ts
|
|
51
|
-
* const debouncer = new Debouncer((value: string) => {
|
|
52
|
-
* saveToDatabase(value);
|
|
53
|
-
* }, { wait: 500 });
|
|
54
|
-
*
|
|
55
|
-
* // Will only save after 500ms of no new input
|
|
56
|
-
* inputElement.addEventListener('input', () => {
|
|
57
|
-
* debouncer.maybeExecute(inputElement.value);
|
|
58
|
-
* });
|
|
59
|
-
* ```
|
|
60
|
-
*/
|
|
61
|
-
var Debouncer = class {
|
|
62
|
-
#timeoutId;
|
|
63
|
-
constructor(fn, initialOptions) {
|
|
64
|
-
this.fn = fn;
|
|
65
|
-
this.store = new _tanstack_store.Store(getDefaultDebouncerState());
|
|
66
|
-
this.setOptions = (newOptions) => {
|
|
67
|
-
this.options = {
|
|
68
|
-
...this.options,
|
|
69
|
-
...newOptions
|
|
70
|
-
};
|
|
71
|
-
if (!this.#getEnabled()) this.cancel();
|
|
72
|
-
};
|
|
73
|
-
this.#setState = (newState) => {
|
|
74
|
-
this.store.setState((state) => {
|
|
75
|
-
const combinedState = {
|
|
76
|
-
...state,
|
|
77
|
-
...newState
|
|
78
|
-
};
|
|
79
|
-
const { isPending } = combinedState;
|
|
80
|
-
return {
|
|
81
|
-
...combinedState,
|
|
82
|
-
status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
|
|
83
|
-
};
|
|
84
|
-
});
|
|
85
|
-
require_event_client.emitChange("Debouncer", this);
|
|
86
|
-
};
|
|
87
|
-
this.#getEnabled = () => {
|
|
88
|
-
return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
|
|
89
|
-
};
|
|
90
|
-
this.#getWait = () => {
|
|
91
|
-
return require_utils.parseFunctionOrValue(this.options.wait, this);
|
|
92
|
-
};
|
|
93
|
-
this.maybeExecute = (...args) => {
|
|
94
|
-
if (!this.#getEnabled()) return void 0;
|
|
95
|
-
this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
|
|
96
|
-
let _didLeadingExecute = false;
|
|
97
|
-
if (this.options.leading && this.store.state.canLeadingExecute) {
|
|
98
|
-
this.#setState({ canLeadingExecute: false });
|
|
99
|
-
_didLeadingExecute = true;
|
|
100
|
-
this.#execute(...args);
|
|
101
|
-
}
|
|
102
|
-
if (this.options.trailing) this.#setState({
|
|
103
|
-
isPending: true,
|
|
104
|
-
lastArgs: args
|
|
105
|
-
});
|
|
106
|
-
if (this.#timeoutId) clearTimeout(this.#timeoutId);
|
|
107
|
-
this.#timeoutId = setTimeout(() => {
|
|
108
|
-
this.#setState({ canLeadingExecute: true });
|
|
109
|
-
if (this.options.trailing && !_didLeadingExecute) this.#execute(...args);
|
|
110
|
-
}, this.#getWait());
|
|
111
|
-
};
|
|
112
|
-
this.#execute = (...args) => {
|
|
113
|
-
if (!this.#getEnabled()) return void 0;
|
|
114
|
-
this.fn(...args);
|
|
115
|
-
this.#setState({
|
|
116
|
-
executionCount: this.store.state.executionCount + 1,
|
|
117
|
-
isPending: false,
|
|
118
|
-
lastArgs: void 0
|
|
119
|
-
});
|
|
120
|
-
this.options.onExecute?.(args, this);
|
|
121
|
-
};
|
|
122
|
-
this.flush = () => {
|
|
123
|
-
if (this.store.state.isPending && this.store.state.lastArgs) {
|
|
124
|
-
this.#clearTimeout();
|
|
125
|
-
this.#execute(...this.store.state.lastArgs);
|
|
126
|
-
}
|
|
127
|
-
};
|
|
128
|
-
this.#clearTimeout = () => {
|
|
129
|
-
if (this.#timeoutId) {
|
|
130
|
-
clearTimeout(this.#timeoutId);
|
|
131
|
-
this.#timeoutId = void 0;
|
|
132
|
-
}
|
|
133
|
-
};
|
|
134
|
-
this.cancel = () => {
|
|
135
|
-
this.#clearTimeout();
|
|
136
|
-
this.#setState({
|
|
137
|
-
canLeadingExecute: true,
|
|
138
|
-
isPending: false
|
|
139
|
-
});
|
|
140
|
-
};
|
|
141
|
-
this.reset = () => {
|
|
142
|
-
this.#setState(getDefaultDebouncerState());
|
|
143
|
-
};
|
|
144
|
-
this.key = initialOptions.key;
|
|
145
|
-
this.options = {
|
|
146
|
-
...defaultOptions,
|
|
147
|
-
...initialOptions
|
|
148
|
-
};
|
|
149
|
-
this.#setState(this.options.initialState ?? {});
|
|
150
|
-
if (this.key) require_event_client.pacerEventClient.on("d-Debouncer", (event) => {
|
|
151
|
-
if (event.payload.key !== this.key) return;
|
|
152
|
-
this.#setState(event.payload.store.state);
|
|
153
|
-
this.setOptions(event.payload.options);
|
|
154
|
-
});
|
|
155
|
-
}
|
|
156
|
-
#setState;
|
|
157
|
-
/**
|
|
158
|
-
* Returns the current enabled state of the debouncer
|
|
159
|
-
*/
|
|
160
|
-
#getEnabled;
|
|
161
|
-
/**
|
|
162
|
-
* Returns the current wait time in milliseconds
|
|
163
|
-
*/
|
|
164
|
-
#getWait;
|
|
165
|
-
#execute;
|
|
166
|
-
#clearTimeout;
|
|
167
|
-
};
|
|
168
|
-
/**
|
|
169
|
-
* Creates a debounced function that delays invoking the provided function until after a specified wait time.
|
|
170
|
-
* Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
|
|
171
|
-
*
|
|
172
|
-
* This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
|
|
173
|
-
*
|
|
174
|
-
* If leading option is true, the function will execute immediately on the first call, then wait the delay
|
|
175
|
-
* before allowing another execution.
|
|
176
|
-
*
|
|
177
|
-
* State Management:
|
|
178
|
-
* - Uses TanStack Store for reactive state management
|
|
179
|
-
* - Use `initialState` to provide initial state values when creating the debouncer
|
|
180
|
-
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
181
|
-
* - The state includes canLeadingExecute, execution count, and isPending status
|
|
182
|
-
* - State can be accessed via the underlying Debouncer instance's `store.state` property
|
|
183
|
-
* - When using framework adapters (React/Solid), state is accessed from the hook's state property
|
|
184
|
-
*
|
|
185
|
-
* @example
|
|
186
|
-
* ```ts
|
|
187
|
-
* const debounced = debounce(() => {
|
|
188
|
-
* saveChanges();
|
|
189
|
-
* }, { wait: 1000 });
|
|
190
|
-
*
|
|
191
|
-
* // Called repeatedly but executes at most once per second
|
|
192
|
-
* inputElement.addEventListener('input', debounced);
|
|
193
|
-
* ```
|
|
194
|
-
*/
|
|
195
|
-
function debounce(fn, initialOptions) {
|
|
196
|
-
return new Debouncer(fn, initialOptions).maybeExecute;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
//#endregion
|
|
200
|
-
exports.Debouncer = Debouncer;
|
|
201
|
-
exports.debounce = debounce;
|
|
202
|
-
exports.debouncerOptions = debouncerOptions;
|
|
203
|
-
//# sourceMappingURL=debouncer.cjs.map
|
package/dist/debouncer.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"debouncer.cjs","names":["Store","#getEnabled","parseFunctionOrValue","#setState","#execute","#timeoutId","#getWait","#clearTimeout"],"sources":["../src/debouncer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface DebouncerState<TFn extends AnyFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the debouncer is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultDebouncerState<\n TFn extends AnyFunction,\n>(): DebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Initial state for the debouncer\n */\n initialState?: Partial<DebouncerState<TFn>>\n /**\n * A key to identify the debouncer.\n * If provided, the debouncer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Whether to execute on the leading edge of the timeout.\n * The first call will execute immediately and the rest will wait the delay.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds before executing the function.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.\n */\nexport function debouncerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<DebouncerOptions<TFn>> = Partial<\n DebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a debounced function.\n *\n * Debouncing ensures that a function is only executed after a certain amount of time has passed\n * since its last invocation. This is useful for handling frequent events like window resizing,\n * scroll events, or input changes where you want to limit the rate of execution.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The debounced function can be configured to execute either at the start of the delay period\n * (leading edge) or at the end (trailing edge, default). Each new call during the wait period\n * will reset the timer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via `debouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\n *\n * // Will only save after 500ms of no new input\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class Debouncer<TFn extends AnyFunction> {\n readonly store: Store<Readonly<DebouncerState<TFn>>> = new Store(\n getDefaultDebouncerState<TFn>(),\n )\n key: string | undefined\n options: DebouncerOptions<TFn>\n #timeoutId: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Debouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<DebouncerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<DebouncerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions = (newOptions: Partial<DebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<DebouncerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\n emitChange('Debouncer', this)\n }\n\n /**\n * Returns the current enabled state of the debouncer\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n _didLeadingExecute = true\n this.#execute(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (this.options.trailing) {\n this.#setState({ isPending: true, lastArgs: args })\n }\n\n // Clear any existing timeout\n if (this.#timeoutId) clearTimeout(this.#timeoutId)\n\n // Set new timeout that will reset canLeadingExecute and execute trailing only if enabled and did not execute leading\n this.#timeoutId = setTimeout(() => {\n this.#setState({ canLeadingExecute: true })\n if (this.options.trailing && !_didLeadingExecute) {\n this.#execute(...args)\n }\n }, this.#getWait())\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#clearTimeout() // clear any pending timeout\n this.#execute(...this.store.state.lastArgs) // execute immediately\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending execution\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n canLeadingExecute: true,\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultDebouncerState<TFn>())\n }\n}\n\n/**\n * Creates a debounced function that delays invoking the provided function until after a specified wait time.\n * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * If leading option is true, the function will execute immediately on the first call, then wait the delay\n * before allowing another execution.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via the underlying Debouncer instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute\n}\n"],"mappings":";;;;;;AAgCA,SAAS,2BAEgB;CACvB,OAAO;EACL,mBAAmB;EACnB,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,QAAQ;EACR,mBAAmB;EACpB;;;;;AAgDH,SAAgB,iBAKd,SAA6B;CAC7B,OAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCD,IAAa,YAAb,MAAgD;CAM9C;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eAR8C,IAAIA,sBACzD,0BAA+B,CAChC;qBA8Ba,eAAqD;GACjE,KAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;GAGjD,IAAI,CAAC,KAAKC,aAAa,EACrB,KAAK,QAAQ;;oBAIJ,aAAiD;GAC5D,KAAK,MA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3D,KAAKI,eAAe;IACpB,KAAKH,SAAS,GAAG,KAAK,MAAM,MAAM,SAAS;;;6BAInB;GAC1B,IAAI,KAAKC,YAAY;IACnB,aAAa,KAAKA,WAAW;IAC7B,KAAKA,aAAa;;;sBAOD;GACnB,KAAKE,eAAe;GACpB,KAAKJ,UAAU;IACb,mBAAmB;IACnB,WAAW;IACZ,CAAC;;qBAMgB;GAClB,KAAKA,UAAU,0BAA+B,CAAC;;EA/I/C,KAAK,MAAM,eAAe;EAC1B,KAAK,UAAU;GACb,GAAG;GACH,GAAG;GACJ;EACD,KAAKA,UAAU,KAAK,QAAQ,gBAAgB,EAAE,CAAC;EAE/C,IAAI,KAAK,KACP,sCAAiB,GAAG,gBAAgB,UAAU;GAC5C,IAAI,MAAM,QAAQ,QAAQ,KAAK,KAAK;GACpC,KAAKA,UACH,MAAM,QAAQ,MAAM,MACrB;GACD,KAAK,WAAW,MAAM,QAAQ,QAA0C;IACxE;;CAgBN;;;;CAsBA;;;;CAOA;CAyCA;CAqBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDF,SAAgB,SACd,IACA,gBACoC;CAEpC,OAAO,IADe,UAAU,IAAI,eACpB,CAAC"}
|
package/dist/debouncer.d.cts
DELETED
|
@@ -1,167 +0,0 @@
|
|
|
1
|
-
import { AnyFunction } from "./types.cjs";
|
|
2
|
-
import { Store } from "@tanstack/store";
|
|
3
|
-
|
|
4
|
-
//#region src/debouncer.d.ts
|
|
5
|
-
interface DebouncerState<TFn extends AnyFunction> {
|
|
6
|
-
/**
|
|
7
|
-
* Whether the debouncer can execute on the leading edge of the timeout
|
|
8
|
-
*/
|
|
9
|
-
canLeadingExecute: boolean;
|
|
10
|
-
/**
|
|
11
|
-
* Number of function executions that have been completed
|
|
12
|
-
*/
|
|
13
|
-
executionCount: number;
|
|
14
|
-
/**
|
|
15
|
-
* Whether the debouncer is waiting for the timeout to trigger execution
|
|
16
|
-
*/
|
|
17
|
-
isPending: boolean;
|
|
18
|
-
/**
|
|
19
|
-
* The arguments from the most recent call to maybeExecute
|
|
20
|
-
*/
|
|
21
|
-
lastArgs: Parameters<TFn> | undefined;
|
|
22
|
-
/**
|
|
23
|
-
* Number of times maybeExecute has been called (for reduction calculations)
|
|
24
|
-
*/
|
|
25
|
-
maybeExecuteCount: number;
|
|
26
|
-
/**
|
|
27
|
-
* Current execution status - 'idle' when not active, 'pending' when waiting for timeout
|
|
28
|
-
*/
|
|
29
|
-
status: 'disabled' | 'idle' | 'pending';
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Options for configuring a debounced function
|
|
33
|
-
*/
|
|
34
|
-
interface DebouncerOptions<TFn extends AnyFunction> {
|
|
35
|
-
/**
|
|
36
|
-
* Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
37
|
-
* Can be a boolean or a function that returns a boolean.
|
|
38
|
-
* Defaults to true.
|
|
39
|
-
*/
|
|
40
|
-
enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean);
|
|
41
|
-
/**
|
|
42
|
-
* Initial state for the debouncer
|
|
43
|
-
*/
|
|
44
|
-
initialState?: Partial<DebouncerState<TFn>>;
|
|
45
|
-
/**
|
|
46
|
-
* A key to identify the debouncer.
|
|
47
|
-
* If provided, the debouncer will be identified by this key in the devtools and PacerProvider if applicable.
|
|
48
|
-
*/
|
|
49
|
-
key?: string;
|
|
50
|
-
/**
|
|
51
|
-
* Whether to execute on the leading edge of the timeout.
|
|
52
|
-
* The first call will execute immediately and the rest will wait the delay.
|
|
53
|
-
* Defaults to false.
|
|
54
|
-
*/
|
|
55
|
-
leading?: boolean;
|
|
56
|
-
/**
|
|
57
|
-
* Callback function that is called after the function is executed
|
|
58
|
-
*/
|
|
59
|
-
onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void;
|
|
60
|
-
/**
|
|
61
|
-
* Whether to execute on the trailing edge of the timeout.
|
|
62
|
-
* Defaults to true.
|
|
63
|
-
*/
|
|
64
|
-
trailing?: boolean;
|
|
65
|
-
/**
|
|
66
|
-
* Delay in milliseconds before executing the function.
|
|
67
|
-
* Can be a number or a function that returns a number.
|
|
68
|
-
* Defaults to 0ms
|
|
69
|
-
*/
|
|
70
|
-
wait: number | ((debouncer: Debouncer<TFn>) => number);
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.
|
|
74
|
-
*/
|
|
75
|
-
declare function debouncerOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<DebouncerOptions<TFn>> = Partial<DebouncerOptions<TFn>>>(options: TOptions): TOptions;
|
|
76
|
-
/**
|
|
77
|
-
* A class that creates a debounced function.
|
|
78
|
-
*
|
|
79
|
-
* Debouncing ensures that a function is only executed after a certain amount of time has passed
|
|
80
|
-
* since its last invocation. This is useful for handling frequent events like window resizing,
|
|
81
|
-
* scroll events, or input changes where you want to limit the rate of execution.
|
|
82
|
-
* This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
|
|
83
|
-
*
|
|
84
|
-
* The debounced function can be configured to execute either at the start of the delay period
|
|
85
|
-
* (leading edge) or at the end (trailing edge, default). Each new call during the wait period
|
|
86
|
-
* will reset the timer.
|
|
87
|
-
*
|
|
88
|
-
* State Management:
|
|
89
|
-
* - Uses TanStack Store for reactive state management
|
|
90
|
-
* - Use `initialState` to provide initial state values when creating the debouncer
|
|
91
|
-
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
92
|
-
* - The state includes canLeadingExecute, execution count, and isPending status
|
|
93
|
-
* - State can be accessed via `debouncer.store.state` when using the class directly
|
|
94
|
-
* - When using framework adapters (React/Solid), state is accessed from `debouncer.state`
|
|
95
|
-
*
|
|
96
|
-
* @example
|
|
97
|
-
* ```ts
|
|
98
|
-
* const debouncer = new Debouncer((value: string) => {
|
|
99
|
-
* saveToDatabase(value);
|
|
100
|
-
* }, { wait: 500 });
|
|
101
|
-
*
|
|
102
|
-
* // Will only save after 500ms of no new input
|
|
103
|
-
* inputElement.addEventListener('input', () => {
|
|
104
|
-
* debouncer.maybeExecute(inputElement.value);
|
|
105
|
-
* });
|
|
106
|
-
* ```
|
|
107
|
-
*/
|
|
108
|
-
declare class Debouncer<TFn extends AnyFunction> {
|
|
109
|
-
#private;
|
|
110
|
-
fn: TFn;
|
|
111
|
-
readonly store: Store<Readonly<DebouncerState<TFn>>>;
|
|
112
|
-
key: string | undefined;
|
|
113
|
-
options: DebouncerOptions<TFn>;
|
|
114
|
-
constructor(fn: TFn, initialOptions: DebouncerOptions<TFn>);
|
|
115
|
-
/**
|
|
116
|
-
* Updates the debouncer options
|
|
117
|
-
*/
|
|
118
|
-
setOptions: (newOptions: Partial<DebouncerOptions<TFn>>) => void;
|
|
119
|
-
/**
|
|
120
|
-
* Attempts to execute the debounced function
|
|
121
|
-
* If a call is already in progress, it will be queued
|
|
122
|
-
*/
|
|
123
|
-
maybeExecute: (...args: Parameters<TFn>) => void;
|
|
124
|
-
/**
|
|
125
|
-
* Processes the current pending execution immediately
|
|
126
|
-
*/
|
|
127
|
-
flush: () => void;
|
|
128
|
-
/**
|
|
129
|
-
* Cancels any pending execution
|
|
130
|
-
*/
|
|
131
|
-
cancel: () => void;
|
|
132
|
-
/**
|
|
133
|
-
* Resets the debouncer state to its default values
|
|
134
|
-
*/
|
|
135
|
-
reset: () => void;
|
|
136
|
-
}
|
|
137
|
-
/**
|
|
138
|
-
* Creates a debounced function that delays invoking the provided function until after a specified wait time.
|
|
139
|
-
* Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
|
|
140
|
-
*
|
|
141
|
-
* This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
|
|
142
|
-
*
|
|
143
|
-
* If leading option is true, the function will execute immediately on the first call, then wait the delay
|
|
144
|
-
* before allowing another execution.
|
|
145
|
-
*
|
|
146
|
-
* State Management:
|
|
147
|
-
* - Uses TanStack Store for reactive state management
|
|
148
|
-
* - Use `initialState` to provide initial state values when creating the debouncer
|
|
149
|
-
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
150
|
-
* - The state includes canLeadingExecute, execution count, and isPending status
|
|
151
|
-
* - State can be accessed via the underlying Debouncer instance's `store.state` property
|
|
152
|
-
* - When using framework adapters (React/Solid), state is accessed from the hook's state property
|
|
153
|
-
*
|
|
154
|
-
* @example
|
|
155
|
-
* ```ts
|
|
156
|
-
* const debounced = debounce(() => {
|
|
157
|
-
* saveChanges();
|
|
158
|
-
* }, { wait: 1000 });
|
|
159
|
-
*
|
|
160
|
-
* // Called repeatedly but executes at most once per second
|
|
161
|
-
* inputElement.addEventListener('input', debounced);
|
|
162
|
-
* ```
|
|
163
|
-
*/
|
|
164
|
-
declare function debounce<TFn extends AnyFunction>(fn: TFn, initialOptions: DebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
|
|
165
|
-
//#endregion
|
|
166
|
-
export { Debouncer, DebouncerOptions, DebouncerState, debounce, debouncerOptions };
|
|
167
|
-
//# sourceMappingURL=debouncer.d.cts.map
|
package/dist/debouncer.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"debouncer.js","names":["#getEnabled","#setState","#execute","#timeoutId","#getWait","#clearTimeout"],"sources":["../src/debouncer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface DebouncerState<TFn extends AnyFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the debouncer is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultDebouncerState<\n TFn extends AnyFunction,\n>(): DebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Initial state for the debouncer\n */\n initialState?: Partial<DebouncerState<TFn>>\n /**\n * A key to identify the debouncer.\n * If provided, the debouncer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Whether to execute on the leading edge of the timeout.\n * The first call will execute immediately and the rest will wait the delay.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds before executing the function.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.\n */\nexport function debouncerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<DebouncerOptions<TFn>> = Partial<\n DebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a debounced function.\n *\n * Debouncing ensures that a function is only executed after a certain amount of time has passed\n * since its last invocation. This is useful for handling frequent events like window resizing,\n * scroll events, or input changes where you want to limit the rate of execution.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The debounced function can be configured to execute either at the start of the delay period\n * (leading edge) or at the end (trailing edge, default). Each new call during the wait period\n * will reset the timer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via `debouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\n *\n * // Will only save after 500ms of no new input\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class Debouncer<TFn extends AnyFunction> {\n readonly store: Store<Readonly<DebouncerState<TFn>>> = new Store(\n getDefaultDebouncerState<TFn>(),\n )\n key: string | undefined\n options: DebouncerOptions<TFn>\n #timeoutId: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Debouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<DebouncerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<DebouncerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions = (newOptions: Partial<DebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<DebouncerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\n emitChange('Debouncer', this)\n }\n\n /**\n * Returns the current enabled state of the debouncer\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n _didLeadingExecute = true\n this.#execute(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (this.options.trailing) {\n this.#setState({ isPending: true, lastArgs: args })\n }\n\n // Clear any existing timeout\n if (this.#timeoutId) clearTimeout(this.#timeoutId)\n\n // Set new timeout that will reset canLeadingExecute and execute trailing only if enabled and did not execute leading\n this.#timeoutId = setTimeout(() => {\n this.#setState({ canLeadingExecute: true })\n if (this.options.trailing && !_didLeadingExecute) {\n this.#execute(...args)\n }\n }, this.#getWait())\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#clearTimeout() // clear any pending timeout\n this.#execute(...this.store.state.lastArgs) // execute immediately\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending execution\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n canLeadingExecute: true,\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultDebouncerState<TFn>())\n }\n}\n\n/**\n * Creates a debounced function that delays invoking the provided function until after a specified wait time.\n * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * If leading option is true, the function will execute immediately on the first call, then wait the delay\n * before allowing another execution.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via the underlying Debouncer instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute\n}\n"],"mappings":";;;;;AAgCA,SAAS,2BAEgB;CACvB,OAAO;EACL,mBAAmB;EACnB,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,QAAQ;EACR,mBAAmB;EACpB;;;;;AAgDH,SAAgB,iBAKd,SAA6B;CAC7B,OAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCD,IAAa,YAAb,MAAgD;CAM9C;CAEA,YACE,AAAO,IACP,gBACA;EA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