@tanstack/preact-pacer 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/async-batcher/index.cjs +3 -3
  2. package/dist/async-batcher/index.d.cts +2 -2
  3. package/dist/async-batcher/index.d.ts +2 -2
  4. package/dist/async-batcher/useAsyncBatcher.cjs +35 -11
  5. package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -1
  6. package/dist/async-batcher/useAsyncBatcher.d.cts +45 -10
  7. package/dist/async-batcher/useAsyncBatcher.d.ts +45 -10
  8. package/dist/async-batcher/useAsyncBatcher.js +32 -8
  9. package/dist/async-batcher/useAsyncBatcher.js.map +1 -1
  10. package/dist/async-debouncer/index.cjs +3 -3
  11. package/dist/async-debouncer/index.d.cts +2 -2
  12. package/dist/async-debouncer/index.d.ts +2 -2
  13. package/dist/async-debouncer/useAsyncDebouncer.cjs +35 -11
  14. package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -1
  15. package/dist/async-debouncer/useAsyncDebouncer.d.cts +45 -10
  16. package/dist/async-debouncer/useAsyncDebouncer.d.ts +45 -10
  17. package/dist/async-debouncer/useAsyncDebouncer.js +32 -8
  18. package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -1
  19. package/dist/async-queuer/index.cjs +3 -3
  20. package/dist/async-queuer/index.d.cts +2 -2
  21. package/dist/async-queuer/index.d.ts +2 -2
  22. package/dist/async-queuer/useAsyncQueuedState.cjs.map +1 -1
  23. package/dist/async-queuer/useAsyncQueuedState.d.cts +2 -2
  24. package/dist/async-queuer/useAsyncQueuedState.d.ts +2 -2
  25. package/dist/async-queuer/useAsyncQueuedState.js.map +1 -1
  26. package/dist/async-queuer/useAsyncQueuer.cjs +35 -11
  27. package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -1
  28. package/dist/async-queuer/useAsyncQueuer.d.cts +45 -10
  29. package/dist/async-queuer/useAsyncQueuer.d.ts +45 -10
  30. package/dist/async-queuer/useAsyncQueuer.js +32 -8
  31. package/dist/async-queuer/useAsyncQueuer.js.map +1 -1
  32. package/dist/async-rate-limiter/index.cjs +3 -3
  33. package/dist/async-rate-limiter/index.d.cts +2 -2
  34. package/dist/async-rate-limiter/index.d.ts +2 -2
  35. package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +35 -11
  36. package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -1
  37. package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +45 -10
  38. package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +45 -10
  39. package/dist/async-rate-limiter/useAsyncRateLimiter.js +32 -8
  40. package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -1
  41. package/dist/async-retryer/index.cjs +3 -3
  42. package/dist/async-throttler/index.cjs +3 -3
  43. package/dist/async-throttler/index.d.cts +2 -2
  44. package/dist/async-throttler/index.d.ts +2 -2
  45. package/dist/async-throttler/useAsyncThrottler.cjs +35 -11
  46. package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -1
  47. package/dist/async-throttler/useAsyncThrottler.d.cts +45 -10
  48. package/dist/async-throttler/useAsyncThrottler.d.ts +45 -10
  49. package/dist/async-throttler/useAsyncThrottler.js +32 -8
  50. package/dist/async-throttler/useAsyncThrottler.js.map +1 -1
  51. package/dist/batcher/index.cjs +3 -3
  52. package/dist/batcher/useBatcher.cjs +35 -11
  53. package/dist/batcher/useBatcher.cjs.map +1 -1
  54. package/dist/batcher/useBatcher.d.cts +42 -7
  55. package/dist/batcher/useBatcher.d.ts +42 -7
  56. package/dist/batcher/useBatcher.js +32 -8
  57. package/dist/batcher/useBatcher.js.map +1 -1
  58. package/dist/debouncer/index.cjs +3 -3
  59. package/dist/debouncer/useDebouncer.cjs +35 -11
  60. package/dist/debouncer/useDebouncer.cjs.map +1 -1
  61. package/dist/debouncer/useDebouncer.d.cts +42 -7
  62. package/dist/debouncer/useDebouncer.d.ts +42 -7
  63. package/dist/debouncer/useDebouncer.js +32 -8
  64. package/dist/debouncer/useDebouncer.js.map +1 -1
  65. package/dist/index.cjs +3 -3
  66. package/dist/index.d.cts +6 -6
  67. package/dist/index.d.ts +6 -6
  68. package/dist/provider/PacerProvider.d.cts +1 -1
  69. package/dist/queuer/index.cjs +3 -3
  70. package/dist/queuer/useQueuer.cjs +35 -11
  71. package/dist/queuer/useQueuer.cjs.map +1 -1
  72. package/dist/queuer/useQueuer.d.cts +42 -7
  73. package/dist/queuer/useQueuer.d.ts +42 -7
  74. package/dist/queuer/useQueuer.js +32 -8
  75. package/dist/queuer/useQueuer.js.map +1 -1
  76. package/dist/rate-limiter/index.cjs +3 -3
  77. package/dist/rate-limiter/useRateLimiter.cjs +35 -11
  78. package/dist/rate-limiter/useRateLimiter.cjs.map +1 -1
  79. package/dist/rate-limiter/useRateLimiter.d.cts +42 -7
  80. package/dist/rate-limiter/useRateLimiter.d.ts +42 -7
  81. package/dist/rate-limiter/useRateLimiter.js +32 -8
  82. package/dist/rate-limiter/useRateLimiter.js.map +1 -1
  83. package/dist/throttler/index.cjs +3 -3
  84. package/dist/throttler/useThrottler.cjs +35 -11
  85. package/dist/throttler/useThrottler.cjs.map +1 -1
  86. package/dist/throttler/useThrottler.d.cts +42 -7
  87. package/dist/throttler/useThrottler.d.ts +42 -7
  88. package/dist/throttler/useThrottler.js +32 -8
  89. package/dist/throttler/useThrottler.js.map +1 -1
  90. package/dist/types/index.cjs +3 -3
  91. package/dist/utils/index.cjs +3 -3
  92. package/package.json +1 -1
  93. package/src/async-batcher/useAsyncBatcher.ts +64 -13
  94. package/src/async-debouncer/useAsyncDebouncer.ts +64 -13
  95. package/src/async-queuer/useAsyncQueuedState.ts +2 -2
  96. package/src/async-queuer/useAsyncQueuer.ts +64 -13
  97. package/src/async-rate-limiter/useAsyncRateLimiter.ts +64 -13
  98. package/src/async-throttler/useAsyncThrottler.ts +64 -13
  99. package/src/batcher/useBatcher.ts +61 -8
  100. package/src/debouncer/useDebouncer.ts +61 -8
  101. package/src/queuer/useQueuer.ts +61 -8
  102. package/src/rate-limiter/useRateLimiter.ts +61 -8
  103. package/src/throttler/useThrottler.ts +61 -8
