@tanstack/solid-pacer 0.21.1 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/README.md +21 -6
  2. package/dist/async-batcher/createAsyncBatcher.d.ts +5 -10
  3. package/dist/async-batcher/createAsyncBatcher.js +2 -5
  4. package/dist/async-debouncer/createAsyncDebouncer.d.ts +8 -12
  5. package/dist/async-debouncer/createAsyncDebouncer.js +5 -7
  6. package/dist/async-queuer/createAsyncQueuer.d.ts +9 -12
  7. package/dist/async-queuer/createAsyncQueuer.js +4 -5
  8. package/dist/async-rate-limiter/createAsyncRateLimiter.d.ts +10 -13
  9. package/dist/async-rate-limiter/createAsyncRateLimiter.js +7 -8
  10. package/dist/async-throttler/createAsyncThrottler.d.ts +8 -14
  11. package/dist/async-throttler/createAsyncThrottler.js +5 -9
  12. package/dist/batcher/createBatcher.d.ts +11 -15
  13. package/dist/batcher/createBatcher.js +6 -8
  14. package/dist/debouncer/createDebouncedSignal.d.ts +2 -5
  15. package/dist/debouncer/createDebouncedSignal.js +1 -2
  16. package/dist/debouncer/createDebouncedValue.d.ts +2 -5
  17. package/dist/debouncer/createDebouncedValue.js +1 -2
  18. package/dist/debouncer/createDebouncer.d.ts +4 -7
  19. package/dist/debouncer/createDebouncer.js +1 -2
  20. package/dist/provider/PacerProvider.d.ts +6 -9
  21. package/dist/provider/PacerProvider.js +1 -2
  22. package/dist/queuer/createQueuedSignal.d.ts +2 -5
  23. package/dist/queuer/createQueuedSignal.js +1 -2
  24. package/dist/queuer/createQueuer.d.ts +4 -7
  25. package/dist/queuer/createQueuer.js +1 -2
  26. package/dist/rate-limiter/createRateLimitedSignal.d.ts +12 -14
  27. package/dist/rate-limiter/createRateLimitedSignal.js +11 -11
  28. package/dist/rate-limiter/createRateLimitedValue.d.ts +2 -5
  29. package/dist/rate-limiter/createRateLimitedValue.js +1 -2
  30. package/dist/rate-limiter/createRateLimiter.d.ts +8 -10
  31. package/dist/rate-limiter/createRateLimiter.js +5 -5
  32. package/dist/throttler/createThrottledSignal.d.ts +2 -7
  33. package/dist/throttler/createThrottledSignal.js +1 -4
  34. package/dist/throttler/createThrottledValue.d.ts +2 -7
  35. package/dist/throttler/createThrottledValue.js +1 -4
  36. package/dist/throttler/createThrottler.d.ts +4 -9
  37. package/dist/throttler/createThrottler.js +1 -4
  38. package/package.json +24 -68
  39. package/dist/async-batcher/createAsyncBatcher.cjs +0 -166
  40. package/dist/async-batcher/createAsyncBatcher.cjs.map +0 -1
  41. package/dist/async-batcher/createAsyncBatcher.d.cts +0 -178
  42. package/dist/async-batcher/createAsyncBatcher.js.map +0 -1
  43. package/dist/async-batcher/index.cjs +0 -11
  44. package/dist/async-batcher/index.d.cts +0 -3
  45. package/dist/async-debouncer/createAsyncDebouncer.cjs +0 -151
  46. package/dist/async-debouncer/createAsyncDebouncer.cjs.map +0 -1
  47. package/dist/async-debouncer/createAsyncDebouncer.d.cts +0 -164
  48. package/dist/async-debouncer/createAsyncDebouncer.js.map +0 -1
  49. package/dist/async-debouncer/index.cjs +0 -11
  50. package/dist/async-debouncer/index.d.cts +0 -3
  51. package/dist/async-queuer/createAsyncQueuer.cjs +0 -158
  52. package/dist/async-queuer/createAsyncQueuer.cjs.map +0 -1
  53. package/dist/async-queuer/createAsyncQueuer.d.cts +0 -170
  54. package/dist/async-queuer/createAsyncQueuer.js.map +0 -1
  55. package/dist/async-queuer/index.cjs +0 -11
  56. package/dist/async-queuer/index.d.cts +0 -3
  57. package/dist/async-rate-limiter/createAsyncRateLimiter.cjs +0 -193
  58. package/dist/async-rate-limiter/createAsyncRateLimiter.cjs.map +0 -1
  59. package/dist/async-rate-limiter/createAsyncRateLimiter.d.cts +0 -209
  60. package/dist/async-rate-limiter/createAsyncRateLimiter.js.map +0 -1
  61. package/dist/async-rate-limiter/index.cjs +0 -11
  62. package/dist/async-rate-limiter/index.d.cts +0 -3
  63. package/dist/async-throttler/createAsyncThrottler.cjs +0 -151
  64. package/dist/async-throttler/createAsyncThrottler.cjs.map +0 -1
  65. package/dist/async-throttler/createAsyncThrottler.d.cts +0 -164
  66. package/dist/async-throttler/createAsyncThrottler.js.map +0 -1
  67. package/dist/async-throttler/index.cjs +0 -11
  68. package/dist/async-throttler/index.d.cts +0 -3
  69. package/dist/batcher/createBatcher.cjs +0 -132
  70. package/dist/batcher/createBatcher.cjs.map +0 -1
  71. package/dist/batcher/createBatcher.d.cts +0 -147
  72. package/dist/batcher/createBatcher.js.map +0 -1
  73. package/dist/batcher/index.cjs +0 -11
  74. package/dist/batcher/index.d.cts +0 -3
  75. package/dist/debouncer/createDebouncedSignal.cjs +0 -88
  76. package/dist/debouncer/createDebouncedSignal.cjs.map +0 -1
  77. package/dist/debouncer/createDebouncedSignal.d.cts +0 -80
  78. package/dist/debouncer/createDebouncedSignal.js.map +0 -1
  79. package/dist/debouncer/createDebouncedValue.cjs +0 -77
  80. package/dist/debouncer/createDebouncedValue.cjs.map +0 -1
  81. package/dist/debouncer/createDebouncedValue.d.cts +0 -71
  82. package/dist/debouncer/createDebouncedValue.js.map +0 -1
  83. package/dist/debouncer/createDebouncer.cjs +0 -129
  84. package/dist/debouncer/createDebouncer.cjs.map +0 -1
  85. package/dist/debouncer/createDebouncer.d.cts +0 -145
  86. package/dist/debouncer/createDebouncer.js.map +0 -1
  87. package/dist/debouncer/index.cjs +0 -15
  88. package/dist/debouncer/index.d.cts +0 -5
  89. package/dist/index.cjs +0 -47
  90. package/dist/index.d.cts +0 -20
  91. package/dist/provider/PacerProvider.cjs +0 -27
  92. package/dist/provider/PacerProvider.cjs.map +0 -1
  93. package/dist/provider/PacerProvider.d.cts +0 -29
  94. package/dist/provider/PacerProvider.js.map +0 -1
  95. package/dist/provider/index.cjs +0 -6
  96. package/dist/provider/index.d.cts +0 -2
  97. package/dist/queuer/createQueuedSignal.cjs +0 -129
  98. package/dist/queuer/createQueuedSignal.cjs.map +0 -1
  99. package/dist/queuer/createQueuedSignal.d.cts +0 -122
  100. package/dist/queuer/createQueuedSignal.js.map +0 -1
  101. package/dist/queuer/createQueuer.cjs +0 -133
  102. package/dist/queuer/createQueuer.cjs.map +0 -1
  103. package/dist/queuer/createQueuer.d.cts +0 -148
  104. package/dist/queuer/createQueuer.js.map +0 -1
  105. package/dist/queuer/index.cjs +0 -13
  106. package/dist/queuer/index.d.cts +0 -4
  107. package/dist/rate-limiter/createRateLimitedSignal.cjs +0 -102
  108. package/dist/rate-limiter/createRateLimitedSignal.cjs.map +0 -1
  109. package/dist/rate-limiter/createRateLimitedSignal.d.cts +0 -94
  110. package/dist/rate-limiter/createRateLimitedSignal.js.map +0 -1
  111. package/dist/rate-limiter/createRateLimitedValue.cjs +0 -102
  112. package/dist/rate-limiter/createRateLimitedValue.cjs.map +0 -1
  113. package/dist/rate-limiter/createRateLimitedValue.d.cts +0 -96
  114. package/dist/rate-limiter/createRateLimitedValue.js.map +0 -1
  115. package/dist/rate-limiter/createRateLimiter.cjs +0 -157
  116. package/dist/rate-limiter/createRateLimiter.cjs.map +0 -1
  117. package/dist/rate-limiter/createRateLimiter.d.cts +0 -174
  118. package/dist/rate-limiter/createRateLimiter.js.map +0 -1
  119. package/dist/rate-limiter/index.cjs +0 -15
  120. package/dist/rate-limiter/index.d.cts +0 -5
  121. package/dist/throttler/createThrottledSignal.cjs +0 -79
  122. package/dist/throttler/createThrottledSignal.cjs.map +0 -1
  123. package/dist/throttler/createThrottledSignal.d.cts +0 -71
  124. package/dist/throttler/createThrottledSignal.js.map +0 -1
  125. package/dist/throttler/createThrottledValue.cjs +0 -74
  126. package/dist/throttler/createThrottledValue.cjs.map +0 -1
  127. package/dist/throttler/createThrottledValue.d.cts +0 -68
  128. package/dist/throttler/createThrottledValue.js.map +0 -1
  129. package/dist/throttler/createThrottler.cjs +0 -132
  130. package/dist/throttler/createThrottler.cjs.map +0 -1
  131. package/dist/throttler/createThrottler.d.cts +0 -148
  132. package/dist/throttler/createThrottler.js.map +0 -1
  133. package/dist/throttler/index.cjs +0 -15
  134. package/dist/throttler/index.d.cts +0 -5
  135. package/dist/types/index.cjs +0 -9
  136. package/dist/types/index.d.cts +0 -1
  137. package/dist/utils/index.cjs +0 -9
  138. package/dist/utils/index.d.cts +0 -1
  139. package/src/async-batcher/createAsyncBatcher.ts +0 -234
  140. package/src/async-batcher/index.ts +0 -3
  141. package/src/async-debouncer/createAsyncDebouncer.ts +0 -225
  142. package/src/async-debouncer/index.ts +0 -4
  143. package/src/async-queuer/createAsyncQueuer.ts +0 -226
  144. package/src/async-queuer/index.ts +0 -3
  145. package/src/async-rate-limiter/createAsyncRateLimiter.ts +0 -269
  146. package/src/async-rate-limiter/index.ts +0 -4
  147. package/src/async-throttler/createAsyncThrottler.ts +0 -225
  148. package/src/async-throttler/index.ts +0 -4
  149. package/src/batcher/createBatcher.ts +0 -199
  150. package/src/batcher/index.ts +0 -3
  151. package/src/debouncer/createDebouncedSignal.ts +0 -92
  152. package/src/debouncer/createDebouncedValue.ts +0 -85
  153. package/src/debouncer/createDebouncer.ts +0 -201
  154. package/src/debouncer/index.ts +0 -6
  155. package/src/index.ts +0 -46
  156. package/src/provider/PacerProvider.tsx +0 -63
  157. package/src/provider/index.ts +0 -1
  158. package/src/queuer/createQueuedSignal.ts +0 -138
  159. package/src/queuer/createQueuer.ts +0 -199
  160. package/src/queuer/index.ts +0 -4
  161. package/src/rate-limiter/createRateLimitedSignal.ts +0 -117
  162. package/src/rate-limiter/createRateLimitedValue.ts +0 -110
  163. package/src/rate-limiter/createRateLimiter.ts +0 -226
  164. package/src/rate-limiter/index.ts +0 -5
  165. package/src/throttler/createThrottledSignal.ts +0 -81
  166. package/src/throttler/createThrottledValue.ts +0 -82
  167. package/src/throttler/createThrottler.ts +0 -204
  168. package/src/throttler/index.ts +0 -6
  169. package/src/types/index.ts +0 -1
  170. package/src/utils/index.ts +0 -1
