{"version":3,"file":"utils.mjs","names":[],"sources":["../../../../src/components/ChannelListItem/utils.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport React from 'react';\nimport ReactMarkdown from 'react-markdown';\nimport type { Channel, LocalMessage, PollVoteResponseData } from 'stream-chat';\n\nimport type { ChatContextValue } from '../../context';\nimport { getTranslatedMessageText } from '../../context/MessageTranslationViewContext';\nimport type { TranslationContextValue } from '../../context/TranslationContext';\nimport { isMessageDeleted } from '../Message/utils';\nimport {\n  previewRemarkPlugins,\n  stripMarkdownToText,\n} from '../SummarizedMessagePreview/previewText';\nimport {\n  deriveChannelDisplayImage,\n  deriveGroupChannelDisplayInfo,\n} from './channelDisplayState';\n\nexport const renderPreviewText = (text: string) => (\n  <ReactMarkdown remarkPlugins={previewRemarkPlugins} skipHtml>\n    {text}\n  </ReactMarkdown>\n);\n\nconst getLatestPollVote = (\n  latestVotesByOption: Record<string, PollVoteResponseData[]>,\n) => {\n  let latestVote: PollVoteResponseData | undefined;\n  for (const optionVotes of Object.values(latestVotesByOption)) {\n    optionVotes.forEach((vote) => {\n      if (latestVote && latestVote.updated_at >= vote.created_at) return;\n      latestVote = vote;\n    });\n  }\n\n  return latestVote;\n};\n\ntype LatestMessagePreviewKind =\n  | 'attachment'\n  | 'command'\n  | 'deleted'\n  | 'empty'\n  | 'location'\n  | 'poll'\n  | 'text';\n\ntype LatestMessagePreviewParts = {\n  /** True only for plain user message text, which the display variant renders as markdown. */\n  isUserMessageText: boolean;\n  /** What the latest message is, so the display and the announcement can phrase it differently. */\n  kind: LatestMessagePreviewKind;\n  latestMessage?: LocalMessage;\n  /** Poll question, for the `poll` kind. */\n  pollName?: string;\n  /** The localized display preview as a plain string. */\n  text: string;\n};\n\n/**\n * Resolves the latest-message preview shared by {@link getLatestMessagePreview} and\n * {@link getLatestMessagePreviewText}: the display string, a `kind`, and the poll question.\n */\nconst getLatestMessagePreviewParts = (\n  channel: Channel,\n  t: TranslationContextValue['t'],\n  userLanguage: TranslationContextValue['userLanguage'] = 'en',\n  latestMessageArg?: LocalMessage,\n): LatestMessagePreviewParts => {\n  // A supplied message keeps the preview consistent with the other parts derived from it.\n  const latestMessage =\n    latestMessageArg ??\n    channel.messagePaginator.aggregateState.getLatestValue().latestMessage ??\n    undefined;\n\n  const previewTextToRender =\n    getTranslatedMessageText({ language: userLanguage, message: latestMessage }) ||\n    latestMessage?.text;\n  const poll = latestMessage?.poll;\n\n  if (!latestMessage) {\n    return {\n      isUserMessageText: false,\n      kind: 'empty',\n      latestMessage,\n      text: t('common.nothingYet.text', 'Nothing yet...'),\n    };\n  }\n\n  if (isMessageDeleted(latestMessage)) {\n    return {\n      isUserMessageText: false,\n      kind: 'deleted',\n      latestMessage,\n      text: t('common.messageDeleted.text', 'Message deleted'),\n    };\n  }\n\n  if (poll) {\n    if (!poll.vote_count) {\n      const createdBy =\n        poll.created_by?.id === channel.getClient().userID\n          ? t('common.you.label', 'You')\n          : (poll.created_by?.name ?? t('common.poll.label', 'Poll'));\n      return {\n        isUserMessageText: false,\n        kind: 'poll',\n        latestMessage,\n        pollName: poll.name,\n        text: t(\n          'channelListItem.created.text',\n          '📊 {{createdBy}} created: {{ pollName}}',\n          {\n            createdBy,\n            pollName: poll.name,\n          },\n        ),\n      };\n    } else {\n      const latestVote = getLatestPollVote(\n        poll.latest_votes_by_option as Record<string, PollVoteResponseData[]>,\n      );\n      const option =\n        latestVote && poll.options.find((opt) => opt.id === latestVote.option_id);\n\n      if (option && latestVote) {\n        return {\n          isUserMessageText: false,\n          kind: 'poll',\n          latestMessage,\n          pollName: poll.name,\n          text: t(\n            'channelListItem.voted.text',\n            '📊 {{votedBy}} voted: {{pollOptionText}}',\n            {\n              pollOptionText: option.text,\n              votedBy:\n                latestVote?.user?.id === channel.getClient().userID\n                  ? t('common.you.label', 'You')\n                  : (latestVote.user?.name ?? t('common.poll.label', 'Poll')),\n            },\n          ),\n        };\n      }\n    }\n  }\n\n  if (previewTextToRender) {\n    return {\n      isUserMessageText: true,\n      kind: 'text',\n      latestMessage,\n      text: previewTextToRender,\n    };\n  }\n\n  if (latestMessage.command) {\n    return {\n      isUserMessageText: false,\n      kind: 'command',\n      latestMessage,\n      text: `/${latestMessage.command}`,\n    };\n  }\n\n  if (latestMessage.attachments?.length) {\n    return {\n      isUserMessageText: false,\n      kind: 'attachment',\n      latestMessage,\n      text: t('channelListItem.attachment.text', '🏙 Attachment...'),\n    };\n  }\n\n  if (latestMessage.shared_location) {\n    return {\n      isUserMessageText: false,\n      kind: 'location',\n      latestMessage,\n      text: t('channelListItem.sharedLocation.text', '📍Shared location'),\n    };\n  }\n\n  return {\n    isUserMessageText: false,\n    kind: 'text',\n    latestMessage,\n    text: t('common.emptyMessage.text', 'Empty message...'),\n  };\n};\n\n/**\n * Maps a known attachment `type` to a localized word. Unknown or custom types return `undefined`.\n * The cases are literal `t()` calls so the translation key generator finds them.\n */\nconst getAttachmentTypeLabel = (\n  type: string | undefined,\n  t: TranslationContextValue['t'],\n): string | undefined => {\n  switch (type) {\n    case 'audio':\n      return t('channelListItem.audio.ariaLabel', 'audio');\n    case 'file':\n      return t('channelListItem.file.ariaLabel', 'file');\n    case 'giphy':\n      return t('channelListItem.gif.ariaLabel', 'GIF');\n    case 'image':\n      return t('channelListItem.image.ariaLabel', 'image');\n    case 'video':\n      return t('channelListItem.video.ariaLabel', 'video');\n    case 'voiceRecording':\n      return t('channelListItem.voiceMessage.ariaLabel', 'voice message');\n    default:\n      return undefined;\n  }\n};\n\n/**\n * The text announced for the channel's latest message. Non-text content gets a phrase that may\n * differ from the visible preview: a poll announces its question and an attachment its type.\n * User message text is stripped of markdown, except AI-generated text, which is returned verbatim.\n *\n * @param channel - Channel whose latest message is announced.\n * @param t - Translation function.\n * @param userLanguage - Language of the translated message text. Defaults to 'en'.\n * @param isMessageAIGenerated - Tells whether a message is AI-generated.\n * @param latestMessage - Message to announce. Defaults to the channel's last message.\n * @returns The announcement text.\n */\nexport const getLatestMessagePreviewText = (\n  channel: Channel,\n  t: TranslationContextValue['t'],\n  userLanguage: TranslationContextValue['userLanguage'] = 'en',\n  isMessageAIGenerated?: ChatContextValue['isMessageAIGenerated'],\n  latestMessage?: LocalMessage,\n): string => {\n  const {\n    isUserMessageText,\n    kind,\n    latestMessage: resolvedLatestMessage,\n    pollName,\n    text,\n  } = getLatestMessagePreviewParts(channel, t, userLanguage, latestMessage);\n\n  switch (kind) {\n    case 'poll':\n      return t('channelListItem.poll.ariaLabel', 'Poll: {{ pollName }}', {\n        pollName: pollName ?? '',\n      });\n    case 'attachment': {\n      // Link previews are announced by the `linkPreview` label part, so only other attachments\n      // count. Several get a generic phrase (the label announces the count), one gets its type.\n      const realAttachments =\n        resolvedLatestMessage?.attachments?.filter(\n          (attachment) => !attachment.og_scrape_url,\n        ) ?? [];\n      if (realAttachments.length > 1)\n        return t(\n          'channelListItem.messageAttachments.ariaLabel',\n          'Message with attachments',\n        );\n      const typeLabel = getAttachmentTypeLabel(realAttachments[0]?.type, t);\n      return typeLabel\n        ? t(\n            'channelListItem.attachment.withAttachmentType.ariaLabel',\n            'Attachment {{ attachmentType }}',\n            { attachmentType: typeLabel },\n          )\n        : t('channelListItem.attachment.ariaLabel', 'Attachment');\n    }\n    case 'location':\n      return t('channelListItem.sharedLocation.ariaLabel', 'Shared location');\n    case 'empty':\n      // The visible text is \"Nothing yet...\"; the announcement spells it out.\n      return t(\n        'channelListItem.noMessagesChat.ariaLabel',\n        'There are no messages in this chat.',\n      );\n    case 'text':\n      // The `resolvedLatestMessage` check is redundant at runtime but narrows the type.\n      return isUserMessageText &&\n        resolvedLatestMessage &&\n        !isMessageAIGenerated?.(resolvedLatestMessage)\n        ? stripMarkdownToText(text)\n        : text;\n    default:\n      // 'deleted' and 'command' read as their display text.\n      return text;\n  }\n};\n\nexport const getLatestMessagePreview = (\n  channel: Channel,\n  t: TranslationContextValue['t'],\n  userLanguage: TranslationContextValue['userLanguage'] = 'en',\n  isMessageAIGenerated?: ChatContextValue['isMessageAIGenerated'],\n  latestMessage?: LocalMessage,\n): ReactNode => {\n  const {\n    isUserMessageText,\n    latestMessage: resolvedLatestMessage,\n    text,\n  } = getLatestMessagePreviewParts(channel, t, userLanguage, latestMessage);\n\n  // Only plain user message text is rendered as markdown, and AI-generated text is not. The\n  // `resolvedLatestMessage` check is redundant at runtime but narrows the type.\n  return isUserMessageText &&\n    resolvedLatestMessage &&\n    !isMessageAIGenerated?.(resolvedLatestMessage)\n    ? renderPreviewText(text)\n    : text;\n};\n\nexport type GroupChannelDisplayInfoMember = {\n  imageUrl?: string;\n  userName?: string;\n};\n\nexport type GroupChannelDisplayInfo = {\n  members: GroupChannelDisplayInfoMember[];\n  /** Not set or read by the SDK; the group avatar derives its \"+N\" count from `members`. */\n  overflowCount?: number;\n};\n\n/** `channel.data.custom.image`, or for a DM (2 members) the other member's `user.image`. */\nexport const getChannelDisplayImage = (\n  channel: Channel,\n  currentUserId?: string,\n): string | undefined =>\n  deriveChannelDisplayImage(\n    { data: channel.data, members: channel.state.members },\n    currentUserId,\n  );\n\nexport const getGroupChannelDisplayInfo = (\n  channel: Channel,\n): GroupChannelDisplayInfo | undefined =>\n  deriveGroupChannelDisplayInfo({ data: channel.data, members: channel.state.members });\n"],"mappings":";;;;;;;;AAkBA,IAAa,qBAAqB,SAChC,oBAAC,eAAD;CAAe,eAAe;CAAsB,UAAA;WACjD;AACY,CAAA;AAGjB,IAAM,qBACJ,wBACG;CACH,IAAI;CACJ,KAAK,MAAM,eAAe,OAAO,OAAO,mBAAmB,GACzD,YAAY,SAAS,SAAS;EAC5B,IAAI,cAAc,WAAW,cAAc,KAAK,YAAY;EAC5D,aAAa;CACf,CAAC;CAGH,OAAO;AACT;;;;;AA2BA,IAAM,gCACJ,SACA,GACA,eAAwD,MACxD,qBAC8B;CAE9B,MAAM,gBACJ,oBACA,QAAQ,iBAAiB,eAAe,eAAe,CAAC,CAAC,iBACzD,KAAA;CAEF,MAAM,sBACJ,yBAAyB;EAAE,UAAU;EAAc,SAAS;CAAc,CAA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