@tanstack/preact-pacer 0.18.0 → 0.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/async-batcher/index.cjs +3 -3
- package/dist/async-batcher/index.d.cts +2 -2
- package/dist/async-batcher/index.d.ts +2 -2
- package/dist/async-batcher/useAsyncBatcher.cjs +35 -11
- package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -1
- package/dist/async-batcher/useAsyncBatcher.d.cts +45 -10
- package/dist/async-batcher/useAsyncBatcher.d.ts +45 -10
- package/dist/async-batcher/useAsyncBatcher.js +32 -8
- package/dist/async-batcher/useAsyncBatcher.js.map +1 -1
- package/dist/async-debouncer/index.cjs +3 -3
- package/dist/async-debouncer/index.d.cts +2 -2
- package/dist/async-debouncer/index.d.ts +2 -2
- package/dist/async-debouncer/useAsyncDebouncer.cjs +35 -11
- package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -1
- package/dist/async-debouncer/useAsyncDebouncer.d.cts +45 -10
- package/dist/async-debouncer/useAsyncDebouncer.d.ts +45 -10
- package/dist/async-debouncer/useAsyncDebouncer.js +32 -8
- package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -1
- package/dist/async-queuer/index.cjs +3 -3
- package/dist/async-queuer/index.d.cts +2 -2
- package/dist/async-queuer/index.d.ts +2 -2
- package/dist/async-queuer/useAsyncQueuedState.cjs.map +1 -1
- package/dist/async-queuer/useAsyncQueuedState.d.cts +2 -2
- package/dist/async-queuer/useAsyncQueuedState.d.ts +2 -2
- package/dist/async-queuer/useAsyncQueuedState.js.map +1 -1
- package/dist/async-queuer/useAsyncQueuer.cjs +35 -11
- package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -1
- package/dist/async-queuer/useAsyncQueuer.d.cts +45 -10
- package/dist/async-queuer/useAsyncQueuer.d.ts +45 -10
- package/dist/async-queuer/useAsyncQueuer.js +32 -8
- package/dist/async-queuer/useAsyncQueuer.js.map +1 -1
- package/dist/async-rate-limiter/index.cjs +3 -3
- package/dist/async-rate-limiter/index.d.cts +2 -2
- package/dist/async-rate-limiter/index.d.ts +2 -2
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +35 -11
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +45 -10
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +45 -10
- package/dist/async-rate-limiter/useAsyncRateLimiter.js +32 -8
- package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -1
- package/dist/async-retryer/index.cjs +3 -3
- package/dist/async-throttler/index.cjs +3 -3
- package/dist/async-throttler/index.d.cts +2 -2
- package/dist/async-throttler/index.d.ts +2 -2
- package/dist/async-throttler/useAsyncThrottler.cjs +35 -11
- package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -1
- package/dist/async-throttler/useAsyncThrottler.d.cts +45 -10
- package/dist/async-throttler/useAsyncThrottler.d.ts +45 -10
- package/dist/async-throttler/useAsyncThrottler.js +32 -8
- package/dist/async-throttler/useAsyncThrottler.js.map +1 -1
- package/dist/batcher/index.cjs +3 -3
- package/dist/batcher/useBatcher.cjs +35 -11
- package/dist/batcher/useBatcher.cjs.map +1 -1
- package/dist/batcher/useBatcher.d.cts +42 -7
- package/dist/batcher/useBatcher.d.ts +42 -7
- package/dist/batcher/useBatcher.js +32 -8
- package/dist/batcher/useBatcher.js.map +1 -1
- package/dist/debouncer/index.cjs +3 -3
- package/dist/debouncer/useDebouncer.cjs +35 -11
- package/dist/debouncer/useDebouncer.cjs.map +1 -1
- package/dist/debouncer/useDebouncer.d.cts +42 -7
- package/dist/debouncer/useDebouncer.d.ts +42 -7
- package/dist/debouncer/useDebouncer.js +32 -8
- package/dist/debouncer/useDebouncer.js.map +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/provider/PacerProvider.d.cts +1 -1
- package/dist/queuer/index.cjs +3 -3
- package/dist/queuer/useQueuer.cjs +35 -11
- package/dist/queuer/useQueuer.cjs.map +1 -1
- package/dist/queuer/useQueuer.d.cts +42 -7
- package/dist/queuer/useQueuer.d.ts +42 -7
- package/dist/queuer/useQueuer.js +32 -8
- package/dist/queuer/useQueuer.js.map +1 -1
- package/dist/rate-limiter/index.cjs +3 -3
- package/dist/rate-limiter/useRateLimiter.cjs +35 -11
- package/dist/rate-limiter/useRateLimiter.cjs.map +1 -1
- package/dist/rate-limiter/useRateLimiter.d.cts +42 -7
- package/dist/rate-limiter/useRateLimiter.d.ts +42 -7
- package/dist/rate-limiter/useRateLimiter.js +32 -8
- package/dist/rate-limiter/useRateLimiter.js.map +1 -1
- package/dist/throttler/index.cjs +3 -3
- package/dist/throttler/useThrottler.cjs +35 -11
- package/dist/throttler/useThrottler.cjs.map +1 -1
- package/dist/throttler/useThrottler.d.cts +42 -7
- package/dist/throttler/useThrottler.d.ts +42 -7
- package/dist/throttler/useThrottler.js +32 -8
- package/dist/throttler/useThrottler.js.map +1 -1
- package/dist/types/index.cjs +3 -3
- package/dist/utils/index.cjs +3 -3
- package/package.json +3 -3
- package/src/async-batcher/useAsyncBatcher.ts +64 -13
- package/src/async-debouncer/useAsyncDebouncer.ts +64 -13
- package/src/async-queuer/useAsyncQueuedState.ts +2 -2
- package/src/async-queuer/useAsyncQueuer.ts +64 -13
- package/src/async-rate-limiter/useAsyncRateLimiter.ts +64 -13
- package/src/async-throttler/useAsyncThrottler.ts +64 -13
- package/src/batcher/useBatcher.ts +61 -8
- package/src/debouncer/useDebouncer.ts +61 -8
- package/src/queuer/useQueuer.ts +61 -8
- package/src/rate-limiter/useRateLimiter.ts +61 -8
- package/src/throttler/useThrottler.ts +61 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useQueuer.js","names":[],"sources":["../../src/queuer/useQueuer.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { Queuer } from '@tanstack/pacer/queuer'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'\n\nexport interface PreactQueuer<TValue, TSelected = {}> extends Omit<\n Queuer<TValue>,\n 'store'\n> {\n /**\n * Reactive state that will be updated and re-rendered when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<QueuerState<TValue>>>\n}\n\n/**\n * A Preact hook that creates and manages a Queuer instance.\n *\n * This is a lower-level hook that provides direct access to the Queuer's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (useState, Redux, Zustand, etc.) by utilizing the onItemsChange callback.\n *\n * For a hook with built-in state management, see useQueuedState.\n *\n * The Queuer extends the base Queue to add processing capabilities. Items are processed\n * synchronously in order, with optional delays between processing each item. The queuer includes\n * an internal tick mechanism that can be started and stopped, making it useful as a scheduler.\n * When started, it will process one item per tick, with an optional wait time between ticks.\n *\n * By default uses FIFO (First In First Out) behavior, but can be configured for LIFO\n * (Last In First Out) by specifying 'front' position when adding items.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
|
|
1
|
+
{"version":3,"file":"useQueuer.js","names":[],"sources":["../../src/queuer/useQueuer.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { Queuer } from '@tanstack/pacer/queuer'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactQueuer<TValue, TSelected = {}> extends Omit<\n Queuer<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the queuer state.\n *\n * This is useful for opting into state re-renders for specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Queue Size: {size}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: QueuerState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<QueuerState<TValue>>>\n}\n\n/**\n * A Preact hook that creates and manages a Queuer instance.\n *\n * This is a lower-level hook that provides direct access to the Queuer's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (useState, Redux, Zustand, etc.) by utilizing the onItemsChange callback.\n *\n * For a hook with built-in state management, see useQueuedState.\n *\n * The Queuer extends the base Queue to add processing capabilities. Items are processed\n * synchronously in order, with optional delays between processing each item. The queuer includes\n * an internal tick mechanism that can be started and stopped, making it useful as a scheduler.\n * When started, it will process one item per tick, with an optional wait time between ticks.\n *\n * By default uses FIFO (First In First Out) behavior, but can be configured for LIFO\n * (Last In First Out) by specifying 'front' position when adding items.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `queuer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `executionCount`: Number of items that have been processed by the queuer\n * - `expirationCount`: Number of items that have been removed due to expiration\n * - `isEmpty`: Whether the queuer has no items to process\n * - `isFull`: Whether the queuer has reached its maximum capacity\n * - `isIdle`: Whether the queuer is not currently processing any items\n * - `isRunning`: Whether the queuer is active and will process items automatically\n * - `items`: Array of items currently waiting to be processed\n * - `itemTimestamps`: Timestamps when items were added for expiration tracking\n * - `pendingTick`: Whether the queuer has a pending timeout for processing the next item\n * - `rejectionCount`: Number of items that have been rejected from being added\n * - `size`: Number of items currently in the queue\n * - `status`: Current processing status ('idle' | 'running' | 'stopped')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const queue = useQueuer(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <queue.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Queue Size: {size}</div>\n * )}\n * </queue.Subscribe>\n *\n * // Opt-in to re-render when queue size changes at hook level (optimized for displaying queue length)\n * const queue = useQueuer(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * size: state.size,\n * isEmpty: state.isEmpty,\n * isFull: state.isFull\n * })\n * );\n *\n * // Opt-in to re-render when processing state changes (optimized for loading indicators)\n * const queue = useQueuer(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * isRunning: state.isRunning,\n * isIdle: state.isIdle,\n * status: state.status,\n * pendingTick: state.pendingTick\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const queue = useQueuer(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * expirationCount: state.expirationCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Example with custom state management and scheduling\n * const [items, setItems] = useState([]);\n *\n * const queue = useQueuer(\n * (item) => console.log('Processing:', item),\n * {\n * started: true, // Start processing immediately\n * wait: 1000, // Process one item every second\n * onItemsChange: (queue) => setItems(queue.peekAllItems()),\n * getPriority: (item) => item.priority // Process higher priority items first\n * }\n * );\n *\n * // Add items to process - they'll be handled automatically\n * queue.addItem('task1');\n * queue.addItem('task2');\n *\n * // Control the scheduler\n * queue.stop(); // Pause processing\n * queue.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { size, isRunning, executionCount } = queue.state;\n * ```\n */\nexport function useQueuer<TValue, TSelected = {}>(\n fn: (item: TValue) => void,\n options: QueuerOptions<TValue> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): PreactQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().queuer,\n ...options,\n } as QueuerOptions<TValue>\n\n const [queuer] = useState(() => {\n const queuerInstance = new Queuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactQueuer<TValue, TSelected>\n\n queuerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: QueuerState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(queuerInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return queuerInstance\n })\n\n queuer.fn = fn\n queuer.setOptions(mergedOptions)\n\n const state = useStore(queuer.store, selector)\n\n return useMemo(\n () =>\n ({\n ...queuer,\n state,\n }) as PreactQueuer<TValue, TSelected>, // omit `store` in favor of `state`\n [queuer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyKA,SAAgB,UACd,IACA,UAAiC,EAAE,EACnC,kBAA6D,EAAE,GAC9B;CACjC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,UAAU,eAAe;EAC9B,MAAM,iBAAiB,IAAI,OACzB,IACA,cACD;AAED,iBAAe,YAAY,SAAS,UAAqB,OAGtD;GACD,MAAM,WAAW,SAAS,eAAe,OAAO,MAAM,SAAS;AAE/D,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,QAAO,KAAK;AACZ,QAAO,WAAW,cAAc;CAEhC,MAAM,QAAQ,SAAS,OAAO,OAAO,SAAS;AAE9C,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,QAAQ,MAAM,CAChB"}
|
|
@@ -7,10 +7,10 @@ exports.useRateLimitedCallback = require_useRateLimitedCallback.useRateLimitedCa
|
|
|
7
7
|
exports.useRateLimitedState = require_useRateLimitedState.useRateLimitedState;
|
|
8
8
|
exports.useRateLimitedValue = require_useRateLimitedValue.useRateLimitedValue;
|
|
9
9
|
exports.useRateLimiter = require_useRateLimiter.useRateLimiter;
|
|
10
|
-
var
|
|
11
|
-
Object.keys(
|
|
10
|
+
var _tanstack_pacer_rate_limiter = require("@tanstack/pacer/rate-limiter");
|
|
11
|
+
Object.keys(_tanstack_pacer_rate_limiter).forEach(function (k) {
|
|
12
12
|
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
13
13
|
enumerable: true,
|
|
14
|
-
get: function () { return
|
|
14
|
+
get: function () { return _tanstack_pacer_rate_limiter[k]; }
|
|
15
15
|
});
|
|
16
16
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const require_PacerProvider = require('../provider/PacerProvider.cjs');
|
|
2
2
|
let preact_hooks = require("preact/hooks");
|
|
3
|
-
let
|
|
4
|
-
let
|
|
3
|
+
let _tanstack_preact_store = require("@tanstack/preact-store");
|
|
4
|
+
let _tanstack_pacer_rate_limiter = require("@tanstack/pacer/rate-limiter");
|
|
5
5
|
|
|
6
6
|
//#region src/rate-limiter/useRateLimiter.ts
|
|
7
7
|
/**
|
|
@@ -27,14 +27,24 @@ let __tanstack_pacer_rate_limiter = require("@tanstack/pacer/rate-limiter");
|
|
|
27
27
|
*
|
|
28
28
|
* ## State Management and Selector
|
|
29
29
|
*
|
|
30
|
-
* The hook uses TanStack Store for reactive state management.
|
|
31
|
-
*
|
|
32
|
-
*
|
|
30
|
+
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
31
|
+
* in two ways:
|
|
32
|
+
*
|
|
33
|
+
* **1. Using `rateLimiter.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
34
|
+
*
|
|
35
|
+
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
36
|
+
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
37
|
+
* in child components.
|
|
38
|
+
*
|
|
39
|
+
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
40
|
+
*
|
|
41
|
+
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
42
|
+
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
43
|
+
* state changes occur.
|
|
33
44
|
*
|
|
34
45
|
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
35
|
-
* tracking by providing a selector function. This prevents unnecessary
|
|
36
|
-
* full control over when your component updates.
|
|
37
|
-
* component re-render when the selected state values change.
|
|
46
|
+
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
47
|
+
* re-renders and gives you full control over when your component updates.
|
|
38
48
|
*
|
|
39
49
|
* Available state properties:
|
|
40
50
|
* - `executionCount`: Number of function executions that have been completed
|
|
@@ -57,7 +67,14 @@ let __tanstack_pacer_rate_limiter = require("@tanstack/pacer/rate-limiter");
|
|
|
57
67
|
* windowType: 'sliding',
|
|
58
68
|
* });
|
|
59
69
|
*
|
|
60
|
-
* //
|
|
70
|
+
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
71
|
+
* <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
|
|
72
|
+
* {({ rejectionCount }) => (
|
|
73
|
+
* <div>Rejections: {rejectionCount}</div>
|
|
74
|
+
* )}
|
|
75
|
+
* </rateLimiter.Subscribe>
|
|
76
|
+
*
|
|
77
|
+
* // Opt-in to re-render when execution count changes at hook level (optimized for tracking successful executions)
|
|
61
78
|
* const rateLimiter = useRateLimiter(
|
|
62
79
|
* apiCall,
|
|
63
80
|
* {
|
|
@@ -123,10 +140,17 @@ function useRateLimiter(fn, options, selector = () => ({})) {
|
|
|
123
140
|
...require_PacerProvider.useDefaultPacerOptions().rateLimiter,
|
|
124
141
|
...options
|
|
125
142
|
};
|
|
126
|
-
const [rateLimiter] = (0, preact_hooks.useState)(() =>
|
|
143
|
+
const [rateLimiter] = (0, preact_hooks.useState)(() => {
|
|
144
|
+
const rateLimiterInstance = new _tanstack_pacer_rate_limiter.RateLimiter(fn, mergedOptions);
|
|
145
|
+
rateLimiterInstance.Subscribe = function Subscribe(props) {
|
|
146
|
+
const selected = (0, _tanstack_preact_store.useStore)(rateLimiterInstance.store, props.selector);
|
|
147
|
+
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
148
|
+
};
|
|
149
|
+
return rateLimiterInstance;
|
|
150
|
+
});
|
|
127
151
|
rateLimiter.fn = fn;
|
|
128
152
|
rateLimiter.setOptions(mergedOptions);
|
|
129
|
-
const state = (0,
|
|
153
|
+
const state = (0, _tanstack_preact_store.useStore)(rateLimiter.store, selector);
|
|
130
154
|
return (0, preact_hooks.useMemo)(() => ({
|
|
131
155
|
...rateLimiter,
|
|
132
156
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRateLimiter.cjs","names":["useDefaultPacerOptions","RateLimiter"],"sources":["../../src/rate-limiter/useRateLimiter.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\nimport type { AnyFunction } from '@tanstack/pacer/types'\n\nexport interface PreactRateLimiter<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<RateLimiter<TFn>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<RateLimiterState>>\n}\n\n/**\n * A low-level Preact hook that creates a `RateLimiter` instance to enforce rate limits on function execution.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Rate limiting is a simple \"hard limit\" approach that allows executions until a maximum count is reached within\n * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,\n * it does not attempt to space out or collapse executions intelligently.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * For smoother execution patterns:\n * - Use throttling when you want consistent spacing between executions (e.g. UI updates)\n * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)\n * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
|
|
1
|
+
{"version":3,"file":"useRateLimiter.cjs","names":["useDefaultPacerOptions","RateLimiter"],"sources":["../../src/rate-limiter/useRateLimiter.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactRateLimiter<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<RateLimiter<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the rate limiter state.\n *\n * This is useful for opting into state re-renders for specific parts of the rate limiter state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {({ rejectionCount }) => (\n * <div>Rejections: {rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: RateLimiterState) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<RateLimiterState>>\n}\n\n/**\n * A low-level Preact hook that creates a `RateLimiter` instance to enforce rate limits on function execution.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Rate limiting is a simple \"hard limit\" approach that allows executions until a maximum count is reached within\n * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,\n * it does not attempt to space out or collapse executions intelligently.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * For smoother execution patterns:\n * - Use throttling when you want consistent spacing between executions (e.g. UI updates)\n * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)\n * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)\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 `rateLimiter.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 * - `executionCount`: Number of function executions that have been completed\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n *\n * The hook returns an object containing:\n * - maybeExecute: The rate-limited function that respects the configured limits\n * - getExecutionCount: Returns the number of successful executions\n * - getRejectionCount: Returns the number of rejected executions due to rate limiting\n * - getRemainingInWindow: Returns how many more executions are allowed in the current window\n * - reset: Resets the execution counts and window timing\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const rateLimiter = useRateLimiter(apiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * });\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {({ rejectionCount }) => (\n * <div>Rejections: {rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n *\n * // Opt-in to re-render when execution count changes at hook level (optimized for tracking successful executions)\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // Multiple state properties - re-render when any of these change\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Monitor rate limit status\n * const handleClick = () => {\n * const remaining = rateLimiter.getRemainingInWindow();\n * if (remaining > 0) {\n * rateLimiter.maybeExecute(data);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state;\n * ```\n */\nexport function useRateLimiter<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: RateLimiterOptions<TFn>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): PreactRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as RateLimiterOptions<TFn>\n\n const [rateLimiter] = useState(() => {\n const rateLimiterInstance = new RateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactRateLimiter<TFn, TSelected>\n\n rateLimiterInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: RateLimiterState) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(rateLimiterInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return rateLimiterInstance\n })\n\n rateLimiter.fn = fn\n rateLimiter.setOptions(mergedOptions)\n\n const state = useStore(rateLimiter.store, selector)\n\n return useMemo(\n () =>\n ({\n ...rateLimiter,\n state,\n }) as PreactRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`\n [rateLimiter, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkLA,SAAgB,eACd,IACA,SACA,kBAA0D,EAAE,GACzB;CACnC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,gDAA8B;EACnC,MAAM,sBAAsB,IAAIC,yCAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,gDAAoB,oBAAoB,OAAO,MAAM,SAAS;AAEpE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;CAErC,MAAM,6CAAiB,YAAY,OAAO,SAAS;AAEnD,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
|
@@ -1,9 +1,27 @@
|
|
|
1
1
|
import { Store } from "@tanstack/preact-store";
|
|
2
|
+
import { ComponentChildren } from "preact";
|
|
2
3
|
import { AnyFunction } from "@tanstack/pacer/types";
|
|
3
4
|
import { RateLimiter, RateLimiterOptions, RateLimiterState } from "@tanstack/pacer/rate-limiter";
|
|
4
5
|
|
|
5
6
|
//#region src/rate-limiter/useRateLimiter.d.ts
|
|
6
7
|
interface PreactRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omit<RateLimiter<TFn>, 'store'> {
|
|
8
|
+
/**
|
|
9
|
+
* A Preact HOC (Higher Order Component) that allows you to subscribe to the rate limiter state.
|
|
10
|
+
*
|
|
11
|
+
* This is useful for opting into state re-renders for specific parts of the rate limiter state
|
|
12
|
+
* deep in your component tree without needing to pass a selector to the hook.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
|
|
16
|
+
* {({ rejectionCount }) => (
|
|
17
|
+
* <div>Rejections: {rejectionCount}</div>
|
|
18
|
+
* )}
|
|
19
|
+
* </rateLimiter.Subscribe>
|
|
20
|
+
*/
|
|
21
|
+
Subscribe: <TSelected>(props: {
|
|
22
|
+
selector: (state: RateLimiterState) => TSelected;
|
|
23
|
+
children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
|
|
24
|
+
}) => ComponentChildren;
|
|
7
25
|
/**
|
|
8
26
|
* Reactive state that will be updated and re-rendered when the rate limiter state changes
|
|
9
27
|
*
|
|
@@ -40,14 +58,24 @@ interface PreactRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omi
|
|
|
40
58
|
*
|
|
41
59
|
* ## State Management and Selector
|
|
42
60
|
*
|
|
43
|
-
* The hook uses TanStack Store for reactive state management.
|
|
44
|
-
*
|
|
45
|
-
*
|
|
61
|
+
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
62
|
+
* in two ways:
|
|
63
|
+
*
|
|
64
|
+
* **1. Using `rateLimiter.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
65
|
+
*
|
|
66
|
+
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
67
|
+
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
68
|
+
* in child components.
|
|
69
|
+
*
|
|
70
|
+
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
71
|
+
*
|
|
72
|
+
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
73
|
+
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
74
|
+
* state changes occur.
|
|
46
75
|
*
|
|
47
76
|
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
48
|
-
* tracking by providing a selector function. This prevents unnecessary
|
|
49
|
-
* full control over when your component updates.
|
|
50
|
-
* component re-render when the selected state values change.
|
|
77
|
+
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
78
|
+
* re-renders and gives you full control over when your component updates.
|
|
51
79
|
*
|
|
52
80
|
* Available state properties:
|
|
53
81
|
* - `executionCount`: Number of function executions that have been completed
|
|
@@ -70,7 +98,14 @@ interface PreactRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omi
|
|
|
70
98
|
* windowType: 'sliding',
|
|
71
99
|
* });
|
|
72
100
|
*
|
|
73
|
-
* //
|
|
101
|
+
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
102
|
+
* <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
|
|
103
|
+
* {({ rejectionCount }) => (
|
|
104
|
+
* <div>Rejections: {rejectionCount}</div>
|
|
105
|
+
* )}
|
|
106
|
+
* </rateLimiter.Subscribe>
|
|
107
|
+
*
|
|
108
|
+
* // Opt-in to re-render when execution count changes at hook level (optimized for tracking successful executions)
|
|
74
109
|
* const rateLimiter = useRateLimiter(
|
|
75
110
|
* apiCall,
|
|
76
111
|
* {
|
|
@@ -1,9 +1,27 @@
|
|
|
1
|
+
import { ComponentChildren } from "preact";
|
|
1
2
|
import { Store } from "@tanstack/preact-store";
|
|
2
3
|
import { RateLimiter, RateLimiterOptions, RateLimiterState } from "@tanstack/pacer/rate-limiter";
|
|
3
4
|
import { AnyFunction } from "@tanstack/pacer/types";
|
|
4
5
|
|
|
5
6
|
//#region src/rate-limiter/useRateLimiter.d.ts
|
|
6
7
|
interface PreactRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omit<RateLimiter<TFn>, 'store'> {
|
|
8
|
+
/**
|
|
9
|
+
* A Preact HOC (Higher Order Component) that allows you to subscribe to the rate limiter state.
|
|
10
|
+
*
|
|
11
|
+
* This is useful for opting into state re-renders for specific parts of the rate limiter state
|
|
12
|
+
* deep in your component tree without needing to pass a selector to the hook.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
|
|
16
|
+
* {({ rejectionCount }) => (
|
|
17
|
+
* <div>Rejections: {rejectionCount}</div>
|
|
18
|
+
* )}
|
|
19
|
+
* </rateLimiter.Subscribe>
|
|
20
|
+
*/
|
|
21
|
+
Subscribe: <TSelected>(props: {
|
|
22
|
+
selector: (state: RateLimiterState) => TSelected;
|
|
23
|
+
children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
|
|
24
|
+
}) => ComponentChildren;
|
|
7
25
|
/**
|
|
8
26
|
* Reactive state that will be updated and re-rendered when the rate limiter state changes
|
|
9
27
|
*
|
|
@@ -40,14 +58,24 @@ interface PreactRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omi
|
|
|
40
58
|
*
|
|
41
59
|
* ## State Management and Selector
|
|
42
60
|
*
|
|
43
|
-
* The hook uses TanStack Store for reactive state management.
|
|
44
|
-
*
|
|
45
|
-
*
|
|
61
|
+
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
62
|
+
* in two ways:
|
|
63
|
+
*
|
|
64
|
+
* **1. Using `rateLimiter.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
65
|
+
*
|
|
66
|
+
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
67
|
+
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
68
|
+
* in child components.
|
|
69
|
+
*
|
|
70
|
+
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
71
|
+
*
|
|
72
|
+
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
73
|
+
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
74
|
+
* state changes occur.
|
|
46
75
|
*
|
|
47
76
|
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
48
|
-
* tracking by providing a selector function. This prevents unnecessary
|
|
49
|
-
* full control over when your component updates.
|
|
50
|
-
* component re-render when the selected state values change.
|
|
77
|
+
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
78
|
+
* re-renders and gives you full control over when your component updates.
|
|
51
79
|
*
|
|
52
80
|
* Available state properties:
|
|
53
81
|
* - `executionCount`: Number of function executions that have been completed
|
|
@@ -70,7 +98,14 @@ interface PreactRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omi
|
|
|
70
98
|
* windowType: 'sliding',
|
|
71
99
|
* });
|
|
72
100
|
*
|
|
73
|
-
* //
|
|
101
|
+
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
102
|
+
* <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
|
|
103
|
+
* {({ rejectionCount }) => (
|
|
104
|
+
* <div>Rejections: {rejectionCount}</div>
|
|
105
|
+
* )}
|
|
106
|
+
* </rateLimiter.Subscribe>
|
|
107
|
+
*
|
|
108
|
+
* // Opt-in to re-render when execution count changes at hook level (optimized for tracking successful executions)
|
|
74
109
|
* const rateLimiter = useRateLimiter(
|
|
75
110
|
* apiCall,
|
|
76
111
|
* {
|
|
@@ -27,14 +27,24 @@ import { RateLimiter } from "@tanstack/pacer/rate-limiter";
|
|
|
27
27
|
*
|
|
28
28
|
* ## State Management and Selector
|
|
29
29
|
*
|
|
30
|
-
* The hook uses TanStack Store for reactive state management.
|
|
31
|
-
*
|
|
32
|
-
*
|
|
30
|
+
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
31
|
+
* in two ways:
|
|
32
|
+
*
|
|
33
|
+
* **1. Using `rateLimiter.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
34
|
+
*
|
|
35
|
+
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
36
|
+
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
37
|
+
* in child components.
|
|
38
|
+
*
|
|
39
|
+
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
40
|
+
*
|
|
41
|
+
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
42
|
+
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
43
|
+
* state changes occur.
|
|
33
44
|
*
|
|
34
45
|
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
35
|
-
* tracking by providing a selector function. This prevents unnecessary
|
|
36
|
-
* full control over when your component updates.
|
|
37
|
-
* component re-render when the selected state values change.
|
|
46
|
+
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
47
|
+
* re-renders and gives you full control over when your component updates.
|
|
38
48
|
*
|
|
39
49
|
* Available state properties:
|
|
40
50
|
* - `executionCount`: Number of function executions that have been completed
|
|
@@ -57,7 +67,14 @@ import { RateLimiter } from "@tanstack/pacer/rate-limiter";
|
|
|
57
67
|
* windowType: 'sliding',
|
|
58
68
|
* });
|
|
59
69
|
*
|
|
60
|
-
* //
|
|
70
|
+
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
71
|
+
* <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
|
|
72
|
+
* {({ rejectionCount }) => (
|
|
73
|
+
* <div>Rejections: {rejectionCount}</div>
|
|
74
|
+
* )}
|
|
75
|
+
* </rateLimiter.Subscribe>
|
|
76
|
+
*
|
|
77
|
+
* // Opt-in to re-render when execution count changes at hook level (optimized for tracking successful executions)
|
|
61
78
|
* const rateLimiter = useRateLimiter(
|
|
62
79
|
* apiCall,
|
|
63
80
|
* {
|
|
@@ -123,7 +140,14 @@ function useRateLimiter(fn, options, selector = () => ({})) {
|
|
|
123
140
|
...useDefaultPacerOptions().rateLimiter,
|
|
124
141
|
...options
|
|
125
142
|
};
|
|
126
|
-
const [rateLimiter] = useState(() =>
|
|
143
|
+
const [rateLimiter] = useState(() => {
|
|
144
|
+
const rateLimiterInstance = new RateLimiter(fn, mergedOptions);
|
|
145
|
+
rateLimiterInstance.Subscribe = function Subscribe(props) {
|
|
146
|
+
const selected = useStore(rateLimiterInstance.store, props.selector);
|
|
147
|
+
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
148
|
+
};
|
|
149
|
+
return rateLimiterInstance;
|
|
150
|
+
});
|
|
127
151
|
rateLimiter.fn = fn;
|
|
128
152
|
rateLimiter.setOptions(mergedOptions);
|
|
129
153
|
const state = useStore(rateLimiter.store, selector);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRateLimiter.js","names":[],"sources":["../../src/rate-limiter/useRateLimiter.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\nimport type { AnyFunction } from '@tanstack/pacer/types'\n\nexport interface PreactRateLimiter<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<RateLimiter<TFn>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<RateLimiterState>>\n}\n\n/**\n * A low-level Preact hook that creates a `RateLimiter` instance to enforce rate limits on function execution.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Rate limiting is a simple \"hard limit\" approach that allows executions until a maximum count is reached within\n * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,\n * it does not attempt to space out or collapse executions intelligently.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * For smoother execution patterns:\n * - Use throttling when you want consistent spacing between executions (e.g. UI updates)\n * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)\n * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
|
|
1
|
+
{"version":3,"file":"useRateLimiter.js","names":[],"sources":["../../src/rate-limiter/useRateLimiter.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactRateLimiter<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<RateLimiter<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the rate limiter state.\n *\n * This is useful for opting into state re-renders for specific parts of the rate limiter state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {({ rejectionCount }) => (\n * <div>Rejections: {rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: RateLimiterState) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<RateLimiterState>>\n}\n\n/**\n * A low-level Preact hook that creates a `RateLimiter` instance to enforce rate limits on function execution.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Rate limiting is a simple \"hard limit\" approach that allows executions until a maximum count is reached within\n * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,\n * it does not attempt to space out or collapse executions intelligently.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * For smoother execution patterns:\n * - Use throttling when you want consistent spacing between executions (e.g. UI updates)\n * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)\n * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)\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 `rateLimiter.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 * - `executionCount`: Number of function executions that have been completed\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n *\n * The hook returns an object containing:\n * - maybeExecute: The rate-limited function that respects the configured limits\n * - getExecutionCount: Returns the number of successful executions\n * - getRejectionCount: Returns the number of rejected executions due to rate limiting\n * - getRemainingInWindow: Returns how many more executions are allowed in the current window\n * - reset: Resets the execution counts and window timing\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const rateLimiter = useRateLimiter(apiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * });\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {({ rejectionCount }) => (\n * <div>Rejections: {rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n *\n * // Opt-in to re-render when execution count changes at hook level (optimized for tracking successful executions)\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // Multiple state properties - re-render when any of these change\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Monitor rate limit status\n * const handleClick = () => {\n * const remaining = rateLimiter.getRemainingInWindow();\n * if (remaining > 0) {\n * rateLimiter.maybeExecute(data);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state;\n * ```\n */\nexport function useRateLimiter<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: RateLimiterOptions<TFn>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): PreactRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as RateLimiterOptions<TFn>\n\n const [rateLimiter] = useState(() => {\n const rateLimiterInstance = new RateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactRateLimiter<TFn, TSelected>\n\n rateLimiterInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: RateLimiterState) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(rateLimiterInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return rateLimiterInstance\n })\n\n rateLimiter.fn = fn\n rateLimiter.setOptions(mergedOptions)\n\n const state = useStore(rateLimiter.store, selector)\n\n return useMemo(\n () =>\n ({\n ...rateLimiter,\n state,\n }) as PreactRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`\n [rateLimiter, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkLA,SAAgB,eACd,IACA,SACA,kBAA0D,EAAE,GACzB;CACnC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,eAAe,eAAe;EACnC,MAAM,sBAAsB,IAAI,YAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,WAAW,SAAS,oBAAoB,OAAO,MAAM,SAAS;AAEpE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;CAErC,MAAM,QAAQ,SAAS,YAAY,OAAO,SAAS;AAEnD,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
package/dist/throttler/index.cjs
CHANGED
|
@@ -7,10 +7,10 @@ exports.useThrottledCallback = require_useThrottledCallback.useThrottledCallback
|
|
|
7
7
|
exports.useThrottledState = require_useThrottledState.useThrottledState;
|
|
8
8
|
exports.useThrottledValue = require_useThrottledValue.useThrottledValue;
|
|
9
9
|
exports.useThrottler = require_useThrottler.useThrottler;
|
|
10
|
-
var
|
|
11
|
-
Object.keys(
|
|
10
|
+
var _tanstack_pacer_throttler = require("@tanstack/pacer/throttler");
|
|
11
|
+
Object.keys(_tanstack_pacer_throttler).forEach(function (k) {
|
|
12
12
|
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
13
13
|
enumerable: true,
|
|
14
|
-
get: function () { return
|
|
14
|
+
get: function () { return _tanstack_pacer_throttler[k]; }
|
|
15
15
|
});
|
|
16
16
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const require_PacerProvider = require('../provider/PacerProvider.cjs');
|
|
2
2
|
let preact_hooks = require("preact/hooks");
|
|
3
|
-
let
|
|
4
|
-
let
|
|
3
|
+
let _tanstack_preact_store = require("@tanstack/preact-store");
|
|
4
|
+
let _tanstack_pacer_throttler = require("@tanstack/pacer/throttler");
|
|
5
5
|
|
|
6
6
|
//#region src/throttler/useThrottler.ts
|
|
7
7
|
/**
|
|
@@ -17,14 +17,24 @@ let __tanstack_pacer_throttler = require("@tanstack/pacer/throttler");
|
|
|
17
17
|
*
|
|
18
18
|
* ## State Management and Selector
|
|
19
19
|
*
|
|
20
|
-
* The hook uses TanStack Store for reactive state management.
|
|
21
|
-
*
|
|
22
|
-
*
|
|
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` HOC (Recommended for component tree subscriptions)**
|
|
24
|
+
*
|
|
25
|
+
* Use the `Subscribe` HOC 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 a re-render
|
|
32
|
+
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
33
|
+
* state changes occur.
|
|
23
34
|
*
|
|
24
35
|
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
25
|
-
* tracking by providing a selector function. This prevents unnecessary
|
|
26
|
-
* full control over when your component updates.
|
|
27
|
-
* component re-render when the selected state values change.
|
|
36
|
+
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
37
|
+
* re-renders and gives you full control over when your component updates.
|
|
28
38
|
*
|
|
29
39
|
* Available state properties:
|
|
30
40
|
* - `executionCount`: Number of function executions that have been completed
|
|
@@ -40,7 +50,14 @@ let __tanstack_pacer_throttler = require("@tanstack/pacer/throttler");
|
|
|
40
50
|
* const [value, setValue] = useState(0);
|
|
41
51
|
* const throttler = useThrottler(setValue, { wait: 1000 });
|
|
42
52
|
*
|
|
43
|
-
* //
|
|
53
|
+
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
54
|
+
* <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
|
|
55
|
+
* {({ isPending }) => (
|
|
56
|
+
* <div>{isPending ? 'Processing...' : 'Ready'}</div>
|
|
57
|
+
* )}
|
|
58
|
+
* </throttler.Subscribe>
|
|
59
|
+
*
|
|
60
|
+
* // Opt-in to re-render when execution count changes at hook level (optimized for tracking executions)
|
|
44
61
|
* const [value, setValue] = useState(0);
|
|
45
62
|
* const throttler = useThrottler(
|
|
46
63
|
* setValue,
|
|
@@ -89,10 +106,17 @@ function useThrottler(fn, options, selector = () => ({})) {
|
|
|
89
106
|
...require_PacerProvider.useDefaultPacerOptions().throttler,
|
|
90
107
|
...options
|
|
91
108
|
};
|
|
92
|
-
const [throttler] = (0, preact_hooks.useState)(() =>
|
|
109
|
+
const [throttler] = (0, preact_hooks.useState)(() => {
|
|
110
|
+
const throttlerInstance = new _tanstack_pacer_throttler.Throttler(fn, mergedOptions);
|
|
111
|
+
throttlerInstance.Subscribe = function Subscribe(props) {
|
|
112
|
+
const selected = (0, _tanstack_preact_store.useStore)(throttlerInstance.store, props.selector);
|
|
113
|
+
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
114
|
+
};
|
|
115
|
+
return throttlerInstance;
|
|
116
|
+
});
|
|
93
117
|
throttler.fn = fn;
|
|
94
118
|
throttler.setOptions(mergedOptions);
|
|
95
|
-
const state = (0,
|
|
119
|
+
const state = (0, _tanstack_preact_store.useStore)(throttler.store, selector);
|
|
96
120
|
(0, preact_hooks.useEffect)(() => {
|
|
97
121
|
return () => {
|
|
98
122
|
throttler.cancel();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useThrottler.cjs","names":["useDefaultPacerOptions","Throttler"],"sources":["../../src/throttler/useThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Throttler } from '@tanstack/pacer/throttler'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface PreactThrottler<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Throttler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<ThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact 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 (useState, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that\n * integrates directly with Preact's useState, see useThrottledState.\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. The `selector` parameter allows you
|
|
1
|
+
{"version":3,"file":"useThrottler.cjs","names":["useDefaultPacerOptions","Throttler"],"sources":["../../src/throttler/useThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Throttler } from '@tanstack/pacer/throttler'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactThrottler<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Throttler<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the throttler state.\n *\n * This is useful for opting into state re-renders for 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 * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<ThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact 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 (useState, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that\n * integrates directly with Preact's useState, see useThrottledState.\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` 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 * - `executionCount`: Number of function executions that have been completed\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(setValue, { wait: 1000 });\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Processing...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n *\n * // Opt-in to re-render when execution count changes at hook level (optimized for tracking executions)\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to re-render when throttling state changes (optimized for loading indicators)\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With any state manager\n * const throttler = useThrottler(\n * (value) => stateManager.setState(value),\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, isPending } = throttler.state;\n * ```\n */\nexport function useThrottler<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: ThrottlerOptions<TFn>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): PreactThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().throttler,\n ...options,\n } as ThrottlerOptions<TFn>\n\n const [throttler] = useState(() => {\n const throttlerInstance = new Throttler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactThrottler<TFn, TSelected>\n\n throttlerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(throttlerInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return throttlerInstance\n })\n\n throttler.fn = fn\n throttler.setOptions(mergedOptions)\n\n const state = useStore(throttler.store, selector)\n\n useEffect(() => {\n return () => {\n throttler.cancel()\n }\n }, [throttler])\n\n return useMemo(\n () =>\n ({\n ...throttler,\n state,\n }) as PreactThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [throttler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgJA,SAAgB,aACd,IACA,SACA,kBAA6D,EAAE,GAC9B;CACjC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,8CAA4B;EACjC,MAAM,oBAAoB,IAAIC,oCAC5B,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,WAAU,KAAK;AACf,WAAU,WAAW,cAAc;CAEnC,MAAM,6CAAiB,UAAU,OAAO,SAAS;AAEjD,mCAAgB;AACd,eAAa;AACX,aAAU,QAAQ;;IAEnB,CAAC,UAAU,CAAC;AAEf,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,WAAW,MAAM,CACnB"}
|