@tanstack/preact-pacer 0.18.0 → 0.19.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.
Files changed (103) hide show
  1. package/dist/async-batcher/index.cjs +3 -3
  2. package/dist/async-batcher/index.d.cts +2 -2
  3. package/dist/async-batcher/index.d.ts +2 -2
  4. package/dist/async-batcher/useAsyncBatcher.cjs +35 -11
  5. package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -1
  6. package/dist/async-batcher/useAsyncBatcher.d.cts +45 -10
  7. package/dist/async-batcher/useAsyncBatcher.d.ts +45 -10
  8. package/dist/async-batcher/useAsyncBatcher.js +32 -8
  9. package/dist/async-batcher/useAsyncBatcher.js.map +1 -1
  10. package/dist/async-debouncer/index.cjs +3 -3
  11. package/dist/async-debouncer/index.d.cts +2 -2
  12. package/dist/async-debouncer/index.d.ts +2 -2
  13. package/dist/async-debouncer/useAsyncDebouncer.cjs +35 -11
  14. package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -1
  15. package/dist/async-debouncer/useAsyncDebouncer.d.cts +45 -10
  16. package/dist/async-debouncer/useAsyncDebouncer.d.ts +45 -10
  17. package/dist/async-debouncer/useAsyncDebouncer.js +32 -8
  18. package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -1
  19. package/dist/async-queuer/index.cjs +3 -3
  20. package/dist/async-queuer/index.d.cts +2 -2
  21. package/dist/async-queuer/index.d.ts +2 -2
  22. package/dist/async-queuer/useAsyncQueuedState.cjs.map +1 -1
  23. package/dist/async-queuer/useAsyncQueuedState.d.cts +2 -2
  24. package/dist/async-queuer/useAsyncQueuedState.d.ts +2 -2
  25. package/dist/async-queuer/useAsyncQueuedState.js.map +1 -1
  26. package/dist/async-queuer/useAsyncQueuer.cjs +35 -11
  27. package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -1
  28. package/dist/async-queuer/useAsyncQueuer.d.cts +45 -10
  29. package/dist/async-queuer/useAsyncQueuer.d.ts +45 -10
  30. package/dist/async-queuer/useAsyncQueuer.js +32 -8
  31. package/dist/async-queuer/useAsyncQueuer.js.map +1 -1
  32. package/dist/async-rate-limiter/index.cjs +3 -3
  33. package/dist/async-rate-limiter/index.d.cts +2 -2
  34. package/dist/async-rate-limiter/index.d.ts +2 -2
  35. package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +35 -11
  36. package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -1
  37. package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +45 -10
  38. package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +45 -10
  39. package/dist/async-rate-limiter/useAsyncRateLimiter.js +32 -8
  40. package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -1
  41. package/dist/async-retryer/index.cjs +3 -3
  42. package/dist/async-throttler/index.cjs +3 -3
  43. package/dist/async-throttler/index.d.cts +2 -2
  44. package/dist/async-throttler/index.d.ts +2 -2
  45. package/dist/async-throttler/useAsyncThrottler.cjs +35 -11
  46. package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -1
  47. package/dist/async-throttler/useAsyncThrottler.d.cts +45 -10
  48. package/dist/async-throttler/useAsyncThrottler.d.ts +45 -10
  49. package/dist/async-throttler/useAsyncThrottler.js +32 -8
  50. package/dist/async-throttler/useAsyncThrottler.js.map +1 -1
  51. package/dist/batcher/index.cjs +3 -3
  52. package/dist/batcher/useBatcher.cjs +35 -11
  53. package/dist/batcher/useBatcher.cjs.map +1 -1
  54. package/dist/batcher/useBatcher.d.cts +42 -7
  55. package/dist/batcher/useBatcher.d.ts +42 -7
  56. package/dist/batcher/useBatcher.js +32 -8
  57. package/dist/batcher/useBatcher.js.map +1 -1
  58. package/dist/debouncer/index.cjs +3 -3
  59. package/dist/debouncer/useDebouncer.cjs +35 -11
  60. package/dist/debouncer/useDebouncer.cjs.map +1 -1
  61. package/dist/debouncer/useDebouncer.d.cts +42 -7
  62. package/dist/debouncer/useDebouncer.d.ts +42 -7
  63. package/dist/debouncer/useDebouncer.js +32 -8
  64. package/dist/debouncer/useDebouncer.js.map +1 -1
  65. package/dist/index.cjs +3 -3
  66. package/dist/index.d.cts +6 -6
  67. package/dist/index.d.ts +6 -6
  68. package/dist/provider/PacerProvider.d.cts +1 -1
  69. package/dist/queuer/index.cjs +3 -3
  70. package/dist/queuer/useQueuer.cjs +35 -11
  71. package/dist/queuer/useQueuer.cjs.map +1 -1
  72. package/dist/queuer/useQueuer.d.cts +42 -7
  73. package/dist/queuer/useQueuer.d.ts +42 -7
  74. package/dist/queuer/useQueuer.js +32 -8
  75. package/dist/queuer/useQueuer.js.map +1 -1
  76. package/dist/rate-limiter/index.cjs +3 -3
  77. package/dist/rate-limiter/useRateLimiter.cjs +35 -11
  78. package/dist/rate-limiter/useRateLimiter.cjs.map +1 -1
  79. package/dist/rate-limiter/useRateLimiter.d.cts +42 -7
  80. package/dist/rate-limiter/useRateLimiter.d.ts +42 -7
  81. package/dist/rate-limiter/useRateLimiter.js +32 -8
  82. package/dist/rate-limiter/useRateLimiter.js.map +1 -1
  83. package/dist/throttler/index.cjs +3 -3
  84. package/dist/throttler/useThrottler.cjs +35 -11
  85. package/dist/throttler/useThrottler.cjs.map +1 -1
  86. package/dist/throttler/useThrottler.d.cts +42 -7
  87. package/dist/throttler/useThrottler.d.ts +42 -7
  88. package/dist/throttler/useThrottler.js +32 -8
  89. package/dist/throttler/useThrottler.js.map +1 -1
  90. package/dist/types/index.cjs +3 -3
  91. package/dist/utils/index.cjs +3 -3
  92. package/package.json +1 -1
  93. package/src/async-batcher/useAsyncBatcher.ts +64 -13
  94. package/src/async-debouncer/useAsyncDebouncer.ts +64 -13
  95. package/src/async-queuer/useAsyncQueuedState.ts +2 -2
  96. package/src/async-queuer/useAsyncQueuer.ts +64 -13
  97. package/src/async-rate-limiter/useAsyncRateLimiter.ts +64 -13
  98. package/src/async-throttler/useAsyncThrottler.ts +64 -13
  99. package/src/batcher/useBatcher.ts +61 -8
  100. package/src/debouncer/useDebouncer.ts +61 -8
  101. package/src/queuer/useQueuer.ts +61 -8
  102. package/src/rate-limiter/useRateLimiter.ts +61 -8
  103. package/src/throttler/useThrottler.ts +61 -8
