{"version":3,"file":"InfiniteScrollPaginator.mjs","names":[],"sources":["../../../../src/components/InfiniteScrollPaginator/InfiniteScrollPaginator.tsx"],"sourcesContent":["import clsx from 'clsx';\nimport throttle from 'lodash.throttle';\nimport type { PropsWithChildren } from 'react';\nimport { forwardRef } from 'react';\nimport React, { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { DEFAULT_LOAD_PAGE_SCROLL_THRESHOLD } from '../../constants/limits';\nimport { useStableCallback } from '../../utils/useStableCallback';\n\n// Prevents Chrome hangups, see:\n// https://stackoverflow.com/questions/47524205/random-high-content-download-time-in-chrome/47684257#47684257\nconst mousewheelListener = (event: Event) => {\n  if (event instanceof WheelEvent && event.deltaY === 1) {\n    event.preventDefault();\n  }\n};\n\ntype DistancesToEdges = { distanceFromBottom: number; distanceFromTop: number };\n\n/** The scroll position's distance to both ends of the content; `null` while hidden or unmounted. */\nconst getDistancesToEdges = (\n  root: HTMLElement | null,\n  content: HTMLElement | null,\n): DistancesToEdges | null => {\n  if (!root || root.offsetParent === null || !content) return null;\n  return {\n    distanceFromBottom: content.scrollHeight - root.scrollTop - root.clientHeight,\n    distanceFromTop: root.scrollTop,\n  };\n};\n\ntype EdgesWithinThreshold = { nearBottom: boolean; nearTop: boolean };\n\nconst NO_EDGE_WITHIN_THRESHOLD: EdgesWithinThreshold = {\n  nearBottom: false,\n  nearTop: false,\n};\n\n/** The edges whose next page the scroll position is close enough to load. */\nconst getEdgesWithinThreshold = (\n  { distanceFromBottom, distanceFromTop }: DistancesToEdges,\n  threshold: number,\n): EdgesWithinThreshold => ({\n  nearBottom: distanceFromBottom < threshold,\n  nearTop: distanceFromTop < threshold,\n});\n\n/** Whether `current` is within the threshold of an edge that `previous` was not. */\nconst reachedAnotherEdge = (\n  previous: EdgesWithinThreshold,\n  current: EdgesWithinThreshold,\n) =>\n  (current.nearTop && !previous.nearTop) || (current.nearBottom && !previous.nearBottom);\n\ntype InfiniteScrollPaginatorOwnProps = {\n  element?: React.ElementType;\n  /**\n   * Props for the inner element that wraps `children`, e.g. `role=\"presentation\"` to keep it out of\n   * the accessibility tree so a `listbox` or `menu` ancestor still owns its `option` or `menuitem`\n   * children.\n   */\n  contentProps?: React.ComponentProps<'div'>;\n  /**\n   * Called with the scroll distances on each check of the distance to the edges (see\n   * `loadNextDebounceMs`).\n   */\n  listenToScroll?: (\n    distanceFromBottom: number,\n    distanceFromTop: number,\n    threshold: number,\n  ) => void;\n  /**\n   * The minimum interval, in milliseconds, between two checks of the distance to the edges while\n   * the list scrolls or resizes. Scrolling is checked as it happens, not once it stops: the first\n   * scroll, and the first one within `threshold` of an edge, are checked at once, and a final check\n   * runs when the interval ends, so the position the scrolling stopped at is always checked.\n   * Defaults to 500.\n   */\n  loadNextDebounceMs?: number;\n  loadNextOnScrollToBottom?: () => void;\n  loadNextOnScrollToTop?: () => void;\n  /** Distance (px) from the top or bottom within which the `loadNextOnScroll*` callbacks fire. */\n  threshold?: number;\n  useCapture?: boolean;\n};\n\n// Polymorphic props, defaulting to 'div'. `ref` comes from `ComponentPropsWithRef<C>`, so no\n// separate `ref?` member is declared (the react-compat lint rule forbids one in a prop type).\nexport type InfiniteScrollPaginatorProps<C extends React.ElementType = 'div'> =\n  PropsWithChildren<\n    InfiniteScrollPaginatorOwnProps & {\n      element?: C;\n    } & Omit<\n        React.ComponentPropsWithRef<C>,\n        keyof InfiniteScrollPaginatorOwnProps | 'element'\n      >\n  >;\n\ntype InfiniteScrollPaginatorComponent = <C extends React.ElementType = 'div'>(\n  props: InfiniteScrollPaginatorProps<C>,\n) => React.ReactNode;\n\nconst renderPolymorphic = <C extends React.ElementType>(\n  Comp: C,\n  props: React.ComponentPropsWithRef<C>,\n  children?: React.ReactNode,\n) => React.createElement(Comp, props, children);\n\nexport const InfiniteScrollPaginator = forwardRef(function InfiniteScrollPaginator<\n  E extends React.ElementType = 'div',\n>(props: InfiniteScrollPaginatorProps<E>, ref: React.ForwardedRef<unknown>) {\n  const {\n    children,\n    className,\n    contentProps,\n    element: Component = 'div' as E,\n    listenToScroll,\n    loadNextDebounceMs = 500,\n    loadNextOnScrollToBottom,\n    loadNextOnScrollToTop,\n    threshold = DEFAULT_LOAD_PAGE_SCROLL_THRESHOLD,\n    useCapture = false,\n    ...componentProps\n  } = props;\n  const { className: contentClassName, ...contentRestProps } = contentProps ?? {};\n\n  const rootRef = useRef<HTMLElement | null>(null);\n  const childRef = useRef<HTMLDivElement | null>(null);\n\n  // Reports the distances and loads the next page at an edge, with the props of the latest render.\n  // The loaders guard against being called while a page loads.\n  const checkEdges = useStableCallback(() => {\n    const distances = getDistancesToEdges(rootRef.current, childRef.current);\n    if (!distances) return;\n\n    listenToScroll?.(distances.distanceFromBottom, distances.distanceFromTop, threshold);\n\n    const { nearBottom, nearTop } = getEdgesWithinThreshold(distances, threshold);\n    if (nearTop) loadNextOnScrollToTop?.();\n    if (nearBottom) loadNextOnScrollToBottom?.();\n  });\n\n  // Runs the check at most once per interval (the first call at once, the latest one when the\n  // interval ends). New callback props do not restart the interval: a check left for its end runs\n  // with them.\n  const checkDistanceToEdges = useMemo(\n    () => throttle(checkEdges, loadNextDebounceMs, { leading: true, trailing: true }),\n    [checkEdges, loadNextDebounceMs],\n  );\n\n  useEffect(() => () => checkDistanceToEdges.cancel(), [checkDistanceToEdges]);\n\n  const edgesWithinThresholdRef = useRef(NO_EDGE_WITHIN_THRESHOLD);\n\n  // Checks while scrolling rather than once it stops. Reaching an edge's threshold runs the check at\n  // once: waiting for the interval to end would let a fast scroll reach the edge before the next\n  // page starts loading.\n  const scrollListener = useCallback(() => {\n    checkDistanceToEdges();\n    const distances = getDistancesToEdges(rootRef.current, childRef.current);\n    const edgesWithinThreshold = distances\n      ? getEdgesWithinThreshold(distances, threshold)\n      : NO_EDGE_WITHIN_THRESHOLD;\n    if (reachedAnotherEdge(edgesWithinThresholdRef.current, edgesWithinThreshold)) {\n      checkDistanceToEdges.flush();\n    }\n    edgesWithinThresholdRef.current = edgesWithinThreshold;\n  }, [checkDistanceToEdges, threshold]);\n\n  useEffect(() => {\n    const scrollElement = rootRef.current;\n    if (!scrollElement) return;\n\n    scrollElement.addEventListener('scroll', scrollListener, useCapture);\n\n    return () => {\n      scrollElement.removeEventListener('scroll', scrollListener, useCapture);\n    };\n  }, [scrollListener, useCapture]);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!root || typeof ResizeObserver === 'undefined') return;\n    // The check runs in the next animation frame, not in the observer's callback. It can load a\n    // page, and the store update renders synchronously before the callback returns: a root sized by\n    // its content would resize while the browser is still delivering resize notifications, which it\n    // reports as \"ResizeObserver loop completed with undelivered notifications\". From a frame, the\n    // page renders before layout, and the observer reports that resize in its next delivery.\n    let frameId: number | undefined;\n    const observer = new ResizeObserver(() => {\n      if (typeof frameId !== 'undefined') return;\n      frameId = window.requestAnimationFrame(() => {\n        frameId = undefined;\n        scrollListener();\n      });\n    });\n    observer.observe(root as Element);\n\n    return () => {\n      observer.disconnect();\n      if (typeof frameId !== 'undefined') window.cancelAnimationFrame(frameId);\n    };\n  }, [scrollListener]);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    if (root) {\n      root.addEventListener('wheel', mousewheelListener, { passive: false });\n    }\n    return () => {\n      if (root) {\n        root.removeEventListener('wheel', mousewheelListener);\n      }\n    };\n  }, []);\n\n  return renderPolymorphic(\n    Component as E,\n    {\n      ...(componentProps as React.ComponentPropsWithRef<E>),\n      className: clsx('str-chat__infinite-scroll-paginator', className),\n      ref: (node: React.ComponentRef<E> | null) => {\n        if (typeof ref === 'function') {\n          ref(node);\n        } else if (ref && 'current' in ref) {\n          (ref as React.RefObject<React.ComponentRef<E> | null>).current = node;\n        }\n        rootRef.current = node && node instanceof HTMLElement ? node : null;\n      },\n    },\n    React.createElement(\n      'div',\n      {\n        ...contentRestProps,\n        className: clsx('str-chat__infinite-scroll-paginator__content', contentClassName),\n        ref: childRef,\n      },\n      children,\n    ),\n  );\n}) as InfiniteScrollPaginatorComponent;\n"],"mappings":";;;;;AAUA,IAAM,sBAA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