@@ -1,132 +0,0 @@
1
- const require_PacerProvider = require('../provider/PacerProvider.cjs');
2
- let solid_js = require("solid-js");
3
- let _tanstack_solid_store = require("@tanstack/solid-store");
4
- let _tanstack_pacer_throttler = require("@tanstack/pacer/throttler");
5
-
6
- //#region src/throttler/createThrottler.ts
7
- /**
8
- * A low-level Solid hook that creates a `Throttler` instance that limits how often the provided function can execute.
9
- *
10
- * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that
11
- * you can integrate with any state management solution (createSignal, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that
12
- * integrates directly with Solid's createSignal, see createThrottledSignal.
13
- *
14
- * Throttling ensures a function executes at most once within a specified time window,
15
- * regardless of how many times it is called. This is useful for rate-limiting
16
- * expensive operations or UI updates.
17
- *
18
- * ## State Management and Selector
19
- *
20
- * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
21
- * in two ways:
22
- *
23
- * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**
24
- *
25
- * Use the `Subscribe` component to subscribe to state changes deep in your component tree without
26
- * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
27
- * in child components.
28
- *
29
- * **2. Using the `selector` parameter (For hook-level subscriptions)**
30
- *
31
- * The `selector` parameter allows you to specify which state changes will trigger reactive updates
32
- * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant
33
- * state changes occur.
34
- *
35
- * **By default, there will be no reactive state subscriptions** and you must opt-in to state
36
- * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary
37
- * updates and gives you full control over when your component tracks state changes.
38
- *
39
- * Available state properties:
40
- * - `canLeadingExecute`: Whether the throttler can execute on the leading edge
41
- * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge
42
- * - `executionCount`: Number of function executions that have been completed
43
- * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
44
- * - `lastArgs`: The arguments from the most recent call to maybeExecute
45
- * - `lastExecutionTime`: Timestamp of the last execution
46
- * - `nextExecutionTime`: Timestamp of the next allowed execution
47
- * - `status`: Current execution status ('disabled' | 'idle' | 'pending')
48
- *
49
- * ## Unmount behavior
50
- *
51
- * By default, the primitive cancels any pending execution when the owning component unmounts.
52
- * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
53
- *
54
- * ```tsx
55
- * const throttler = createThrottler(fn, {
56
- * wait: 1000,
57
- * onUnmount: (t) => t.flush()
58
- * });
59
- * ```
60
- *
61
- * @example
62
- * ```tsx
63
- * // Default behavior - no reactive state subscriptions
64
- * const throttler = createThrottler(setValue, { wait: 1000 });
65
- *
66
- * // Subscribe to state changes deep in component tree using Subscribe component
67
- * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
68
- * {(state) => (
69
- * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>
70
- * )}
71
- * </throttler.Subscribe>
72
- *
73
- * // Opt-in to track isPending changes at hook level (optimized for loading states)
74
- * const throttler = createThrottler(
75
- * setValue,
76
- * { wait: 1000 },
77
- * (state) => ({ isPending: state.isPending })
78
- * );
79
- *
80
- * // Opt-in to track executionCount changes (optimized for tracking execution)
81
- * const throttler = createThrottler(
82
- * setValue,
83
- * { wait: 1000 },
84
- * (state) => ({ executionCount: state.executionCount })
85
- * );
86
- *
87
- * // Multiple state properties - track when any of these change
88
- * const throttler = createThrottler(
89
- * setValue,
90
- * {
91
- * wait: 2000,
92
- * leading: true, // Execute immediately on first call
93
- * trailing: false // Skip trailing edge updates
94
- * },
95
- * (state) => ({
96
- * isPending: state.isPending,
97
- * executionCount: state.executionCount,
98
- * lastExecutionTime: state.lastExecutionTime,
99
- * nextExecutionTime: state.nextExecutionTime
100
- * })
101
- * );
102
- *
103
- * // Access the selected state (will be empty object {} unless selector provided)
104
- * const { isPending, executionCount } = throttler.state();
105
- * ```
106
- */
107
- function createThrottler(fn, options, selector = () => ({})) {
108
- const mergedOptions = {
109
- ...require_PacerProvider.useDefaultPacerOptions().throttler,
110
- ...options
111
- };
112
- const asyncThrottler = new _tanstack_pacer_throttler.Throttler(fn, mergedOptions);
113
- asyncThrottler.Subscribe = function Subscribe(props) {
114
- const selected = (0, _tanstack_solid_store.useSelector)(asyncThrottler.store, props.selector, { compare: _tanstack_solid_store.shallow });
115
- return typeof props.children === "function" ? props.children(selected) : props.children;
116
- };
117
- const state = (0, _tanstack_solid_store.useSelector)(asyncThrottler.store, selector, { compare: _tanstack_solid_store.shallow });
118
- (0, solid_js.createEffect)(() => {
119
- (0, solid_js.onCleanup)(() => {
120
- if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncThrottler);
121
- else asyncThrottler.cancel();
122
- });
123
- });
124
- return {
125
- ...asyncThrottler,
126
- state
127
- };
128
- }
129
-
130
- //#endregion
131
- exports.createThrottler = createThrottler;
132
- //# sourceMappingURL=createThrottler.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createThrottler.cjs","names":["useDefaultPacerOptions","Throttler","shallow"],"sources":["../../src/throttler/createThrottler.ts"],"sourcesContent":["import { Throttler } from '@tanstack/pacer/throttler'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { shallow, useSelector } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface SolidThrottlerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends ThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidThrottler<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Throttler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<ThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates a `Throttler` instance that limits how often the provided function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that\n * integrates directly with Solid's createSignal, see createThrottledSignal.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\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 `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const throttler = createThrottler(setValue, { wait: 1000 });\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n *\n * // Opt-in to track isPending changes at hook level (optimized for loading states)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to track executionCount changes (optimized for tracking execution)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const throttler = createThrottler(\n * setValue,\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, executionCount } = throttler.state();\n * ```\n */\nexport function createThrottler<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidThrottlerOptions<TFn, TSelected>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().throttler,\n ...options,\n } as SolidThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new Throttler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncThrottler.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidThrottler<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8JA,SAAgB,gBACd,IACA,SACA,kBAA6D,EAAE,GAC/B;CAChC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAIC,oCACzB,IACA,cACD;CAED,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,kDAAuB,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,eAAe,OAAO,UAAU,EACxD,SAASA,+BACV,CAAC;CAEF,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAEvC,eAAe,QAAQ;IAEzB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"}
@@ -1,148 +0,0 @@
1
- import { Store } from "@tanstack/solid-store";
2
- import { Accessor, JSX } from "solid-js";
3
- import { AnyFunction } from "@tanstack/pacer/types";
4
- import { Throttler, ThrottlerOptions, ThrottlerState } from "@tanstack/pacer/throttler";
5
-
6
- //#region src/throttler/createThrottler.d.ts
7
- interface SolidThrottlerOptions<TFn extends AnyFunction, TSelected = {}> extends ThrottlerOptions<TFn> {
8
- /**
9
- * Optional callback invoked when the owning component unmounts. Receives the throttler instance.
10
- * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.
11
- */
12
- onUnmount?: (throttler: SolidThrottler<TFn, TSelected>) => void;
13
- }
14
- interface SolidThrottler<TFn extends AnyFunction, TSelected = {}> extends Omit<Throttler<TFn>, 'store'> {
15
- /**
16
- * A Solid component that allows you to subscribe to the throttler state.
17
- *
18
- * This is useful for tracking specific parts of the throttler state
19
- * deep in your component tree without needing to pass a selector to the hook.
20
- *
21
- * @example
22
- * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
23
- * {(state) => (
24
- * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>
25
- * )}
26
- * </throttler.Subscribe>
27
- */
28
- Subscribe: <TSelected>(props: {
29
- selector: (state: ThrottlerState<TFn>) => TSelected;
30
- children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element;
31
- }) => JSX.Element;
32
- /**
33
- * Reactive state that will be updated when the throttler state changes
34
- *
35
- * Use this instead of `throttler.store.state`
36
- */
37
- readonly state: Accessor<Readonly<TSelected>>;
38
- /**
39
- * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.
40
- * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
41
- * Although, you can make the state reactive by using the `useSelector` in your own usage.
42
- */
43
- readonly store: Store<Readonly<ThrottlerState<TFn>>>;
44
- }
45
- /**
46
- * A low-level Solid hook that creates a `Throttler` instance that limits how often the provided function can execute.
47
- *
48
- * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that
49
- * you can integrate with any state management solution (createSignal, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that
50
- * integrates directly with Solid's createSignal, see createThrottledSignal.
51
- *
52
- * Throttling ensures a function executes at most once within a specified time window,
53
- * regardless of how many times it is called. This is useful for rate-limiting
54
- * expensive operations or UI updates.
55
- *
56
- * ## State Management and Selector
57
- *
58
- * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
59
- * in two ways:
60
- *
61
- * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**
62
- *
63
- * Use the `Subscribe` component to subscribe to state changes deep in your component tree without
64
- * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
65
- * in child components.
66
- *
67
- * **2. Using the `selector` parameter (For hook-level subscriptions)**
68
- *
69
- * The `selector` parameter allows you to specify which state changes will trigger reactive updates
70
- * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant
71
- * state changes occur.
72
- *
73
- * **By default, there will be no reactive state subscriptions** and you must opt-in to state
74
- * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary
75
- * updates and gives you full control over when your component tracks state changes.
76
- *
77
- * Available state properties:
78
- * - `canLeadingExecute`: Whether the throttler can execute on the leading edge
79
- * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge
80
- * - `executionCount`: Number of function executions that have been completed
81
- * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
82
- * - `lastArgs`: The arguments from the most recent call to maybeExecute
83
- * - `lastExecutionTime`: Timestamp of the last execution
84
- * - `nextExecutionTime`: Timestamp of the next allowed execution
85
- * - `status`: Current execution status ('disabled' | 'idle' | 'pending')
86
- *
87
- * ## Unmount behavior
88
- *
89
- * By default, the primitive cancels any pending execution when the owning component unmounts.
90
- * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
91
- *
92
- * ```tsx
93
- * const throttler = createThrottler(fn, {
94
- * wait: 1000,
95
- * onUnmount: (t) => t.flush()
96
- * });
97
- * ```
98
- *
99
- * @example
100
- * ```tsx
101
- * // Default behavior - no reactive state subscriptions
102
- * const throttler = createThrottler(setValue, { wait: 1000 });
103
- *
104
- * // Subscribe to state changes deep in component tree using Subscribe component
105
- * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
106
- * {(state) => (
107
- * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>
108
- * )}
109
- * </throttler.Subscribe>
110
- *
111
- * // Opt-in to track isPending changes at hook level (optimized for loading states)
112
- * const throttler = createThrottler(
113
- * setValue,
114
- * { wait: 1000 },
115
- * (state) => ({ isPending: state.isPending })
116
- * );
117
- *
118
- * // Opt-in to track executionCount changes (optimized for tracking execution)
119
- * const throttler = createThrottler(
120
- * setValue,
121
- * { wait: 1000 },
122
- * (state) => ({ executionCount: state.executionCount })
123
- * );
124
- *
125
- * // Multiple state properties - track when any of these change
126
- * const throttler = createThrottler(
127
- * setValue,
128
- * {
129
- * wait: 2000,
130
- * leading: true, // Execute immediately on first call
131
- * trailing: false // Skip trailing edge updates
132
- * },
133
- * (state) => ({
134
- * isPending: state.isPending,
135
- * executionCount: state.executionCount,
136
- * lastExecutionTime: state.lastExecutionTime,
137
- * nextExecutionTime: state.nextExecutionTime
138
- * })
139
- * );
140
- *
141
- * // Access the selected state (will be empty object {} unless selector provided)
142
- * const { isPending, executionCount } = throttler.state();
143
- * ```
144
- */
145
- declare function createThrottler<TFn extends AnyFunction, TSelected = {}>(fn: TFn, options: SolidThrottlerOptions<TFn, TSelected>, selector?: (state: ThrottlerState<TFn>) => TSelected): SolidThrottler<TFn, TSelected>;
146
- //#endregion
147
- export { SolidThrottler, SolidThrottlerOptions, createThrottler };
148
- //# sourceMappingURL=createThrottler.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createThrottler.js","names":[],"sources":["../../src/throttler/createThrottler.ts"],"sourcesContent":["import { Throttler } from '@tanstack/pacer/throttler'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { shallow, useSelector } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface SolidThrottlerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends ThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidThrottler<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Throttler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<ThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates a `Throttler` instance that limits how often the provided function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that\n * integrates directly with Solid's createSignal, see createThrottledSignal.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\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 `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const throttler = createThrottler(setValue, { wait: 1000 });\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n *\n * // Opt-in to track isPending changes at hook level (optimized for loading states)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to track executionCount changes (optimized for tracking execution)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const throttler = createThrottler(\n * setValue,\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, executionCount } = throttler.state();\n * ```\n */\nexport function createThrottler<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidThrottlerOptions<TFn, TSelected>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().throttler,\n ...options,\n } as SolidThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new Throttler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncThrottler.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidThrottler<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8JA,SAAgB,gBACd,IACA,SACA,kBAA6D,EAAE,GAC/B;CAChC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAI,UACzB,IACA,cACD;CAED,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,SACV,CAAC;CAEF,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAEvC,eAAe,QAAQ;IAEzB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"}
@@ -1,15 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_createThrottler = require('./createThrottler.cjs');
3
- const require_createThrottledSignal = require('./createThrottledSignal.cjs');
4
- const require_createThrottledValue = require('./createThrottledValue.cjs');
5
-
6
- exports.createThrottledSignal = require_createThrottledSignal.createThrottledSignal;
7
- exports.createThrottledValue = require_createThrottledValue.createThrottledValue;
8
- exports.createThrottler = require_createThrottler.createThrottler;
9
- var _tanstack_pacer_throttler = require("@tanstack/pacer/throttler");
10
- Object.keys(_tanstack_pacer_throttler).forEach(function (k) {
11
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
12
- enumerable: true,
13
- get: function () { return _tanstack_pacer_throttler[k]; }
14
- });
15
- });
@@ -1,5 +0,0 @@
1
- import { SolidThrottler, SolidThrottlerOptions, createThrottler } from "./createThrottler.cjs";
2
- import { createThrottledSignal } from "./createThrottledSignal.cjs";
3
- import { createThrottledValue } from "./createThrottledValue.cjs";
4
- export * from "@tanstack/pacer/throttler";
5
- export { SolidThrottler, SolidThrottlerOptions, createThrottledSignal, createThrottledValue, createThrottler };
@@ -1,9 +0,0 @@
1
-
2
-
3
- var _tanstack_pacer_types = require("@tanstack/pacer/types");
4
- Object.keys(_tanstack_pacer_types).forEach(function (k) {
5
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
6
- enumerable: true,
7
- get: function () { return _tanstack_pacer_types[k]; }
8
- });
9
- });
@@ -1 +0,0 @@
1
- export * from "@tanstack/pacer/types";
@@ -1,9 +0,0 @@
1
-
2
-
3
- var _tanstack_pacer_utils = require("@tanstack/pacer/utils");
4
- Object.keys(_tanstack_pacer_utils).forEach(function (k) {
5
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
6
- enumerable: true,
7
- get: function () { return _tanstack_pacer_utils[k]; }
8
- });
9
- });
@@ -1 +0,0 @@
1
- export * from "@tanstack/pacer/utils";
@@ -1,234 +0,0 @@
1
- import { AsyncBatcher } from '@tanstack/pacer/async-batcher'
2
- import { shallow, useSelector } from '@tanstack/solid-store'
3
- import { createEffect, onCleanup } from 'solid-js'
4
- import { useDefaultPacerOptions } from '../provider/PacerProvider'
5
- import type { Store } from '@tanstack/solid-store'
6
- import type { Accessor, JSX } from 'solid-js'
7
- import type {
8
- AsyncBatcherOptions,
9
- AsyncBatcherState,
10
- } from '@tanstack/pacer/async-batcher'
11
-
12
- export interface SolidAsyncBatcherOptions<
13
- TValue,
14
- TSelected = {},
15
- > extends AsyncBatcherOptions<TValue> {
16
- /**
17
- * Optional callback invoked when the owning component unmounts. Receives the batcher instance.
18
- * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.
19
- */
20
- onUnmount?: (batcher: SolidAsyncBatcher<TValue, TSelected>) => void
21
- }
22
-
23
- export interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<
24
- AsyncBatcher<TValue>,
25
- 'store'
26
- > {
27
- /**
28
- * A Solid component that allows you to subscribe to the batcher state.
29
- *
30
- * This is useful for tracking specific parts of the batcher state
31
- * deep in your component tree without needing to pass a selector to the hook.
32
- *
33
- * @example
34
- * <batcher.Subscribe selector={(state) => ({ size: state.size, isExecuting: state.isExecuting })}>
35
- * {(state) => (
36
- * <div>Batch: {state().size} items, {state().isExecuting ? 'Executing...' : 'Idle'}</div>
37
- * )}
38
- * </batcher.Subscribe>
39
- */
40
- Subscribe: <TSelected>(props: {
41
- selector: (state: AsyncBatcherState<TValue>) => TSelected
42
- children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element
43
- }) => JSX.Element
44
- /**
45
- * Reactive state that will be updated when the batcher state changes
46
- *
47
- * Use this instead of `batcher.store.state`
48
- */
49
- readonly state: Accessor<Readonly<TSelected>>
50
- /**
51
- * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.
52
- * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
53
- * Although, you can make the state reactive by using the `useSelector` in your own usage.
54
- */
55
- readonly store: Store<Readonly<AsyncBatcherState<TValue>>>
56
- }
57
-
58
- /**
59
- * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.
60
- *
61
- * This is the async version of the createBatcher hook. Unlike the sync version, this async batcher:
62
- * - Handles promises and returns results from batch executions
63
- * - Provides error handling with configurable error behavior
64
- * - Tracks success, error, and settle counts separately
65
- * - Has state tracking for when batches are executing
66
- * - Returns the result of the batch function execution
67
- *
68
- * Features:
69
- * - Configurable batch size and wait time
70
- * - Custom batch processing logic via getShouldExecute
71
- * - Event callbacks for monitoring batch operations
72
- * - Error handling for failed batch operations
73
- * - Automatic or manual batch processing
74
- * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity
75
- *
76
- * The batcher collects items and processes them in batches based on:
77
- * - Maximum batch size (number of items per batch)
78
- * - Time-based batching (process after X milliseconds)
79
- * - Custom batch processing logic via getShouldExecute
80
- *
81
- * Error Handling:
82
- * - If an `onError` handler is provided, it will be called with the error and batcher instance
83
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
84
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
85
- * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown
86
- * - The error state can be checked using the underlying AsyncBatcher instance
87
- *
88
- * ## State Management and Selector
89
- *
90
- * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
91
- * in two ways:
92
- *
93
- * **1. Using `batcher.Subscribe` component (Recommended for component tree subscriptions)**
94
- *
95
- * Use the `Subscribe` component to subscribe to state changes deep in your component tree without
96
- * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
97
- * in child components.
98
- *
99
- * **2. Using the `selector` parameter (For hook-level subscriptions)**
100
- *
101
- * The `selector` parameter allows you to specify which state changes will trigger reactive updates
102
- * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant
103
- * state changes occur.
104
- *
105
- * **By default, there will be no reactive state subscriptions** and you must opt-in to state
106
- * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary
107
- * updates and gives you full control over when your component tracks state changes.
108
- *
109
- * Available state properties:
110
- * - `errorCount`: Number of failed batch executions
111
- * - `executionCount`: Total number of batch execution attempts (successful + failed)
112
- * - `hasError`: Whether the last batch execution resulted in an error
113
- * - `isExecuting`: Whether a batch execution is currently in progress
114
- * - `items`: Array of items currently queued for batching
115
- * - `lastError`: The error from the most recent failed batch execution (if any)
116
- * - `lastResult`: The result from the most recent successful batch execution
117
- * - `settleCount`: Number of batch executions that have completed (successful or failed)
118
- * - `successCount`: Number of successful batch executions
119
- *
120
- * ## Unmount behavior
121
- *
122
- * By default, the primitive cancels any pending batch and aborts any in-flight execution when the owning component unmounts.
123
- * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
124
- * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
125
- *
126
- * ```tsx
127
- * const batcher = createAsyncBatcher(fn, {
128
- * maxSize: 10,
129
- * wait: 2000,
130
- * onUnmount: (b) => b.flush()
131
- * });
132
- * ```
133
- *
134
- * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
135
- * If your batch function updates Solid signals, those updates may run after the component has
136
- * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
137
- * using onUnmount with flush.
138
- *
139
- * Example usage:
140
- * ```tsx
141
- * // Default behavior - no reactive state subscriptions
142
- * const asyncBatcher = createAsyncBatcher(
143
- * async (items) => {
144
- * const results = await Promise.all(items.map(item => processItem(item)));
145
- * return results;
146
- * },
147
- * {
148
- * maxSize: 10,
149
- * wait: 2000,
150
- * onSuccess: (result) => {
151
- * console.log('Batch processed successfully:', result);
152
- * },
153
- * onError: (error) => {
154
- * console.error('Batch processing failed:', error);
155
- * }
156
- * }
157
- * );
158
- *
159
- * // Opt-in to track items or isExecuting changes (optimized for UI updates)
160
- * const asyncBatcher = createAsyncBatcher(
161
- * async (items) => {
162
- * const results = await Promise.all(items.map(item => processItem(item)));
163
- * return results;
164
- * },
165
- * { maxSize: 10, wait: 2000 },
166
- * (state) => ({ items: state.items, isExecuting: state.isExecuting })
167
- * );
168
- *
169
- * // Opt-in to track error state changes (optimized for error handling)
170
- * const asyncBatcher = createAsyncBatcher(
171
- * async (items) => {
172
- * const results = await Promise.all(items.map(item => processItem(item)));
173
- * return results;
174
- * },
175
- * { maxSize: 10, wait: 2000 },
176
- * (state) => ({ hasError: state.hasError, lastError: state.lastError })
177
- * );
178
- *
179
- * // Add items to batch
180
- * asyncBatcher.addItem(newItem);
181
- *
182
- * // Manually execute batch
183
- * const result = await asyncBatcher.execute();
184
- *
185
- * // Access the selected state (will be empty object {} unless selector provided)
186
- * const { items, isExecuting } = asyncBatcher.state();
187
- * ```
188
- */
189
- export function createAsyncBatcher<TValue, TSelected = {}>(
190
- fn: (items: Array<TValue>) => Promise<any>,
191
- options: SolidAsyncBatcherOptions<TValue, TSelected> = {},
192
- selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>
193
- ({}) as TSelected,
194
- ): SolidAsyncBatcher<TValue, TSelected> {
195
- const mergedOptions = {
196
- ...useDefaultPacerOptions().asyncBatcher,
197
- ...options,
198
- } as SolidAsyncBatcherOptions<TValue, TSelected>
199
- const asyncBatcher = new AsyncBatcher<TValue>(
200
- fn,
201
- mergedOptions,
202
- ) as unknown as SolidAsyncBatcher<TValue, TSelected>
203
-
204
- asyncBatcher.Subscribe = function Subscribe<TSelected>(props: {
205
- selector: (state: AsyncBatcherState<TValue>) => TSelected
206
- children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element
207
- }) {
208
- const selected = useSelector(asyncBatcher.store, props.selector, {
209
- compare: shallow,
210
- })
211
-
212
- return typeof props.children === 'function'
213
- ? props.children(selected)
214
- : props.children
215
- }
216
-
217
- const state = useSelector(asyncBatcher.store, selector, { compare: shallow })
218
-
219
- createEffect(() => {
220
- onCleanup(() => {
221
- if (mergedOptions.onUnmount) {
222
- mergedOptions.onUnmount(asyncBatcher)
223
- } else {
224
- asyncBatcher.cancel()
225
- asyncBatcher.abort()
226
- }
227
- })
228
- })
229
-
230
- return {
231
- ...asyncBatcher,
232
- state,
233
- } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`
234
- }
@@ -1,3 +0,0 @@
1
- export * from '@tanstack/pacer/async-batcher'
2
-
3
- export * from './createAsyncBatcher'