@@ -3,10 +3,10 @@ const require_useAsyncBatchedCallback = require('./useAsyncBatchedCallback.cjs')
3
3
 
4
4
  exports.useAsyncBatchedCallback = require_useAsyncBatchedCallback.useAsyncBatchedCallback;
5
5
  exports.useAsyncBatcher = require_useAsyncBatcher.useAsyncBatcher;
6
- var __tanstack_pacer_async_batcher = require("@tanstack/pacer/async-batcher");
7
- Object.keys(__tanstack_pacer_async_batcher).forEach(function (k) {
6
+ var _tanstack_pacer_async_batcher = require("@tanstack/pacer/async-batcher");
7
+ Object.keys(_tanstack_pacer_async_batcher).forEach(function (k) {
8
8
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
9
9
  enumerable: true,
10
- get: function () { return __tanstack_pacer_async_batcher[k]; }
10
+ get: function () { return _tanstack_pacer_async_batcher[k]; }
11
11
  });
12
12
  });
@@ -1,4 +1,4 @@
1
- import { ReactAsyncBatcher, useAsyncBatcher } from "./useAsyncBatcher.cjs";
1
+ import { PreactAsyncBatcher, useAsyncBatcher } from "./useAsyncBatcher.cjs";
2
2
  import { useAsyncBatchedCallback } from "./useAsyncBatchedCallback.cjs";
