@tanstack/preact-pacer 0.21.1 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/async-batcher/useAsyncBatcher.cjs +2 -2
- package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -1
- package/dist/async-batcher/useAsyncBatcher.d.cts +2 -2
- package/dist/async-batcher/useAsyncBatcher.d.ts +2 -2
- package/dist/async-batcher/useAsyncBatcher.js +3 -3
- package/dist/async-batcher/useAsyncBatcher.js.map +1 -1
- package/dist/async-debouncer/useAsyncDebouncer.cjs +2 -2
- package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -1
- package/dist/async-debouncer/useAsyncDebouncer.d.cts +2 -2
- package/dist/async-debouncer/useAsyncDebouncer.d.ts +2 -2
- package/dist/async-debouncer/useAsyncDebouncer.js +3 -3
- package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -1
- package/dist/async-queuer/useAsyncQueuer.cjs +2 -2
- package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -1
- package/dist/async-queuer/useAsyncQueuer.d.cts +2 -2
- package/dist/async-queuer/useAsyncQueuer.d.ts +2 -2
- package/dist/async-queuer/useAsyncQueuer.js +3 -3
- package/dist/async-queuer/useAsyncQueuer.js.map +1 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +2 -2
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +2 -2
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +2 -2
- package/dist/async-rate-limiter/useAsyncRateLimiter.js +3 -3
- package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -1
- package/dist/async-throttler/useAsyncThrottler.cjs +2 -2
- package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -1
- package/dist/async-throttler/useAsyncThrottler.d.cts +2 -2
- package/dist/async-throttler/useAsyncThrottler.d.ts +2 -2
- package/dist/async-throttler/useAsyncThrottler.js +3 -3
- package/dist/async-throttler/useAsyncThrottler.js.map +1 -1
- package/dist/batcher/useBatcher.cjs +2 -2
- package/dist/batcher/useBatcher.cjs.map +1 -1
- package/dist/batcher/useBatcher.d.cts +2 -2
- package/dist/batcher/useBatcher.d.ts +2 -2
- package/dist/batcher/useBatcher.js +3 -3
- package/dist/batcher/useBatcher.js.map +1 -1
- package/dist/debouncer/useDebouncer.cjs +2 -2
- package/dist/debouncer/useDebouncer.cjs.map +1 -1
- package/dist/debouncer/useDebouncer.d.cts +2 -2
- package/dist/debouncer/useDebouncer.d.ts +2 -2
- package/dist/debouncer/useDebouncer.js +3 -3
- package/dist/debouncer/useDebouncer.js.map +1 -1
- package/dist/queuer/useQueuer.cjs +2 -2
- package/dist/queuer/useQueuer.cjs.map +1 -1
- package/dist/queuer/useQueuer.d.cts +2 -2
- package/dist/queuer/useQueuer.d.ts +2 -2
- package/dist/queuer/useQueuer.js +3 -3
- package/dist/queuer/useQueuer.js.map +1 -1
- package/dist/rate-limiter/useRateLimiter.cjs +2 -2
- package/dist/rate-limiter/useRateLimiter.cjs.map +1 -1
- package/dist/rate-limiter/useRateLimiter.d.cts +2 -2
- package/dist/rate-limiter/useRateLimiter.d.ts +2 -2
- package/dist/rate-limiter/useRateLimiter.js +3 -3
- package/dist/rate-limiter/useRateLimiter.js.map +1 -1
- package/dist/throttler/useThrottler.cjs +2 -2
- package/dist/throttler/useThrottler.cjs.map +1 -1
- package/dist/throttler/useThrottler.d.cts +2 -2
- package/dist/throttler/useThrottler.d.ts +2 -2
- package/dist/throttler/useThrottler.js +3 -3
- package/dist/throttler/useThrottler.js.map +1 -1
- package/package.json +5 -5
- package/src/async-batcher/useAsyncBatcher.ts +6 -6
- package/src/async-debouncer/useAsyncDebouncer.ts +8 -6
- package/src/async-queuer/useAsyncQueuer.ts +6 -6
- package/src/async-rate-limiter/useAsyncRateLimiter.ts +8 -6
- package/src/async-throttler/useAsyncThrottler.ts +8 -6
- package/src/batcher/useBatcher.ts +6 -6
- package/src/debouncer/useDebouncer.ts +6 -6
- package/src/queuer/useQueuer.ts +6 -6
- package/src/rate-limiter/useRateLimiter.ts +6 -6
- package/src/throttler/useThrottler.ts +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDebouncer.cjs","names":["useDefaultPacerOptions","Debouncer","shallow"],"sources":["../../src/debouncer/useDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Debouncer } from '@tanstack/pacer/debouncer'\nimport { shallow,
|
|
1
|
+
{"version":3,"file":"useDebouncer.cjs","names":["useDefaultPacerOptions","Debouncer","shallow"],"sources":["../../src/debouncer/useDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Debouncer } from '@tanstack/pacer/debouncer'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactDebouncerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends DebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: PreactDebouncer<TFn, TSelected>) => void\n}\n\nexport interface PreactDebouncer<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Debouncer<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the debouncer state.\n *\n * This is useful for opting into state re-renders for specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: DebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<DebouncerState<TFn>>>\n}\n\n/**\n * A Preact hook that creates and manages a Debouncer instance.\n *\n * This is a lower-level hook that provides direct access to the Debouncer'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.).\n *\n * This hook provides debouncing functionality to limit how often a function can be called,\n * waiting for a specified delay before executing the latest call. This is useful for handling\n * frequent events like window resizing, scroll events, or real-time search inputs.\n *\n * The debouncer will only execute the function after the specified wait time has elapsed\n * since the last call. If the function is called again before the wait time expires, the\n * timer resets and starts waiting again.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending execution when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = useDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const searchDebouncer = useDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Searching...' : 'Ready'}</div>\n * )}\n * </searchDebouncer.Subscribe>\n *\n * // Opt-in to re-render when isPending changes at hook level (optimized for loading states)\n * const searchDebouncer = useDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to re-render when executionCount changes (optimized for tracking execution)\n * const searchDebouncer = useDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - re-render when any of these change\n * const searchDebouncer = useDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * status: state.status\n * })\n * );\n *\n * // In an event handler\n * const handleChange = (e) => {\n * searchDebouncer.maybeExecute(e.target.value);\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending } = searchDebouncer.state;\n * ```\n */\nexport function useDebouncer<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: PreactDebouncerOptions<TFn, TSelected>,\n selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected,\n): PreactDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().debouncer,\n ...options,\n } as PreactDebouncerOptions<TFn, TSelected>\n const [debouncer] = useState(() => {\n const debouncerInstance = new Debouncer(\n fn,\n mergedOptions,\n ) as unknown as PreactDebouncer<TFn, TSelected>\n\n debouncerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: DebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useSelector(debouncerInstance.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return debouncerInstance\n })\n\n debouncer.fn = fn\n debouncer.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(debouncer)\n } else {\n debouncer.cancel()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(debouncer.store, selector, { compare: shallow })\n\n return useMemo(\n () =>\n ({\n ...debouncer,\n state,\n }) as PreactDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n [debouncer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkKA,SAAgB,aACd,IACA,SACA,kBAA6D,EAAE,GAC9B;CACjC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,8CAA4B;EACjC,MAAM,oBAAoB,IAAIC,oCAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,mDAAuB,kBAAkB,OAAO,MAAM,UAAU,EACpE,SAASC,gCACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,WAAU,KAAK;AACf,WAAU,WAAW,cAAc;AAGnC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,UAAU;OAElC,WAAU,QAAQ;;IAGrB,EAAE,CAAC;CAGN,MAAM,gDAAoB,UAAU,OAAO,UAAU,EAAE,SAASA,gCAAS,CAAC;AAE1E,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,WAAW,MAAM,CACnB"}
|
|
@@ -37,8 +37,8 @@ interface PreactDebouncer<TFn extends AnyFunction, TSelected = {}> extends Omit<
|
|
|
37
37
|
readonly state: Readonly<TSelected>;
|
|
38
38
|
/**
|
|
39
39
|
* @deprecated Use `debouncer.state` instead of `debouncer.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 `
|
|
41
|
-
* Although, you can make the state reactive by using the `
|
|
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
42
|
*/
|
|
43
43
|
readonly store: Store<Readonly<DebouncerState<TFn>>>;
|
|
44
44
|
}
|
|
@@ -37,8 +37,8 @@ interface PreactDebouncer<TFn extends AnyFunction, TSelected = {}> extends Omit<
|
|
|
37
37
|
readonly state: Readonly<TSelected>;
|
|
38
38
|
/**
|
|
39
39
|
* @deprecated Use `debouncer.state` instead of `debouncer.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 `
|
|
41
|
-
* Although, you can make the state reactive by using the `
|
|
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
42
|
*/
|
|
43
43
|
readonly store: Store<Readonly<DebouncerState<TFn>>>;
|
|
44
44
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
2
|
import { useEffect, useMemo, useState } from "preact/hooks";
|
|
3
|
-
import { shallow,
|
|
3
|
+
import { shallow, useSelector } from "@tanstack/preact-store";
|
|
4
4
|
import { Debouncer } from "@tanstack/pacer/debouncer";
|
|
5
5
|
|
|
6
6
|
//#region src/debouncer/useDebouncer.ts
|
|
@@ -116,7 +116,7 @@ function useDebouncer(fn, options, selector = () => ({})) {
|
|
|
116
116
|
const [debouncer] = useState(() => {
|
|
117
117
|
const debouncerInstance = new Debouncer(fn, mergedOptions);
|
|
118
118
|
debouncerInstance.Subscribe = function Subscribe(props) {
|
|
119
|
-
const selected =
|
|
119
|
+
const selected = useSelector(debouncerInstance.store, props.selector, { compare: shallow });
|
|
120
120
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
121
121
|
};
|
|
122
122
|
return debouncerInstance;
|
|
@@ -129,7 +129,7 @@ function useDebouncer(fn, options, selector = () => ({})) {
|
|
|
129
129
|
else debouncer.cancel();
|
|
130
130
|
};
|
|
131
131
|
}, []);
|
|
132
|
-
const state =
|
|
132
|
+
const state = useSelector(debouncer.store, selector, { compare: shallow });
|
|
133
133
|
return useMemo(() => ({
|
|
134
134
|
...debouncer,
|
|
135
135
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDebouncer.js","names":[],"sources":["../../src/debouncer/useDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Debouncer } from '@tanstack/pacer/debouncer'\nimport { shallow,
|
|
1
|
+
{"version":3,"file":"useDebouncer.js","names":[],"sources":["../../src/debouncer/useDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Debouncer } from '@tanstack/pacer/debouncer'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactDebouncerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends DebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: PreactDebouncer<TFn, TSelected>) => void\n}\n\nexport interface PreactDebouncer<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Debouncer<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the debouncer state.\n *\n * This is useful for opting into state re-renders for specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: DebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<DebouncerState<TFn>>>\n}\n\n/**\n * A Preact hook that creates and manages a Debouncer instance.\n *\n * This is a lower-level hook that provides direct access to the Debouncer'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.).\n *\n * This hook provides debouncing functionality to limit how often a function can be called,\n * waiting for a specified delay before executing the latest call. This is useful for handling\n * frequent events like window resizing, scroll events, or real-time search inputs.\n *\n * The debouncer will only execute the function after the specified wait time has elapsed\n * since the last call. If the function is called again before the wait time expires, the\n * timer resets and starts waiting again.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending execution when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = useDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const searchDebouncer = useDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Searching...' : 'Ready'}</div>\n * )}\n * </searchDebouncer.Subscribe>\n *\n * // Opt-in to re-render when isPending changes at hook level (optimized for loading states)\n * const searchDebouncer = useDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to re-render when executionCount changes (optimized for tracking execution)\n * const searchDebouncer = useDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - re-render when any of these change\n * const searchDebouncer = useDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * status: state.status\n * })\n * );\n *\n * // In an event handler\n * const handleChange = (e) => {\n * searchDebouncer.maybeExecute(e.target.value);\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending } = searchDebouncer.state;\n * ```\n */\nexport function useDebouncer<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: PreactDebouncerOptions<TFn, TSelected>,\n selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected,\n): PreactDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().debouncer,\n ...options,\n } as PreactDebouncerOptions<TFn, TSelected>\n const [debouncer] = useState(() => {\n const debouncerInstance = new Debouncer(\n fn,\n mergedOptions,\n ) as unknown as PreactDebouncer<TFn, TSelected>\n\n debouncerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: DebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useSelector(debouncerInstance.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return debouncerInstance\n })\n\n debouncer.fn = fn\n debouncer.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(debouncer)\n } else {\n debouncer.cancel()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(debouncer.store, selector, { compare: shallow })\n\n return useMemo(\n () =>\n ({\n ...debouncer,\n state,\n }) as PreactDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n [debouncer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkKA,SAAgB,aACd,IACA,SACA,kBAA6D,EAAE,GAC9B;CACjC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,aAAa,eAAe;EACjC,MAAM,oBAAoB,IAAI,UAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,WAAW,YAAY,kBAAkB,OAAO,MAAM,UAAU,EACpE,SAAS,SACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,WAAU,KAAK;AACf,WAAU,WAAW,cAAc;AAGnC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,UAAU;OAElC,WAAU,QAAQ;;IAGrB,EAAE,CAAC;CAGN,MAAM,QAAQ,YAAY,UAAU,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;AAE1E,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,WAAW,MAAM,CACnB"}
|
|
@@ -151,7 +151,7 @@ function useQueuer(fn, options = {}, selector = () => ({})) {
|
|
|
151
151
|
const [queuer] = (0, preact_hooks.useState)(() => {
|
|
152
152
|
const queuerInstance = new _tanstack_pacer_queuer.Queuer(fn, mergedOptions);
|
|
153
153
|
queuerInstance.Subscribe = function Subscribe(props) {
|
|
154
|
-
const selected = (0, _tanstack_preact_store.
|
|
154
|
+
const selected = (0, _tanstack_preact_store.useSelector)(queuerInstance.store, props.selector, { compare: _tanstack_preact_store.shallow });
|
|
155
155
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
156
156
|
};
|
|
157
157
|
return queuerInstance;
|
|
@@ -164,7 +164,7 @@ function useQueuer(fn, options = {}, selector = () => ({})) {
|
|
|
164
164
|
else queuer.stop();
|
|
165
165
|
};
|
|
166
166
|
}, []);
|
|
167
|
-
const state = (0, _tanstack_preact_store.
|
|
167
|
+
const state = (0, _tanstack_preact_store.useSelector)(queuer.store, selector, { compare: _tanstack_preact_store.shallow });
|
|
168
168
|
return (0, preact_hooks.useMemo)(() => ({
|
|
169
169
|
...queuer,
|
|
170
170
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useQueuer.cjs","names":["useDefaultPacerOptions","Queuer","shallow"],"sources":["../../src/queuer/useQueuer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Queuer } from '@tanstack/pacer/queuer'\nimport { shallow, 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 PreactQueuerOptions<\n TValue,\n TSelected = {},\n> extends QueuerOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: PreactQueuer<TValue, TSelected>) => void\n}\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 * ## Unmount behavior\n *\n * By default, the hook stops the queuer when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queue = useQueuer(fn, {\n * started: true,\n * wait: 1000,\n * onUnmount: (q) => q.flush()\n * });\n * ```\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: PreactQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): PreactQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().queuer,\n ...options,\n } as PreactQueuerOptions<TValue, TSelected>\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 equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return queuerInstance\n })\n\n queuer.fn = fn\n queuer.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(queuer)\n } else {\n queuer.stop()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(queuer.store, selector, { equal: shallow })\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiMA,SAAgB,UACd,IACA,UAAkD,EAAE,EACpD,kBAA6D,EAAE,GAC9B;CACjC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,2CAAyB;EAC9B,MAAM,iBAAiB,IAAIC,8BACzB,IACA,cACD;AAED,iBAAe,YAAY,SAAS,UAAqB,OAGtD;GACD,MAAM,gDAAoB,eAAe,OAAO,MAAM,UAAU,EAC9D,OAAOC,gCACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,QAAO,KAAK;AACZ,QAAO,WAAW,cAAc;AAGhC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,OAAO;OAE/B,QAAO,MAAM;;IAGhB,EAAE,CAAC;CAGN,MAAM,6CAAiB,OAAO,OAAO,UAAU,EAAE,OAAOA,gCAAS,CAAC;AAElE,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,QAAQ,MAAM,CAChB"}
|
|
1
|
+
{"version":3,"file":"useQueuer.cjs","names":["useDefaultPacerOptions","Queuer","shallow"],"sources":["../../src/queuer/useQueuer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Queuer } from '@tanstack/pacer/queuer'\nimport { shallow, useSelector } 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 PreactQueuerOptions<\n TValue,\n TSelected = {},\n> extends QueuerOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: PreactQueuer<TValue, TSelected>) => void\n}\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 `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<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 * ## Unmount behavior\n *\n * By default, the hook stops the queuer when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queue = useQueuer(fn, {\n * started: true,\n * wait: 1000,\n * onUnmount: (q) => q.flush()\n * });\n * ```\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: PreactQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): PreactQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().queuer,\n ...options,\n } as PreactQueuerOptions<TValue, TSelected>\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 = useSelector(queuerInstance.store, props.selector, {\n compare: shallow,\n })\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 /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(queuer)\n } else {\n queuer.stop()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(queuer.store, selector, { compare: shallow })\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiMA,SAAgB,UACd,IACA,UAAkD,EAAE,EACpD,kBAA6D,EAAE,GAC9B;CACjC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,2CAAyB;EAC9B,MAAM,iBAAiB,IAAIC,8BACzB,IACA,cACD;AAED,iBAAe,YAAY,SAAS,UAAqB,OAGtD;GACD,MAAM,mDAAuB,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,gCACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,QAAO,KAAK;AACZ,QAAO,WAAW,cAAc;AAGhC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,OAAO;OAE/B,QAAO,MAAM;;IAGhB,EAAE,CAAC;CAGN,MAAM,gDAAoB,OAAO,OAAO,UAAU,EAAE,SAASA,gCAAS,CAAC;AAEvE,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,QAAQ,MAAM,CAChB"}
|
|
@@ -36,8 +36,8 @@ interface PreactQueuer<TValue, TSelected = {}> extends Omit<Queuer<TValue>, 'sto
|
|
|
36
36
|
readonly state: Readonly<TSelected>;
|
|
37
37
|
/**
|
|
38
38
|
* @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state.
|
|
39
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `
|
|
40
|
-
* Although, you can make the state reactive by using the `
|
|
39
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
40
|
+
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
41
41
|
*/
|
|
42
42
|
readonly store: Store<Readonly<QueuerState<TValue>>>;
|
|
43
43
|
}
|
|
@@ -36,8 +36,8 @@ interface PreactQueuer<TValue, TSelected = {}> extends Omit<Queuer<TValue>, 'sto
|
|
|
36
36
|
readonly state: Readonly<TSelected>;
|
|
37
37
|
/**
|
|
38
38
|
* @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state.
|
|
39
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `
|
|
40
|
-
* Although, you can make the state reactive by using the `
|
|
39
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
40
|
+
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
41
41
|
*/
|
|
42
42
|
readonly store: Store<Readonly<QueuerState<TValue>>>;
|
|
43
43
|
}
|
package/dist/queuer/useQueuer.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
2
|
import { useEffect, useMemo, useState } from "preact/hooks";
|
|
3
|
-
import { shallow,
|
|
3
|
+
import { shallow, useSelector } from "@tanstack/preact-store";
|
|
4
4
|
import { Queuer } from "@tanstack/pacer/queuer";
|
|
5
5
|
|
|
6
6
|
//#region src/queuer/useQueuer.ts
|
|
@@ -151,7 +151,7 @@ function useQueuer(fn, options = {}, selector = () => ({})) {
|
|
|
151
151
|
const [queuer] = useState(() => {
|
|
152
152
|
const queuerInstance = new Queuer(fn, mergedOptions);
|
|
153
153
|
queuerInstance.Subscribe = function Subscribe(props) {
|
|
154
|
-
const selected =
|
|
154
|
+
const selected = useSelector(queuerInstance.store, props.selector, { compare: shallow });
|
|
155
155
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
156
156
|
};
|
|
157
157
|
return queuerInstance;
|
|
@@ -164,7 +164,7 @@ function useQueuer(fn, options = {}, selector = () => ({})) {
|
|
|
164
164
|
else queuer.stop();
|
|
165
165
|
};
|
|
166
166
|
}, []);
|
|
167
|
-
const state =
|
|
167
|
+
const state = useSelector(queuer.store, selector, { compare: shallow });
|
|
168
168
|
return useMemo(() => ({
|
|
169
169
|
...queuer,
|
|
170
170
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useQueuer.js","names":[],"sources":["../../src/queuer/useQueuer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Queuer } from '@tanstack/pacer/queuer'\nimport { shallow, 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 PreactQueuerOptions<\n TValue,\n TSelected = {},\n> extends QueuerOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: PreactQueuer<TValue, TSelected>) => void\n}\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 * ## Unmount behavior\n *\n * By default, the hook stops the queuer when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queue = useQueuer(fn, {\n * started: true,\n * wait: 1000,\n * onUnmount: (q) => q.flush()\n * });\n * ```\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: PreactQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): PreactQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().queuer,\n ...options,\n } as PreactQueuerOptions<TValue, TSelected>\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 equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return queuerInstance\n })\n\n queuer.fn = fn\n queuer.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(queuer)\n } else {\n queuer.stop()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(queuer.store, selector, { equal: shallow })\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiMA,SAAgB,UACd,IACA,UAAkD,EAAE,EACpD,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,UAAU,EAC9D,OAAO,SACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,QAAO,KAAK;AACZ,QAAO,WAAW,cAAc;AAGhC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,OAAO;OAE/B,QAAO,MAAM;;IAGhB,EAAE,CAAC;CAGN,MAAM,QAAQ,SAAS,OAAO,OAAO,UAAU,EAAE,OAAO,SAAS,CAAC;AAElE,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,QAAQ,MAAM,CAChB"}
|
|
1
|
+
{"version":3,"file":"useQueuer.js","names":[],"sources":["../../src/queuer/useQueuer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Queuer } from '@tanstack/pacer/queuer'\nimport { shallow, useSelector } 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 PreactQueuerOptions<\n TValue,\n TSelected = {},\n> extends QueuerOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: PreactQueuer<TValue, TSelected>) => void\n}\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 `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<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 * ## Unmount behavior\n *\n * By default, the hook stops the queuer when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queue = useQueuer(fn, {\n * started: true,\n * wait: 1000,\n * onUnmount: (q) => q.flush()\n * });\n * ```\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: PreactQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): PreactQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().queuer,\n ...options,\n } as PreactQueuerOptions<TValue, TSelected>\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 = useSelector(queuerInstance.store, props.selector, {\n compare: shallow,\n })\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 /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(queuer)\n } else {\n queuer.stop()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(queuer.store, selector, { compare: shallow })\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiMA,SAAgB,UACd,IACA,UAAkD,EAAE,EACpD,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,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,SACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,QAAO,KAAK;AACZ,QAAO,WAAW,cAAc;AAGhC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,OAAO;OAE/B,QAAO,MAAM;;IAGhB,EAAE,CAAC;CAGN,MAAM,QAAQ,YAAY,OAAO,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;AAEvE,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,QAAQ,MAAM,CAChB"}
|
|
@@ -143,7 +143,7 @@ function useRateLimiter(fn, options, selector = () => ({})) {
|
|
|
143
143
|
const [rateLimiter] = (0, preact_hooks.useState)(() => {
|
|
144
144
|
const rateLimiterInstance = new _tanstack_pacer_rate_limiter.RateLimiter(fn, mergedOptions);
|
|
145
145
|
rateLimiterInstance.Subscribe = function Subscribe(props) {
|
|
146
|
-
const selected = (0, _tanstack_preact_store.
|
|
146
|
+
const selected = (0, _tanstack_preact_store.useSelector)(rateLimiterInstance.store, props.selector, { compare: _tanstack_preact_store.shallow });
|
|
147
147
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
148
148
|
};
|
|
149
149
|
return rateLimiterInstance;
|
|
@@ -155,7 +155,7 @@ function useRateLimiter(fn, options, selector = () => ({})) {
|
|
|
155
155
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(rateLimiter);
|
|
156
156
|
};
|
|
157
157
|
}, []);
|
|
158
|
-
const state = (0, _tanstack_preact_store.
|
|
158
|
+
const state = (0, _tanstack_preact_store.useSelector)(rateLimiter.store, selector, { compare: _tanstack_preact_store.shallow });
|
|
159
159
|
return (0, preact_hooks.useMemo)(() => ({
|
|
160
160
|
...rateLimiter,
|
|
161
161
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRateLimiter.cjs","names":["useDefaultPacerOptions","RateLimiter","shallow"],"sources":["../../src/rate-limiter/useRateLimiter.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { shallow, 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 PreactRateLimiterOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends RateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup; use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: PreactRateLimiter<TFn, TSelected>) => void\n}\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: PreactRateLimiterOptions<TFn, TSelected>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): PreactRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as PreactRateLimiterOptions<TFn, TSelected>\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 equal: shallow,\n })\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 /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(rateLimiter)\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(rateLimiter.store, selector, { equal: shallow })\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6LA,SAAgB,eACd,IACA,SACA,kBAA0D,EAAE,GACzB;CACnC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,gDAA8B;EACnC,MAAM,sBAAsB,IAAIC,yCAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,gDAAoB,oBAAoB,OAAO,MAAM,UAAU,EACnE,OAAOC,gCACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;AAGrC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;;IAGvC,EAAE,CAAC;CAGN,MAAM,6CAAiB,YAAY,OAAO,UAAU,EAAE,OAAOA,gCAAS,CAAC;AAEvE,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
|
1
|
+
{"version":3,"file":"useRateLimiter.cjs","names":["useDefaultPacerOptions","RateLimiter","shallow"],"sources":["../../src/rate-limiter/useRateLimiter.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { shallow, useSelector } 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 PreactRateLimiterOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends RateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup; use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: PreactRateLimiter<TFn, TSelected>) => void\n}\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 `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<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: PreactRateLimiterOptions<TFn, TSelected>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): PreactRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as PreactRateLimiterOptions<TFn, TSelected>\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 = useSelector(rateLimiterInstance.store, props.selector, {\n compare: shallow,\n })\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 /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(rateLimiter)\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(rateLimiter.store, selector, { compare: shallow })\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6LA,SAAgB,eACd,IACA,SACA,kBAA0D,EAAE,GACzB;CACnC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,gDAA8B;EACnC,MAAM,sBAAsB,IAAIC,yCAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,mDAAuB,oBAAoB,OAAO,MAAM,UAAU,EACtE,SAASC,gCACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;AAGrC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;;IAGvC,EAAE,CAAC;CAGN,MAAM,gDAAoB,YAAY,OAAO,UAAU,EAAE,SAASA,gCAAS,CAAC;AAE5E,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
|
@@ -37,8 +37,8 @@ interface PreactRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omi
|
|
|
37
37
|
readonly state: Readonly<TSelected>;
|
|
38
38
|
/**
|
|
39
39
|
* @deprecated Use `rateLimiter.state` instead of `rateLimiter.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 `
|
|
41
|
-
* Although, you can make the state reactive by using the `
|
|
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
42
|
*/
|
|
43
43
|
readonly store: Store<Readonly<RateLimiterState>>;
|
|
44
44
|
}
|
|
@@ -37,8 +37,8 @@ interface PreactRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omi
|
|
|
37
37
|
readonly state: Readonly<TSelected>;
|
|
38
38
|
/**
|
|
39
39
|
* @deprecated Use `rateLimiter.state` instead of `rateLimiter.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 `
|
|
41
|
-
* Although, you can make the state reactive by using the `
|
|
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
42
|
*/
|
|
43
43
|
readonly store: Store<Readonly<RateLimiterState>>;
|
|
44
44
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
2
|
import { useEffect, useMemo, useState } from "preact/hooks";
|
|
3
|
-
import { shallow,
|
|
3
|
+
import { shallow, useSelector } from "@tanstack/preact-store";
|
|
4
4
|
import { RateLimiter } from "@tanstack/pacer/rate-limiter";
|
|
5
5
|
|
|
6
6
|
//#region src/rate-limiter/useRateLimiter.ts
|
|
@@ -143,7 +143,7 @@ function useRateLimiter(fn, options, selector = () => ({})) {
|
|
|
143
143
|
const [rateLimiter] = useState(() => {
|
|
144
144
|
const rateLimiterInstance = new RateLimiter(fn, mergedOptions);
|
|
145
145
|
rateLimiterInstance.Subscribe = function Subscribe(props) {
|
|
146
|
-
const selected =
|
|
146
|
+
const selected = useSelector(rateLimiterInstance.store, props.selector, { compare: shallow });
|
|
147
147
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
148
148
|
};
|
|
149
149
|
return rateLimiterInstance;
|
|
@@ -155,7 +155,7 @@ function useRateLimiter(fn, options, selector = () => ({})) {
|
|
|
155
155
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(rateLimiter);
|
|
156
156
|
};
|
|
157
157
|
}, []);
|
|
158
|
-
const state =
|
|
158
|
+
const state = useSelector(rateLimiter.store, selector, { compare: shallow });
|
|
159
159
|
return useMemo(() => ({
|
|
160
160
|
...rateLimiter,
|
|
161
161
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRateLimiter.js","names":[],"sources":["../../src/rate-limiter/useRateLimiter.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { shallow, 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 PreactRateLimiterOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends RateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup; use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: PreactRateLimiter<TFn, TSelected>) => void\n}\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: PreactRateLimiterOptions<TFn, TSelected>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): PreactRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as PreactRateLimiterOptions<TFn, TSelected>\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 equal: shallow,\n })\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 /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(rateLimiter)\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(rateLimiter.store, selector, { equal: shallow })\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6LA,SAAgB,eACd,IACA,SACA,kBAA0D,EAAE,GACzB;CACnC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,eAAe,eAAe;EACnC,MAAM,sBAAsB,IAAI,YAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,WAAW,SAAS,oBAAoB,OAAO,MAAM,UAAU,EACnE,OAAO,SACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;AAGrC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;;IAGvC,EAAE,CAAC;CAGN,MAAM,QAAQ,SAAS,YAAY,OAAO,UAAU,EAAE,OAAO,SAAS,CAAC;AAEvE,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
|
1
|
+
{"version":3,"file":"useRateLimiter.js","names":[],"sources":["../../src/rate-limiter/useRateLimiter.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { shallow, useSelector } 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 PreactRateLimiterOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends RateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup; use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: PreactRateLimiter<TFn, TSelected>) => void\n}\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 `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<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: PreactRateLimiterOptions<TFn, TSelected>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): PreactRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as PreactRateLimiterOptions<TFn, TSelected>\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 = useSelector(rateLimiterInstance.store, props.selector, {\n compare: shallow,\n })\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 /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(rateLimiter)\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(rateLimiter.store, selector, { compare: shallow })\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6LA,SAAgB,eACd,IACA,SACA,kBAA0D,EAAE,GACzB;CACnC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,eAAe,eAAe;EACnC,MAAM,sBAAsB,IAAI,YAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,WAAW,YAAY,oBAAoB,OAAO,MAAM,UAAU,EACtE,SAAS,SACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;AAGrC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;;IAGvC,EAAE,CAAC;CAGN,MAAM,QAAQ,YAAY,YAAY,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;AAE5E,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
|
@@ -121,14 +121,14 @@ function useThrottler(fn, options, selector = () => ({})) {
|
|
|
121
121
|
const [throttler] = (0, preact_hooks.useState)(() => {
|
|
122
122
|
const throttlerInstance = new _tanstack_pacer_throttler.Throttler(fn, mergedOptions);
|
|
123
123
|
throttlerInstance.Subscribe = function Subscribe(props) {
|
|
124
|
-
const selected = (0, _tanstack_preact_store.
|
|
124
|
+
const selected = (0, _tanstack_preact_store.useSelector)(throttlerInstance.store, props.selector, { compare: _tanstack_preact_store.shallow });
|
|
125
125
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
126
126
|
};
|
|
127
127
|
return throttlerInstance;
|
|
128
128
|
});
|
|
129
129
|
throttler.fn = fn;
|
|
130
130
|
throttler.setOptions(mergedOptions);
|
|
131
|
-
const state = (0, _tanstack_preact_store.
|
|
131
|
+
const state = (0, _tanstack_preact_store.useSelector)(throttler.store, selector, { compare: _tanstack_preact_store.shallow });
|
|
132
132
|
(0, preact_hooks.useEffect)(() => {
|
|
133
133
|
return () => {
|
|
134
134
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(throttler);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useThrottler.cjs","names":["useDefaultPacerOptions","Throttler","shallow"],"sources":["../../src/throttler/useThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Throttler } from '@tanstack/pacer/throttler'\nimport { shallow,
|
|
1
|
+
{"version":3,"file":"useThrottler.cjs","names":["useDefaultPacerOptions","Throttler","shallow"],"sources":["../../src/throttler/useThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Throttler } from '@tanstack/pacer/throttler'\nimport { shallow, useSelector } 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 PreactThrottlerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends ThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the 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: PreactThrottler<TFn, TSelected>) => void\n}\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 `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 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 * ## Unmount behavior\n *\n * By default, the hook cancels any pending execution when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = useThrottler(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 [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: PreactThrottlerOptions<TFn, TSelected>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): PreactThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().throttler,\n ...options,\n } as PreactThrottlerOptions<TFn, TSelected>\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 = useSelector(throttlerInstance.store, props.selector, {\n compare: shallow,\n })\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 = useSelector(throttler.store, selector, { compare: shallow })\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(throttler)\n } else {\n throttler.cancel()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuKA,SAAgB,aACd,IACA,SACA,kBAA6D,EAAE,GAC9B;CACjC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,8CAA4B;EACjC,MAAM,oBAAoB,IAAIC,oCAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,mDAAuB,kBAAkB,OAAO,MAAM,UAAU,EACpE,SAASC,gCACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,WAAU,KAAK;AACf,WAAU,WAAW,cAAc;CAEnC,MAAM,gDAAoB,UAAU,OAAO,UAAU,EAAE,SAASA,gCAAS,CAAC;AAG1E,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,UAAU;OAElC,WAAU,QAAQ;;IAGrB,EAAE,CAAC;AAGN,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,WAAW,MAAM,CACnB"}
|
|
@@ -37,8 +37,8 @@ interface PreactThrottler<TFn extends AnyFunction, TSelected = {}> extends Omit<
|
|
|
37
37
|
readonly state: Readonly<TSelected>;
|
|
38
38
|
/**
|
|
39
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 `
|
|
41
|
-
* Although, you can make the state reactive by using the `
|
|
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
42
|
*/
|
|
43
43
|
readonly store: Store<Readonly<ThrottlerState<TFn>>>;
|
|
44
44
|
}
|