@@ -1,9 +1,27 @@
1
1
  import { Store } from "@tanstack/preact-store";
2
+ import { ComponentChildren } from "preact";
2
3
  import { AnyFunction } from "@tanstack/pacer/types";
3
4
  import { Throttler, ThrottlerOptions, ThrottlerState } from "@tanstack/pacer/throttler";
4
5
 
5
6
  //#region src/throttler/useThrottler.d.ts
6
7
  interface PreactThrottler<TFn extends AnyFunction, TSelected = {}> extends Omit<Throttler<TFn>, 'store'> {
8
+ /**
9
+ * A Preact HOC (Higher Order Component) that allows you to subscribe to the throttler state.
10
+ *
11
+ * This is useful for opting into state re-renders for specific parts of the throttler state
12
+ * deep in your component tree without needing to pass a selector to the hook.
13
+ *
14
+ * @example
15
+ * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
16
+ * {({ isPending }) => (
17
+ * <div>{isPending ? 'Loading...' : 'Ready'}</div>
18
+ * )}
19
+ * </throttler.Subscribe>
20
+ */
21
+ Subscribe: <TSelected>(props: {
22
+ selector: (state: ThrottlerState<TFn>) => TSelected;
23
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
24
+ }) => ComponentChildren;
7
25
  /**
8
26
  * Reactive state that will be updated and re-rendered when the throttler state changes
9
27
  *
@@ -30,14 +48,24 @@ interface PreactThrottler<TFn extends AnyFunction, TSelected = {}> extends Omit<
30
48
  *
31
49
  * ## State Management and Selector
32
50
  *
33
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
34
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
35
- * unnecessary re-renders when irrelevant state changes occur.
51
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
52
+ * in two ways:
53
+ *
54
+ * **1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**
55
+ *
56
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
57
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
58
+ * in child components.
59
+ *
60
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
61
+ *
62
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
63
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
64
+ * state changes occur.
36
65
  *
37
66
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
38
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
39
- * full control over when your component updates. Only when you provide a selector will the
40
- * component re-render when the selected state values change.
67
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
68
+ * re-renders and gives you full control over when your component updates.
41
69
  *
42
70
  * Available state properties:
43
71
  * - `executionCount`: Number of function executions that have been completed
@@ -53,7 +81,14 @@ interface PreactThrottler<TFn extends AnyFunction, TSelected = {}> extends Omit<
53
81
  * const [value, setValue] = useState(0);
54
82
  * const throttler = useThrottler(setValue, { wait: 1000 });
55
83
  *
56
- * // Opt-in to re-render when execution count changes (optimized for tracking executions)
84
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
85
+ * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
86
+ * {({ isPending }) => (
87
+ * <div>{isPending ? 'Processing...' : 'Ready'}</div>
88
+ * )}
89
+ * </throttler.Subscribe>
90
+ *
91
+ * // Opt-in to re-render when execution count changes at hook level (optimized for tracking executions)
57
92
  * const [value, setValue] = useState(0);
58
93
  * const throttler = useThrottler(
59
94
  * setValue,
@@ -1,9 +1,27 @@
1
+ import { ComponentChildren } from "preact";
1
2
  import { Store } from "@tanstack/preact-store";
2
3
  import { Throttler, ThrottlerOptions, ThrottlerState } from "@tanstack/pacer/throttler";
3
4
  import { AnyFunction } from "@tanstack/pacer/types";
4
5
 
5
6
  //#region src/throttler/useThrottler.d.ts
6
7
  interface PreactThrottler<TFn extends AnyFunction, TSelected = {}> extends Omit<Throttler<TFn>, 'store'> {
8
+ /**
9
+ * A Preact HOC (Higher Order Component) that allows you to subscribe to the throttler state.
10
+ *
11
+ * This is useful for opting into state re-renders for specific parts of the throttler state
12
+ * deep in your component tree without needing to pass a selector to the hook.
13
+ *
14
+ * @example
15
+ * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
16
+ * {({ isPending }) => (
17
+ * <div>{isPending ? 'Loading...' : 'Ready'}</div>
18
+ * )}
19
+ * </throttler.Subscribe>
20
+ */
21
+ Subscribe: <TSelected>(props: {
22
+ selector: (state: ThrottlerState<TFn>) => TSelected;
23
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
24
+ }) => ComponentChildren;
7
25
  /**
8
26
  * Reactive state that will be updated and re-rendered when the throttler state changes
9
27
  *
@@ -30,14 +48,24 @@ interface PreactThrottler<TFn extends AnyFunction, TSelected = {}> extends Omit<
30
48
  *
31
49
  * ## State Management and Selector
32
50
  *
33
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
34
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
35
- * unnecessary re-renders when irrelevant state changes occur.
51
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
52
+ * in two ways:
53
+ *
54
+ * **1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**
55
+ *
56
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
57
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
58
+ * in child components.
59
+ *
60
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
61
+ *
62
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
63
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
64
+ * state changes occur.
36
65
  *
37
66
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
38
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
39
- * full control over when your component updates. Only when you provide a selector will the
40
- * component re-render when the selected state values change.
67
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
68
+ * re-renders and gives you full control over when your component updates.
41
69
  *
42
70
  * Available state properties:
43
71
  * - `executionCount`: Number of function executions that have been completed
@@ -53,7 +81,14 @@ interface PreactThrottler<TFn extends AnyFunction, TSelected = {}> extends Omit<
53
81
  * const [value, setValue] = useState(0);
54
82
  * const throttler = useThrottler(setValue, { wait: 1000 });
55
83
  *
56
- * // Opt-in to re-render when execution count changes (optimized for tracking executions)
84
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
85
+ * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
86
+ * {({ isPending }) => (
87
+ * <div>{isPending ? 'Processing...' : 'Ready'}</div>
88
+ * )}
89
+ * </throttler.Subscribe>
90
+ *
91
+ * // Opt-in to re-render when execution count changes at hook level (optimized for tracking executions)
57
92
  * const [value, setValue] = useState(0);
58
93
  * const throttler = useThrottler(
59
94
  * setValue,
@@ -17,14 +17,24 @@ import { Throttler } from "@tanstack/pacer/throttler";
17
17
  *
18
18
  * ## State Management and Selector
19
19
  *
20
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
21
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
22
- * unnecessary re-renders when irrelevant state changes occur.
20
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
21
+ * in two ways:
22
+ *
23
+ * **1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**
24
+ *
25
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
26
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
27
+ * in child components.
28
+ *
29
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
30
+ *
31
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
32
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
33
+ * state changes occur.
23
34
  *
24
35
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
25
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
26
- * full control over when your component updates. Only when you provide a selector will the
27
- * component re-render when the selected state values change.
36
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
37
+ * re-renders and gives you full control over when your component updates.
28
38
  *
29
39
  * Available state properties:
30
40
  * - `executionCount`: Number of function executions that have been completed
@@ -40,7 +50,14 @@ import { Throttler } from "@tanstack/pacer/throttler";
40
50
  * const [value, setValue] = useState(0);
41
51
  * const throttler = useThrottler(setValue, { wait: 1000 });
42
52
  *
43
- * // Opt-in to re-render when execution count changes (optimized for tracking executions)
53
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
54
+ * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
55
+ * {({ isPending }) => (
56
+ * <div>{isPending ? 'Processing...' : 'Ready'}</div>
57
+ * )}
58
+ * </throttler.Subscribe>
59
+ *
60
+ * // Opt-in to re-render when execution count changes at hook level (optimized for tracking executions)
44
61
  * const [value, setValue] = useState(0);
45
62
  * const throttler = useThrottler(
46
63
  * setValue,
@@ -89,7 +106,14 @@ function useThrottler(fn, options, selector = () => ({})) {
89
106
  ...useDefaultPacerOptions().throttler,
90
107
  ...options
91
108
  };
92
- const [throttler] = useState(() => new Throttler(fn, mergedOptions));
109
+ const [throttler] = useState(() => {
110
+ const throttlerInstance = new Throttler(fn, mergedOptions);
111
+ throttlerInstance.Subscribe = function Subscribe(props) {
112
+ const selected = useStore(throttlerInstance.store, props.selector);
113
+ return typeof props.children === "function" ? props.children(selected) : props.children;
114
+ };
115
+ return throttlerInstance;
116
+ });
93
117
  throttler.fn = fn;
94
118
  throttler.setOptions(mergedOptions);
95
119
  const state = useStore(throttler.store, selector);
@@ -1 +1 @@
1
- {"version":3,"file":"useThrottler.js","names":[],"sources":["../../src/throttler/useThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Throttler } from '@tanstack/pacer/throttler'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface PreactThrottler<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Throttler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<ThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates a `Throttler` instance that limits how often the provided function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that\n * integrates directly with Preact's useState, see useThrottledState.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `executionCount`: Number of function executions that have been completed\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(setValue, { wait: 1000 });\n *\n * // Opt-in to re-render when execution count changes (optimized for tracking executions)\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to re-render when throttling state changes (optimized for loading indicators)\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With any state manager\n * const throttler = useThrottler(\n * (value) => stateManager.setState(value),\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, isPending } = throttler.state;\n * ```\n */\nexport function useThrottler<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: ThrottlerOptions<TFn>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): PreactThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().throttler,\n ...options,\n } as ThrottlerOptions<TFn>\n\n const [throttler] = useState(() => new Throttler<TFn>(fn, mergedOptions))\n\n throttler.fn = fn\n throttler.setOptions(mergedOptions)\n\n const state = useStore(throttler.store, selector)\n\n useEffect(() => {\n return () => {\n throttler.cancel()\n }\n }, [throttler])\n\n return useMemo(\n () =>\n ({\n ...throttler,\n state,\n }) as PreactThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [throttler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6GA,SAAgB,aACd,IACA,SACA,kBAA6D,EAAE,GAC9B;CACjC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,aAAa,eAAe,IAAI,UAAe,IAAI,cAAc,CAAC;AAEzE,WAAU,KAAK;AACf,WAAU,WAAW,cAAc;CAEnC,MAAM,QAAQ,SAAS,UAAU,OAAO,SAAS;AAEjD,iBAAgB;AACd,eAAa;AACX,aAAU,QAAQ;;IAEnB,CAAC,UAAU,CAAC;AAEf,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,WAAW,MAAM,CACnB"}
1
+ {"version":3,"file":"useThrottler.js","names":[],"sources":["../../src/throttler/useThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Throttler } from '@tanstack/pacer/throttler'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactThrottler<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Throttler<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the throttler state.\n *\n * This is useful for opting into state re-renders for specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<ThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates a `Throttler` instance that limits how often the provided function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that\n * integrates directly with Preact's useState, see useThrottledState.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `executionCount`: Number of function executions that have been completed\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(setValue, { wait: 1000 });\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Processing...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n *\n * // Opt-in to re-render when execution count changes at hook level (optimized for tracking executions)\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to re-render when throttling state changes (optimized for loading indicators)\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const [value, setValue] = useState(0);\n * const throttler = useThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With any state manager\n * const throttler = useThrottler(\n * (value) => stateManager.setState(value),\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, isPending } = throttler.state;\n * ```\n */\nexport function useThrottler<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: ThrottlerOptions<TFn>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): PreactThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().throttler,\n ...options,\n } as ThrottlerOptions<TFn>\n\n const [throttler] = useState(() => {\n const throttlerInstance = new Throttler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactThrottler<TFn, TSelected>\n\n throttlerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(throttlerInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return throttlerInstance\n })\n\n throttler.fn = fn\n throttler.setOptions(mergedOptions)\n\n const state = useStore(throttler.store, selector)\n\n useEffect(() => {\n return () => {\n throttler.cancel()\n }\n }, [throttler])\n\n return useMemo(\n () =>\n ({\n ...throttler,\n state,\n }) as PreactThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [throttler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgJA,SAAgB,aACd,IACA,SACA,kBAA6D,EAAE,GAC9B;CACjC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,aAAa,eAAe;EACjC,MAAM,oBAAoB,IAAI,UAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,WAAW,SAAS,kBAAkB,OAAO,MAAM,SAAS;AAElE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,WAAU,KAAK;AACf,WAAU,WAAW,cAAc;CAEnC,MAAM,QAAQ,SAAS,UAAU,OAAO,SAAS;AAEjD,iBAAgB;AACd,eAAa;AACX,aAAU,QAAQ;;IAEnB,CAAC,UAAU,CAAC;AAEf,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,WAAW,MAAM,CACnB"}
@@ -1,9 +1,9 @@
1
1
 
2
2
 
3
- var __tanstack_pacer_types = require("@tanstack/pacer/types");
4
- Object.keys(__tanstack_pacer_types).forEach(function (k) {
3
+ var _tanstack_pacer_types = require("@tanstack/pacer/types");
4
+ Object.keys(_tanstack_pacer_types).forEach(function (k) {
5
5
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
6
6
  enumerable: true,
7
- get: function () { return __tanstack_pacer_types[k]; }
7
+ get: function () { return _tanstack_pacer_types[k]; }
8
8
  });
9
9
  });
@@ -1,9 +1,9 @@
1
1
 
2
2
 
3
- var __tanstack_pacer_utils = require("@tanstack/pacer/utils");
4
- Object.keys(__tanstack_pacer_utils).forEach(function (k) {
3
+ var _tanstack_pacer_utils = require("@tanstack/pacer/utils");
4
+ Object.keys(_tanstack_pacer_utils).forEach(function (k) {
5
5
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
6
6
  enumerable: true,
7
- get: function () { return __tanstack_pacer_utils[k]; }
7
+ get: function () { return _tanstack_pacer_utils[k]; }
8
8
  });
9
9
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/preact-pacer",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "Utilities for debouncing and throttling functions in Preact.",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -7,11 +7,29 @@ import type {
7
7
  AsyncBatcherOptions,
8
8
  AsyncBatcherState,
9
9
  } from '@tanstack/pacer/async-batcher'
10
+ import type { ComponentChildren } from 'preact'
10
11
 
11
- export interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<
12
+ export interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<
12
13
  AsyncBatcher<TValue>,
13
14
  'store'
14
15
  > {
16
+ /**
17
+ * A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.
18
+ *
19
+ * This is useful for opting into state re-renders for specific parts of the batcher state
20
+ * deep in your component tree without needing to pass a selector to the hook.
21
+ *
22
+ * @example
23
+ * <batcher.Subscribe selector={(state) => ({ size: state.size })}>
24
+ * {({ size }) => (
25
+ * <div>Batch Size: {size}</div>
26
+ * )}
27
+ * </batcher.Subscribe>
28
+ */
29
+ Subscribe: <TSelected>(props: {
30
+ selector: (state: AsyncBatcherState<TValue>) => TSelected
31
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren
32
+ }) => ComponentChildren
15
33
  /**
16
34
  * Reactive state that will be updated and re-rendered when the batcher state changes
17
35
  *
@@ -57,14 +75,24 @@ export interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<
57
75
  *
58
76
  * ## State Management and Selector
59
77
  *
60
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
61
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
62
- * unnecessary re-renders when irrelevant state changes occur.
78
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
79
+ * in two ways:
80
+ *
81
+ * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**
82
+ *
83
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
84
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
85
+ * in child components.
86
+ *
87
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
88
+ *
89
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
90
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
91
+ * state changes occur.
63
92
  *
64
93
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
65
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
66
- * full control over when your component updates. Only when you provide a selector will the
67
- * component re-render when the selected state values change.
94
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
95
+ * re-renders and gives you full control over when your component updates.
68
96
  *
69
97
  * Available state properties:
70
98
  * - `errorCount`: Number of batch executions that have resulted in errors
@@ -93,7 +121,14 @@ export interface ReactAsyncBatcher<TValue, TSelected = {}> extends Omit<
93
121
  * { maxSize: 10, wait: 2000 }
94
122
  * );
95
123
  *
96
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
124
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
125
+ * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>
126
+ * {({ size }) => (
127
+ * <div>Batch Size: {size}</div>
128
+ * )}
129
+ * </asyncBatcher.Subscribe>
130
+ *
131
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
97
132
  * const asyncBatcher = useAsyncBatcher(
98
133
  * async (items) => {
99
134
  * const results = await Promise.all(items.map(item => processItem(item)));
@@ -172,15 +207,31 @@ export function useAsyncBatcher<TValue, TSelected = {}>(
172
207
  options: AsyncBatcherOptions<TValue> = {},
173
208
  selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>
174
209
  ({}) as TSelected,
175
- ): ReactAsyncBatcher<TValue, TSelected> {
210
+ ): PreactAsyncBatcher<TValue, TSelected> {
176
211
  const mergedOptions = {
177
212
  ...useDefaultPacerOptions().asyncBatcher,
178
213
  ...options,
179
214
  } as AsyncBatcherOptions<TValue>
180
215
 
181
- const [asyncBatcher] = useState(
182
- () => new AsyncBatcher<TValue>(fn, mergedOptions),
183
- )
216
+ const [asyncBatcher] = useState(() => {
217
+ const batcherInstance = new AsyncBatcher<TValue>(
218
+ fn,
219
+ mergedOptions,
220
+ ) as unknown as PreactAsyncBatcher<TValue, TSelected>
221
+
222
+ batcherInstance.Subscribe = function Subscribe<TSelected>(props: {
223
+ selector: (state: AsyncBatcherState<TValue>) => TSelected
224
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren
225
+ }) {
226
+ const selected = useStore(batcherInstance.store, props.selector)
227
+
228
+ return typeof props.children === 'function'
229
+ ? props.children(selected)
230
+ : props.children
231
+ }
232
+
233
+ return batcherInstance
234
+ })
184
235
 
185
236
  asyncBatcher.fn = fn
186
237
  asyncBatcher.setOptions(mergedOptions)
@@ -192,7 +243,7 @@ export function useAsyncBatcher<TValue, TSelected = {}>(
192
243
  ({
193
244
  ...asyncBatcher,
194
245
  state,
195
- }) as ReactAsyncBatcher<TValue, TSelected>, // omit `store` in favor of `state`
246
+ }) as PreactAsyncBatcher<TValue, TSelected>, // omit `store` in favor of `state`
196
247
  [asyncBatcher, state],
197
248
  )
198
249
  }
@@ -8,11 +8,29 @@ import type {
8
8
  AsyncDebouncerOptions,
9
9
  AsyncDebouncerState,
10
10
  } from '@tanstack/pacer/async-debouncer'
11
+ import type { ComponentChildren } from 'preact'
11
12
 
12
- export interface ReactAsyncDebouncer<
13
+ export interface PreactAsyncDebouncer<
13
14
  TFn extends AnyAsyncFunction,
14
15
  TSelected = {},
15
16
  > extends Omit<AsyncDebouncer<TFn>, 'store'> {
17
+ /**
18
+ * A Preact HOC (Higher Order Component) that allows you to subscribe to the async debouncer state.
19
+ *
20
+ * This is useful for opting into state re-renders for specific parts of the debouncer state
21
+ * deep in your component tree without needing to pass a selector to the hook.
22
+ *
23
+ * @example
24
+ * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>
25
+ * {({ isPending }) => (
26
+ * <div>{isPending ? 'Loading...' : 'Ready'}</div>
27
+ * )}
28
+ * </debouncer.Subscribe>
29
+ */
30
+ Subscribe: <TSelected>(props: {
31
+ selector: (state: AsyncDebouncerState<TFn>) => TSelected
32
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren
33
+ }) => ComponentChildren
16
34
  /**
17
35
  * Reactive state that will be updated and re-rendered when the debouncer state changes
18
36
  *
@@ -53,14 +71,24 @@ export interface ReactAsyncDebouncer<
53
71
  *
54
72
  * ## State Management and Selector
55
73
  *
56
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
57
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
58
- * unnecessary re-renders when irrelevant state changes occur.
74
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
75
+ * in two ways:
76
+ *
77
+ * **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**
78
+ *
79
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
80
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
81
+ * in child components.
82
+ *
83
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
84
+ *
85
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
86
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
87
+ * state changes occur.
59
88
  *
60
89
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
61
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
62
- * full control over when your component updates. Only when you provide a selector will the
63
- * component re-render when the selected state values change.
90
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
91
+ * re-renders and gives you full control over when your component updates.
64
92
  *
65
93
  * Available state properties:
66
94
  * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge
@@ -84,7 +112,14 @@ export interface ReactAsyncDebouncer<
84
112
  * { wait: 500 }
85
113
  * );
86
114
  *
87
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
115
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
116
+ * <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>
117
+ * {({ isPending }) => (
118
+ * <div>{isPending ? 'Searching...' : 'Ready'}</div>
119
+ * )}
120
+ * </searchDebouncer.Subscribe>
121
+ *
122
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
88
123
  * const searchDebouncer = useAsyncDebouncer(
89
124
  * async (query: string) => {
90
125
  * const results = await api.search(query);
@@ -152,15 +187,31 @@ export function useAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(
152
187
  options: AsyncDebouncerOptions<TFn>,
153
188
  selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>
154
189
  ({}) as TSelected,
155
- ): ReactAsyncDebouncer<TFn, TSelected> {
190
+ ): PreactAsyncDebouncer<TFn, TSelected> {
156
191
  const mergedOptions = {
157
192
  ...useDefaultPacerOptions().asyncDebouncer,
158
193
  ...options,
159
194
  } as AsyncDebouncerOptions<TFn>
160
195
 
161
- const [asyncDebouncer] = useState(
162
- () => new AsyncDebouncer<TFn>(fn, mergedOptions),
163
- )
196
+ const [asyncDebouncer] = useState(() => {
197
+ const debouncerInstance = new AsyncDebouncer<TFn>(
198
+ fn,
199
+ mergedOptions,
200
+ ) as unknown as PreactAsyncDebouncer<TFn, TSelected>
201
+
202
+ debouncerInstance.Subscribe = function Subscribe<TSelected>(props: {
203
+ selector: (state: AsyncDebouncerState<TFn>) => TSelected
204
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren
205
+ }) {
206
+ const selected = useStore(debouncerInstance.store, props.selector)
207
+
208
+ return typeof props.children === 'function'
209
+ ? props.children(selected)
210
+ : props.children
211
+ }
212
+
213
+ return debouncerInstance
214
+ })
164
215
 
165
216
  asyncDebouncer.fn = fn
166
217
  asyncDebouncer.setOptions(mergedOptions)
@@ -178,7 +229,7 @@ export function useAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(
178
229
  ({
179
230
  ...asyncDebouncer,
180
231
  state,
181
- }) as ReactAsyncDebouncer<TFn, TSelected>, // omit `store` in favor of `state`
232
+ }) as PreactAsyncDebouncer<TFn, TSelected>, // omit `store` in favor of `state`
182
233
  [asyncDebouncer, state],
183
234
  )
184
235
  }
@@ -1,5 +1,5 @@
1
1
  import { useAsyncQueuer } from './useAsyncQueuer'
2
- import type { ReactAsyncQueuer } from './useAsyncQueuer'
2
+ import type { PreactAsyncQueuer } from './useAsyncQueuer'
3
3
  import type {
4
4
  AsyncQueuerOptions,
5
5
  AsyncQueuerState,
@@ -158,7 +158,7 @@ export function useAsyncQueuedState<
158
158
  fn: (value: TValue) => Promise<any>,
159
159
  options: AsyncQueuerOptions<TValue> = {},
160
160
  selector?: (state: AsyncQueuerState<TValue>) => TSelected,
161
- ): [Array<TValue>, ReactAsyncQueuer<TValue, TSelected>] {
161
+ ): [Array<TValue>, PreactAsyncQueuer<TValue, TSelected>] {
162
162
  const asyncQueuer = useAsyncQueuer(fn, options, selector)
163
163
 
164
164
  return [asyncQueuer.state.items, asyncQueuer]