3
3
  export * from "@tanstack/pacer/async-batcher";
4
- export { ReactAsyncBatcher, useAsyncBatchedCallback, useAsyncBatcher };
4
+ export { PreactAsyncBatcher, useAsyncBatchedCallback, useAsyncBatcher };
@@ -1,4 +1,4 @@
1
- import { ReactAsyncBatcher, useAsyncBatcher } from "./useAsyncBatcher.js";
1
+ import { PreactAsyncBatcher, useAsyncBatcher } from "./useAsyncBatcher.js";
2
2
  import { useAsyncBatchedCallback } from "./useAsyncBatchedCallback.js";
3
3
  export * from "@tanstack/pacer/async-batcher";
4
- export { ReactAsyncBatcher, useAsyncBatchedCallback, useAsyncBatcher };
4
+ export { PreactAsyncBatcher, useAsyncBatchedCallback, useAsyncBatcher };
@@ -1,7 +1,7 @@
1
1
  const require_PacerProvider = require('../provider/PacerProvider.cjs');
2
2
  let preact_hooks = require("preact/hooks");
3
- let __tanstack_pacer_async_batcher = require("@tanstack/pacer/async-batcher");
4
- let __tanstack_preact_store = require("@tanstack/preact-store");
3
+ let _tanstack_pacer_async_batcher = require("@tanstack/pacer/async-batcher");
4
+ let _tanstack_preact_store = require("@tanstack/preact-store");
5
5
 
6
6
  //#region src/async-batcher/useAsyncBatcher.ts
