{"version":3,"file":"ThreadList.mjs","names":[],"sources":["../../../../../src/components/Threads/ThreadList/ThreadList.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useRef } from 'react';\nimport type { ComputeItemKey, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';\nimport { Virtuoso } from 'react-virtuoso';\nimport type { PaginatorState, Thread } from 'stream-chat';\n\nimport { useVirtualizedListboxKeyboardNavigation } from '../../../a11y/hooks/useVirtualizedListboxKeyboardNavigation';\nimport { ThreadListItem as DefaultThreadListItem } from './ThreadListItem';\nimport { ThreadListEmptyPlaceholder as DefaultThreadListEmptyPlaceholder } from './ThreadListEmptyPlaceholder';\nimport { ThreadListUnseenThreadsBanner as DefaultThreadListUnseenThreadsBanner } from './ThreadListUnseenThreadsBanner';\nimport { useThreadHighlighting } from './useThreadHighlighting';\nimport { ThreadListLoadingIndicator as DefaultThreadListLoadingIndicator } from './ThreadListLoadingIndicator';\nimport {\n  ListLoadErrorIndicator as BaseListLoadErrorIndicator,\n  type ListLoadErrorIndicatorProps,\n  LoadingChannels,\n} from '../../Loading';\nimport { NotificationList } from '../../Notifications';\nimport { getFirstPageLoadError } from '../../Loading/getFirstPageLoadError';\nimport { useFirstPageLoadRetry } from '../../Loading/hooks/useFirstPageLoadRetry';\nimport { useAddNotificationOnError } from '../../Notifications/hooks/useAddNotificationOnError';\nimport {\n  useChatContext,\n  useComponentContext,\n  useTranslationContext,\n} from '../../../context';\nimport { useStateStore } from '../../../store';\nimport { ThreadListHeader as DefaultThreadListHeader } from './ThreadListHeader';\n\nconst noThreads: Thread[] = [];\n\nconst selector = (nextValue: PaginatorState<Thread>) => ({\n  // A failed first load leaves no threads to show; a failed reload keeps the loaded ones.\n  firstPageLoadError: getFirstPageLoadError(nextValue),\n  isLoading: nextValue.isLoading,\n  lastQueryError: nextValue.lastQueryError,\n  threads: nextValue.items ?? noThreads,\n});\n\nconst DefaultListLoadErrorIndicator = (props: ListLoadErrorIndicatorProps) => (\n  <BaseListLoadErrorIndicator {...props} listType='thread' />\n);\n\nconst computeItemKey: ComputeItemKey<Thread, unknown> = (_, item) => item.id;\n\ntype ThreadListProps = {\n  virtuosoProps?: VirtuosoProps<Thread, unknown>;\n};\n\nexport const useThreadList = () => {\n  const { client } = useChatContext();\n\n  useEffect(() => {\n    // Fresh list on every mount; the reload sizes its own page from the loaded and unseen threads.\n    void client.threads.reload({ force: true });\n\n    const handleVisibilityChange = () => {\n      if (document.visibilityState === 'visible') {\n        client.threads.activate();\n      }\n      if (document.visibilityState === 'hidden') {\n        client.threads.deactivate();\n      }\n    };\n\n    handleVisibilityChange();\n\n    document.addEventListener('visibilitychange', handleVisibilityChange);\n    return () => {\n      client.threads.deactivate();\n      document.removeEventListener('visibilitychange', handleVisibilityChange);\n    };\n  }, [client]);\n};\n\nexport const ThreadList = ({ virtuosoProps }: ThreadListProps) => {\n  const { client } = useChatContext();\n  const { t } = useTranslationContext();\n  const {\n    FirstPageLoadingIndicator = LoadingChannels,\n    ListLoadErrorIndicator = DefaultListLoadErrorIndicator,\n    NotificationList: NotificationListFromContext = NotificationList,\n    ThreadListEmptyPlaceholder = DefaultThreadListEmptyPlaceholder,\n    ThreadListHeader = DefaultThreadListHeader,\n    ThreadListItem = DefaultThreadListItem,\n    ThreadListLoadingIndicator = DefaultThreadListLoadingIndicator,\n    ThreadListUnseenThreadsBanner = DefaultThreadListUnseenThreadsBanner,\n  } = useComponentContext();\n  const { firstPageLoadError, isLoading, lastQueryError, threads } = useStateStore(\n    client.threads.paginator.state,\n    selector,\n  );\n\n  const resetByThreadId = useThreadHighlighting(client.threads);\n\n  // The list is virtualized, so keyboard navigation indexes into the full `threads` array and uses\n  // Virtuoso's `scrollIntoView` to render off-window rows before focusing them.\n  const virtuosoRef = useRef<VirtuosoHandle>(null);\n  const scrollerRef = useRef<HTMLElement | null>(null);\n\n  const scrollIndexIntoView = useCallback((index: number, onRendered: () => void) => {\n    virtuosoRef.current?.scrollIntoView({ done: onRendered, index });\n  }, []);\n\n  const { onKeyDown } = useVirtualizedListboxKeyboardNavigation({\n    getItemId: (thread) => thread.id,\n    itemIdAttribute: 'data-thread-id',\n    items: threads,\n    scrollerRef,\n    scrollIndexIntoView,\n  });\n\n  useThreadList();\n\n  useAddNotificationOnError(lastQueryError, {\n    emitter: 'ThreadList',\n    message: t('threadList.loadError.text', \"Couldn't load threads\"),\n    targetPanels: ['thread-list'],\n    type: 'api:thread:query:failed',\n  });\n\n  const firstPageLoadRetry = useFirstPageLoadRetry({\n    firstPageLoadError,\n    loadedMessage: t('threadList.loaded.text', 'Threads loaded'),\n    paginator: client.threads.paginator,\n    reload: () => client.threads.reload({ force: true }),\n  });\n\n  // Only the first load shows the skeleton; a reload keeps the loaded threads until new ones land.\n  const isLoadingFirstPage = isLoading && !threads.length;\n\n  const renderList = () => (\n    <>\n      {/* TODO: allow re-load on stale ThreadManager state */}\n      <ThreadListUnseenThreadsBanner />\n      <Virtuoso\n        aria-label={t('threadList.threadList.ariaLabel', 'Thread list')}\n        atBottomStateChange={(atBottom) => atBottom && client.threads.paginator.toTail()}\n        className='str-chat__thread-list'\n        components={{\n          EmptyPlaceholder: ThreadListEmptyPlaceholder,\n          Footer: ThreadListLoadingIndicator,\n        }}\n        computeItemKey={computeItemKey}\n        data={threads}\n        itemContent={(_, thread) => (\n          <ThreadListItem\n            thread={thread}\n            threadListItemUIProps={{\n              resetHighlighting: resetByThreadId[thread.id],\n            }}\n          />\n        )}\n        onKeyDown={(event) =>\n          onKeyDown(event as unknown as React.KeyboardEvent<HTMLElement>)\n        }\n        ref={virtuosoRef}\n        role='listbox'\n        scrollerRef={(el) => {\n          scrollerRef.current = el instanceof HTMLElement ? el : null;\n        }}\n        // TODO: handle visibility (for a button that scrolls to the unread thread)\n        // itemsRendered={(items) => console.log({ items })}\n        {...virtuosoProps}\n      />\n    </>\n  );\n\n  // A failed first load shows the error instead of the empty placeholder, which would read as\n  // \"no threads\".\n  const renderFirstPageLoadError = (error: Error) => (\n    <ListLoadErrorIndicator\n      error={error}\n      isRetrying={firstPageLoadRetry.isRetrying}\n      retry={firstPageLoadRetry.retry}\n    />\n  );\n\n  const renderFirstPageLoading = () => (\n    <div className='str-chat__thread-list str-chat__thread-list--loading'>\n      <FirstPageLoadingIndicator />\n    </div>\n  );\n\n  return (\n    <div className='str-chat__thread-list-container'>\n      <ThreadListHeader />\n      {/* The error comes first: a retry loads, and keeps the error on screen while it runs. */}\n      {firstPageLoadRetry.error\n        ? renderFirstPageLoadError(firstPageLoadRetry.error)\n        : isLoadingFirstPage\n          ? renderFirstPageLoading()\n          : renderList()}\n      <NotificationListFromContext panel='thread-list' />\n    </div>\n  );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4BA,IAAM,YAAsB,CAAC;AAE7B,IAAM,YAAY,eAAuC;CAEvD,oBAAoB,sBAAsB,SAAS;CACnD,WAAW,UAAU;CACrB,gBAAgB,UAAU;CAC1B,SAAS,UAAU,SAAS;AAC9B;AAEA,IAAM,iCAAiC,UACrC,oBAAC,wBAAD;CAA4B,GAAI;CAAO,UAAS;AAAU,CAAA;AAG5D,IAAM,kBAAmD,GAAG,SAAS,KAAK;AAM1E,IAAa,sBAAsB;CACjC,MAAM,EAAE,WAAW,eAAe;CAElC,gBAAgB;EAEd,OAAY,QAAQ,OAAO,EAAE,OAAO,KAAK,CAAC;EAE1C,MAAM,+BAA+B;GACnC,IAAI,SAAS,oBAAoB,WAC/B,OAAO,QAAQ,SAAS;GAE1B,IAAI,SAAS,oBAAoB,UAC/B,OAAO,QAAQ,WAAW;EAE9B;EAEA,uBAAuB;EAEvB,SAAS,iBAAiB,oBAAoB,sBAAsB;EACpE,aAAa;GACX,OAAO,QAAQ,WAAW;GAC1B,SAAS,oBAAoB,oBAAoB,sBAAsB;EACzE;CACF,GAAG,CAAC,MAAM,CAAC;AACb;AAEA,IAAa,cAAc,EAAE,oBAAqC;CAChE,MAAM,EAAE,WAAW,eAAe;CAClC,MAAM,EAAE,MAAM,sBAAsB;CACpC,MAAM,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