{"version":3,"file":"utils.mjs","names":[],"sources":["../../../../src/components/Message/utils.tsx"],"sourcesContent":["import deepequal from 'react-fast-compare';\n\nimport { EMOJI_REGEX } from './emojiRegex';\n\nimport type {\n  LocalMessage,\n  MessageResponse,\n  StreamChat,\n  UserMuteResponse,\n  UserResponse,\n} from 'stream-chat';\nimport type { MessageProps } from './types';\nimport type { MessageContextValue } from '../../context';\nimport type { StreamTFunction } from '../../i18n/types';\n\n/**\n * Calls `func` with `args` and returns the result when it is a string, otherwise null.\n *\n * @param func - Function returning a notification message. Null is returned when not a function.\n * @param args - Arguments for `func`. A non-array value is wrapped in an array.\n * @returns The string `func` returned, or null.\n */\nexport const validateAndGetMessage = <T extends unknown[]>(\n  func: (...args: T) => unknown,\n  args: T,\n) => {\n  if (!func || typeof func !== 'function') return null;\n\n  // Tests pass a single argument rather than an array.\n  if (!Array.isArray(args)) {\n    args = [args] as unknown as T;\n  }\n\n  const returnValue = func(...args);\n\n  if (typeof returnValue !== 'string') return null;\n\n  return returnValue;\n};\n\n/**\n * Whether the author of the message is muted.\n *\n * @param message - Message whose author is checked.\n * @param mutes - Muted users. False is returned when it is missing.\n * @returns True when the author is among the muted users.\n */\nexport const isUserMuted = (message: LocalMessage, mutes?: UserMuteResponse[]) => {\n  if (!mutes || !message) return false;\n\n  return mutes.some(({ target }) => target?.id === message.user?.id);\n};\n\n/** `MessageActionSetItem['type']`s that a thread reply does not support. */\nexport const ACTIONS_NOT_WORKING_IN_THREAD: string[] = ['pin', 'reply', 'markUnread'];\n\nfunction areMessagesEqual(prevMessage: LocalMessage, nextMessage: LocalMessage): boolean {\n  if (prevMessage === nextMessage) return true;\n\n  const areBaseMessagesEqual = (prevMessage: LocalMessage, nextMessage: LocalMessage) =>\n    prevMessage.deleted_at === nextMessage.deleted_at &&\n    prevMessage.attachments === nextMessage.attachments &&\n    prevMessage.latest_reactions === nextMessage.latest_reactions &&\n    prevMessage.own_reactions === nextMessage.own_reactions &&\n    prevMessage.reaction_groups === nextMessage.reaction_groups &&\n    prevMessage.shared_location === nextMessage.shared_location &&\n    prevMessage.pinned === nextMessage.pinned &&\n    prevMessage.reply_count === nextMessage.reply_count &&\n    prevMessage.show_in_channel === nextMessage.show_in_channel &&\n    prevMessage.status === nextMessage.status &&\n    prevMessage.text === nextMessage.text &&\n    prevMessage.type === nextMessage.type &&\n    prevMessage.updated_at === nextMessage.updated_at &&\n    prevMessage.user?.updated_at === nextMessage.user?.updated_at;\n\n  return (\n    areBaseMessagesEqual(prevMessage, nextMessage) &&\n    Boolean(prevMessage.quoted_message) === Boolean(nextMessage.quoted_message) &&\n    ((!prevMessage.quoted_message && !nextMessage.quoted_message) ||\n      areBaseMessagesEqual(\n        prevMessage.quoted_message as LocalMessage,\n        nextMessage.quoted_message as LocalMessage,\n      ))\n  );\n}\n\ntype MemoizedMessageProps = MessageProps &\n  Pick<MessageContextValue, 'onMentionsClickMessage' | 'onMentionsHoverMessage'> & {\n    showDetailedReactions?: boolean;\n  };\n\nexport const areMessagePropsEqual = (\n  prevProps: MemoizedMessageProps,\n  nextProps: MemoizedMessageProps,\n) => {\n  const { message: prevMessage } = prevProps;\n  const { message: nextMessage } = nextProps;\n\n  // The message UI component itself is not compared here: it is resolved from\n  // `ComponentContext`, and context updates re-render consumers regardless of `React.memo`.\n  if (nextProps.showDetailedReactions !== prevProps.showDetailedReactions) {\n    return false;\n  }\n\n  if (nextProps.closeReactionSelectorOnClick !== prevProps.closeReactionSelectorOnClick) {\n    return false;\n  }\n\n  if (nextProps.showAvatar !== prevProps.showAvatar) return false;\n\n  // Whether a mention handler is set decides if mentions are interactive, so a handler set or\n  // removed after the first render has to reach the message. Their identity is not compared.\n  if (\n    !!nextProps.onMentionsClickMessage !== !!prevProps.onMentionsClickMessage ||\n    !!nextProps.onMentionsHoverMessage !== !!prevProps.onMentionsHoverMessage\n  ) {\n    return false;\n  }\n\n  const messagesAreEqual = areMessagesEqual(prevMessage, nextMessage);\n  if (!messagesAreEqual) return false;\n\n  const deepEqualProps =\n    deepequal(nextProps.readBy, prevProps.readBy) &&\n    deepequal(nextProps.deliveredTo, prevProps.deliveredTo) &&\n    deepequal(nextProps.highlighted, prevProps.highlighted) &&\n    deepequal(nextProps.groupStyles, prevProps.groupStyles) && // depends on neighboring messages\n    deepequal(nextProps.lastReceivedId, prevProps.lastReceivedId);\n\n  if (!deepEqualProps) return false;\n\n  return (\n    prevProps.messageListRect === nextProps.messageListRect // MessageList wrapper layout changes\n  );\n};\n\nexport const areMessageUIPropsEqual = (\n  prevProps: MessageContextValue & {\n    showDetailedReactions?: boolean;\n  },\n  nextProps: MessageContextValue & {\n    showDetailedReactions?: boolean;\n  },\n) => {\n  const { lastReceivedId: prevLastReceivedId, message: prevMessage } = prevProps;\n  const { lastReceivedId: nextLastReceivedId, message: nextMessage } = nextProps;\n\n  if (prevProps.highlighted !== nextProps.highlighted) return false;\n  if (prevProps.readBy?.length !== nextProps.readBy?.length) return false;\n  if (prevProps.deliveredTo?.length !== nextProps.deliveredTo?.length) return false;\n  if (prevProps.groupStyles !== nextProps.groupStyles) return false;\n  if (prevProps.showAvatar !== nextProps.showAvatar) return false;\n\n  if (prevProps.showDetailedReactions !== nextProps.showDetailedReactions) {\n    return false;\n  }\n\n  if (\n    (prevMessage.id === prevLastReceivedId || prevMessage.id === nextLastReceivedId) &&\n    prevLastReceivedId !== nextLastReceivedId\n  ) {\n    return false;\n  }\n\n  return areMessagesEqual(prevMessage, nextMessage);\n};\n\nexport const messageHasReactions = (message?: LocalMessage) =>\n  Object.values(message?.reaction_groups ?? {}).some(({ count }) => count > 0);\n\nexport const messageHasQuotedMessage = (message?: LocalMessage) =>\n  !!message?.quoted_message;\n\nexport const messageHasAttachments = (message?: LocalMessage) =>\n  !!message?.attachments && !!message.attachments.length;\n\nexport const messageHasSingleAttachment = (message?: LocalMessage) =>\n  message?.attachments?.length === 1;\n\nexport const messageHasGiphyAttachment = (message?: LocalMessage) =>\n  !!message?.attachments?.some((att) => att.type === 'giphy');\n\nexport const getImages = (message?: MessageResponse) => {\n  if (!message?.attachments) {\n    return [];\n  }\n  return message.attachments.filter((item) => item.type === 'image');\n};\n\nexport const getNonImageAttachments = (message?: MessageResponse) => {\n  if (!message?.attachments) {\n    return [];\n  }\n  return message.attachments.filter((item) => item.type !== 'image');\n};\n\nexport interface TooltipUsernameMapper {\n  (user: UserResponse): string;\n}\n\n/**\n * Default tooltip username mapper.\n *\n * @param user - User to map.\n * @returns The user's name, falling back to the ID.\n */\nexport const mapToUserNameOrId: TooltipUsernameMapper = (user) => user.name || user.id;\n\nexport const getReadByTooltipText = (\n  users: UserResponse[],\n  t: StreamTFunction,\n  client: StreamChat,\n  tooltipUserNameMapper: TooltipUsernameMapper,\n) => {\n  let outStr = '';\n\n  if (!t) {\n    throw new Error(\n      'getReadByTooltipText was called, but translation function is not available',\n    );\n  }\n\n  if (!tooltipUserNameMapper) {\n    throw new Error(\n      'getReadByTooltipText was called, but tooltipUserNameMapper function is not available',\n    );\n  }\n  // Exclude the current user so `restLength` does not count it.\n  const otherUsers = users\n    .filter((item) => item && client?.user && item.id !== client.user.id)\n    .map(tooltipUserNameMapper);\n\n  const slicedArr = otherUsers.slice(0, 5);\n  const restLength = otherUsers.length - slicedArr.length;\n\n  if (slicedArr.length === 1) {\n    outStr = `${slicedArr[0]} `;\n  } else if (slicedArr.length === 2) {\n    // Two users: \"bob and sam\".\n    outStr = t(\n      'message.and.withFirstUserAndSecondUser.label',\n      '{{ firstUser }} and {{ secondUser }}',\n      {\n        firstUser: slicedArr[0],\n        secondUser: slicedArr[1],\n      },\n    );\n  } else if (slicedArr.length > 2) {\n    // Three or more: when all fit, the last one follows \", and\" (Oxford comma); otherwise an\n    // \"and N more\" suffix follows.\n    if (restLength === 0) {\n      // Splice out the last user to display it separately.\n      const [lastUser] = slicedArr.splice(slicedArr.length - 1, 1);\n      outStr = t(\n        'message.and.withCommaSeparatedUsersAndLastUser.label',\n        '{{ commaSeparatedUsers }}, and {{ lastUser }}',\n        {\n          commaSeparatedUsers: slicedArr.join(', '),\n          lastUser,\n        },\n      );\n    } else {\n      outStr = t(\n        'message.more.label',\n        '{{ commaSeparatedUsers }} and {{ moreCount }} more',\n        {\n          commaSeparatedUsers: slicedArr.join(', '),\n          moreCount: restLength,\n        },\n      );\n    }\n  }\n\n  return outStr;\n};\n\nexport const countEmojis = (text?: string) => {\n  const matches = text?.match(EMOJI_REGEX);\n  return matches ? matches.length : 0;\n};\n\nexport const messageTextHasEmojisOnly = (message: LocalMessage) => {\n  if (!message.text) return false;\n\n  const noEmojis = message.text.replace(EMOJI_REGEX, '');\n  const noSpace = noEmojis.replace(/[\\s\\n]/gm, '');\n\n  return !noSpace;\n};\n\nexport const isMessageErrorRetryable = (message: LocalMessage) =>\n  message.status === 'failed' && message.error?.status !== 403;\n\nexport const isNetworkSendFailure = (message: Pick<LocalMessage, 'error' | 'status'>) =>\n  message.status === 'failed' && message.error?.status === 0;\n\nexport const isMessageBounced = (message: Pick<LocalMessage, 'type' | 'moderation'>) =>\n  message.type === 'error' && message.moderation?.action === 'bounce';\n\nexport const isMessageBlocked = (\n  message: Pick<LocalMessage, 'type' | 'moderation' | 'shadowed'>,\n) =>\n  message.shadowed ||\n  (message.type === 'error' && message.moderation?.action === 'remove');\n\nexport const isMessageDeleted = (message: LocalMessage): boolean =>\n  Boolean(\n    message.deleted_at != null || message.type === 'deleted' || message.deleted_for_me,\n  );\n\nexport const isMessageEdited = (message: Pick<LocalMessage, 'message_text_updated_at'>) =>\n  message.message_text_updated_at != null;\n"],"mappings":";;;;;;;;;;AAsBA,IAAa,yBACX,MACA,SACG;CACH,IAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,OAAO;CAGhD,IAAI,CAAC,MAAM,QAAQ,IAAI,GACrB,OAAO,CAAC,IAAI;CAGd,MAAM,cAAc,KAAK,GAAG,IAAI;CAEhC,IAAI,OAAO,gBAAgB,UAAU,OAAO;CAE5C,OAAO;AACT;;;;;;;;AASA,IAAa,eAAe,SAAuB,UAA+B;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