7
7
  /**
@@ -35,14 +35,24 @@ let __tanstack_preact_store = require("@tanstack/preact-store");
35
35
  *
36
36
  * ## State Management and Selector
37
37
  *
38
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
39
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
40
- * unnecessary re-renders when irrelevant state changes occur.
38
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
39
+ * in two ways:
40
+ *
41
+ * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**
42
+ *
43
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
44
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
45
+ * in child components.
46
+ *
47
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
48
+ *
49
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
50
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
51
+ * state changes occur.
41
52
  *
42
53
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
43
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
44
- * full control over when your component updates. Only when you provide a selector will the
45
- * component re-render when the selected state values change.
54
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
55
+ * re-renders and gives you full control over when your component updates.
46
56
  *
47
57
  * Available state properties:
48
58
  * - `errorCount`: Number of batch executions that have resulted in errors
@@ -71,7 +81,14 @@ let __tanstack_preact_store = require("@tanstack/preact-store");
71
81
  * { maxSize: 10, wait: 2000 }
72
82
  * );
73
83
  *
74
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
84
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
85
+ * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>
86
+ * {({ size }) => (
87
+ * <div>Batch Size: {size}</div>
88
+ * )}
89
+ * </asyncBatcher.Subscribe>
90
+ *
91
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
75
92
  * const asyncBatcher = useAsyncBatcher(
76
93
  * async (items) => {
77
94
  * const results = await Promise.all(items.map(item => processItem(item)));
@@ -150,10 +167,17 @@ function useAsyncBatcher(fn, options = {}, selector = () => ({})) {
150
167
  ...require_PacerProvider.useDefaultPacerOptions().asyncBatcher,
151
168
  ...options
152
169
  };
153
- const [asyncBatcher] = (0, preact_hooks.useState)(() => new __tanstack_pacer_async_batcher.AsyncBatcher(fn, mergedOptions));
170
+ const [asyncBatcher] = (0, preact_hooks.useState)(() => {
171
+ const batcherInstance = new _tanstack_pacer_async_batcher.AsyncBatcher(fn, mergedOptions);
172
+ batcherInstance.Subscribe = function Subscribe(props) {
173
+ const selected = (0, _tanstack_preact_store.useStore)(batcherInstance.store, props.selector);
174
+ return typeof props.children === "function" ? props.children(selected) : props.children;
175
+ };
176
+ return batcherInstance;
177
+ });
154
178
  asyncBatcher.fn = fn;
155
179
  asyncBatcher.setOptions(mergedOptions);
156
- const state = (0, __tanstack_preact_store.useStore)(asyncBatcher.store, selector);
180
+ const state = (0, _tanstack_preact_store.useStore)(asyncBatcher.store, selector);
157
181
  return (0, preact_hooks.useMemo)(() => ({
158
182
  ...asyncBatcher,
159
183
  state
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncBatcher.cjs","names":["useDefaultPacerOptions","AsyncBatcher"],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { 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'\n\nexport interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `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 * @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 * // Opt-in to re-render when execution state changes (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: AsyncBatcherOptions<TValue> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): ReactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as AsyncBatcherOptions<TValue>\n\n const [asyncBatcher] = useState(\n () => new AsyncBatcher<TValue>(fn, mergedOptions),\n )\n\n asyncBatcher.fn = fn\n asyncBatcher.setOptions(mergedOptions)\n\n const state = useStore(asyncBatcher.store, selector)\n\n return useMemo(\n () =>\n ({\n ...asyncBatcher,\n state,\n }) as ReactAsyncBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncBatcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyKA,SAAgB,gBACd,IACA,UAAuC,EAAE,EACzC,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,iDACC,IAAIC,4CAAqB,IAAI,cAAc,CAClD;AAED,cAAa,KAAK;AAClB,cAAa,WAAW,cAAc;CAEtC,MAAM,8CAAiB,aAAa,OAAO,SAAS;AAEpD,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
1
+ {"version":3,"file":"useAsyncBatcher.cjs","names":["useDefaultPacerOptions","AsyncBatcher"],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { 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 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 * @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: AsyncBatcherOptions<TValue> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as AsyncBatcherOptions<TValue>\n\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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4MA,SAAgB,gBACd,IACA,UAAuC,EAAE,EACzC,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,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;CAEtC,MAAM,6CAAiB,aAAa,OAAO,SAAS;AAEpD,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
@@ -1,8 +1,26 @@
1
1
  import { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState } from "@tanstack/pacer/async-batcher";
2
2
  import { Store } from "@tanstack/preact-store";
3
+ import { ComponentChildren } from "preact";
3
4
 
4
5
  //#region src/async-batcher/useAsyncBatcher.d.ts
5
- interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> {
6
+ interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> {
7
+ /**
8
+ * A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.
9
+ *
10
+ * This is useful for opting into state re-renders for specific parts of the batcher state
11
+ * deep in your component tree without needing to pass a selector to the hook.
12
+ *
13
+ * @example
14
+ * <batcher.Subscribe selector={(state) => ({ size: state.size })}>
15
+ * {({ size }) => (
16
+ * <div>Batch Size: {size}</div>
17
+ * )}
18
+ * </batcher.Subscribe>
19
+ */
20
+ Subscribe: <TSelected>(props: {
21
+ selector: (state: AsyncBatcherState<TValue>) => TSelected;
22
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
23
+ }) => ComponentChildren;
6
24
  /**
7
25
  * Reactive state that will be updated and re-rendered when the batcher state changes
8
26
  *
@@ -47,14 +65,24 @@ interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
47
65
  *
48
66
  * ## State Management and Selector
49
67
  *
50
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
51
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
52
- * unnecessary re-renders when irrelevant state changes occur.
68
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
69
+ * in two ways:
70
+ *
71
+ * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**
72
+ *
73
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
74
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
75
+ * in child components.
76
+ *
77
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
78
+ *
79
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
80
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
81
+ * state changes occur.
53
82
  *
54
83
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
55
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
56
- * full control over when your component updates. Only when you provide a selector will the
57
- * component re-render when the selected state values change.
84
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
85
+ * re-renders and gives you full control over when your component updates.
58
86
  *
59
87
  * Available state properties:
60
88
  * - `errorCount`: Number of batch executions that have resulted in errors
@@ -83,7 +111,14 @@ interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
83
111
  * { maxSize: 10, wait: 2000 }
84
112
  * );
85
113
  *
86
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
114
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
115
+ * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>
116
+ * {({ size }) => (
117
+ * <div>Batch Size: {size}</div>
118
+ * )}
119
+ * </asyncBatcher.Subscribe>
120
+ *
121
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
87
122
  * const asyncBatcher = useAsyncBatcher(
88
123
  * async (items) => {
89
124
  * const results = await Promise.all(items.map(item => processItem(item)));
@@ -157,7 +192,7 @@ interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
157
192
  * const { isExecuting, lastResult, size } = asyncBatcher.state;
158
193
  * ```
159
194
  */
