{"version":3,"file":"useBatcher.cjs","names":["useDefaultPacerOptions","Batcher","shallow"],"sources":["../../src/batcher/useBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'react'\nimport { Batcher } from '@tanstack/pacer/batcher'\nimport { shallow, useSelector } from '@tanstack/react-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/react-store'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\nimport type { FunctionComponent, ReactNode } from 'react'\n\nexport interface ReactBatcherOptions<\n  TValue,\n  TSelected = {},\n> extends BatcherOptions<TValue> {\n  /**\n   * Optional callback invoked when the component unmounts. Receives the batcher instance.\n   * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n   */\n  onUnmount?: (batcher: ReactBatcher<TValue, TSelected>) => void\n}\n\nexport interface ReactBatcher<TValue, TSelected = {}> extends Omit<\n  Batcher<TValue>,\n  'store'\n> {\n  /**\n   * A React HOC (Higher Order Component) that allows you to subscribe to the batcher state.\n   *\n   * This is useful for opting into state re-renders for specific parts of the batcher state\n   * deep in your component tree without needing to pass a selector to the hook.\n   *\n   * @example\n   * <batcher.Subscribe selector={(state) => ({ size: state.size, isPending: state.isPending })}>\n   *   {({ size, isPending }) => (\n   *     <div>Batch: {size} items, {isPending ? 'Pending' : 'Ready'}</div>\n   *   )}\n   * </batcher.Subscribe>\n   */\n  Subscribe: <TSelected>(props: {\n    selector: (state: BatcherState<TValue>) => TSelected\n    children: ((state: TSelected) => ReactNode) | ReactNode\n  }) => ReturnType<FunctionComponent>\n  /**\n   * Reactive state that will be updated and re-rendered when the batcher state changes\n   *\n   * Use this instead of `batcher.store.state`\n   */\n  readonly state: Readonly<TSelected>\n  /**\n   * @deprecated Use `batcher.state` instead of `batcher.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<BatcherState<TValue>>>\n}\n\n/**\n * A React hook that creates and manages a Batcher instance.\n *\n * This is a lower-level hook that provides direct access to the Batcher'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 * The Batcher collects items and processes them in batches based on configurable conditions:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\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 `batcher.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 batch executions that have been completed\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending')\n * - `totalItemsProcessed`: Total number of items processed across all batches\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useBatcher(fn, {\n *   maxSize: 5,\n *   wait: 2000,\n *   onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = useBatcher<number>(\n *   (items) => console.log('Processing batch:', items),\n *   { maxSize: 5, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <batcher.Subscribe selector={(state) => ({ size: state.size, isPending: state.isPending })}>\n *   {({ size, isPending }) => (\n *     <div>Batch: {size} items, {isPending ? 'Pending' : 'Ready'}</div>\n *   )}\n * </batcher.Subscribe>\n *\n * // Opt-in to re-render when batch size changes at hook level (optimized for displaying queue size)\n * const batcher = useBatcher<number>(\n *   (items) => console.log('Processing batch:', items),\n *   { maxSize: 5, wait: 2000 },\n *   (state) => ({\n *     size: state.size,\n *     isEmpty: state.isEmpty\n *   })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const batcher = useBatcher<number>(\n *   (items) => console.log('Processing batch:', items),\n *   { maxSize: 5, wait: 2000 },\n *   (state) => ({\n *     executionCount: state.executionCount,\n *     totalItemsProcessed: state.totalItemsProcessed\n *   })\n * );\n *\n * // Opt-in to re-render when processing state changes (optimized for loading indicators)\n * const batcher = useBatcher<number>(\n *   (items) => console.log('Processing batch:', items),\n *   { maxSize: 5, wait: 2000 },\n *   (state) => ({\n *     isPending: state.isPending,\n *     isRunning: state.isRunning,\n *     status: state.status\n *   })\n * );\n *\n * // Example with custom state management and batching\n * const [items, setItems] = useState([]);\n *\n * const batcher = useBatcher<number>(\n *   (items) => console.log('Processing batch:', items),\n *   {\n *     maxSize: 5,\n *     wait: 2000,\n *     onItemsChange: (batcher) => setItems(batcher.peekAllItems()),\n *     getShouldExecute: (items) => items.length >= 3\n *   }\n * );\n *\n * // Add items to batch - they'll be processed when conditions are met\n * batcher.addItem(1);\n * batcher.addItem(2);\n * batcher.addItem(3); // Triggers batch processing\n *\n * // Control the batcher\n * batcher.stop();  // Pause batching\n * batcher.start(); // Resume batching\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { size, isPending } = batcher.state;\n * ```\n */\nexport function useBatcher<TValue, TSelected = {}>(\n  fn: (items: Array<TValue>) => void,\n  options: ReactBatcherOptions<TValue, TSelected> = {},\n  selector: (state: BatcherState<TValue>) => TSelected = () =>\n    ({}) as TSelected,\n): ReactBatcher<TValue, TSelected> {\n  const mergedOptions = {\n    ...useDefaultPacerOptions().batcher,\n    ...options,\n  } as ReactBatcherOptions<TValue, TSelected>\n  const [batcher] = useState(() => {\n    const batcherInstance = new Batcher<TValue>(\n      fn,\n      mergedOptions,\n    ) as unknown as ReactBatcher<TValue, TSelected>\n\n    /* eslint-disable-next-line @eslint-react/component-hook-factories -- Subscribe attached once in useState lazy init; stable per instance */\n    batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n      selector: (state: BatcherState<TValue>) => TSelected\n      children: ((state: TSelected) => ReactNode) | ReactNode\n    }) {\n      const selected = useSelector(batcherInstance.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 batcherInstance\n  })\n\n  batcher.fn = fn\n  batcher.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(batcher)\n      } else {\n        batcher.cancel()\n      }\n    }\n  }, [])\n  /* eslint-enable react-hooks/exhaustive-deps, @eslint-react/exhaustive-deps, react-compiler/react-compiler */\n\n  const state = useSelector(batcher.store, selector, { compare: shallow })\n\n  return useMemo(\n    () =>\n      ({\n        ...batcher,\n        state,\n      }) as ReactBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n    [batcher, state],\n  )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsLA,SAAgB,WACd,IACA,UAAkD,EAAE,EACpD,kBACG,EAAE,GAC4B;CACjC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,qCAA0B;EAC/B,MAAM,kBAAkB,IAAIC,gCAC1B,IACA,cACD;AAGD,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,kDAAuB,gBAAgB,OAAO,MAAM,UAAU,EAClE,SAASC,+BACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,SAAQ,KAAK;AACb,SAAQ,WAAW,cAAc;AAGjC,4BAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,QAAQ;OAEhC,SAAQ,QAAQ;;IAGnB,EAAE,CAAC;CAGN,MAAM,+CAAoB,QAAQ,OAAO,UAAU,EAAE,SAASA,+BAAS,CAAC;AAExE,kCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,SAAS,MAAM,CACjB"}