@tanstack/preact-pacer 0.20.0 → 0.21.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 +6 -6
- package/dist/async-batcher/useAsyncBatcher.cjs +2 -2
- package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -1
- package/dist/async-batcher/useAsyncBatcher.js +3 -3
- package/dist/async-batcher/useAsyncBatcher.js.map +1 -1
- package/dist/async-debouncer/useAsyncDebouncer.cjs +2 -2
- package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -1
- package/dist/async-debouncer/useAsyncDebouncer.js +3 -3
- package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -1
- package/dist/async-queuer/useAsyncQueuer.cjs +2 -2
- package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -1
- package/dist/async-queuer/useAsyncQueuer.js +3 -3
- package/dist/async-queuer/useAsyncQueuer.js.map +1 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +2 -2
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.js +3 -3
- package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -1
- package/dist/async-throttler/useAsyncThrottler.cjs +2 -2
- package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -1
- package/dist/async-throttler/useAsyncThrottler.js +3 -3
- package/dist/async-throttler/useAsyncThrottler.js.map +1 -1
- package/dist/batcher/useBatcher.cjs +2 -2
- package/dist/batcher/useBatcher.cjs.map +1 -1
- package/dist/batcher/useBatcher.js +3 -3
- package/dist/batcher/useBatcher.js.map +1 -1
- package/dist/debouncer/useDebouncer.cjs +2 -2
- package/dist/debouncer/useDebouncer.cjs.map +1 -1
- package/dist/debouncer/useDebouncer.js +3 -3
- package/dist/debouncer/useDebouncer.js.map +1 -1
- package/dist/provider/PacerProvider.cjs.map +1 -1
- package/dist/provider/PacerProvider.js.map +1 -1
- package/dist/queuer/useQueuer.cjs +2 -2
- package/dist/queuer/useQueuer.cjs.map +1 -1
- package/dist/queuer/useQueuer.js +3 -3
- package/dist/queuer/useQueuer.js.map +1 -1
- package/dist/rate-limiter/useRateLimiter.cjs +2 -2
- package/dist/rate-limiter/useRateLimiter.cjs.map +1 -1
- package/dist/rate-limiter/useRateLimiter.js +3 -3
- package/dist/rate-limiter/useRateLimiter.js.map +1 -1
- package/dist/throttler/useThrottler.cjs +2 -2
- package/dist/throttler/useThrottler.cjs.map +1 -1
- package/dist/throttler/useThrottler.js +3 -3
- package/dist/throttler/useThrottler.js.map +1 -1
- package/package.json +5 -5
- package/src/async-batcher/useAsyncBatcher.ts +5 -3
- package/src/async-debouncer/useAsyncDebouncer.ts +5 -3
- package/src/async-queuer/useAsyncQueuer.ts +5 -3
- package/src/async-rate-limiter/useAsyncRateLimiter.ts +5 -3
- package/src/async-throttler/useAsyncThrottler.ts +5 -3
- package/src/batcher/useBatcher.ts +5 -3
- package/src/debouncer/useDebouncer.ts +5 -3
- package/src/queuer/useQueuer.ts +5 -3
- package/src/rate-limiter/useRateLimiter.ts +5 -3
- package/src/throttler/useThrottler.ts +5 -3
package/README.md
CHANGED
|
@@ -109,18 +109,18 @@ A lightweight timing and scheduling library for debouncing, throttling, rate lim
|
|
|
109
109
|
<td>
|
|
110
110
|
<a href="https://www.coderabbit.ai/?via=tanstack&dub_id=aCcEEdAOqqutX6OS" >
|
|
111
111
|
<picture>
|
|
112
|
-
<source media="(prefers-color-scheme: dark)" srcset="https://tanstack.com/assets/coderabbit-dark-
|
|
113
|
-
<source media="(prefers-color-scheme: light)" srcset="https://tanstack.com/assets/coderabbit-light-
|
|
114
|
-
<img src="https://tanstack.com/assets/coderabbit-light-
|
|
112
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://tanstack.com/assets/coderabbit-dark-D643Zkrv.svg" height="40" />
|
|
113
|
+
<source media="(prefers-color-scheme: light)" srcset="https://tanstack.com/assets/coderabbit-light-CIzGLYU_.svg" height="40" />
|
|
114
|
+
<img src="https://tanstack.com/assets/coderabbit-light-CIzGLYU_.svg" height="40" alt="CodeRabbit" />
|
|
115
115
|
</picture>
|
|
116
116
|
</a>
|
|
117
117
|
</td>
|
|
118
118
|
<td>
|
|
119
119
|
<a href="https://www.cloudflare.com?utm_source=tanstack">
|
|
120
120
|
<picture>
|
|
121
|
-
<source media="(prefers-color-scheme: dark)" srcset="https://tanstack.com/assets/cloudflare-white-
|
|
122
|
-
<source media="(prefers-color-scheme: light)" srcset="https://tanstack.com/assets/cloudflare-black-
|
|
123
|
-
<img src="https://tanstack.com/assets/cloudflare-black-
|
|
121
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://tanstack.com/assets/cloudflare-white-Co-Tyjbl.svg" height="60" />
|
|
122
|
+
<source media="(prefers-color-scheme: light)" srcset="https://tanstack.com/assets/cloudflare-black-6Ojsn8yh.svg" height="60" />
|
|
123
|
+
<img src="https://tanstack.com/assets/cloudflare-black-6Ojsn8yh.svg" height="60" alt="Cloudflare" />
|
|
124
124
|
</picture>
|
|
125
125
|
</a>
|
|
126
126
|
</td>
|
|
@@ -189,7 +189,7 @@ function useAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
|
189
189
|
const [asyncBatcher] = (0, preact_hooks.useState)(() => {
|
|
190
190
|
const batcherInstance = new _tanstack_pacer_async_batcher.AsyncBatcher(fn, mergedOptions);
|
|
191
191
|
batcherInstance.Subscribe = function Subscribe(props) {
|
|
192
|
-
const selected = (0, _tanstack_preact_store.useStore)(batcherInstance.store, props.selector);
|
|
192
|
+
const selected = (0, _tanstack_preact_store.useStore)(batcherInstance.store, props.selector, { equal: _tanstack_preact_store.shallow });
|
|
193
193
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
194
194
|
};
|
|
195
195
|
return batcherInstance;
|
|
@@ -205,7 +205,7 @@ function useAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
|
205
205
|
}
|
|
206
206
|
};
|
|
207
207
|
}, []);
|
|
208
|
-
const state = (0, _tanstack_preact_store.useStore)(asyncBatcher.store, selector);
|
|
208
|
+
const state = (0, _tanstack_preact_store.useStore)(asyncBatcher.store, selector, { equal: _tanstack_preact_store.shallow });
|
|
209
209
|
return (0, preact_hooks.useMemo)(() => ({
|
|
210
210
|
...asyncBatcher,
|
|
211
211
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncBatcher.cjs","names":["useDefaultPacerOptions","AsyncBatcher"],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: PreactAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.\n *\n * This is useful for opting into state re-renders for specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: 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<AsyncBatcherState<TValue>>>\n}\n\n/**\n * A Preact hook that creates an `AsyncBatcher` instance for managing asynchronous batches of items.\n *\n * This is the async version of the useBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\n *\n * The batcher collects items and processes them in batches based on:\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 *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher 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 AsyncBatcher instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `errorCount`: Number of batch executions that have resulted in errors\n * - `failedItems`: Array of items that failed during batch processing\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isExecuting`: Whether a batch is currently being processed asynchronously\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `lastResult`: The result from the most recent batch execution\n * - `settleCount`: Number of batch executions that have completed (success or error)\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending' | 'executing' | 'populated')\n * - `successCount`: Number of batch executions that have completed successfully\n * - `totalItemsProcessed`: Total number of items processed across all batches\n * - `totalItemsFailed`: Total number of items that have failed processing\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useAsyncBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your batch function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Basic async batcher for API requests - no reactive state subscriptions\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </asyncBatcher.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onError: (error) => console.error('Batch processing failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * failedItems: state.failedItems,\n * totalItemsFailed: state.totalItemsFailed\n * })\n * );\n *\n * // Complete example with all callbacks\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onSuccess: (result) => {\n * console.log('Batch processed successfully:', result);\n * },\n * onError: (error) => {\n * console.error('Batch processing failed:', error);\n * }\n * }\n * );\n *\n * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, size } = asyncBatcher.state;\n * ```\n */\nexport function useAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: PreactAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as PreactAsyncBatcherOptions<TValue, TSelected>\n const [asyncBatcher] = useState(() => {\n const batcherInstance = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncBatcher<TValue, TSelected>\n\n batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(batcherInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return batcherInstance\n })\n\n asyncBatcher.fn = fn\n asyncBatcher.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(asyncBatcher.store, selector)\n\n return useMemo(\n () =>\n ({\n ...asyncBatcher,\n state,\n }) as PreactAsyncBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncBatcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0OA,SAAgB,gBACd,IACA,UAAwD,EAAE,EAC1D,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,iDAA+B;EACpC,MAAM,kBAAkB,IAAIC,2CAC1B,IACA,cACD;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,gDAAoB,gBAAgB,OAAO,MAAM,SAAS;AAEhE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,cAAa,KAAK;AAClB,cAAa,WAAW,cAAc;AAGtC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;;IAGvB,EAAE,CAAC;CAGN,MAAM,6CAAiB,aAAa,OAAO,SAAS;AAEpD,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
|
|
1
|
+
{"version":3,"file":"useAsyncBatcher.cjs","names":["useDefaultPacerOptions","AsyncBatcher","shallow"],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: PreactAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.\n *\n * This is useful for opting into state re-renders for specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: 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<AsyncBatcherState<TValue>>>\n}\n\n/**\n * A Preact hook that creates an `AsyncBatcher` instance for managing asynchronous batches of items.\n *\n * This is the async version of the useBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\n *\n * The batcher collects items and processes them in batches based on:\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 *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher 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 AsyncBatcher instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `errorCount`: Number of batch executions that have resulted in errors\n * - `failedItems`: Array of items that failed during batch processing\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isExecuting`: Whether a batch is currently being processed asynchronously\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `lastResult`: The result from the most recent batch execution\n * - `settleCount`: Number of batch executions that have completed (success or error)\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending' | 'executing' | 'populated')\n * - `successCount`: Number of batch executions that have completed successfully\n * - `totalItemsProcessed`: Total number of items processed across all batches\n * - `totalItemsFailed`: Total number of items that have failed processing\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useAsyncBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your batch function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Basic async batcher for API requests - no reactive state subscriptions\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </asyncBatcher.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onError: (error) => console.error('Batch processing failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * failedItems: state.failedItems,\n * totalItemsFailed: state.totalItemsFailed\n * })\n * );\n *\n * // Complete example with all callbacks\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onSuccess: (result) => {\n * console.log('Batch processed successfully:', result);\n * },\n * onError: (error) => {\n * console.error('Batch processing failed:', error);\n * }\n * }\n * );\n *\n * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, size } = asyncBatcher.state;\n * ```\n */\nexport function useAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: PreactAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as PreactAsyncBatcherOptions<TValue, TSelected>\n const [asyncBatcher] = useState(() => {\n const batcherInstance = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncBatcher<TValue, TSelected>\n\n batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(batcherInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return batcherInstance\n })\n\n asyncBatcher.fn = fn\n asyncBatcher.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(asyncBatcher.store, selector, { equal: shallow })\n\n return useMemo(\n () =>\n ({\n ...asyncBatcher,\n state,\n }) as PreactAsyncBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncBatcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0OA,SAAgB,gBACd,IACA,UAAwD,EAAE,EAC1D,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,iDAA+B;EACpC,MAAM,kBAAkB,IAAIC,2CAC1B,IACA,cACD;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,gDAAoB,gBAAgB,OAAO,MAAM,UAAU,EAC/D,OAAOC,gCACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,cAAa,KAAK;AAClB,cAAa,WAAW,cAAc;AAGtC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;;IAGvB,EAAE,CAAC;CAGN,MAAM,6CAAiB,aAAa,OAAO,UAAU,EAAE,OAAOA,gCAAS,CAAC;AAExE,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
2
|
import { useEffect, useMemo, useState } from "preact/hooks";
|
|
3
3
|
import { AsyncBatcher } from "@tanstack/pacer/async-batcher";
|
|
4
|
-
import { useStore } from "@tanstack/preact-store";
|
|
4
|
+
import { shallow, useStore } from "@tanstack/preact-store";
|
|
5
5
|
|
|
6
6
|
//#region src/async-batcher/useAsyncBatcher.ts
|
|
7
7
|
/**
|
|
@@ -189,7 +189,7 @@ function useAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
|
189
189
|
const [asyncBatcher] = useState(() => {
|
|
190
190
|
const batcherInstance = new AsyncBatcher(fn, mergedOptions);
|
|
191
191
|
batcherInstance.Subscribe = function Subscribe(props) {
|
|
192
|
-
const selected = useStore(batcherInstance.store, props.selector);
|
|
192
|
+
const selected = useStore(batcherInstance.store, props.selector, { equal: shallow });
|
|
193
193
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
194
194
|
};
|
|
195
195
|
return batcherInstance;
|
|
@@ -205,7 +205,7 @@ function useAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
|
205
205
|
}
|
|
206
206
|
};
|
|
207
207
|
}, []);
|
|
208
|
-
const state = useStore(asyncBatcher.store, selector);
|
|
208
|
+
const state = useStore(asyncBatcher.store, selector, { equal: shallow });
|
|
209
209
|
return useMemo(() => ({
|
|
210
210
|
...asyncBatcher,
|
|
211
211
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncBatcher.js","names":[],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: PreactAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.\n *\n * This is useful for opting into state re-renders for specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: 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<AsyncBatcherState<TValue>>>\n}\n\n/**\n * A Preact hook that creates an `AsyncBatcher` instance for managing asynchronous batches of items.\n *\n * This is the async version of the useBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\n *\n * The batcher collects items and processes them in batches based on:\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 *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher 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 AsyncBatcher instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `errorCount`: Number of batch executions that have resulted in errors\n * - `failedItems`: Array of items that failed during batch processing\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isExecuting`: Whether a batch is currently being processed asynchronously\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `lastResult`: The result from the most recent batch execution\n * - `settleCount`: Number of batch executions that have completed (success or error)\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending' | 'executing' | 'populated')\n * - `successCount`: Number of batch executions that have completed successfully\n * - `totalItemsProcessed`: Total number of items processed across all batches\n * - `totalItemsFailed`: Total number of items that have failed processing\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useAsyncBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your batch function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Basic async batcher for API requests - no reactive state subscriptions\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </asyncBatcher.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onError: (error) => console.error('Batch processing failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * failedItems: state.failedItems,\n * totalItemsFailed: state.totalItemsFailed\n * })\n * );\n *\n * // Complete example with all callbacks\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onSuccess: (result) => {\n * console.log('Batch processed successfully:', result);\n * },\n * onError: (error) => {\n * console.error('Batch processing failed:', error);\n * }\n * }\n * );\n *\n * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, size } = asyncBatcher.state;\n * ```\n */\nexport function useAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: PreactAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as PreactAsyncBatcherOptions<TValue, TSelected>\n const [asyncBatcher] = useState(() => {\n const batcherInstance = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncBatcher<TValue, TSelected>\n\n batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(batcherInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return batcherInstance\n })\n\n asyncBatcher.fn = fn\n asyncBatcher.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(asyncBatcher.store, selector)\n\n return useMemo(\n () =>\n ({\n ...asyncBatcher,\n state,\n }) as PreactAsyncBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncBatcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0OA,SAAgB,gBACd,IACA,UAAwD,EAAE,EAC1D,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,gBAAgB,eAAe;EACpC,MAAM,kBAAkB,IAAI,aAC1B,IACA,cACD;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,WAAW,SAAS,gBAAgB,OAAO,MAAM,SAAS;AAEhE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,cAAa,KAAK;AAClB,cAAa,WAAW,cAAc;AAGtC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;;IAGvB,EAAE,CAAC;CAGN,MAAM,QAAQ,SAAS,aAAa,OAAO,SAAS;AAEpD,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
|
|
1
|
+
{"version":3,"file":"useAsyncBatcher.js","names":[],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: PreactAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.\n *\n * This is useful for opting into state re-renders for specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: 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<AsyncBatcherState<TValue>>>\n}\n\n/**\n * A Preact hook that creates an `AsyncBatcher` instance for managing asynchronous batches of items.\n *\n * This is the async version of the useBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\n *\n * The batcher collects items and processes them in batches based on:\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 *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher 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 AsyncBatcher instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `errorCount`: Number of batch executions that have resulted in errors\n * - `failedItems`: Array of items that failed during batch processing\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isExecuting`: Whether a batch is currently being processed asynchronously\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `lastResult`: The result from the most recent batch execution\n * - `settleCount`: Number of batch executions that have completed (success or error)\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending' | 'executing' | 'populated')\n * - `successCount`: Number of batch executions that have completed successfully\n * - `totalItemsProcessed`: Total number of items processed across all batches\n * - `totalItemsFailed`: Total number of items that have failed processing\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useAsyncBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your batch function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Basic async batcher for API requests - no reactive state subscriptions\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </asyncBatcher.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onError: (error) => console.error('Batch processing failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * failedItems: state.failedItems,\n * totalItemsFailed: state.totalItemsFailed\n * })\n * );\n *\n * // Complete example with all callbacks\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onSuccess: (result) => {\n * console.log('Batch processed successfully:', result);\n * },\n * onError: (error) => {\n * console.error('Batch processing failed:', error);\n * }\n * }\n * );\n *\n * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, size } = asyncBatcher.state;\n * ```\n */\nexport function useAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: PreactAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as PreactAsyncBatcherOptions<TValue, TSelected>\n const [asyncBatcher] = useState(() => {\n const batcherInstance = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncBatcher<TValue, TSelected>\n\n batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(batcherInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return batcherInstance\n })\n\n asyncBatcher.fn = fn\n asyncBatcher.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(asyncBatcher.store, selector, { equal: shallow })\n\n return useMemo(\n () =>\n ({\n ...asyncBatcher,\n state,\n }) as PreactAsyncBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncBatcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0OA,SAAgB,gBACd,IACA,UAAwD,EAAE,EAC1D,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,gBAAgB,eAAe;EACpC,MAAM,kBAAkB,IAAI,aAC1B,IACA,cACD;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,WAAW,SAAS,gBAAgB,OAAO,MAAM,UAAU,EAC/D,OAAO,SACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,cAAa,KAAK;AAClB,cAAa,WAAW,cAAc;AAGtC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;;IAGvB,EAAE,CAAC;CAGN,MAAM,QAAQ,SAAS,aAAa,OAAO,UAAU,EAAE,OAAO,SAAS,CAAC;AAExE,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
|
|
@@ -167,14 +167,14 @@ function useAsyncDebouncer(fn, options, selector = () => ({})) {
|
|
|
167
167
|
const [asyncDebouncer] = (0, preact_hooks.useState)(() => {
|
|
168
168
|
const debouncerInstance = new _tanstack_pacer_async_debouncer.AsyncDebouncer(fn, mergedOptions);
|
|
169
169
|
debouncerInstance.Subscribe = function Subscribe(props) {
|
|
170
|
-
const selected = (0, _tanstack_preact_store.useStore)(debouncerInstance.store, props.selector);
|
|
170
|
+
const selected = (0, _tanstack_preact_store.useStore)(debouncerInstance.store, props.selector, { equal: _tanstack_preact_store.shallow });
|
|
171
171
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
172
172
|
};
|
|
173
173
|
return debouncerInstance;
|
|
174
174
|
});
|
|
175
175
|
asyncDebouncer.fn = fn;
|
|
176
176
|
asyncDebouncer.setOptions(mergedOptions);
|
|
177
|
-
const state = (0, _tanstack_preact_store.useStore)(asyncDebouncer.store, selector);
|
|
177
|
+
const state = (0, _tanstack_preact_store.useStore)(asyncDebouncer.store, selector, { equal: _tanstack_preact_store.shallow });
|
|
178
178
|
(0, preact_hooks.useEffect)(() => {
|
|
179
179
|
return () => {
|
|
180
180
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncDebouncer);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncDebouncer.cjs","names":["useDefaultPacerOptions","AsyncDebouncer"],"sources":["../../src/async-debouncer/useAsyncDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: PreactAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async debouncer state.\n *\n * This is useful for opting into state re-renders for specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: 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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced 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 debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer 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 AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the debounced function is currently executing asynchronously\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 * - `lastResult`: The result from the most recent successful function execution\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending execution and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = useAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Searching...' : 'Ready'}</div>\n * )}\n * </searchDebouncer.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * {\n * wait: 500,\n * onError: (error) => console.error('Search failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // With state management\n * const [results, setResults] = useState([]);\n * const { maybeExecute, state } = useAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * setResults(data);\n * },\n * {\n * wait: 300,\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 * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: PreactAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as PreactAsyncDebouncerOptions<TFn, TSelected>\n const [asyncDebouncer] = useState(() => {\n const debouncerInstance = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncDebouncer<TFn, TSelected>\n\n debouncerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(debouncerInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return debouncerInstance\n })\n\n asyncDebouncer.fn = fn\n asyncDebouncer.setOptions(mergedOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return useMemo(\n () =>\n ({\n ...asyncDebouncer,\n state,\n }) as PreactAsyncDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncDebouncer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqNA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,mDAAiC;EACtC,MAAM,oBAAoB,IAAIC,+CAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,gDAAoB,kBAAkB,OAAO,MAAM,SAAS;AAElE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,6CAAiB,eAAe,OAAO,SAAS;AAGtD,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;;IAGzB,EAAE,CAAC;AAGN,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
|
|
1
|
+
{"version":3,"file":"useAsyncDebouncer.cjs","names":["useDefaultPacerOptions","AsyncDebouncer","shallow"],"sources":["../../src/async-debouncer/useAsyncDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: PreactAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async debouncer state.\n *\n * This is useful for opting into state re-renders for specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: 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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced 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 debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer 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 AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the debounced function is currently executing asynchronously\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 * - `lastResult`: The result from the most recent successful function execution\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending execution and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = useAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Searching...' : 'Ready'}</div>\n * )}\n * </searchDebouncer.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * {\n * wait: 500,\n * onError: (error) => console.error('Search failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // With state management\n * const [results, setResults] = useState([]);\n * const { maybeExecute, state } = useAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * setResults(data);\n * },\n * {\n * wait: 300,\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 * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: PreactAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as PreactAsyncDebouncerOptions<TFn, TSelected>\n const [asyncDebouncer] = useState(() => {\n const debouncerInstance = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncDebouncer<TFn, TSelected>\n\n debouncerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(debouncerInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return debouncerInstance\n })\n\n asyncDebouncer.fn = fn\n asyncDebouncer.setOptions(mergedOptions)\n\n const state = useStore(asyncDebouncer.store, selector, { equal: shallow })\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return useMemo(\n () =>\n ({\n ...asyncDebouncer,\n state,\n }) as PreactAsyncDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncDebouncer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqNA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,mDAAiC;EACtC,MAAM,oBAAoB,IAAIC,+CAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,gDAAoB,kBAAkB,OAAO,MAAM,UAAU,EACjE,OAAOC,gCACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,6CAAiB,eAAe,OAAO,UAAU,EAAE,OAAOA,gCAAS,CAAC;AAG1E,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;;IAGzB,EAAE,CAAC;AAGN,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
2
|
import { useEffect, useMemo, useState } from "preact/hooks";
|
|
3
|
-
import { useStore } from "@tanstack/preact-store";
|
|
3
|
+
import { shallow, useStore } from "@tanstack/preact-store";
|
|
4
4
|
import { AsyncDebouncer } from "@tanstack/pacer/async-debouncer";
|
|
5
5
|
|
|
6
6
|
//#region src/async-debouncer/useAsyncDebouncer.ts
|
|
@@ -167,14 +167,14 @@ function useAsyncDebouncer(fn, options, selector = () => ({})) {
|
|
|
167
167
|
const [asyncDebouncer] = useState(() => {
|
|
168
168
|
const debouncerInstance = new AsyncDebouncer(fn, mergedOptions);
|
|
169
169
|
debouncerInstance.Subscribe = function Subscribe(props) {
|
|
170
|
-
const selected = useStore(debouncerInstance.store, props.selector);
|
|
170
|
+
const selected = useStore(debouncerInstance.store, props.selector, { equal: shallow });
|
|
171
171
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
172
172
|
};
|
|
173
173
|
return debouncerInstance;
|
|
174
174
|
});
|
|
175
175
|
asyncDebouncer.fn = fn;
|
|
176
176
|
asyncDebouncer.setOptions(mergedOptions);
|
|
177
|
-
const state = useStore(asyncDebouncer.store, selector);
|
|
177
|
+
const state = useStore(asyncDebouncer.store, selector, { equal: shallow });
|
|
178
178
|
useEffect(() => {
|
|
179
179
|
return () => {
|
|
180
180
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncDebouncer);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncDebouncer.js","names":[],"sources":["../../src/async-debouncer/useAsyncDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: PreactAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async debouncer state.\n *\n * This is useful for opting into state re-renders for specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: 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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced 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 debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer 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 AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the debounced function is currently executing asynchronously\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 * - `lastResult`: The result from the most recent successful function execution\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending execution and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = useAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Searching...' : 'Ready'}</div>\n * )}\n * </searchDebouncer.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * {\n * wait: 500,\n * onError: (error) => console.error('Search failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // With state management\n * const [results, setResults] = useState([]);\n * const { maybeExecute, state } = useAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * setResults(data);\n * },\n * {\n * wait: 300,\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 * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: PreactAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as PreactAsyncDebouncerOptions<TFn, TSelected>\n const [asyncDebouncer] = useState(() => {\n const debouncerInstance = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncDebouncer<TFn, TSelected>\n\n debouncerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(debouncerInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return debouncerInstance\n })\n\n asyncDebouncer.fn = fn\n asyncDebouncer.setOptions(mergedOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return useMemo(\n () =>\n ({\n ...asyncDebouncer,\n state,\n }) as PreactAsyncDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncDebouncer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqNA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,kBAAkB,eAAe;EACtC,MAAM,oBAAoB,IAAI,eAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,WAAW,SAAS,kBAAkB,OAAO,MAAM,SAAS;AAElE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,QAAQ,SAAS,eAAe,OAAO,SAAS;AAGtD,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;;IAGzB,EAAE,CAAC;AAGN,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
|
|
1
|
+
{"version":3,"file":"useAsyncDebouncer.js","names":[],"sources":["../../src/async-debouncer/useAsyncDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: PreactAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async debouncer state.\n *\n * This is useful for opting into state re-renders for specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: 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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced 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 debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer 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 AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the debounced function is currently executing asynchronously\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 * - `lastResult`: The result from the most recent successful function execution\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending execution and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = useAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Searching...' : 'Ready'}</div>\n * )}\n * </searchDebouncer.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * {\n * wait: 500,\n * onError: (error) => console.error('Search failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // With state management\n * const [results, setResults] = useState([]);\n * const { maybeExecute, state } = useAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * setResults(data);\n * },\n * {\n * wait: 300,\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 * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: PreactAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as PreactAsyncDebouncerOptions<TFn, TSelected>\n const [asyncDebouncer] = useState(() => {\n const debouncerInstance = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncDebouncer<TFn, TSelected>\n\n debouncerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(debouncerInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return debouncerInstance\n })\n\n asyncDebouncer.fn = fn\n asyncDebouncer.setOptions(mergedOptions)\n\n const state = useStore(asyncDebouncer.store, selector, { equal: shallow })\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return useMemo(\n () =>\n ({\n ...asyncDebouncer,\n state,\n }) as PreactAsyncDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncDebouncer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqNA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,kBAAkB,eAAe;EACtC,MAAM,oBAAoB,IAAI,eAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,WAAW,SAAS,kBAAkB,OAAO,MAAM,UAAU,EACjE,OAAO,SACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,QAAQ,SAAS,eAAe,OAAO,UAAU,EAAE,OAAO,SAAS,CAAC;AAG1E,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;;IAGzB,EAAE,CAAC;AAGN,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
|
|
@@ -189,7 +189,7 @@ function useAsyncQueuer(fn, options = {}, selector = () => ({})) {
|
|
|
189
189
|
const [asyncQueuer] = (0, preact_hooks.useState)(() => {
|
|
190
190
|
const queuerInstance = new _tanstack_pacer_async_queuer.AsyncQueuer(fn, mergedOptions);
|
|
191
191
|
queuerInstance.Subscribe = function Subscribe(props) {
|
|
192
|
-
const selected = (0, _tanstack_preact_store.useStore)(queuerInstance.store, props.selector);
|
|
192
|
+
const selected = (0, _tanstack_preact_store.useStore)(queuerInstance.store, props.selector, { equal: _tanstack_preact_store.shallow });
|
|
193
193
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
194
194
|
};
|
|
195
195
|
return queuerInstance;
|
|
@@ -205,7 +205,7 @@ function useAsyncQueuer(fn, options = {}, selector = () => ({})) {
|
|
|
205
205
|
}
|
|
206
206
|
};
|
|
207
207
|
}, []);
|
|
208
|
-
const state = (0, _tanstack_preact_store.useStore)(asyncQueuer.store, selector);
|
|
208
|
+
const state = (0, _tanstack_preact_store.useStore)(asyncQueuer.store, selector, { equal: _tanstack_preact_store.shallow });
|
|
209
209
|
return (0, preact_hooks.useMemo)(() => ({
|
|
210
210
|
...asyncQueuer,
|
|
211
211
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncQueuer.cjs","names":["useDefaultPacerOptions","AsyncQueuer"],"sources":["../../src/async-queuer/useAsyncQueuer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncQueuerOptions<\n TValue,\n TSelected = {},\n> extends AsyncQueuerOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop + abort); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: PreactAsyncQueuer<TValue, TSelected>) => void\n}\n\nexport interface PreactAsyncQueuer<TValue, TSelected = {}> extends Omit<\n AsyncQueuer<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async queuer state.\n *\n * This is useful for opting into state re-renders for specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Queue Size: {size}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.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<AsyncQueuerState<TValue>>>\n}\n\n/**\n * A lower-level Preact hook that creates an `AsyncQueuer` instance for managing an async queue of items.\n *\n * Features:\n * - Priority queue support via getPriority option\n * - Configurable concurrency limit\n * - Task success/error/completion callbacks\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume task processing\n * - Task cancellation\n * - Item expiration to clear stale items from the queue\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if below the concurrency limit.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `queuer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `activeItems`: Items currently being processed by the queuer\n * - `errorCount`: Number of task executions that have resulted in errors\n * - `expirationCount`: Number of items that have been removed due to expiration\n * - `isEmpty`: Whether the queuer has no items to process\n * - `isFull`: Whether the queuer has reached its maximum capacity\n * - `isIdle`: Whether the queuer is not currently processing any items\n * - `isRunning`: Whether the queuer is active and will process items automatically\n * - `items`: Array of items currently waiting to be processed\n * - `itemTimestamps`: Timestamps when items were added for expiration tracking\n * - `lastResult`: The result from the most recent task execution\n * - `pendingTick`: Whether the queuer has a pending timeout for processing the next item\n * - `rejectionCount`: Number of items that have been rejected from being added\n * - `settledCount`: Number of task executions that have completed (success or error)\n * - `size`: Number of items currently in the queue\n * - `status`: Current processing status ('idle' | 'running' | 'stopped')\n * - `successCount`: Number of task executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook stops the queuer and aborts any in-flight task executions when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queuer = useAsyncQueuer(fn, {\n * concurrency: 2,\n * started: false,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your task function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncQueuer.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Queue Size: {size}</div>\n * )}\n * </asyncQueuer.Subscribe>\n *\n * // Opt-in to re-render when queue size changes at hook level (optimized for displaying queue length)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * size: state.size,\n * isEmpty: state.isEmpty,\n * isFull: state.isFull\n * })\n * );\n *\n * // Opt-in to re-render when processing state changes (optimized for loading indicators)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * isRunning: state.isRunning,\n * isIdle: state.isIdle,\n * status: state.status,\n * activeItems: state.activeItems,\n * pendingTick: state.pendingTick\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settledCount: state.settledCount,\n * expirationCount: state.expirationCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * {\n * concurrency: 2,\n * maxSize: 100,\n * started: false,\n * onSuccess: (result) => {\n * console.log('Item processed:', result);\n * },\n * onError: (error) => {\n * console.error('Processing failed:', error);\n * }\n * },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { size, isRunning, activeItems } = asyncQueuer.state;\n * ```\n */\nexport function useAsyncQueuer<TValue, TSelected = {}>(\n fn: (value: TValue) => Promise<any>,\n options: PreactAsyncQueuerOptions<TValue, TSelected> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncQueuer,\n ...options,\n } as PreactAsyncQueuerOptions<TValue, TSelected>\n const [asyncQueuer] = useState(() => {\n const queuerInstance = new AsyncQueuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncQueuer<TValue, TSelected>\n\n queuerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(queuerInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return queuerInstance\n })\n\n asyncQueuer.fn = fn\n asyncQueuer.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncQueuer)\n } else {\n asyncQueuer.stop()\n asyncQueuer.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(asyncQueuer.store, selector)\n\n return useMemo(\n () =>\n ({\n ...asyncQueuer,\n state,\n }) as PreactAsyncQueuer<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncQueuer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0OA,SAAgB,eACd,IACA,UAAuD,EAAE,EACzD,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,gDAA8B;EACnC,MAAM,iBAAiB,IAAIC,yCACzB,IACA,cACD;AAED,iBAAe,YAAY,SAAS,UAAqB,OAGtD;GACD,MAAM,gDAAoB,eAAe,OAAO,MAAM,SAAS;AAE/D,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;AAGrC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;QAC/B;AACL,gBAAY,MAAM;AAClB,gBAAY,OAAO;;;IAGtB,EAAE,CAAC;CAGN,MAAM,6CAAiB,YAAY,OAAO,SAAS;AAEnD,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
|
1
|
+
{"version":3,"file":"useAsyncQueuer.cjs","names":["useDefaultPacerOptions","AsyncQueuer","shallow"],"sources":["../../src/async-queuer/useAsyncQueuer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncQueuerOptions<\n TValue,\n TSelected = {},\n> extends AsyncQueuerOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop + abort); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: PreactAsyncQueuer<TValue, TSelected>) => void\n}\n\nexport interface PreactAsyncQueuer<TValue, TSelected = {}> extends Omit<\n AsyncQueuer<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async queuer state.\n *\n * This is useful for opting into state re-renders for specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Queue Size: {size}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.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<AsyncQueuerState<TValue>>>\n}\n\n/**\n * A lower-level Preact hook that creates an `AsyncQueuer` instance for managing an async queue of items.\n *\n * Features:\n * - Priority queue support via getPriority option\n * - Configurable concurrency limit\n * - Task success/error/completion callbacks\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume task processing\n * - Task cancellation\n * - Item expiration to clear stale items from the queue\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if below the concurrency limit.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `queuer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `activeItems`: Items currently being processed by the queuer\n * - `errorCount`: Number of task executions that have resulted in errors\n * - `expirationCount`: Number of items that have been removed due to expiration\n * - `isEmpty`: Whether the queuer has no items to process\n * - `isFull`: Whether the queuer has reached its maximum capacity\n * - `isIdle`: Whether the queuer is not currently processing any items\n * - `isRunning`: Whether the queuer is active and will process items automatically\n * - `items`: Array of items currently waiting to be processed\n * - `itemTimestamps`: Timestamps when items were added for expiration tracking\n * - `lastResult`: The result from the most recent task execution\n * - `pendingTick`: Whether the queuer has a pending timeout for processing the next item\n * - `rejectionCount`: Number of items that have been rejected from being added\n * - `settledCount`: Number of task executions that have completed (success or error)\n * - `size`: Number of items currently in the queue\n * - `status`: Current processing status ('idle' | 'running' | 'stopped')\n * - `successCount`: Number of task executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook stops the queuer and aborts any in-flight task executions when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queuer = useAsyncQueuer(fn, {\n * concurrency: 2,\n * started: false,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your task function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncQueuer.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Queue Size: {size}</div>\n * )}\n * </asyncQueuer.Subscribe>\n *\n * // Opt-in to re-render when queue size changes at hook level (optimized for displaying queue length)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * size: state.size,\n * isEmpty: state.isEmpty,\n * isFull: state.isFull\n * })\n * );\n *\n * // Opt-in to re-render when processing state changes (optimized for loading indicators)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * isRunning: state.isRunning,\n * isIdle: state.isIdle,\n * status: state.status,\n * activeItems: state.activeItems,\n * pendingTick: state.pendingTick\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settledCount: state.settledCount,\n * expirationCount: state.expirationCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * {\n * concurrency: 2,\n * maxSize: 100,\n * started: false,\n * onSuccess: (result) => {\n * console.log('Item processed:', result);\n * },\n * onError: (error) => {\n * console.error('Processing failed:', error);\n * }\n * },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { size, isRunning, activeItems } = asyncQueuer.state;\n * ```\n */\nexport function useAsyncQueuer<TValue, TSelected = {}>(\n fn: (value: TValue) => Promise<any>,\n options: PreactAsyncQueuerOptions<TValue, TSelected> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncQueuer,\n ...options,\n } as PreactAsyncQueuerOptions<TValue, TSelected>\n const [asyncQueuer] = useState(() => {\n const queuerInstance = new AsyncQueuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncQueuer<TValue, TSelected>\n\n queuerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(queuerInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return queuerInstance\n })\n\n asyncQueuer.fn = fn\n asyncQueuer.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncQueuer)\n } else {\n asyncQueuer.stop()\n asyncQueuer.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(asyncQueuer.store, selector, { equal: shallow })\n\n return useMemo(\n () =>\n ({\n ...asyncQueuer,\n state,\n }) as PreactAsyncQueuer<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncQueuer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0OA,SAAgB,eACd,IACA,UAAuD,EAAE,EACzD,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,gDAA8B;EACnC,MAAM,iBAAiB,IAAIC,yCACzB,IACA,cACD;AAED,iBAAe,YAAY,SAAS,UAAqB,OAGtD;GACD,MAAM,gDAAoB,eAAe,OAAO,MAAM,UAAU,EAC9D,OAAOC,gCACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;AAGrC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;QAC/B;AACL,gBAAY,MAAM;AAClB,gBAAY,OAAO;;;IAGtB,EAAE,CAAC;CAGN,MAAM,6CAAiB,YAAY,OAAO,UAAU,EAAE,OAAOA,gCAAS,CAAC;AAEvE,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
2
|
import { useEffect, useMemo, useState } from "preact/hooks";
|
|
3
|
-
import { useStore } from "@tanstack/preact-store";
|
|
3
|
+
import { shallow, useStore } from "@tanstack/preact-store";
|
|
4
4
|
import { AsyncQueuer } from "@tanstack/pacer/async-queuer";
|
|
5
5
|
|
|
6
6
|
//#region src/async-queuer/useAsyncQueuer.ts
|
|
@@ -189,7 +189,7 @@ function useAsyncQueuer(fn, options = {}, selector = () => ({})) {
|
|
|
189
189
|
const [asyncQueuer] = useState(() => {
|
|
190
190
|
const queuerInstance = new AsyncQueuer(fn, mergedOptions);
|
|
191
191
|
queuerInstance.Subscribe = function Subscribe(props) {
|
|
192
|
-
const selected = useStore(queuerInstance.store, props.selector);
|
|
192
|
+
const selected = useStore(queuerInstance.store, props.selector, { equal: shallow });
|
|
193
193
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
194
194
|
};
|
|
195
195
|
return queuerInstance;
|
|
@@ -205,7 +205,7 @@ function useAsyncQueuer(fn, options = {}, selector = () => ({})) {
|
|
|
205
205
|
}
|
|
206
206
|
};
|
|
207
207
|
}, []);
|
|
208
|
-
const state = useStore(asyncQueuer.store, selector);
|
|
208
|
+
const state = useStore(asyncQueuer.store, selector, { equal: shallow });
|
|
209
209
|
return useMemo(() => ({
|
|
210
210
|
...asyncQueuer,
|
|
211
211
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncQueuer.js","names":[],"sources":["../../src/async-queuer/useAsyncQueuer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncQueuerOptions<\n TValue,\n TSelected = {},\n> extends AsyncQueuerOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop + abort); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: PreactAsyncQueuer<TValue, TSelected>) => void\n}\n\nexport interface PreactAsyncQueuer<TValue, TSelected = {}> extends Omit<\n AsyncQueuer<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async queuer state.\n *\n * This is useful for opting into state re-renders for specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Queue Size: {size}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.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<AsyncQueuerState<TValue>>>\n}\n\n/**\n * A lower-level Preact hook that creates an `AsyncQueuer` instance for managing an async queue of items.\n *\n * Features:\n * - Priority queue support via getPriority option\n * - Configurable concurrency limit\n * - Task success/error/completion callbacks\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume task processing\n * - Task cancellation\n * - Item expiration to clear stale items from the queue\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if below the concurrency limit.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `queuer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `activeItems`: Items currently being processed by the queuer\n * - `errorCount`: Number of task executions that have resulted in errors\n * - `expirationCount`: Number of items that have been removed due to expiration\n * - `isEmpty`: Whether the queuer has no items to process\n * - `isFull`: Whether the queuer has reached its maximum capacity\n * - `isIdle`: Whether the queuer is not currently processing any items\n * - `isRunning`: Whether the queuer is active and will process items automatically\n * - `items`: Array of items currently waiting to be processed\n * - `itemTimestamps`: Timestamps when items were added for expiration tracking\n * - `lastResult`: The result from the most recent task execution\n * - `pendingTick`: Whether the queuer has a pending timeout for processing the next item\n * - `rejectionCount`: Number of items that have been rejected from being added\n * - `settledCount`: Number of task executions that have completed (success or error)\n * - `size`: Number of items currently in the queue\n * - `status`: Current processing status ('idle' | 'running' | 'stopped')\n * - `successCount`: Number of task executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook stops the queuer and aborts any in-flight task executions when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queuer = useAsyncQueuer(fn, {\n * concurrency: 2,\n * started: false,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your task function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncQueuer.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Queue Size: {size}</div>\n * )}\n * </asyncQueuer.Subscribe>\n *\n * // Opt-in to re-render when queue size changes at hook level (optimized for displaying queue length)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * size: state.size,\n * isEmpty: state.isEmpty,\n * isFull: state.isFull\n * })\n * );\n *\n * // Opt-in to re-render when processing state changes (optimized for loading indicators)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * isRunning: state.isRunning,\n * isIdle: state.isIdle,\n * status: state.status,\n * activeItems: state.activeItems,\n * pendingTick: state.pendingTick\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settledCount: state.settledCount,\n * expirationCount: state.expirationCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * {\n * concurrency: 2,\n * maxSize: 100,\n * started: false,\n * onSuccess: (result) => {\n * console.log('Item processed:', result);\n * },\n * onError: (error) => {\n * console.error('Processing failed:', error);\n * }\n * },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { size, isRunning, activeItems } = asyncQueuer.state;\n * ```\n */\nexport function useAsyncQueuer<TValue, TSelected = {}>(\n fn: (value: TValue) => Promise<any>,\n options: PreactAsyncQueuerOptions<TValue, TSelected> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncQueuer,\n ...options,\n } as PreactAsyncQueuerOptions<TValue, TSelected>\n const [asyncQueuer] = useState(() => {\n const queuerInstance = new AsyncQueuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncQueuer<TValue, TSelected>\n\n queuerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(queuerInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return queuerInstance\n })\n\n asyncQueuer.fn = fn\n asyncQueuer.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncQueuer)\n } else {\n asyncQueuer.stop()\n asyncQueuer.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(asyncQueuer.store, selector)\n\n return useMemo(\n () =>\n ({\n ...asyncQueuer,\n state,\n }) as PreactAsyncQueuer<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncQueuer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0OA,SAAgB,eACd,IACA,UAAuD,EAAE,EACzD,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,eAAe,eAAe;EACnC,MAAM,iBAAiB,IAAI,YACzB,IACA,cACD;AAED,iBAAe,YAAY,SAAS,UAAqB,OAGtD;GACD,MAAM,WAAW,SAAS,eAAe,OAAO,MAAM,SAAS;AAE/D,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;AAGrC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;QAC/B;AACL,gBAAY,MAAM;AAClB,gBAAY,OAAO;;;IAGtB,EAAE,CAAC;CAGN,MAAM,QAAQ,SAAS,YAAY,OAAO,SAAS;AAEnD,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
|
1
|
+
{"version":3,"file":"useAsyncQueuer.js","names":[],"sources":["../../src/async-queuer/useAsyncQueuer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncQueuerOptions<\n TValue,\n TSelected = {},\n> extends AsyncQueuerOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop + abort); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: PreactAsyncQueuer<TValue, TSelected>) => void\n}\n\nexport interface PreactAsyncQueuer<TValue, TSelected = {}> extends Omit<\n AsyncQueuer<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async queuer state.\n *\n * This is useful for opting into state re-renders for specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Queue Size: {size}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.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<AsyncQueuerState<TValue>>>\n}\n\n/**\n * A lower-level Preact hook that creates an `AsyncQueuer` instance for managing an async queue of items.\n *\n * Features:\n * - Priority queue support via getPriority option\n * - Configurable concurrency limit\n * - Task success/error/completion callbacks\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume task processing\n * - Task cancellation\n * - Item expiration to clear stale items from the queue\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if below the concurrency limit.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `queuer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * 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 or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `activeItems`: Items currently being processed by the queuer\n * - `errorCount`: Number of task executions that have resulted in errors\n * - `expirationCount`: Number of items that have been removed due to expiration\n * - `isEmpty`: Whether the queuer has no items to process\n * - `isFull`: Whether the queuer has reached its maximum capacity\n * - `isIdle`: Whether the queuer is not currently processing any items\n * - `isRunning`: Whether the queuer is active and will process items automatically\n * - `items`: Array of items currently waiting to be processed\n * - `itemTimestamps`: Timestamps when items were added for expiration tracking\n * - `lastResult`: The result from the most recent task execution\n * - `pendingTick`: Whether the queuer has a pending timeout for processing the next item\n * - `rejectionCount`: Number of items that have been rejected from being added\n * - `settledCount`: Number of task executions that have completed (success or error)\n * - `size`: Number of items currently in the queue\n * - `status`: Current processing status ('idle' | 'running' | 'stopped')\n * - `successCount`: Number of task executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook stops the queuer and aborts any in-flight task executions when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queuer = useAsyncQueuer(fn, {\n * concurrency: 2,\n * started: false,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your task function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncQueuer.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Queue Size: {size}</div>\n * )}\n * </asyncQueuer.Subscribe>\n *\n * // Opt-in to re-render when queue size changes at hook level (optimized for displaying queue length)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * size: state.size,\n * isEmpty: state.isEmpty,\n * isFull: state.isFull\n * })\n * );\n *\n * // Opt-in to re-render when processing state changes (optimized for loading indicators)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * isRunning: state.isRunning,\n * isIdle: state.isIdle,\n * status: state.status,\n * activeItems: state.activeItems,\n * pendingTick: state.pendingTick\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * { concurrency: 2, maxSize: 100, started: false },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settledCount: state.settledCount,\n * expirationCount: state.expirationCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncQueuer = useAsyncQueuer(\n * async (item) => {\n * const result = await processItem(item);\n * return result;\n * },\n * {\n * concurrency: 2,\n * maxSize: 100,\n * started: false,\n * onSuccess: (result) => {\n * console.log('Item processed:', result);\n * },\n * onError: (error) => {\n * console.error('Processing failed:', error);\n * }\n * },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { size, isRunning, activeItems } = asyncQueuer.state;\n * ```\n */\nexport function useAsyncQueuer<TValue, TSelected = {}>(\n fn: (value: TValue) => Promise<any>,\n options: PreactAsyncQueuerOptions<TValue, TSelected> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncQueuer,\n ...options,\n } as PreactAsyncQueuerOptions<TValue, TSelected>\n const [asyncQueuer] = useState(() => {\n const queuerInstance = new AsyncQueuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncQueuer<TValue, TSelected>\n\n queuerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(queuerInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return queuerInstance\n })\n\n asyncQueuer.fn = fn\n asyncQueuer.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncQueuer)\n } else {\n asyncQueuer.stop()\n asyncQueuer.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(asyncQueuer.store, selector, { equal: shallow })\n\n return useMemo(\n () =>\n ({\n ...asyncQueuer,\n state,\n }) as PreactAsyncQueuer<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncQueuer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0OA,SAAgB,eACd,IACA,UAAuD,EAAE,EACzD,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,eAAe,eAAe;EACnC,MAAM,iBAAiB,IAAI,YACzB,IACA,cACD;AAED,iBAAe,YAAY,SAAS,UAAqB,OAGtD;GACD,MAAM,WAAW,SAAS,eAAe,OAAO,MAAM,UAAU,EAC9D,OAAO,SACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;AAGrC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;QAC/B;AACL,gBAAY,MAAM;AAClB,gBAAY,OAAO;;;IAGtB,EAAE,CAAC;CAGN,MAAM,QAAQ,SAAS,YAAY,OAAO,UAAU,EAAE,OAAO,SAAS,CAAC;AAEvE,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
|
@@ -184,7 +184,7 @@ function useAsyncRateLimiter(fn, options, selector = () => ({})) {
|
|
|
184
184
|
const [asyncRateLimiter] = (0, preact_hooks.useState)(() => {
|
|
185
185
|
const rateLimiterInstance = new _tanstack_pacer_async_rate_limiter.AsyncRateLimiter(fn, mergedOptions);
|
|
186
186
|
rateLimiterInstance.Subscribe = function Subscribe(props) {
|
|
187
|
-
const selected = (0, _tanstack_preact_store.useStore)(rateLimiterInstance.store, props.selector);
|
|
187
|
+
const selected = (0, _tanstack_preact_store.useStore)(rateLimiterInstance.store, props.selector, { equal: _tanstack_preact_store.shallow });
|
|
188
188
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
189
189
|
};
|
|
190
190
|
return rateLimiterInstance;
|
|
@@ -197,7 +197,7 @@ function useAsyncRateLimiter(fn, options, selector = () => ({})) {
|
|
|
197
197
|
else asyncRateLimiter.abort();
|
|
198
198
|
};
|
|
199
199
|
}, []);
|
|
200
|
-
const state = (0, _tanstack_preact_store.useStore)(asyncRateLimiter.store, selector);
|
|
200
|
+
const state = (0, _tanstack_preact_store.useStore)(asyncRateLimiter.store, selector, { equal: _tanstack_preact_store.shallow });
|
|
201
201
|
return (0, preact_hooks.useMemo)(() => ({
|
|
202
202
|
...asyncRateLimiter,
|
|
203
203
|
state
|