160
- declare function useAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?: AsyncBatcherOptions<TValue>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): ReactAsyncBatcher<TValue, TSelected>;
195
+ declare function useAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?: AsyncBatcherOptions<TValue>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): PreactAsyncBatcher<TValue, TSelected>;
161
196
  //#endregion
162
- export { ReactAsyncBatcher, useAsyncBatcher };
197
+ export { PreactAsyncBatcher, useAsyncBatcher };
163
198
  //# sourceMappingURL=useAsyncBatcher.d.cts.map
@@ -1,8 +1,26 @@
1
+ import { ComponentChildren } from "preact";
1
2
  import { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState } from "@tanstack/pacer/async-batcher";
2
3
  import { Store } from "@tanstack/preact-store";
3
4
 
4
5
  //#region src/async-batcher/useAsyncBatcher.d.ts
5
- interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> {
6
+ interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> {
7
+ /**
8
+ * A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.
9
+ *
10
+ * This is useful for opting into state re-renders for specific parts of the batcher state
11
+ * deep in your component tree without needing to pass a selector to the hook.
12
+ *
13
+ * @example
14
+ * <batcher.Subscribe selector={(state) => ({ size: state.size })}>
15
+ * {({ size }) => (
16
+ * <div>Batch Size: {size}</div>
17
+ * )}
18
+ * </batcher.Subscribe>
19
+ */
20
+ Subscribe: <TSelected>(props: {
21
+ selector: (state: AsyncBatcherState<TValue>) => TSelected;
22
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
23
+ }) => ComponentChildren;
6
24
  /**
7
25
  * Reactive state that will be updated and re-rendered when the batcher state changes
8
26
  *
@@ -47,14 +65,24 @@ interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
47
65
  *
48
66
  * ## State Management and Selector
49
67
  *
50
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
51
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
52
- * unnecessary re-renders when irrelevant state changes occur.
68
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
69
+ * in two ways:
70
+ *
71
+ * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**
72
+ *
73
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
74
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
75
+ * in child components.
76
+ *
77
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
78
+ *
79
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
80
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
81
+ * state changes occur.
53
82
  *
54
83
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
55
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
56
- * full control over when your component updates. Only when you provide a selector will the
57
- * component re-render when the selected state values change.
84
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
85
+ * re-renders and gives you full control over when your component updates.
58
86
  *
59
87
  * Available state properties:
60
88
  * - `errorCount`: Number of batch executions that have resulted in errors
@@ -83,7 +111,14 @@ interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
83
111
  * { maxSize: 10, wait: 2000 }
84
112
  * );
85
113
  *
86
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
114
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
115
+ * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>
116
+ * {({ size }) => (
117
+ * <div>Batch Size: {size}</div>
118
+ * )}
119
+ * </asyncBatcher.Subscribe>
120
+ *
121
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
87
122
  * const asyncBatcher = useAsyncBatcher(
88
123
  * async (items) => {
89
124
  * const results = await Promise.all(items.map(item => processItem(item)));
@@ -157,7 +192,7 @@ interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
157
192
  * const { isExecuting, lastResult, size } = asyncBatcher.state;
158
193
  * ```
159
194
  */
160
- declare function useAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?: AsyncBatcherOptions<TValue>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): ReactAsyncBatcher<TValue, TSelected>;
195
+ declare function useAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?: AsyncBatcherOptions<TValue>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): PreactAsyncBatcher<TValue, TSelected>;
161
196
  //#endregion
