useScrollToCurrentItem.tsx 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import {RefObject, useEffect, useMemo} from 'react';
  2. import type {List as ReactVirtualizedList} from 'react-virtualized';
  3. import {useReplayContext} from 'sentry/components/replays/replayContext';
  4. import type {Crumb} from 'sentry/types/breadcrumbs';
  5. import {getPrevReplayEvent} from 'sentry/utils/replays/getReplayEvent';
  6. type Opts = {
  7. breadcrumbs: undefined | Crumb[];
  8. ref: RefObject<ReactVirtualizedList>;
  9. startTimestampMs: number;
  10. };
  11. function useScrollToCurrentItem({breadcrumbs, ref, startTimestampMs}: Opts) {
  12. const {currentTime} = useReplayContext();
  13. const itemLookup = useMemo(
  14. () =>
  15. breadcrumbs &&
  16. breadcrumbs
  17. .map(({timestamp}, i) => [+new Date(timestamp || ''), i])
  18. .sort(([a], [b]) => a - b),
  19. [breadcrumbs]
  20. );
  21. const current = useMemo(
  22. () =>
  23. getPrevReplayEvent({
  24. itemLookup,
  25. items: breadcrumbs || [],
  26. targetTimestampMs: startTimestampMs + currentTime,
  27. }),
  28. [itemLookup, breadcrumbs, currentTime, startTimestampMs]
  29. );
  30. useEffect(() => {
  31. if (ref.current && current) {
  32. const index = breadcrumbs?.findIndex(crumb => crumb.id === current.id);
  33. ref.current?.scrollToRow(index);
  34. }
  35. }, [breadcrumbs, current, ref]);
  36. }
  37. export default useScrollToCurrentItem;