{"version":3,"file":"SearchResultItem.mjs","names":[],"sources":["../../../../../src/components/Search/SearchResults/SearchResultItem.tsx"],"sourcesContent":["import React, { useCallback, useMemo } from 'react';\nimport type { ComponentType } from 'react';\nimport { convertTimestampToDate, formatMessage } from 'stream-chat';\nimport type {\n  Channel,\n  ChannelLifecycleState,\n  ChannelResponse,\n  MessageFocusSignalState,\n  MessageResponse,\n  StreamChat,\n  UserResponse,\n} from 'stream-chat';\n\nimport { useSearchContext } from '../SearchContext';\nimport { Avatar as DefaultAvatar } from '../../../components/Avatar';\nimport { extractDisplayInfo as defaultExtractDisplayInfo } from '../../../components/Avatar/utils';\nimport { ChannelListItem } from '../../../components/ChannelListItem';\nimport {\n  useChatContext,\n  useComponentContext,\n  useTranslationContext,\n  useWorkspaceNavigation,\n} from '../../../context';\nimport type { TranslationContextValue } from '../../../context';\nimport { Timestamp as DefaultTimestamp } from '../../../components/Message/Timestamp';\nimport { useStateStore } from '../../../store';\n\ntype SearchResultMessage = MessageResponse & { channel?: ChannelResponse };\n\nconst pendingDisposalSelector = (state: ChannelLifecycleState) => ({\n  pendingDisposal: state.pendingDisposal,\n});\n\n/**\n * Reports that a channel opened from a search result failed to load, which nothing else on screen\n * shows: the channel keeps only what the search loaded and gets no new messages. For a user\n * result, the direct-messaging channel was not created.\n */\nconst reportLoadFailed = ({\n  channel,\n  client,\n  emitter,\n  error,\n  t,\n}: {\n  channel: Channel;\n  client: StreamChat;\n  emitter: string;\n  error: unknown;\n  t: TranslationContextValue['t'];\n}) => {\n  client.notifications.addError({\n    message: t('search.results.loadChannelFailed.text', 'Failed to load the channel'),\n    options: {\n      originalError: error instanceof Error ? error : new Error(String(error)),\n      type: 'api:channel:watch:failed',\n    },\n    origin: { context: { channel }, emitter },\n  });\n};\n\nconst messageFocusSignalSelector = (state: MessageFocusSignalState) => ({\n  focusedMessageId: state.signal?.messageId,\n});\n\nexport type ChannelSearchResultItemProps = {\n  item: Channel;\n  /** Replaces the default selection, which opens the channel in a layout slot. */\n  onSelect?: (event: React.MouseEvent) => void;\n};\n\nexport const ChannelSearchResultItem = ({\n  item,\n  onSelect,\n}: ChannelSearchResultItemProps) => {\n  const { openChannel } = useWorkspaceNavigation();\n  const { channelManager, client } = useChatContext();\n  const { t } = useTranslationContext();\n\n  const handleSelect = useCallback(\n    (event: React.MouseEvent) => {\n      if (onSelect) {\n        onSelect(event);\n        return;\n      }\n      // The event is forwarded so an `openChannel` override (via `deriveWorkspaceNavigation`) can\n      // honor ⌘/ctrl-click.\n      openChannel(item, { event });\n      // Neither channel search nor `Channel` watches, so watch here to receive the channel events.\n      item.watch().catch((error) =>\n        reportLoadFailed({\n          channel: item,\n          client,\n          emitter: 'ChannelSearchResultItem',\n          error,\n          t,\n        }),\n      );\n      // The channel manager adds it to the lists that own it (deduped by cid, sorted, filtered)\n      // without a re-query.\n      channelManager.ingestChannel(item);\n    },\n    [item, openChannel, channelManager, client, onSelect, t],\n  );\n\n  return (\n    <ChannelListItem\n      channel={item}\n      className='str-chat__search-result'\n      onSelect={handleSelect}\n    />\n  );\n};\n\nexport type ChannelByMessageSearchResultItemProps = {\n  item: SearchResultMessage;\n  /** Replaces the default selection, which jumps to the message and opens its channel. */\n  onSelect?: (event: React.MouseEvent) => void;\n};\n\nexport const MessageSearchResultItem = ({\n  item,\n  onSelect,\n}: ChannelByMessageSearchResultItemProps) => {\n  const { channelManager, client } = useChatContext();\n  const { isChannelActive, openChannel } = useWorkspaceNavigation();\n  const { t } = useTranslationContext();\n\n  // Looked up, not created: message search stores every result's channel and keeps it while the\n  // search is active. A message without a stored channel shows no row.\n  const cid = item.cid ?? item.channel?.cid;\n  const storedChannel = cid ? channelManager.get(cid) : undefined;\n  // An ended channel (deleted, user removed, logout) leaves the store without re-rendering this\n  // row, so the row subscribes to its disposal state and renders nothing once it is pending.\n  const { pendingDisposal } = useStateStore(\n    storedChannel?.state,\n    pendingDisposalSelector,\n  ) ?? { pendingDisposal: false };\n  const channel = storedChannel && !pendingDisposal ? storedChannel : undefined;\n\n  const channelOpenInSlot = isChannelActive(channel?.cid ?? undefined);\n  const { focusedMessageId } = useStateStore(\n    channel?.messagePaginator.messageFocusSignal,\n    messageFocusSignalSelector,\n  ) ?? { focusedMessageId: undefined };\n\n  const handleSelect = useCallback(\n    (event: React.MouseEvent) => {\n      if (onSelect) {\n        onSelect(event);\n        return;\n      }\n      // Read at click time: the rendered instance may have ended since.\n      const current = cid ? channelManager.get(cid) : undefined;\n      if (!current || current.pendingDisposal) return;\n      openChannel(current, { event });\n      channelManager.ingestChannel(current);\n      // One request loads the page around the message and the channel state, and watches a\n      // channel not watched yet (e.g. one a thread created), so it receives its events.\n      current.messagePaginator\n        .jumpToMessage(item.id, { watchChannel: true })\n        .catch((error) =>\n          reportLoadFailed({\n            channel: current,\n            client,\n            emitter: 'MessageSearchResultItem',\n            error,\n            t,\n          }),\n        );\n    },\n    [cid, item, openChannel, channelManager, client, onSelect, t],\n  );\n\n  // The row previews the matched message, not the channel's latest.\n  const previewedMessage = useMemo(() => formatMessage(item), [item]);\n\n  if (!channel) return null;\n\n  return (\n    <ChannelListItem\n      active={channelOpenInSlot && focusedMessageId === item.id}\n      channel={channel}\n      className='str-chat__search-result'\n      onSelect={handleSelect}\n      previewedMessage={previewedMessage}\n    />\n  );\n};\n\nexport type UserSearchResultItemProps = {\n  item: UserResponse;\n  /** Replaces the default selection, which opens a direct-messaging channel with the user. */\n  onSelect?: (event: React.MouseEvent) => void;\n};\n\nexport const UserSearchResultItem = ({ item, onSelect }: UserSearchResultItemProps) => {\n  const { channelManager, client } = useChatContext();\n  const { openChannel } = useWorkspaceNavigation();\n  const { directMessagingChannelType } = useSearchContext();\n  const { t } = useTranslationContext();\n  const {\n    Avatar = DefaultAvatar,\n    extractDisplayInfo = defaultExtractDisplayInfo,\n    Timestamp = DefaultTimestamp,\n  } = useComponentContext();\n\n  const onClick = useCallback(\n    (event: React.MouseEvent) => {\n      if (onSelect) {\n        onSelect(event);\n        return;\n      }\n      const newChannel = client.channel(directMessagingChannelType, {\n        members: [{ user_id: client.userId as string }, { user_id: item.id }],\n      });\n      // The event is forwarded so an `openChannel` override can honor ⌘/ctrl-click.\n      openChannel(newChannel, { event });\n      newChannel.watch().then(\n        // Listed only once the watch gives a new DM its ID, since lists refuse a channel without\n        // one. `watch()` resolves with the stored instance if another took that ID\n        // meanwhile.\n        (channel) => channelManager.ingestChannel(channel),\n        (error) =>\n          reportLoadFailed({\n            channel: newChannel,\n            client,\n            emitter: 'UserSearchResultItem',\n            error,\n            t,\n          }),\n      );\n    },\n    [client, item, openChannel, channelManager, directMessagingChannelType, onSelect, t],\n  );\n\n  return (\n    <div className='str-chat__search-result-container'>\n      <button\n        aria-label={t(\n          'search.resultItem.selectUserChannel.ariaLabel',\n          'Select User Channel: {{ name }}',\n          {\n            name: item.name || '',\n          },\n        )}\n        className='str-chat__search-result str-chat__search-result--user'\n        data-testid='search-result-user'\n        onClick={onClick}\n        role='option'\n      >\n        <Avatar\n          {...extractDisplayInfo({ user: item })}\n          isOnline={item.online}\n          size='xl'\n        />\n        <div className='str-chat__search-result-data'>\n          <div className='str-chat__search-result__display-name'>\n            {/* @ts-expect-error username is not typed */}\n            {item.name || item.custom?.username || item.id}\n          </div>\n          <Timestamp\n            customClass='str-chat__search-result__last-active-timestamp'\n            timestamp={convertTimestampToDate(item.last_active)}\n          />\n        </div>\n      </button>\n    </div>\n  );\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type SearchResultItemComponents = Record<string, ComponentType<{ item: any }>>;\n\nexport const DefaultSearchResultItems: SearchResultItemComponents = {\n  channels: ChannelSearchResultItem,\n  messages: MessageSearchResultItem,\n  users: UserSearchResultItem,\n};\n"],"mappings":";;;;;;;;;;;;;;AA6BA,IAAM,2BAA2B,WAAkC,EACjE,iBAAiB,MAAM,gBACzB;;;;;;AAOA,IAAM,oBAAoB,EACxB,SACA,QACA,SACA,OACA,QAOI;CACJ,OAAO,cAAc,SAAS;EAC5B,SAAS,EAAE,yCAA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