162
- export { ReactAsyncBatcher, useAsyncBatcher };
197
+ export { PreactAsyncBatcher, useAsyncBatcher };
163
198
  //# sourceMappingURL=useAsyncBatcher.d.ts.map
@@ -35,14 +35,24 @@ import { useStore } from "@tanstack/preact-store";
35
35
  *
36
36
  * ## State Management and Selector
37
37
  *
38
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
39
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
40
- * unnecessary re-renders when irrelevant state changes occur.
38
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
39
+ * in two ways:
40
+ *
41
+ * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**
42
+ *
43
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
44
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
45
+ * in child components.
46
+ *
47
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
48
+ *
49
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
50
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
51
+ * state changes occur.
41
52
  *
42
53
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
43
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
44
- * full control over when your component updates. Only when you provide a selector will the
45
- * component re-render when the selected state values change.
54
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
55
+ * re-renders and gives you full control over when your component updates.
46
56
  *
47
57
  * Available state properties:
48
58
  * - `errorCount`: Number of batch executions that have resulted in errors
@@ -71,7 +81,14 @@ import { useStore } from "@tanstack/preact-store";
71
81
  * { maxSize: 10, wait: 2000 }
72
82
  * );
73
83
  *
74
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
84
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
85
+ * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>
86
+ * {({ size }) => (
87
+ * <div>Batch Size: {size}</div>
88
+ * )}
89
+ * </asyncBatcher.Subscribe>
90
+ *
91
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
75
92
  * const asyncBatcher = useAsyncBatcher(
76
93
  * async (items) => {
77
94
  * const results = await Promise.all(items.map(item => processItem(item)));
@@ -150,7 +167,14 @@ function useAsyncBatcher(fn, options = {}, selector = () => ({})) {
150
167
  ...useDefaultPacerOptions().asyncBatcher,
151
168
  ...options
152
169
  };
153
- const [asyncBatcher] = useState(() => new AsyncBatcher(fn, mergedOptions));
170
+ const [asyncBatcher] = useState(() => {
171
+ const batcherInstance = new AsyncBatcher(fn, mergedOptions);
172
+ batcherInstance.Subscribe = function Subscribe(props) {
173
+ const selected = useStore(batcherInstance.store, props.selector);
174
+ return typeof props.children === "function" ? props.children(selected) : props.children;
175
+ };
176
+ return batcherInstance;
177
+ });
154
178
  asyncBatcher.fn = fn;
155
179
  asyncBatcher.setOptions(mergedOptions);
156
180
  const state = useStore(asyncBatcher.store, selector);
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncBatcher.js","names":[],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { 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'\n\nexport interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `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 * @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 * // Opt-in to re-render when execution state changes (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: AsyncBatcherOptions<TValue> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): ReactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as AsyncBatcherOptions<TValue>\n\n const [asyncBatcher] = useState(\n () => new AsyncBatcher<TValue>(fn, mergedOptions),\n )\n\n asyncBatcher.fn = fn\n asyncBatcher.setOptions(mergedOptions)\n\n const state = useStore(asyncBatcher.store, selector)\n\n return useMemo(\n () =>\n ({\n ...asyncBatcher,\n state,\n }) as ReactAsyncBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncBatcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyKA,SAAgB,gBACd,IACA,UAAuC,EAAE,EACzC,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,gBAAgB,eACf,IAAI,aAAqB,IAAI,cAAc,CAClD;AAED,cAAa,KAAK;AAClB,cAAa,WAAW,cAAc;CAEtC,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 { 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 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 * @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: AsyncBatcherOptions<TValue> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as AsyncBatcherOptions<TValue>\n\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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4MA,SAAgB,gBACd,IACA,UAAuC,EAAE,EACzC,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,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;CAEtC,MAAM,QAAQ,SAAS,aAAa,OAAO,SAAS;AAEpD,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
@@ -3,10 +3,10 @@ const require_useAsyncDebouncedCallback = require('./useAsyncDebouncedCallback.c
3
3
 
4
4
  exports.useAsyncDebouncedCallback = require_useAsyncDebouncedCallback.useAsyncDebouncedCallback;
5
5
  exports.useAsyncDebouncer = require_useAsyncDebouncer.useAsyncDebouncer;
6
- var __tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer");
7
- Object.keys(__tanstack_pacer_async_debouncer).forEach(function (k) {
6
+ var _tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer");
7
+ Object.keys(_tanstack_pacer_async_debouncer).forEach(function (k) {
8
8
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
9
9
  enumerable: true,
10
- get: function () { return __tanstack_pacer_async_debouncer[k]; }
10
+ get: function () { return _tanstack_pacer_async_debouncer[k]; }
11
11
  });
12
12
  });
@@ -1,4 +1,4 @@
1
- import { ReactAsyncDebouncer, useAsyncDebouncer } from "./useAsyncDebouncer.cjs";
1
+ import { PreactAsyncDebouncer, useAsyncDebouncer } from "./useAsyncDebouncer.cjs";
2
2
  import { useAsyncDebouncedCallback } from "./useAsyncDebouncedCallback.cjs";
3
3
  export * from "@tanstack/pacer/async-debouncer";
4
- export { ReactAsyncDebouncer, useAsyncDebouncedCallback, useAsyncDebouncer };
4
+ export { PreactAsyncDebouncer, useAsyncDebouncedCallback, useAsyncDebouncer };
@@ -1,4 +1,4 @@
1
- import { ReactAsyncDebouncer, useAsyncDebouncer } from "./useAsyncDebouncer.js";
1
+ import { PreactAsyncDebouncer, useAsyncDebouncer } from "./useAsyncDebouncer.js";
2
2
  import { useAsyncDebouncedCallback } from "./useAsyncDebouncedCallback.js";
3
3
  export * from "@tanstack/pacer/async-debouncer";
4
- export { ReactAsyncDebouncer, useAsyncDebouncedCallback, useAsyncDebouncer };
4
+ export { PreactAsyncDebouncer, useAsyncDebouncedCallback, useAsyncDebouncer };
@@ -1,7 +1,7 @@
1
1
  const require_PacerProvider = require('../provider/PacerProvider.cjs');
2
2
  let preact_hooks = require("preact/hooks");
3
- let __tanstack_preact_store = require("@tanstack/preact-store");
4
- let __tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer");
3
+ let _tanstack_preact_store = require("@tanstack/preact-store");
4
+ let _tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer");
5
5
 
6
6
  //#region src/async-debouncer/useAsyncDebouncer.ts
7
7
  /**
@@ -30,14 +30,24 @@ let __tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer"
30
30
  *
31
31
  * ## State Management and Selector
32
32
  *
33
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
34
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
35
- * unnecessary re-renders when irrelevant state changes occur.
33
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
34
+ * in two ways:
35
+ *
36
+ * **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**
37
+ *
38
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
39
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
40
+ * in child components.
41
+ *
42
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
43
+ *
44
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
45
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
46
+ * state changes occur.
36
47
  *
37
48
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
38
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
39
- * full control over when your component updates. Only when you provide a selector will the
40
- * component re-render when the selected state values change.
49
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
50
+ * re-renders and gives you full control over when your component updates.
41
51
  *
42
52
  * Available state properties:
43
53
  * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge
@@ -61,7 +71,14 @@ let __tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer"
61
71
  * { wait: 500 }
62
72
  * );
63
73
  *
64
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
74
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
75
+ * <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>
76
+ * {({ isPending }) => (
77
+ * <div>{isPending ? 'Searching...' : 'Ready'}</div>
78
+ * )}
79
+ * </searchDebouncer.Subscribe>
80
+ *
81
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
65
82
  * const searchDebouncer = useAsyncDebouncer(
66
83
  * async (query: string) => {
67
84
  * const results = await api.search(query);
@@ -129,10 +146,17 @@ function useAsyncDebouncer(fn, options, selector = () => ({})) {
129
146
  ...require_PacerProvider.useDefaultPacerOptions().asyncDebouncer,
130
147
  ...options
131
148
  };
132
- const [asyncDebouncer] = (0, preact_hooks.useState)(() => new __tanstack_pacer_async_debouncer.AsyncDebouncer(fn, mergedOptions));
149
+ const [asyncDebouncer] = (0, preact_hooks.useState)(() => {
150
+ const debouncerInstance = new _tanstack_pacer_async_debouncer.AsyncDebouncer(fn, mergedOptions);
151
+ debouncerInstance.Subscribe = function Subscribe(props) {
152
+ const selected = (0, _tanstack_preact_store.useStore)(debouncerInstance.store, props.selector);
153
+ return typeof props.children === "function" ? props.children(selected) : props.children;
154
+ };
155
+ return debouncerInstance;
156
+ });
133
157
  asyncDebouncer.fn = fn;
134
158
  asyncDebouncer.setOptions(mergedOptions);
135
- const state = (0, __tanstack_preact_store.useStore)(asyncDebouncer.store, selector);
159
+ const state = (0, _tanstack_preact_store.useStore)(asyncDebouncer.store, selector);
136
160
  (0, preact_hooks.useEffect)(() => {
137
161
  return () => {
138
162
  asyncDebouncer.cancel();
@@ -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'\n\nexport interface ReactAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `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 * @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 * // Opt-in to re-render when execution state changes (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: AsyncDebouncerOptions<TFn>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): ReactAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as AsyncDebouncerOptions<TFn>\n\n const [asyncDebouncer] = useState(\n () => new AsyncDebouncer<TFn>(fn, mergedOptions),\n )\n\n asyncDebouncer.fn = fn\n asyncDebouncer.setOptions(mergedOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n useEffect(() => {\n return () => {\n asyncDebouncer.cancel()\n }\n }, [asyncDebouncer])\n\n return useMemo(\n () =>\n ({\n ...asyncDebouncer,\n state,\n }) as ReactAsyncDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncDebouncer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqJA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,mDACC,IAAIC,gDAAoB,IAAI,cAAc,CACjD;AAED,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,8CAAiB,eAAe,OAAO,SAAS;AAEtD,mCAAgB;AACd,eAAa;AACX,kBAAe,QAAQ;;IAExB,CAAC,eAAe,CAAC;AAEpB,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
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 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 * @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: AsyncDebouncerOptions<TFn>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as AsyncDebouncerOptions<TFn>\n\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 useEffect(() => {\n return () => {\n asyncDebouncer.cancel()\n }\n }, [asyncDebouncer])\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwLA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,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;AAEtD,mCAAgB;AACd,eAAa;AACX,kBAAe,QAAQ;;IAExB,CAAC,eAAe,CAAC;AAEpB,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}