// Copyright 2018-2022 Signal Messenger, LLC // SPDX-License-Identifier: AGPL-3.0-only import type { ReactNode, RefObject } from 'react'; import React from 'react'; import ReactDOM, { createPortal } from 'react-dom'; import classNames from 'classnames'; import { drop, groupBy, orderBy, take, unescape } from 'lodash'; import { ContextMenu, ContextMenuTrigger, MenuItem } from 'react-contextmenu'; import { Manager, Popper, Reference } from 'react-popper'; import type { PreventOverflowModifier } from '@popperjs/core/lib/modifiers/preventOverflow'; import type { ConversationType, ConversationTypeType, InteractionModeType, } from '../../state/ducks/conversations'; import type { TimelineItemType } from './TimelineItem'; import { ReadStatus } from '../../messages/MessageReadStatus'; import { Avatar, AvatarSize } from '../Avatar'; import { AvatarSpacer } from '../AvatarSpacer'; import { Spinner } from '../Spinner'; import { doesMessageBodyOverflow, MessageBodyReadMore, } from './MessageBodyReadMore'; import { MessageMetadata } from './MessageMetadata'; import { MessageTextMetadataSpacer } from './MessageTextMetadataSpacer'; import { ImageGrid } from './ImageGrid'; import { GIF } from './GIF'; import { Image } from './Image'; import { ContactName } from './ContactName'; import type { QuotedAttachmentType } from './Quote'; import { Quote } from './Quote'; import { EmbeddedContact } from './EmbeddedContact'; import type { OwnProps as ReactionViewerProps } from './ReactionViewer'; import { ReactionViewer } from './ReactionViewer'; import type { Props as ReactionPickerProps } from './ReactionPicker'; import { Emoji } from '../emoji/Emoji'; import { LinkPreviewDate } from './LinkPreviewDate'; import type { LinkPreviewType } from '../../types/message/LinkPreviews'; import { shouldUseFullSizeLinkPreviewImage } from '../../linkPreviews/shouldUseFullSizeLinkPreviewImage'; import { WidthBreakpoint } from '../_util'; import * as log from '../../logging/log'; import type { AttachmentType } from '../../types/Attachment'; import { canDisplayImage, getExtensionForDisplay, getGridDimensions, getImageDimensions, hasImage, isDownloaded, hasVideoScreenshot, isAudio, isImage, isImageAttachment, isVideo, isGIF, } from '../../types/Attachment'; import type { EmbeddedContactType } from '../../types/EmbeddedContact'; import { getIncrement } from '../../util/timer'; import { clearTimeoutIfNecessary } from '../../util/clearTimeoutIfNecessary'; import { isFileDangerous } from '../../util/isFileDangerous'; import { missingCaseError } from '../../util/missingCaseError'; import type { BodyRangesType, LocalizerType, ThemeType, } from '../../types/Util'; import type { PreferredBadgeSelectorType } from '../../state/selectors/badges'; import type { ContactNameColorType, ConversationColorType, CustomColorType, } from '../../types/Colors'; import { createRefMerger } from '../../util/refMerger'; import { emojiToData, getEmojiCount } from '../emoji/lib'; import { isEmojiOnlyText } from '../../util/isEmojiOnlyText'; import type { SmartReactionPicker } from '../../state/smart/ReactionPicker'; import { getCustomColorStyle } from '../../util/getCustomColorStyle'; import { offsetDistanceModifier } from '../../util/popperUtil'; import * as KeyboardLayout from '../../services/keyboardLayout'; import { StopPropagation } from '../StopPropagation'; type Trigger = { handleContextClick: (event: React.MouseEvent) => void; }; const GUESS_METADATA_WIDTH_TIMESTAMP_SIZE = 10; const GUESS_METADATA_WIDTH_EXPIRE_TIMER_SIZE = 18; const GUESS_METADATA_WIDTH_OUTGOING_SIZE: Record = { delivered: 24, error: 24, paused: 18, 'partial-sent': 24, read: 24, sending: 18, sent: 24, viewed: 24, }; const EXPIRATION_CHECK_MINIMUM = 2000; const EXPIRED_DELAY = 600; const GROUP_AVATAR_SIZE = AvatarSize.TWENTY_EIGHT; const STICKER_SIZE = 200; const GIF_SIZE = 300; // Note: this needs to match the animation time const SELECTED_TIMEOUT = 1200; const THREE_HOURS = 3 * 60 * 60 * 1000; const SENT_STATUSES = new Set([ 'delivered', 'read', 'sent', 'viewed', ]); enum MetadataPlacement { NotRendered, RenderedByMessageAudioComponent, InlineWithText, Bottom, } export enum TextDirection { LeftToRight = 'LeftToRight', RightToLeft = 'RightToLeft', Default = 'Default', None = 'None', } export const MessageStatuses = [ 'delivered', 'error', 'paused', 'partial-sent', 'read', 'sending', 'sent', 'viewed', ] as const; export type MessageStatusType = typeof MessageStatuses[number]; export const Directions = ['incoming', 'outgoing'] as const; export type DirectionType = typeof Directions[number]; export type AudioAttachmentProps = { renderingContext: string; i18n: LocalizerType; buttonRef: React.RefObject; theme: ThemeType | undefined; attachment: AttachmentType; collapseMetadata: boolean; withContentAbove: boolean; withContentBelow: boolean; direction: DirectionType; expirationLength?: number; expirationTimestamp?: number; id: string; played: boolean; showMessageDetail: (id: string) => void; status?: MessageStatusType; textPending?: boolean; timestamp: number; kickOffAttachmentDownload(): void; onCorrupted(): void; onFirstPlayed(): void; }; export type PropsData = { id: string; renderingContext: string; contactNameColor?: ContactNameColorType; conversationColor: ConversationColorType; customColor?: CustomColorType; conversationId: string; displayLimit?: number; text?: string; textDirection: TextDirection; textPending?: boolean; isSticker?: boolean; isSelected?: boolean; isSelectedCounter?: number; direction: DirectionType; timestamp: number; status?: MessageStatusType; contact?: EmbeddedContactType; author: Pick< ConversationType, | 'acceptedMessageRequest' | 'avatarPath' | 'badges' | 'color' | 'id' | 'isMe' | 'name' | 'phoneNumber' | 'profileName' | 'sharedGroupNames' | 'title' | 'unblurredAvatarPath' >; reducedMotion?: boolean; conversationType: ConversationTypeType; attachments?: Array; quote?: { conversationColor: ConversationColorType; customColor?: CustomColorType; text: string; rawAttachment?: QuotedAttachmentType; isFromMe: boolean; sentAt: number; authorId: string; authorPhoneNumber?: string; authorProfileName?: string; authorTitle: string; authorName?: string; bodyRanges?: BodyRangesType; referencedMessageNotFound: boolean; isViewOnce: boolean; }; storyReplyContext?: { authorTitle: string; conversationColor: ConversationColorType; customColor?: CustomColorType; isFromMe: boolean; rawAttachment?: QuotedAttachmentType; }; previews: Array; isTapToView?: boolean; isTapToViewExpired?: boolean; isTapToViewError?: boolean; readStatus: ReadStatus; expirationLength?: number; expirationTimestamp?: number; reactions?: ReactionViewerProps['reactions']; selectedReaction?: string; deletedForEveryone?: boolean; canRetry: boolean; canRetryDeleteForEveryone: boolean; canReact: boolean; canReply: boolean; canDownload: boolean; canDeleteForEveryone: boolean; isBlocked: boolean; isMessageRequestAccepted: boolean; bodyRanges?: BodyRangesType; }; export type PropsHousekeeping = { containerElementRef: RefObject; containerWidthBreakpoint: WidthBreakpoint; disableMenu?: boolean; disableScroll?: boolean; getPreferredBadge: PreferredBadgeSelectorType; i18n: LocalizerType; interactionMode: InteractionModeType; item?: TimelineItemType; renderAudioAttachment: (props: AudioAttachmentProps) => JSX.Element; renderReactionPicker: ( props: React.ComponentProps ) => JSX.Element; shouldCollapseAbove: boolean; shouldCollapseBelow: boolean; shouldHideMetadata: boolean; theme: ThemeType; }; export type PropsActions = { clearSelectedMessage: () => unknown; doubleCheckMissingQuoteReference: (messageId: string) => unknown; messageExpanded: (id: string, displayLimit: number) => unknown; checkForAccount: (identifier: string) => unknown; reactToMessage: ( id: string, { emoji, remove }: { emoji: string; remove: boolean } ) => void; replyToMessage: (id: string) => void; retryDeleteForEveryone: (id: string) => void; retrySend: (id: string) => void; showForwardMessageModal: (id: string) => void; deleteMessage: (id: string) => void; deleteMessageForEveryone: (id: string) => void; showMessageDetail: (id: string) => void; openConversation: (conversationId: string, messageId?: string) => void; showContactDetail: (options: { contact: EmbeddedContactType; signalAccount?: string; }) => void; showContactModal: (contactId: string, conversationId?: string) => void; kickOffAttachmentDownload: (options: { attachment: AttachmentType; messageId: string; }) => void; markAttachmentAsCorrupted: (options: { attachment: AttachmentType; messageId: string; }) => void; markViewed(messageId: string): void; showVisualAttachment: (options: { attachment: AttachmentType; messageId: string; }) => void; downloadAttachment: (options: { attachment: AttachmentType; timestamp: number; isDangerous: boolean; }) => void; displayTapToViewMessage: (messageId: string) => unknown; openLink: (url: string) => void; scrollToQuotedMessage: (options: { authorId: string; sentAt: number; }) => void; selectMessage?: (messageId: string, conversationId: string) => unknown; showExpiredIncomingTapToViewToast: () => unknown; showExpiredOutgoingTapToViewToast: () => unknown; }; export type Props = PropsData & PropsHousekeeping & PropsActions & Pick; type State = { metadataWidth: number; expiring: boolean; expired: boolean; imageBroken: boolean; isSelected?: boolean; prevSelectedCounter?: number; reactionViewerRoot: HTMLDivElement | null; reactionPickerRoot: HTMLDivElement | null; hasDeleteForEveryoneTimerExpired: boolean; }; export class Message extends React.PureComponent { public menuTriggerRef: Trigger | undefined; public focusRef: React.RefObject = React.createRef(); public audioButtonRef: React.RefObject = React.createRef(); public reactionsContainerRef: React.RefObject = React.createRef(); public reactionsContainerRefMerger = createRefMerger(); public expirationCheckInterval: NodeJS.Timeout | undefined; public expiredTimeout: NodeJS.Timeout | undefined; public selectedTimeout: NodeJS.Timeout | undefined; public deleteForEveryoneTimeout: NodeJS.Timeout | undefined; public constructor(props: Props) { super(props); this.state = { metadataWidth: this.guessMetadataWidth(), expiring: false, expired: false, imageBroken: false, isSelected: props.isSelected, prevSelectedCounter: props.isSelectedCounter, reactionViewerRoot: null, reactionPickerRoot: null, hasDeleteForEveryoneTimerExpired: this.getTimeRemainingForDeleteForEveryone() <= 0, }; } public static getDerivedStateFromProps(props: Props, state: State): State { if (!props.isSelected) { return { ...state, isSelected: false, prevSelectedCounter: 0, }; } if ( props.isSelected && props.isSelectedCounter !== state.prevSelectedCounter ) { return { ...state, isSelected: props.isSelected, prevSelectedCounter: props.isSelectedCounter, }; } return state; } private hasReactions(): boolean { const { reactions } = this.props; return Boolean(reactions && reactions.length); } public captureMenuTrigger = (triggerRef: Trigger): void => { this.menuTriggerRef = triggerRef; }; public showMenu = (event: React.MouseEvent): void => { if (this.menuTriggerRef) { this.menuTriggerRef.handleContextClick(event); } }; public showContextMenu = (event: React.MouseEvent): void => { const selection = window.getSelection(); if (selection && !selection.isCollapsed) { return; } if (event.target instanceof HTMLAnchorElement) { return; } this.showMenu(event); }; public handleImageError = (): void => { const { id } = this.props; log.info( `Message ${id}: Image failed to load; failing over to placeholder` ); this.setState({ imageBroken: true, }); }; public handleFocus = (): void => { const { interactionMode } = this.props; if (interactionMode === 'keyboard') { this.setSelected(); } }; public setSelected = (): void => { const { id, conversationId, selectMessage } = this.props; if (selectMessage) { selectMessage(id, conversationId); } }; public setFocus = (): void => { const container = this.focusRef.current; if (container && !container.contains(document.activeElement)) { container.focus(); } }; public override componentDidMount(): void { const { conversationId } = this.props; window.ConversationController?.onConvoMessageMount(conversationId); this.startSelectedTimer(); this.startDeleteForEveryoneTimerIfApplicable(); const { isSelected } = this.props; if (isSelected) { this.setFocus(); } const { expirationLength } = this.props; if (expirationLength) { const increment = getIncrement(expirationLength); const checkFrequency = Math.max(EXPIRATION_CHECK_MINIMUM, increment); this.checkExpired(); this.expirationCheckInterval = setInterval(() => { this.checkExpired(); }, checkFrequency); } const { contact, checkForAccount } = this.props; if (contact && contact.firstNumber && !contact.isNumberOnSignal) { checkForAccount(contact.firstNumber); } } public override componentWillUnmount(): void { clearTimeoutIfNecessary(this.selectedTimeout); clearTimeoutIfNecessary(this.expirationCheckInterval); clearTimeoutIfNecessary(this.expiredTimeout); clearTimeoutIfNecessary(this.deleteForEveryoneTimeout); this.toggleReactionViewer(true); this.toggleReactionPicker(true); } public override componentDidUpdate(prevProps: Readonly): void { const { isSelected, status, timestamp } = this.props; this.startSelectedTimer(); this.startDeleteForEveryoneTimerIfApplicable(); if (!prevProps.isSelected && isSelected) { this.setFocus(); } this.checkExpired(); if ( prevProps.status === 'sending' && (status === 'sent' || status === 'delivered' || status === 'read' || status === 'viewed') ) { const delta = Date.now() - timestamp; window.CI?.handleEvent('message:send-complete', { timestamp, delta, }); log.info( `Message.tsx: Rendered 'send complete' for message ${timestamp}; took ${delta}ms` ); } } private getMetadataPlacement( { attachments, deletedForEveryone, expirationLength, expirationTimestamp, shouldHideMetadata, status, text, textDirection, }: Readonly = this.props ): MetadataPlacement { const isRTL = textDirection === TextDirection.RightToLeft; if ( !expirationLength && !expirationTimestamp && (!status || SENT_STATUSES.has(status)) && shouldHideMetadata ) { return MetadataPlacement.NotRendered; } if (!text && !deletedForEveryone) { return isAudio(attachments) ? MetadataPlacement.RenderedByMessageAudioComponent : MetadataPlacement.Bottom; } if (this.canRenderStickerLikeEmoji()) { return MetadataPlacement.Bottom; } if (isRTL) { return MetadataPlacement.Bottom; } return MetadataPlacement.InlineWithText; } /** * A lot of the time, we add an invisible inline spacer for messages. This spacer is the * same size as the message metadata. Unfortunately, we don't know how wide it is until * we render it. * * This will probably guess wrong, but it's valuable to get close to the real value * because it can reduce layout jumpiness. */ private guessMetadataWidth(): number { const { direction, expirationLength, expirationTimestamp, status } = this.props; let result = GUESS_METADATA_WIDTH_TIMESTAMP_SIZE; const hasExpireTimer = Boolean( expirationLength && (expirationTimestamp || direction === 'outgoing') ); if (hasExpireTimer) { result += GUESS_METADATA_WIDTH_EXPIRE_TIMER_SIZE; } if (direction === 'outgoing' && status) { result += GUESS_METADATA_WIDTH_OUTGOING_SIZE[status]; } return result; } public startSelectedTimer(): void { const { clearSelectedMessage, interactionMode } = this.props; const { isSelected } = this.state; if (interactionMode === 'keyboard' || !isSelected) { return; } if (!this.selectedTimeout) { this.selectedTimeout = setTimeout(() => { this.selectedTimeout = undefined; this.setState({ isSelected: false }); clearSelectedMessage(); }, SELECTED_TIMEOUT); } } private getTimeRemainingForDeleteForEveryone(): number { const { timestamp } = this.props; return Math.max(timestamp - Date.now() + THREE_HOURS, 0); } private canDeleteForEveryone(): boolean { const { canDeleteForEveryone } = this.props; const { hasDeleteForEveryoneTimerExpired } = this.state; return canDeleteForEveryone && !hasDeleteForEveryoneTimerExpired; } private startDeleteForEveryoneTimerIfApplicable(): void { const { canDeleteForEveryone } = this.props; const { hasDeleteForEveryoneTimerExpired } = this.state; if ( !canDeleteForEveryone || hasDeleteForEveryoneTimerExpired || this.deleteForEveryoneTimeout ) { return; } this.deleteForEveryoneTimeout = setTimeout(() => { this.setState({ hasDeleteForEveryoneTimerExpired: true }); delete this.deleteForEveryoneTimeout; }, this.getTimeRemainingForDeleteForEveryone()); } public checkExpired(): void { const now = Date.now(); const { expirationTimestamp, expirationLength } = this.props; if (!expirationTimestamp || !expirationLength) { return; } if (this.expiredTimeout) { return; } if (now >= expirationTimestamp) { this.setState({ expiring: true, }); const setExpired = () => { this.setState({ expired: true, }); }; this.expiredTimeout = setTimeout(setExpired, EXPIRED_DELAY); } } private areLinksEnabled(): boolean { const { isMessageRequestAccepted, isBlocked } = this.props; return isMessageRequestAccepted && !isBlocked; } private shouldRenderAuthor(): boolean { const { author, conversationType, direction, shouldCollapseAbove } = this.props; return Boolean( direction === 'incoming' && conversationType === 'group' && author.title && !shouldCollapseAbove ); } private canRenderStickerLikeEmoji(): boolean { const { text, quote, attachments, previews } = this.props; return Boolean( text && isEmojiOnlyText(text) && getEmojiCount(text) < 6 && !quote && (!attachments || !attachments.length) && (!previews || !previews.length) ); } private updateMetadataWidth = (newMetadataWidth: number): void => { this.setState(({ metadataWidth }) => ({ // We don't want text to jump around if the metadata shrinks, but we want to make // sure we have enough room. metadataWidth: Math.max(metadataWidth, newMetadataWidth), })); }; private renderMetadata(): ReactNode { let isInline: boolean; const metadataPlacement = this.getMetadataPlacement(); switch (metadataPlacement) { case MetadataPlacement.NotRendered: case MetadataPlacement.RenderedByMessageAudioComponent: return null; case MetadataPlacement.InlineWithText: isInline = true; break; case MetadataPlacement.Bottom: isInline = false; break; default: log.error(missingCaseError(metadataPlacement)); isInline = false; break; } const { deletedForEveryone, direction, expirationLength, expirationTimestamp, isSticker, isTapToViewExpired, status, i18n, text, textPending, timestamp, id, showMessageDetail, } = this.props; const isStickerLike = isSticker || this.canRenderStickerLikeEmoji(); return ( ); } private renderAuthor(): ReactNode { const { author, contactNameColor, isSticker, isTapToView, isTapToViewExpired, } = this.props; if (!this.shouldRenderAuthor()) { return null; } const withTapToViewExpired = isTapToView && isTapToViewExpired; const stickerSuffix = isSticker ? '_with_sticker' : ''; const tapToViewSuffix = withTapToViewExpired ? '--with-tap-to-view-expired' : ''; const moduleName = `module-message__author${stickerSuffix}${tapToViewSuffix}`; return (
); } public renderAttachment(): JSX.Element | null { const { attachments, direction, expirationLength, expirationTimestamp, i18n, id, isSticker, kickOffAttachmentDownload, markAttachmentAsCorrupted, markViewed, quote, readStatus, reducedMotion, renderAudioAttachment, renderingContext, showMessageDetail, showVisualAttachment, shouldCollapseAbove, shouldCollapseBelow, status, text, textPending, theme, timestamp, } = this.props; const { imageBroken } = this.state; const collapseMetadata = this.getMetadataPlacement() === MetadataPlacement.NotRendered; if (!attachments || !attachments[0]) { return null; } const firstAttachment = attachments[0]; // For attachments which aren't full-frame const withContentBelow = Boolean(text); const withContentAbove = Boolean(quote) || this.shouldRenderAuthor(); const displayImage = canDisplayImage(attachments); if (displayImage && !imageBroken) { const prefix = isSticker ? 'sticker' : 'attachment'; const containerClassName = classNames( `module-message__${prefix}-container`, withContentAbove ? `module-message__${prefix}-container--with-content-above` : null, withContentBelow ? 'module-message__attachment-container--with-content-below' : null, isSticker && !collapseMetadata ? 'module-message__sticker-container--with-content-below' : null ); if (isGIF(attachments)) { return (
{ showVisualAttachment({ attachment: firstAttachment, messageId: id, }); }} kickOffAttachmentDownload={() => { kickOffAttachmentDownload({ attachment: firstAttachment, messageId: id, }); }} />
); } if (isImage(attachments) || isVideo(attachments)) { const bottomOverlay = !isSticker && !collapseMetadata; // We only want users to tab into this if there's more than one const tabIndex = attachments.length > 1 ? 0 : -1; return (
{ if (!isDownloaded(attachment)) { kickOffAttachmentDownload({ attachment, messageId: id }); } else { showVisualAttachment({ attachment, messageId: id }); } }} />
); } } if (isAudio(attachments)) { let played: boolean; switch (direction) { case 'outgoing': played = status === 'viewed'; break; case 'incoming': played = readStatus === ReadStatus.Viewed; break; default: log.error(missingCaseError(direction)); played = false; break; } return renderAudioAttachment({ i18n, buttonRef: this.audioButtonRef, renderingContext, theme, attachment: firstAttachment, collapseMetadata, withContentAbove, withContentBelow, direction, expirationLength, expirationTimestamp, id, played, showMessageDetail, status, textPending, timestamp, kickOffAttachmentDownload() { kickOffAttachmentDownload({ attachment: firstAttachment, messageId: id, }); }, onCorrupted() { markAttachmentAsCorrupted({ attachment: firstAttachment, messageId: id, }); }, onFirstPlayed() { markViewed(id); }, }); } const { pending, fileName, fileSize, contentType } = firstAttachment; const extension = getExtensionForDisplay({ contentType, fileName }); const isDangerous = isFileDangerous(fileName || ''); return ( ); } public renderPreview(): JSX.Element | null { const { id, attachments, conversationType, direction, i18n, openLink, previews, quote, theme, kickOffAttachmentDownload, } = this.props; // Attachments take precedence over Link Previews if (attachments && attachments.length) { return null; } if (!previews || previews.length < 1) { return null; } const first = previews[0]; if (!first) { return null; } const withContentAbove = Boolean(quote) || (conversationType === 'group' && direction === 'incoming'); const previewHasImage = isImageAttachment(first.image); const isFullSizeImage = shouldUseFullSizeLinkPreviewImage(first); const linkPreviewDate = first.date || null; const isClickable = this.areLinksEnabled(); const className = classNames( 'module-message__link-preview', `module-message__link-preview--${direction}`, { 'module-message__link-preview--with-content-above': withContentAbove, 'module-message__link-preview--nonclickable': !isClickable, } ); const onPreviewImageClick = () => { if (first.image && !isDownloaded(first.image)) { kickOffAttachmentDownload({ attachment: first.image, messageId: id, }); return; } openLink(first.url); }; const contents = ( <> {first.image && previewHasImage && isFullSizeImage ? ( ) : null}
{first.image && previewHasImage && !isFullSizeImage ? (
{i18n('previewThumbnail',
) : null}
{first.title}
{first.description && (
{unescape(first.description)}
)}
{first.domain}
); return isClickable ? (
{ if (event.key === 'Enter' || event.key === 'Space') { event.stopPropagation(); event.preventDefault(); openLink(first.url); } }} onClick={(event: React.MouseEvent) => { event.stopPropagation(); event.preventDefault(); openLink(first.url); }} > {contents}
) : (
{contents}
); } public renderQuote(): JSX.Element | null { const { conversationColor, customColor, direction, disableScroll, doubleCheckMissingQuoteReference, i18n, id, quote, scrollToQuotedMessage, shouldCollapseAbove, } = this.props; if (!quote) { return null; } const { isViewOnce, referencedMessageNotFound } = quote; const clickHandler = disableScroll ? undefined : () => { scrollToQuotedMessage({ authorId: quote.authorId, sentAt: quote.sentAt, }); }; const isIncoming = direction === 'incoming'; let curveTopLeft: boolean; let curveTopRight: boolean; if (this.shouldRenderAuthor()) { curveTopLeft = false; curveTopRight = false; } else if (isIncoming) { curveTopLeft = !shouldCollapseAbove; curveTopRight = true; } else { curveTopLeft = true; curveTopRight = !shouldCollapseAbove; } return ( doubleCheckMissingQuoteReference(id) } /> ); } public renderStoryReplyContext(): JSX.Element | null { const { conversationColor, customColor, direction, i18n, storyReplyContext, shouldCollapseAbove, } = this.props; if (!storyReplyContext) { return null; } const isIncoming = direction === 'incoming'; let curveTopLeft: boolean; let curveTopRight: boolean; if (this.shouldRenderAuthor()) { curveTopLeft = false; curveTopRight = false; } else if (isIncoming) { curveTopLeft = !shouldCollapseAbove; curveTopRight = true; } else { curveTopLeft = true; curveTopRight = !shouldCollapseAbove; } return ( { // TODO DESKTOP-3255 }} rawAttachment={storyReplyContext.rawAttachment} referencedMessageNotFound={false} text={i18n('message--getNotificationText--text-with-emoji', { text: i18n('message--getNotificationText--photo'), emoji: '📷', })} /> ); } public renderEmbeddedContact(): JSX.Element | null { const { contact, conversationType, direction, i18n, showContactDetail, text, } = this.props; if (!contact) { return null; } const withCaption = Boolean(text); const withContentAbove = conversationType === 'group' && direction === 'incoming'; const withContentBelow = withCaption || this.getMetadataPlacement() !== MetadataPlacement.NotRendered; const otherContent = (contact && contact.firstNumber && contact.isNumberOnSignal) || withCaption; const tabIndex = otherContent ? 0 : -1; return ( { showContactDetail({ contact, signalAccount: contact.firstNumber }); }} withContentAbove={withContentAbove} withContentBelow={withContentBelow} tabIndex={tabIndex} /> ); } public renderSendMessageButton(): JSX.Element | null { const { contact, openConversation, i18n } = this.props; if (!contact) { return null; } const { firstNumber, isNumberOnSignal } = contact; if (!firstNumber || !isNumberOnSignal) { return null; } return ( ); } private renderAvatar(): ReactNode { const { author, conversationId, conversationType, direction, getPreferredBadge, i18n, shouldCollapseBelow, showContactModal, theme, } = this.props; if (conversationType !== 'group' || direction !== 'incoming') { return null; } return (
{shouldCollapseBelow ? ( ) : ( { event.stopPropagation(); event.preventDefault(); showContactModal(author.id, conversationId); }} phoneNumber={author.phoneNumber} profileName={author.profileName} sharedGroupNames={author.sharedGroupNames} size={GROUP_AVATAR_SIZE} theme={theme} title={author.title} unblurredAvatarPath={author.unblurredAvatarPath} /> )}
); } public renderText(): JSX.Element | null { const { bodyRanges, deletedForEveryone, direction, displayLimit, i18n, id, messageExpanded, openConversation, status, text, textDirection, textPending, } = this.props; const { metadataWidth } = this.state; const isRTL = textDirection === TextDirection.RightToLeft; // eslint-disable-next-line no-nested-ternary const contents = deletedForEveryone ? i18n('message--deletedForEveryone') : direction === 'incoming' && status === 'error' ? i18n('incomingError') : text; if (!contents) { return null; } return (
{!isRTL && this.getMetadataPlacement() === MetadataPlacement.InlineWithText && ( )}
); } private renderError(): ReactNode { const { status, direction } = this.props; if ( status !== 'paused' && status !== 'error' && status !== 'partial-sent' ) { return null; } return (
); } private renderMenu(triggerId: string): ReactNode { const { attachments, canDownload, canReact, canReply, direction, disableMenu, i18n, id, isSticker, isTapToView, reactToMessage, renderEmojiPicker, renderReactionPicker, replyToMessage, selectedReaction, } = this.props; if (disableMenu) { return null; } const { reactionPickerRoot } = this.state; const multipleAttachments = attachments && attachments.length > 1; const firstAttachment = attachments && attachments[0]; const downloadButton = !isSticker && !multipleAttachments && !isTapToView && firstAttachment && !firstAttachment.pending ? ( // This a menu meant for mouse use only // eslint-disable-next-line max-len // eslint-disable-next-line jsx-a11y/interactive-supports-focus, jsx-a11y/click-events-have-key-events
) : null; const reactButton = ( {({ ref: popperRef }) => { // Only attach the popper reference to the reaction button if it is // visible (it is hidden when the timeline is narrow) const maybePopperRef = this.isWindowWidthNotNarrow() ? popperRef : undefined; return ( // This a menu meant for mouse use only // eslint-disable-next-line max-len // eslint-disable-next-line jsx-a11y/interactive-supports-focus, jsx-a11y/click-events-have-key-events
{ event.stopPropagation(); event.preventDefault(); this.toggleReactionPicker(); }} role="button" className="module-message__buttons__react" aria-label={i18n('reactToMessage')} /> ); }} ); const replyButton = ( // This a menu meant for mouse use only // eslint-disable-next-line max-len // eslint-disable-next-line jsx-a11y/interactive-supports-focus, jsx-a11y/click-events-have-key-events
{ event.stopPropagation(); event.preventDefault(); replyToMessage(id); }} // This a menu meant for mouse use only role="button" aria-label={i18n('replyToMessage')} className={classNames( 'module-message__buttons__reply', `module-message__buttons__download--${direction}` )} /> ); // This a menu meant for mouse use only /* eslint-disable jsx-a11y/interactive-supports-focus */ /* eslint-disable jsx-a11y/click-events-have-key-events */ const menuButton = ( {({ ref: popperRef }) => { // Only attach the popper reference to the collapsed menu button if the reaction // button is not visible (it is hidden when the timeline is narrow) const maybePopperRef = !this.isWindowWidthNotNarrow() ? popperRef : undefined; return (
); }} ); /* eslint-enable jsx-a11y/interactive-supports-focus */ /* eslint-enable jsx-a11y/click-events-have-key-events */ return (
{this.isWindowWidthNotNarrow() && ( <> {canReact ? reactButton : null} {canDownload ? downloadButton : null} {canReply ? replyButton : null} )} {menuButton}
{reactionPickerRoot && createPortal( {({ ref, style }) => renderReactionPicker({ ref, style, selected: selectedReaction, onClose: this.toggleReactionPicker, onPick: emoji => { this.toggleReactionPicker(true); reactToMessage(id, { emoji, remove: emoji === selectedReaction, }); }, renderEmojiPicker, }) } , reactionPickerRoot )}
); } public renderContextMenu(triggerId: string): JSX.Element { const { attachments, canDownload, canReact, canReply, canRetry, canRetryDeleteForEveryone, deleteMessage, deleteMessageForEveryone, deletedForEveryone, i18n, id, isSticker, isTapToView, replyToMessage, retrySend, retryDeleteForEveryone, showForwardMessageModal, showMessageDetail, text, } = this.props; const canForward = !isTapToView && !deletedForEveryone; const multipleAttachments = attachments && attachments.length > 1; const shouldShowAdditional = doesMessageBodyOverflow(text || '') || !this.isWindowWidthNotNarrow(); const menu = ( {canDownload && shouldShowAdditional && !isSticker && !multipleAttachments && !isTapToView && attachments && attachments[0] ? ( {i18n('downloadAttachment')} ) : null} {shouldShowAdditional ? ( <> {canReply && ( { event.stopPropagation(); event.preventDefault(); replyToMessage(id); }} > {i18n('replyToMessage')} )} {canReact && ( { event.stopPropagation(); event.preventDefault(); this.toggleReactionPicker(); }} > {i18n('reactToMessage')} )} ) : null} { event.stopPropagation(); event.preventDefault(); showMessageDetail(id); }} > {i18n('moreInfo')} {canRetry ? ( { event.stopPropagation(); event.preventDefault(); retrySend(id); }} > {i18n('retrySend')} ) : null} {canRetryDeleteForEveryone ? ( { event.stopPropagation(); event.preventDefault(); retryDeleteForEveryone(id); }} > {i18n('retryDeleteForEveryone')} ) : null} {canForward ? ( { event.stopPropagation(); event.preventDefault(); showForwardMessageModal(id); }} > {i18n('forwardMessage')} ) : null} { event.stopPropagation(); event.preventDefault(); deleteMessage(id); }} > {i18n('deleteMessage')} {this.canDeleteForEveryone() ? ( { event.stopPropagation(); event.preventDefault(); deleteMessageForEveryone(id); }} > {i18n('deleteMessageForEveryone')} ) : null} ); return ReactDOM.createPortal(menu, document.body); } private isWindowWidthNotNarrow(): boolean { const { containerWidthBreakpoint } = this.props; return containerWidthBreakpoint !== WidthBreakpoint.Narrow; } public getWidth(): number | undefined { const { attachments, isSticker, previews } = this.props; if (attachments && attachments.length) { if (isGIF(attachments)) { // Message container border return GIF_SIZE + 2; } if (isSticker) { // Padding is 8px, on both sides return STICKER_SIZE + 8 * 2; } const dimensions = getGridDimensions(attachments); if (dimensions) { return dimensions.width; } } const firstLinkPreview = (previews || [])[0]; if ( firstLinkPreview && firstLinkPreview.image && shouldUseFullSizeLinkPreviewImage(firstLinkPreview) ) { const dimensions = getImageDimensions(firstLinkPreview.image); if (dimensions) { return dimensions.width; } } return undefined; } public isShowingImage(): boolean { const { isTapToView, attachments, previews } = this.props; const { imageBroken } = this.state; if (imageBroken || isTapToView) { return false; } if (attachments && attachments.length) { const displayImage = canDisplayImage(attachments); return displayImage && (isImage(attachments) || isVideo(attachments)); } if (previews && previews.length) { const first = previews[0]; const { image } = first; return isImageAttachment(image); } return false; } public isAttachmentPending(): boolean { const { attachments } = this.props; if (!attachments || attachments.length < 1) { return false; } const first = attachments[0]; return Boolean(first.pending); } public renderTapToViewIcon(): JSX.Element { const { direction, isTapToViewExpired } = this.props; const isDownloadPending = this.isAttachmentPending(); return !isTapToViewExpired && isDownloadPending ? (
) : (
); } public renderTapToViewText(): string | undefined { const { attachments, direction, i18n, isTapToViewExpired, isTapToViewError, } = this.props; const incomingString = isTapToViewExpired ? i18n('Message--tap-to-view-expired') : i18n( `Message--tap-to-view--incoming${ isVideo(attachments) ? '-video' : '' }` ); const outgoingString = i18n('Message--tap-to-view--outgoing'); const isDownloadPending = this.isAttachmentPending(); if (isDownloadPending) { return; } // eslint-disable-next-line no-nested-ternary return isTapToViewError ? i18n('incomingError') : direction === 'outgoing' ? outgoingString : incomingString; } public renderTapToView(): JSX.Element { const { conversationType, direction, isTapToViewExpired, isTapToViewError, } = this.props; const collapseMetadata = this.getMetadataPlacement() === MetadataPlacement.NotRendered; const withContentBelow = !collapseMetadata; const withContentAbove = !collapseMetadata && conversationType === 'group' && direction === 'incoming'; return (
{isTapToViewError ? null : this.renderTapToViewIcon()}
{this.renderTapToViewText()}
); } private popperPreventOverflowModifier(): Partial { const { containerElementRef } = this.props; return { name: 'preventOverflow', options: { altAxis: true, boundary: containerElementRef.current || undefined, padding: { bottom: 16, left: 8, right: 8, top: 16, }, }, }; } public toggleReactionViewer = (onlyRemove = false): void => { this.setState(({ reactionViewerRoot }) => { if (reactionViewerRoot) { document.body.removeChild(reactionViewerRoot); document.body.removeEventListener( 'click', this.handleClickOutsideReactionViewer, true ); return { reactionViewerRoot: null }; } if (!onlyRemove) { const root = document.createElement('div'); document.body.appendChild(root); document.body.addEventListener( 'click', this.handleClickOutsideReactionViewer, true ); return { reactionViewerRoot: root, }; } return null; }); }; public toggleReactionPicker = (onlyRemove = false): void => { this.setState(({ reactionPickerRoot }) => { if (reactionPickerRoot) { document.body.removeChild(reactionPickerRoot); document.body.removeEventListener( 'click', this.handleClickOutsideReactionPicker, true ); return { reactionPickerRoot: null }; } if (!onlyRemove) { const root = document.createElement('div'); document.body.appendChild(root); document.body.addEventListener( 'click', this.handleClickOutsideReactionPicker, true ); return { reactionPickerRoot: root, }; } return null; }); }; public handleClickOutsideReactionViewer = (e: MouseEvent): void => { const { reactionViewerRoot } = this.state; const { current: reactionsContainer } = this.reactionsContainerRef; if (reactionViewerRoot && reactionsContainer) { if ( !reactionViewerRoot.contains(e.target as HTMLElement) && !reactionsContainer.contains(e.target as HTMLElement) ) { this.toggleReactionViewer(true); } } }; public handleClickOutsideReactionPicker = (e: MouseEvent): void => { const { reactionPickerRoot } = this.state; if (reactionPickerRoot) { if (!reactionPickerRoot.contains(e.target as HTMLElement)) { this.toggleReactionPicker(true); } } }; public renderReactions(outgoing: boolean): JSX.Element | null { const { getPreferredBadge, reactions = [], i18n, theme } = this.props; if (!this.hasReactions()) { return null; } const reactionsWithEmojiData = reactions.map(reaction => ({ ...reaction, ...emojiToData(reaction.emoji), })); // Group by emoji and order each group by timestamp descending const groupedAndSortedReactions = Object.values( groupBy(reactionsWithEmojiData, 'short_name') ).map(groupedReactions => orderBy( groupedReactions, [reaction => reaction.from.isMe, 'timestamp'], ['desc', 'desc'] ) ); // Order groups by length and subsequently by most recent reaction const ordered = orderBy( groupedAndSortedReactions, ['length', ([{ timestamp }]) => timestamp], ['desc', 'desc'] ); // Take the first three groups for rendering const toRender = take(ordered, 3).map(res => ({ emoji: res[0].emoji, count: res.length, isMe: res.some(re => Boolean(re.from.isMe)), })); const someNotRendered = ordered.length > 3; // We only drop two here because the third emoji would be replaced by the // more button const maybeNotRendered = drop(ordered, 2); const maybeNotRenderedTotal = maybeNotRendered.reduce( (sum, res) => sum + res.length, 0 ); const notRenderedIsMe = someNotRendered && maybeNotRendered.some(res => res.some(re => Boolean(re.from.isMe))); const { reactionViewerRoot } = this.state; const popperPlacement = outgoing ? 'bottom-end' : 'bottom-start'; return ( {({ ref: popperRef }) => (
{toRender.map((re, i) => { const isLast = i === toRender.length - 1; const isMore = isLast && someNotRendered; const isMoreWithMe = isMore && notRenderedIsMe; return ( ); })}
)}
{reactionViewerRoot && createPortal( {({ ref, style }) => ( )} , reactionViewerRoot )}
); } public renderContents(): JSX.Element | null { const { isTapToView, deletedForEveryone } = this.props; if (deletedForEveryone) { return ( <> {this.renderText()} {this.renderMetadata()} ); } if (isTapToView) { return ( <> {this.renderTapToView()} {this.renderMetadata()} ); } return ( <> {this.renderQuote()} {this.renderStoryReplyContext()} {this.renderAttachment()} {this.renderPreview()} {this.renderEmbeddedContact()} {this.renderText()} {this.renderMetadata()} {this.renderSendMessageButton()} ); } public handleOpen = ( event: React.KeyboardEvent | React.MouseEvent ): void => { const { attachments, contact, displayTapToViewMessage, direction, id, isTapToView, isTapToViewExpired, kickOffAttachmentDownload, openConversation, showContactDetail, showVisualAttachment, showExpiredIncomingTapToViewToast, showExpiredOutgoingTapToViewToast, } = this.props; const { imageBroken } = this.state; const isAttachmentPending = this.isAttachmentPending(); if (isTapToView) { if (isAttachmentPending) { log.info( ' handleOpen: tap-to-view attachment is pending; not showing the lightbox' ); return; } if (attachments && !isDownloaded(attachments[0])) { event.preventDefault(); event.stopPropagation(); kickOffAttachmentDownload({ attachment: attachments[0], messageId: id, }); return; } if (isTapToViewExpired) { const action = direction === 'outgoing' ? showExpiredOutgoingTapToViewToast : showExpiredIncomingTapToViewToast; action(); } else { event.preventDefault(); event.stopPropagation(); displayTapToViewMessage(id); } return; } if ( !imageBroken && attachments && attachments.length > 0 && !isAttachmentPending && (isImage(attachments) || isVideo(attachments)) && !isDownloaded(attachments[0]) ) { event.preventDefault(); event.stopPropagation(); const attachment = attachments[0]; kickOffAttachmentDownload({ attachment, messageId: id }); return; } if ( !imageBroken && attachments && attachments.length > 0 && !isAttachmentPending && canDisplayImage(attachments) && ((isImage(attachments) && hasImage(attachments)) || (isVideo(attachments) && hasVideoScreenshot(attachments))) ) { event.preventDefault(); event.stopPropagation(); const attachment = attachments[0]; showVisualAttachment({ attachment, messageId: id }); return; } if ( attachments && attachments.length === 1 && !isAttachmentPending && !isAudio(attachments) ) { event.preventDefault(); event.stopPropagation(); this.openGenericAttachment(); return; } if ( !isAttachmentPending && isAudio(attachments) && this.audioButtonRef && this.audioButtonRef.current ) { event.preventDefault(); event.stopPropagation(); this.audioButtonRef.current.click(); } if (contact && contact.firstNumber && contact.isNumberOnSignal) { openConversation(contact.firstNumber); event.preventDefault(); event.stopPropagation(); } if (contact) { showContactDetail({ contact, signalAccount: contact.firstNumber }); event.preventDefault(); event.stopPropagation(); } }; public openGenericAttachment = (event?: React.MouseEvent): void => { const { id, attachments, downloadAttachment, timestamp, kickOffAttachmentDownload, } = this.props; if (event) { event.preventDefault(); event.stopPropagation(); } if (!attachments || attachments.length !== 1) { return; } const attachment = attachments[0]; if (!isDownloaded(attachment)) { kickOffAttachmentDownload({ attachment, messageId: id, }); return; } const { fileName } = attachment; const isDangerous = isFileDangerous(fileName || ''); downloadAttachment({ isDangerous, attachment, timestamp, }); }; public handleKeyDown = (event: React.KeyboardEvent): void => { // Do not allow reactions to error messages const { canReact } = this.props; const key = KeyboardLayout.lookup(event.nativeEvent); if ( (key === 'E' || key === 'e') && (event.metaKey || event.ctrlKey) && event.shiftKey && canReact ) { this.toggleReactionPicker(); } if (event.key !== 'Enter' && event.key !== 'Space') { return; } this.handleOpen(event); }; public handleClick = (event: React.MouseEvent): void => { // We don't want clicks on body text to result in the 'default action' for the message const { text } = this.props; if (text && text.length > 0) { return; } this.handleOpen(event); }; public renderContainer(): JSX.Element { const { attachments, conversationColor, customColor, deletedForEveryone, direction, isSticker, isTapToView, isTapToViewExpired, isTapToViewError, text, } = this.props; const { isSelected } = this.state; const isAttachmentPending = this.isAttachmentPending(); const width = this.getWidth(); const isShowingImage = this.isShowingImage(); const isEmojiOnly = this.canRenderStickerLikeEmoji(); const isStickerLike = isSticker || isEmojiOnly; // If it's a mostly-normal gray incoming text box, we don't want to darken it as much const lighterSelect = isSelected && direction === 'incoming' && !isStickerLike && (text || (!isVideo(attachments) && !isImage(attachments))); const containerClassnames = classNames( 'module-message__container', isGIF(attachments) ? 'module-message__container--gif' : null, isSelected ? 'module-message__container--selected' : null, lighterSelect ? 'module-message__container--selected-lighter' : null, !isStickerLike ? `module-message__container--${direction}` : null, isEmojiOnly ? 'module-message__container--emoji' : null, isTapToView ? 'module-message__container--with-tap-to-view' : null, isTapToView && isTapToViewExpired ? 'module-message__container--with-tap-to-view-expired' : null, !isStickerLike && direction === 'outgoing' ? `module-message__container--outgoing-${conversationColor}` : null, isTapToView && isAttachmentPending && !isTapToViewExpired ? 'module-message__container--with-tap-to-view-pending' : null, isTapToView && isAttachmentPending && !isTapToViewExpired ? `module-message__container--${direction}-${conversationColor}-tap-to-view-pending` : null, isTapToViewError ? 'module-message__container--with-tap-to-view-error' : null, this.hasReactions() ? 'module-message__container--with-reactions' : null, deletedForEveryone ? 'module-message__container--deleted-for-everyone' : null ); const containerStyles = { width: isShowingImage ? width : undefined, }; if (!isStickerLike && direction === 'outgoing') { Object.assign(containerStyles, getCustomColorStyle(customColor)); } return (
{this.renderAuthor()} {this.renderContents()}
{this.renderReactions(direction === 'outgoing')}
); } public override render(): JSX.Element | null { const { author, attachments, direction, id, isSticker, shouldCollapseAbove, shouldCollapseBelow, timestamp, } = this.props; const { expired, expiring, imageBroken, isSelected } = this.state; // This id is what connects our triple-dot click with our associated pop-up menu. // It needs to be unique. const triggerId = String(id || `${author.id}-${timestamp}`); if (expired) { return null; } if (isSticker && (imageBroken || !attachments || !attachments.length)) { return null; } return (
{this.renderError()} {this.renderAvatar()} {this.renderContainer()} {this.renderMenu(triggerId)} {this.renderContextMenu(triggerId)}
); } }