{"version":3,"file":"VirtualizedMessageList.mjs","names":[],"sources":["../../../../src/components/MessageList/VirtualizedMessageList.tsx"],"sourcesContent":["import type { RefObject } from 'react';\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { FloatingDateSeparator } from './FloatingDateSeparator';\nimport type { ComputeItemKey, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';\nimport { Virtuoso } from 'react-virtuoso';\n\nimport { GiphyPreviewMessage as DefaultGiphyPreviewMessage } from './GiphyPreviewMessage';\nimport { useLastReadData } from './hooks';\nimport {\n  useGiphyPreview,\n  useMessageSetKey,\n  useNewMessageNotification,\n  usePrependedMessagesCount,\n  useScrollToBottomOnNewMessage,\n  useShouldForceScrollToBottom,\n  useUnreadMessagesNotificationVirtualized,\n} from './hooks/VirtualizedMessageList';\nimport { useMarkRead } from './hooks/useMarkRead';\nimport { useScrollerViewport } from './hooks/VirtualizedMessageList/useScrollerViewport';\nimport { useMessageFocusSignalViewed } from './hooks/VirtualizedMessageList/useMessageFocusSignalViewed';\n\nimport {\n  NotificationList as DefaultNotificationList,\n  useNotificationTarget,\n} from '../Notifications';\nimport { useIncomingMessageAnnouncements } from '../Accessibility';\nimport { NewMessageNotification as DefaultNewMessageNotification } from './NewMessageNotification';\nimport { MessageListMainPanel as DefaultMessageListMainPanel } from './MessageListMainPanel';\nimport type {\n  GetGroupStyles,\n  GroupStyle,\n  ProcessMessagesParams,\n  RenderedMessage,\n} from './utils';\nimport { getLastReceived, getMessageGroupStyles, processMessages } from './utils';\nimport { omitUndefinedProps } from './omitUndefinedProps';\nimport type { MessageProps } from '../Message';\nimport { UnreadMessagesNotification as DefaultUnreadMessagesNotification } from './UnreadMessagesNotification';\nimport {\n  calculateFirstItemIndex,\n  calculateItemIndex,\n  EmptyPlaceholder,\n  Header,\n  Item,\n  makeItemsRenderedHandler,\n  messageRenderer,\n} from './VirtualizedMessageListComponents';\n\nimport {\n  ScrollToLatestMessageButton as DefaultScrollToLatestMessageButton,\n  UnreadMessagesSeparator as DefaultUnreadMessagesSeparator,\n} from '../MessageList';\nimport { DateSeparator as DefaultDateSeparator } from '../DateSeparator';\nimport { EventComponent as DefaultMessageSystem } from '../EventComponent';\n\nimport { DialogManagerProvider, useChannel, WithComponents } from '../../context';\nimport type { ChatContextValue } from '../../context/ChatContext';\nimport { useChatContext } from '../../context/ChatContext';\nimport type { ComponentContextValue } from '../../context/ComponentContext';\nimport { useComponentContext } from '../../context/ComponentContext';\nimport { MessageTranslationViewProvider } from '../../context/MessageTranslationViewContext';\nimport { VirtualizedMessageListContextProvider } from '../../context/VirtualizedMessageListContext';\nimport { getMessageSourceKey } from './messageSourceKey';\nimport { useStateStore } from '../../store';\nimport { useThreadContext } from '../Threads';\nimport { useThreadHead } from './hooks/useThreadHead';\nimport { useMessagePaginator } from '../../hooks';\n\nimport type {\n  Channel,\n  LocalMessage,\n  MessageFocusSignalState,\n  MessagePaginatorState,\n  ChannelState as StreamChannelState,\n  TimestampNS,\n  UnreadSnapshotState,\n  UserResponse,\n} from 'stream-chat';\nimport type { UnknownType } from '../../types/types';\nimport { useCanPaginateReplies } from './hooks/useCanPaginateReplies';\nimport { useStableId } from '../UtilityComponents/useStableId';\nimport { useLastDeliveredData } from './hooks/useLastDeliveredData';\nimport { useLastOwnMessage } from './hooks/useLastOwnMessage';\n\ntype PropsDrilledToMessage =\n  | 'formatDate'\n  | 'onMentionsClick'\n  | 'onMentionsHover'\n  | 'onUserClick'\n  | 'onUserHover'\n  | 'reactionDetailsSort'\n  | 'renderText'\n  | 'showAvatar'\n  | 'sortReactions'\n  | 'unsafeHTML';\n\ntype VirtualizedMessageListPropsForContext =\n  | PropsDrilledToMessage\n  | 'closeReactionSelectorOnClick'\n  | 'customMessageRenderer'\n  | 'groupByUser'\n  | 'returnAllReadData';\n\n/** Virtuoso `context`, handed to the components and callbacks that Virtuoso invokes. */\nexport type VirtuosoContext = Required<\n  Pick<\n    ComponentContextValue,\n    'DateSeparator' | 'MessageSystem' | 'UnreadMessagesSeparator'\n  >\n> &\n  Pick<VirtualizedMessageListProps, VirtualizedMessageListPropsForContext> &\n  Pick<ChatContextValue, 'customClasses'> & {\n    channel: Channel;\n    /** The thread parent message rendered above the replies, or null outside a thread. */\n    head: React.ReactElement | null;\n    lastReceivedMessageId: string | null | undefined;\n    loadingMore: boolean;\n    /** Maps a message ID to its position in a group of consecutive messages from one user. */\n    messageGroupStyles: Record<string, GroupStyle>;\n    /** Number of messages prepended to the first page, used to compute virtual indexes. */\n    numItemsPrepended: number;\n    /** Maps the ID of each own message to the users it was delivered to. */\n    ownMessagesDeliveredToOthers: Record<string, UserResponse[]>;\n    /** Maps the ID of each own message to the users who read it. */\n    ownMessagesReadByOthers: Record<string, UserResponse[]>;\n    /**\n     * The messages with date separators inserted and, when configured, deleted messages and the\n     * giphy preview left out.\n     */\n    processedMessages: RenderedMessage[];\n    virtuosoRef: RefObject<VirtuosoHandle | null>;\n    lastOwnMessage?: LocalMessage;\n    firstUnreadMessageId: string | null;\n    /** Unix nanoseconds, as `messagePaginator.unreadStateSnapshot.lastReadAt` carries it. */\n    lastReadDate: TimestampNS | null;\n    lastReadMessageId: string | null;\n    unreadMessageCount: number;\n    /** ID of the message targeted by the paginator's focus signal. */\n    focusedMessageId?: string | null;\n  };\n\ntype VirtualizedMessageListWithContextProps = VirtualizedMessageListProps & {\n  channel: Channel;\n  read?: StreamChannelState['read'];\n};\n\nconst channelReadSelector = (nextValue: { read: StreamChannelState['read'] }) => ({\n  read: nextValue.read,\n});\n\nfunction captureResizeObserverExceededError(e: ErrorEvent) {\n  if (\n    e.message === 'ResizeObserver loop completed with undelivered notifications.' ||\n    e.message === 'ResizeObserver loop limit exceeded'\n  ) {\n    e.stopImmediatePropagation();\n  }\n}\n\nfunction useCaptureResizeObserverExceededError() {\n  useEffect(() => {\n    window.addEventListener('error', captureResizeObserverExceededError);\n    return () => {\n      window.removeEventListener('error', captureResizeObserverExceededError);\n    };\n  }, []);\n}\n\nfunction fractionalItemSize(element: HTMLElement) {\n  return element.getBoundingClientRect().height;\n}\n\nfunction findMessageIndex(messages: RenderedMessage[], id: string) {\n  return messages.findIndex((message) => message.id === id);\n}\n\nfunction calculateInitialTopMostItemIndex(\n  messages: RenderedMessage[],\n  focusedMessageId: string | undefined,\n) {\n  if (focusedMessageId) {\n    const index = findMessageIndex(messages, focusedMessageId);\n    if (index !== -1) {\n      return { align: 'center', index } as const;\n    }\n  }\n  // A bare index aligns the row's top to the viewport top, which leaves a last message taller than\n  // the list hanging below the fold. Anchoring its end opens the list at the true bottom.\n  return { align: 'end', index: messages.length - 1 } as const;\n}\n\nconst unreadStateSnapshotSelector = (state: UnreadSnapshotState) => state;\nconst messageFocusSignalSelector = (state: MessageFocusSignalState) => ({\n  messageFocusSignal: state.signal,\n});\n\nconst messagePaginatorStateSelector = (state: MessagePaginatorState) => ({\n  hasMoreNewer: state.hasMoreHead,\n  isLoading: state.isLoading,\n  messages: state.items ?? [],\n});\n\nconst VirtualizedMessageListWithContext = (\n  props: VirtualizedMessageListWithContextProps,\n) => {\n  const {\n    additionalVirtuosoProps = {},\n    channel,\n    closeReactionSelectorOnClick,\n    customMessageRenderer,\n    formatDate,\n    getGroupStyles,\n    groupByUser = false,\n    hideDeletedMessages = false,\n    hideNewMessageSeparator = false,\n    maxTimeBetweenGroupedMessages,\n    onMentionsClick,\n    onMentionsHover,\n    onUserClick,\n    onUserHover,\n    reactionDetailsSort,\n    renderText,\n    returnAllReadData = false,\n    reviewProcessedMessage,\n    scrollToLatestMessageOnFocus = false,\n    separateGiphyPreview = false,\n    showAvatar,\n    showUnreadNotificationAlways,\n    sortReactions,\n    stickToBottomScrollBehavior = 'smooth',\n    suppressAutoscroll: suppressAutoscrollFromProps = false,\n    unsafeHTML,\n    withDateSeparator = false,\n  } = props;\n  const thread = useThreadContext();\n  const isThreadList = !!thread;\n  // The list-wide props every message gets, the thread's parent message and the separate giphy\n  // preview included.\n  const messageProps: Pick<\n    VirtualizedMessageListProps,\n    PropsDrilledToMessage | 'closeReactionSelectorOnClick'\n  > = {\n    closeReactionSelectorOnClick,\n    formatDate,\n    onMentionsClick,\n    onMentionsHover,\n    onUserClick,\n    onUserHover,\n    reactionDetailsSort,\n    renderText,\n    showAvatar,\n    sortReactions,\n    unsafeHTML,\n  };\n  const threadHead = useThreadHead(messageProps);\n  const [suppressAutoscrollWhileLoadingOlder, setSuppressAutoscrollWhileLoadingOlder] =\n    React.useState(false);\n  const suppressAutoscroll =\n    suppressAutoscrollFromProps || suppressAutoscrollWhileLoadingOlder;\n  const loadingOlderRef = useRef(false);\n\n  const { components: virtuosoComponentsFromProps, ...overridingVirtuosoProps } =\n    additionalVirtuosoProps;\n\n  // Keeps react-virtuoso's ResizeObserver loop errors from reaching Sentry or other trackers.\n  useCaptureResizeObserverExceededError();\n\n  const {\n    DateSeparator = DefaultDateSeparator,\n    GiphyPreviewMessage = DefaultGiphyPreviewMessage,\n    MessageSystem = DefaultMessageSystem,\n    NewMessageNotification = DefaultNewMessageNotification,\n    ScrollToLatestMessageButton = DefaultScrollToLatestMessageButton,\n    TypingIndicator,\n    UnreadMessagesNotification = DefaultUnreadMessagesNotification,\n    UnreadMessagesSeparator = DefaultUnreadMessagesSeparator,\n    VirtualMessage,\n  } = useComponentContext();\n  // `VirtualMessage` overrides `MessageUI` through this subtree's `ComponentContext`. Memoized so\n  // consumers below do not get a new value each render.\n  const virtualMessageOverrides = useMemo(\n    () => ({ MessageUI: VirtualMessage }),\n    [VirtualMessage],\n  );\n\n  const { client, customClasses } = useChatContext();\n  const messagePaginator = useMessagePaginator();\n\n  const { hasMoreNewer, isLoading, messages } = useStateStore(\n    messagePaginator.state,\n    messagePaginatorStateSelector,\n  );\n  const { messageFocusSignal } = useStateStore(\n    messagePaginator.messageFocusSignal,\n    messageFocusSignalSelector,\n  );\n\n  const channelUnreadUiState = useStateStore(\n    messagePaginator.unreadStateSnapshot,\n    unreadStateSnapshotSelector,\n  );\n  const focusedMessageId = messageFocusSignal?.messageId;\n\n  const virtuoso = useRef<VirtuosoHandle>(null);\n  const virtualListRef = useRef<HTMLDivElement>(null);\n\n  const lastRead = useMemo(() => channel.lastRead?.(), [channel]);\n\n  const {\n    show: showUnreadMessagesNotification,\n    toggleShowUnreadMessagesNotification,\n    unreadIsBelow,\n  } = useUnreadMessagesNotificationVirtualized({\n    showAlways: !!showUnreadNotificationAlways,\n  });\n\n  const { giphyPreviewMessage, setGiphyPreviewMessage } =\n    useGiphyPreview(separateGiphyPreview);\n\n  const processedMessages = useMemo(() => {\n    if (typeof messages === 'undefined') {\n      return [];\n    }\n\n    if (\n      !withDateSeparator &&\n      !hideDeletedMessages &&\n      hideNewMessageSeparator &&\n      !separateGiphyPreview\n    ) {\n      return messages;\n    }\n\n    return processMessages({\n      hideDeletedMessages,\n      hideNewMessageSeparator,\n      lastRead,\n      messages,\n      reviewProcessedMessage,\n      setGiphyPreviewMessage,\n      userId: client.userID || '',\n      withDateSeparator,\n    });\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [\n    withDateSeparator,\n    hideDeletedMessages,\n    hideNewMessageSeparator,\n    lastRead,\n    messages,\n    messages?.length,\n    client.userID,\n  ]);\n\n  // Virtuoso's `itemsRendered` is set at render time, while `FloatingDateSeparator` is a child that\n  // owns the actual handler and assigns it to this ref.\n  const floatingDateItemsRenderedRef = useRef<\n    ((rendered: RenderedMessage[]) => void) | null\n  >(null);\n\n  const lastOwnMessage = useLastOwnMessage({ messages, ownUserId: client.user?.id });\n\n  const ownMessagesReadByOthers = useLastReadData({\n    channel,\n    lastOwnMessage,\n    messages: messages || [],\n    returnAllReadData,\n  });\n\n  const ownMessagesDeliveredToOthers = useLastDeliveredData({\n    channel,\n    lastOwnMessage,\n    messages: messages || [],\n    returnAllReadData,\n  });\n\n  const lastReceivedMessageId = useMemo(\n    () => getLastReceived(processedMessages),\n    [processedMessages],\n  );\n\n  const messageGroupStyles = useMemo(\n    () =>\n      getMessageGroupStyles({\n        getGroupStyles,\n        groupByUser,\n        maxTimeBetweenGroupedMessages,\n        messages: processedMessages,\n      }),\n    [getGroupStyles, groupByUser, maxTimeBetweenGroupedMessages, processedMessages],\n  );\n\n  const {\n    atBottom,\n    isMessageListScrolledToBottom,\n    newMessagesNotification,\n    setIsMessageListScrolledToBottom,\n    setNewMessagesNotification,\n  } = useNewMessageNotification(processedMessages, client.userID);\n\n  const { handleScrollerRef, isAtTrueBottom, remeasure, threshold } =\n    useScrollerViewport();\n\n  // `scrollerRef` and `totalListHeightChanged` are composed with the integrator's and applied after\n  // the `additionalVirtuosoProps` spread, so an override cannot switch the measurement off.\n  const {\n    customScrollParent,\n    scrollerRef: scrollerRefFromProps,\n    totalListHeightChanged: totalListHeightChangedFromProps,\n    useWindowScroll,\n  } = overridingVirtuosoProps;\n\n  // Virtuoso's window-scroll path never calls the supplied `scrollerRef` (it passes its own no-op),\n  // so in these two modes the hook must be told what to measure. Otherwise the thresholds stay at\n  // their full-height defaults and the true-bottom check always answers \"yes\".\n  useEffect(() => {\n    if (!useWindowScroll && !customScrollParent) return;\n    handleScrollerRef(customScrollParent ?? window);\n  }, [customScrollParent, handleScrollerRef, useWindowScroll]);\n\n  const [scrollerElement, setScrollerElement] = useState<HTMLElement | Window | null>(\n    null,\n  );\n\n  const scrollerRef = useCallback(\n    (element: HTMLElement | Window | null) => {\n      handleScrollerRef(element);\n      setScrollerElement(element);\n      scrollerRefFromProps?.(element);\n    },\n    [handleScrollerRef, scrollerRefFromProps],\n  );\n\n  // The element whose scrolling shows the floating date. In the window-scroll modes Virtuoso never\n  // calls `scrollerRef`, so the scroll parent is named directly. In those modes the floating date is\n  // not pinned to the scroller's top edge, so its placement there is best-effort.\n  const floatingDateScrollElement =\n    customScrollParent ??\n    (useWindowScroll && typeof window !== 'undefined' ? window : scrollerElement);\n\n  // Content can grow without the scroller resizing or scrolling (e.g. an avatar or image loading\n  // late), which moves the true bottom without firing either event the hook observes.\n  const totalListHeightChanged = useCallback(\n    (height: number) => {\n      remeasure();\n      totalListHeightChangedFromProps?.(height);\n    },\n    [remeasure, totalListHeightChangedFromProps],\n  );\n\n  useMarkRead({\n    hasMoreNewer,\n    // Virtuoso's at-bottom flag has a threshold, so on a short list it reads true while part of the\n    // last message is still clipped. Marking a channel read needs the stricter signal.\n    isAtTrueBottom,\n    isMessageListScrolledToBottom,\n    messageListIsThread: isThreadList,\n  });\n\n  useIncomingMessageAnnouncements({\n    activeThreadId: thread?.id,\n    channel,\n    ownUserId: channel.getClient().user?.id,\n    threadList: isThreadList,\n  });\n\n  const scrollToBottom = useCallback(async () => {\n    if (messagePaginator.hasMoreHead) {\n      await messagePaginator.jumpToTheLatestMessage();\n    } else if (virtuoso.current) {\n      // Without `align: 'end'` a last message taller than the viewport lands with its bottom\n      // clipped.\n      virtuoso.current.scrollToIndex({\n        align: 'end',\n        index: processedMessages.length - 1,\n      });\n    }\n\n    setNewMessagesNotification(false);\n  }, [\n    messagePaginator,\n    virtuoso,\n    processedMessages,\n    setNewMessagesNotification,\n    // `processedMessages` can be rebuilt with a new identity, hence the `.length` dependency.\n    // processedMessages.length,\n  ]);\n\n  useScrollToBottomOnNewMessage({\n    messages,\n    scrollToBottom,\n    scrollToLatestMessageOnFocus,\n  });\n\n  const numItemsPrepended = usePrependedMessagesCount(\n    processedMessages,\n    withDateSeparator,\n  );\n\n  const { messageSetKey } = useMessageSetKey({ messages });\n\n  const shouldForceScrollToBottom = useShouldForceScrollToBottom(\n    processedMessages,\n    client.userID,\n  );\n\n  const handleItemsRendered = useMemo(\n    () =>\n      makeItemsRenderedHandler(\n        [\n          toggleShowUnreadMessagesNotification,\n          (rendered) => floatingDateItemsRenderedRef.current?.(rendered),\n        ],\n        processedMessages,\n      ),\n    [processedMessages, toggleShowUnreadMessagesNotification],\n  );\n  const followOutput = (isAtBottom: boolean) => {\n    if (messagePaginator.hasMoreHead || suppressAutoscroll) {\n      return false;\n    }\n\n    if (shouldForceScrollToBottom()) {\n      return isAtBottom ? stickToBottomScrollBehavior : 'auto';\n    }\n    // A message from another user arrived: only follow when already at the bottom.\n    return isAtBottom ? stickToBottomScrollBehavior : false;\n  };\n\n  const computeItemKey = useCallback<ComputeItemKey<UnknownType, VirtuosoContext>>(\n    (index, _, { numItemsPrepended, processedMessages }) =>\n      processedMessages[calculateItemIndex(index, numItemsPrepended)].id,\n    [],\n  );\n\n  const canPaginateReplies = useCanPaginateReplies();\n\n  const atBottomStateChange = (isAtBottom: boolean) => {\n    atBottom.current = isAtBottom;\n    setIsMessageListScrolledToBottom(isAtBottom);\n\n    if (isAtBottom) {\n      // An empty thread is at both ends at once, so Virtuoso reports both on mount;\n      // `canPaginateReplies` keeps that from becoming a request.\n      if (canPaginateReplies) messagePaginator.toHead();\n      setNewMessagesNotification?.(false);\n    }\n  };\n  const atTopStateChange = (isAtTop: boolean) => {\n    if (isAtTop) {\n      if (!canPaginateReplies) return;\n      if (loadingOlderRef.current) return;\n      loadingOlderRef.current = true;\n      setSuppressAutoscrollWhileLoadingOlder(true);\n      void messagePaginator.toTail().finally(() => {\n        loadingOlderRef.current = false;\n        setSuppressAutoscrollWhileLoadingOlder(false);\n      });\n    }\n  };\n\n  const focusViewedSignalRef = useMessageFocusSignalViewed({\n    containerRef: virtualListRef,\n    isMessageInList:\n      !!focusedMessageId && findMessageIndex(processedMessages, focusedMessageId) !== -1,\n    messageFocusSignal,\n    messagePaginator,\n    scrollElement: floatingDateScrollElement,\n  });\n\n  // Brings the focused message into view, again whenever the list changes (its page loads, the\n  // list remounts for the new message set), until the reader has viewed it. After that the reader\n  // may scroll away, and later changes of the list must not pull them back.\n  useEffect(() => {\n    let scrollTimeout: ReturnType<typeof setTimeout>;\n    if (messageFocusSignal && focusViewedSignalRef.current !== messageFocusSignal) {\n      const index = findMessageIndex(processedMessages, messageFocusSignal.messageId);\n      if (index !== -1) {\n        scrollTimeout = setTimeout(() => {\n          virtuoso.current?.scrollToIndex({ align: 'center', index });\n        }, 0);\n      }\n    }\n    return () => {\n      clearTimeout(scrollTimeout);\n    };\n  }, [focusViewedSignalRef, messageFocusSignal, processedMessages]);\n\n  const id = useStableId();\n\n  const dialogManagerId = isThreadList\n    ? `virtualized-message-list-dialog-manager-thread-${id}`\n    : `virtualized-message-list-dialog-manager-${id}`;\n\n  const list = (\n    <VirtualizedMessageListContextProvider value={{ scrollToBottom }}>\n      <MessageTranslationViewProvider>\n        <DialogManagerProvider id={dialogManagerId}>\n          {!isThreadList && showUnreadMessagesNotification && (\n            <UnreadMessagesNotification\n              unreadCount={channelUnreadUiState?.unreadCount}\n              unreadIsBelow={unreadIsBelow}\n            />\n          )}\n          <div\n            className={customClasses?.virtualizedMessageList || 'str-chat__virtual-list'}\n            ref={virtualListRef}\n          >\n            <FloatingDateSeparator\n              itemsRenderedRef={floatingDateItemsRenderedRef}\n              processedMessages={processedMessages}\n              scrollElement={floatingDateScrollElement}\n              withDateSeparator={withDateSeparator}\n            />\n            <Virtuoso<UnknownType, VirtuosoContext>\n              atBottomStateChange={atBottomStateChange}\n              atBottomThreshold={threshold}\n              atTopStateChange={atTopStateChange}\n              atTopThreshold={threshold}\n              className='str-chat__message-list-scroll'\n              components={{\n                EmptyPlaceholder,\n                Header,\n                Item,\n                ...virtuosoComponentsFromProps,\n              }}\n              computeItemKey={computeItemKey}\n              context={{\n                ...messageProps,\n                channel,\n                customClasses,\n                customMessageRenderer,\n                DateSeparator,\n                firstUnreadMessageId: channelUnreadUiState?.firstUnreadMessageId,\n                focusedMessageId,\n                groupByUser,\n                head: threadHead,\n                lastOwnMessage,\n                lastReadDate: channelUnreadUiState?.lastReadAt,\n                lastReadMessageId: channelUnreadUiState?.lastReadMessageId,\n                lastReceivedMessageId,\n                loadingMore: isLoading,\n                messageGroupStyles,\n                MessageSystem,\n                numItemsPrepended,\n                ownMessagesDeliveredToOthers,\n                ownMessagesReadByOthers,\n                processedMessages,\n                returnAllReadData,\n                unreadMessageCount: channelUnreadUiState?.unreadCount,\n                UnreadMessagesSeparator,\n                virtuosoRef: virtuoso,\n              }}\n              firstItemIndex={calculateFirstItemIndex(numItemsPrepended)}\n              followOutput={followOutput}\n              increaseViewportBy={{ bottom: 200, top: 0 }}\n              initialTopMostItemIndex={calculateInitialTopMostItemIndex(\n                processedMessages,\n                focusedMessageId,\n              )}\n              itemContent={messageRenderer}\n              itemSize={fractionalItemSize}\n              itemsRendered={handleItemsRendered}\n              key={messageSetKey}\n              ref={virtuoso}\n              style={{ overflowX: 'hidden' }}\n              totalCount={processedMessages.length}\n              {...overridingVirtuosoProps}\n              scrollerRef={scrollerRef}\n              totalListHeightChanged={totalListHeightChanged}\n            />\n            {/* Only for messages that arrived while the reader was scrolled up. Reading an older\n                  window (e.g. after a jump) is signalled by ScrollToLatestMessageButton instead. */}\n            <NewMessageNotification\n              newMessageCount={channelUnreadUiState?.unreadCount}\n              showNotification={newMessagesNotification && !isMessageListScrolledToBottom}\n            />\n            {/* An empty list has nothing to jump to but can report \"not at bottom\". */}\n            {messages.length > 0 && (\n              <ScrollToLatestMessageButton\n                isMessageListScrolledToBottom={isMessageListScrolledToBottom}\n                isNotAtLatestMessageSet={hasMoreNewer && messages.length > 0}\n                onClick={scrollToBottom}\n              />\n            )}\n          </div>\n        </DialogManagerProvider>\n        {TypingIndicator && (\n          <TypingIndicator\n            isMessageListScrolledToBottom={isMessageListScrolledToBottom}\n            scrollToBottom={scrollToBottom}\n          />\n        )}\n        {giphyPreviewMessage && (\n          <GiphyPreviewMessage\n            {...omitUndefinedProps(messageProps)}\n            message={giphyPreviewMessage}\n          />\n        )}\n      </MessageTranslationViewProvider>\n    </VirtualizedMessageListContextProvider>\n  );\n\n  // Only wrap when there is something to override, so the common case adds no provider.\n  return VirtualMessage ? (\n    <WithComponents overrides={virtualMessageOverrides}>{list}</WithComponents>\n  ) : (\n    list\n  );\n};\n\nexport type VirtualizedMessageListProps = Partial<\n  Pick<MessageProps, PropsDrilledToMessage>\n> & {\n  /** Props passed to the underlying [`react-virtuoso`](https://virtuoso.dev/virtuoso-api-reference/). */\n  additionalVirtuosoProps?: VirtuosoProps<UnknownType, VirtuosoContext>;\n  /** Closes the reaction selector after a reaction is picked. */\n  closeReactionSelectorOnClick?: boolean;\n  /** Replaces the default item renderer, so the props that renderer reads are ignored. */\n  customMessageRenderer?: (\n    messageList: RenderedMessage[],\n    index: number,\n  ) => React.ReactElement;\n  /** Computes the group style of a message from its neighbors. Defaults to `getGroupStyles`. */\n  getGroupStyles?: GetGroupStyles;\n  /** Groups consecutive messages from the same user. Defaults to `false`. */\n  groupByUser?: boolean;\n  /** Hides deleted messages from the list. Defaults to `false`. */\n  hideDeletedMessages?: boolean;\n  /** Hides the date separator before the first unread incoming message. Defaults to `false`. */\n  hideNewMessageSeparator?: boolean;\n  /** Maximum time (ms) between two messages for them to stay in the same group. */\n  maxTimeBetweenGroupedMessages?: number;\n  /** Computes read and delivery data for every own message, not only the last one. */\n  returnAllReadData?: boolean;\n  /**\n   * Reviews the changes made around each message (e.g. a date separator injected before it). The\n   * returned array is appended to the rendered messages in place of `changes`.\n   */\n  reviewProcessedMessage?: ProcessMessagesParams['reviewProcessedMessage'];\n  /**\n   * Scrolls to the latest message when the window regains focus, if the messages changed while it\n   * was blurred. Defaults to `false`.\n   */\n  scrollToLatestMessageOnFocus?: boolean;\n  /**\n   * Renders the Giphy preview as a separate component after the list instead of inline. Defaults\n   * to `false`.\n   */\n  separateGiphyPreview?: boolean;\n  /**\n   * Shows the unread notification whenever the `UnreadMessagesSeparator` is out of view. Defaults\n   * to `false`: it shows only when the separator is scrolled above the viewport.\n   */\n  showUnreadNotificationAlways?: boolean;\n  /**\n   * `scrollTo` behavior when new messages arrive while at the bottom: `'smooth'` for regular\n   * channels, `'auto'` (instant) for high throughput. Defaults to `'smooth'`.\n   */\n  stickToBottomScrollBehavior?: 'smooth' | 'auto';\n  /** Prevents autoscrolling to the bottom on new messages. */\n  suppressAutoscroll?: boolean;\n  /** Injects date separators into the list. Defaults to `false`. */\n  withDateSeparator?: boolean;\n};\n\n/** Renders the messages of the active channel or thread in a virtualized list. */\nexport function VirtualizedMessageList(props: VirtualizedMessageListProps) {\n  const channel = useChannel();\n  const thread = useThreadContext();\n  const notificationTarget = useNotificationTarget();\n  const {\n    MessageListMainPanel = DefaultMessageListMainPanel,\n    NotificationList = DefaultNotificationList,\n  } = useComponentContext();\n\n  const { read } = useStateStore(channel?.state, channelReadSelector) ?? {};\n\n  // The panel and the notification list sit outside the keyed list so a notification survives a\n  // switch.\n  // todo: finalize the props shape for VirtualizedMessageList\n  return (\n    <MessageListMainPanel>\n      <VirtualizedMessageListWithContext\n        channel={channel}\n        // The list's local state (Virtuoso's scroll offset above all) belongs to one thread or\n        // channel and resets on a switch.\n        key={getMessageSourceKey({ channel, thread })}\n        read={read}\n        {...props}\n      />\n      <NotificationList panel={notificationTarget} />\n    </MessageListMainPanel>\n  );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmJA,IAAM,uBAAuB,eAAqD,EAChF,MAAM,UAAU,KAClB;AAEA,SAAS,mCAAmC,GAAe;CACzD,IACE,EAAE,YAAY,mEACd,EAAE,YAAY,sCAEd,EAAE,yBAAyB;AAE/B;AAEA,SAAS,wCAAwC;CAC/C,gBAAgB;EACd,OAAO,iBAAiB,SAAS,kCAAkC;EACnE,aAAa;GACX,OAAO,oBAAoB,SAAS,kCAAkC;EACxE;CACF,GAAG,CAAC,CAAC;AACP;AAEA,SAAS,mBAAmB,SAAsB;CAChD,OAAO,QAAQ,sBAAsB,CAAC,CAAC;AACzC;AAEA,SAAS,iBAAiB,UAA6B,IAAY;CACjE,OAAO,SAAS,WAAW,YAAY,QAAQ,OAAO,EAAE;AAC1D;AAEA,SAAS,iCACP,UACA,kBACA;CACA,IAAI,kBAAkB;EACpB,MAAM,QAAQ,iBAAiB,UAAU,gBAAgB;EACzD,IAAI,UAAU,IACZ,OAAO;GAAE,OAAO;GAAU;EAAM;CAEpC;CAGA,OAAO;EAAE,OAAO;EAAO,OAAO,SAAS,SAAS;CAAE;AACpD;AAEA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