{"version":3,"file":"useDebouncer.cjs","names":["useDefaultPacerOptions","Debouncer","shallow"],"sources":["../../src/debouncer/useDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'react'\nimport { Debouncer } from '@tanstack/pacer/debouncer'\nimport { shallow, useSelector } from '@tanstack/react-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/react-store'\nimport type {\n  DebouncerOptions,\n  DebouncerState,\n} from '@tanstack/pacer/debouncer'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type { FunctionComponent, ReactNode } from 'react'\n\nexport interface ReactDebouncerOptions<\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: ReactDebouncer<TFn, TSelected>) => void\n}\n\nexport interface ReactDebouncer<\n  TFn extends AnyFunction,\n  TSelected = {},\n> extends Omit<Debouncer<TFn>, 'store'> {\n  /**\n   * A React 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) => ReactNode) | ReactNode\n  }) => ReturnType<FunctionComponent>\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 React 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: ReactDebouncerOptions<TFn, TSelected>,\n  selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected,\n): ReactDebouncer<TFn, TSelected> {\n  const mergedOptions = {\n    ...useDefaultPacerOptions().debouncer,\n    ...options,\n  } as ReactDebouncerOptions<TFn, TSelected>\n  const [debouncer] = useState(() => {\n    const debouncerInstance = new Debouncer(\n      fn,\n      mergedOptions,\n    ) as unknown as ReactDebouncer<TFn, TSelected>\n\n    /* eslint-disable-next-line @eslint-react/component-hook-factories -- Subscribe attached once in useState lazy init; stable per instance */\n    debouncerInstance.Subscribe = function Subscribe<TSelected>(props: {\n      selector: (state: DebouncerState<TFn>) => TSelected\n      children: ((state: TSelected) => ReactNode) | ReactNode\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, @eslint-react/exhaustive-deps, react-compiler/react-compiler -- unmount cleanup only; empty deps keep teardown stable */\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, @eslint-react/exhaustive-deps, react-compiler/react-compiler */\n\n  const state = useSelector(debouncer.store, selector, { compare: shallow })\n\n  return useMemo(\n    () =>\n      ({\n        ...debouncer,\n        state,\n      }) as ReactDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n    [debouncer, state],\n  )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkKA,SAAgB,aACd,IACA,SACA,kBAA6D,EAAE,GAC/B;CAChC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,uCAA4B;EACjC,MAAM,oBAAoB,IAAIC,oCAC5B,IACA,cACD;AAGD,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,kDAAuB,kBAAkB,OAAO,MAAM,UAAU,EACpE,SAASC,+BACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,WAAU,KAAK;AACf,WAAU,WAAW,cAAc;AAGnC,4BAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,UAAU;OAElC,WAAU,QAAQ;;IAGrB,EAAE,CAAC;CAGN,MAAM,+CAAoB,UAAU,OAAO,UAAU,EAAE,SAASA,+BAAS,CAAC;AAE1E,kCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,WAAW,MAAM,CACnB"}