import React, { useState } from 'react'; import DateTimePicker, { DateTimePickerEvent } from '@react-native-community/datetimepicker'; import { Image, Linking, Modal, Platform, Pressable, StatusBar, StyleSheet, Text, View } from 'react-native'; import Video from 'react-native-video'; import { cachedImageSource, cachedVideoSource } from '../cachedMedia'; import { EnxAction, EnxChatTheme, EnxChoice, EnxMessage, EnxMessageSender, EnxMessageType, EnxSuggestionType } from '../types'; import { ChatMarkdown } from './ChatMarkdown'; type FullscreenMedia = { kind: 'image' | 'video'; uri: string }; type Props = { message: EnxMessage; theme: EnxChatTheme; onSuggestionTap?: (titles: string[], type: EnxSuggestionType) => void; onActionTap?: (action: EnxAction) => void; }; const time = (d: Date): string => d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); export const MessageCell = ({ message, theme, onSuggestionTap, onActionTap }: Props): React.JSX.Element => { const isUser = message.sender === EnxMessageSender.User; const [choices, setChoices] = useState(() => (message.choices ?? []).map((c) => ({ ...c }))); const isMulti = message.suggestionType === EnxSuggestionType.Multiple; const [showCalendarPicker, setShowCalendarPicker] = useState(false); const [selectedDate, setSelectedDate] = useState(new Date()); const [fullscreenMedia, setFullscreenMedia] = useState(null); const [inlineVideoPaused, setInlineVideoPaused] = useState(false); const mediaUri = (message.media?.localUri ?? message.media?.url)?.trim(); const mediaMime = (message.media?.mimeType ?? '').toLowerCase(); const looksLikeImageUri = !!mediaUri && (/^data:image\//.test(mediaUri) || /\.(png|jpe?g|gif|webp|bmp|svg)(\?|$)/i.test(mediaUri)); const looksLikeVideoUri = !!mediaUri && (/^data:video\//.test(mediaUri) || /\.(mp4|m4v|mov|webm|mkv|m3u8)(\?|$)/i.test(mediaUri)); /** Video URL / mime wins so a `.mp4` link is never treated as an image if `type` is wrong. */ const shouldRenderVideo = !message.linkCard && !!mediaUri && (message.type === EnxMessageType.Video || mediaMime.startsWith('video/') || looksLikeVideoUri); const shouldRenderImage = !message.linkCard && !!mediaUri && !shouldRenderVideo && (message.type === EnxMessageType.Image || mediaMime.startsWith('image/') || looksLikeImageUri); /** Inline image/video bubbles: no duplicate URL or title under the media. */ const imageOnlyBubble = message.type === EnxMessageType.Image && shouldRenderImage; const videoOnlyBubble = message.type === EnxMessageType.Video && shouldRenderVideo; const mediaOnlyBubble = imageOnlyBubble || videoOnlyBubble; if ( message.displayStyle === 'systemCentered' && message.sender === EnxMessageSender.Bot && message.text?.trim() ) { return ( {message.text.trim()} ); } const sendCalendarDate = (date: Date): void => { onSuggestionTap?.([date.toISOString().slice(0, 10)], EnxSuggestionType.Single); }; const handleCalendarChange = (event: DateTimePickerEvent, date?: Date): void => { if (Platform.OS === 'android') { setShowCalendarPicker(false); if (event.type === 'set' && date) { setSelectedDate(date); sendCalendarDate(date); } return; } if (date) setSelectedDate(date); }; const extraActions = message.linkCard && message.actions?.length ? message.actions.filter((a) => a.url && a.url !== message.linkCard?.url) : message.actions; /** Single/multi-choice and action rows read as menus — use full allowed width, not shrink-to-label. */ const hasMenuBubble = choices.length > 0 || message.type === EnxMessageType.Suggestion || (!!extraActions?.length && !message.linkCard); const bubble = ( {message.linkCard && ( {!!message.linkCard.imageUrl && ( void Linking.openURL(message.linkCard!.url)} accessibilityRole="imagebutton" accessibilityLabel="Preview image, open link" > )} {!!message.linkCard.title && ( void Linking.openURL(message.linkCard!.url)}> )} {!!message.linkCard.description && ( )} {time(message.timestamp)} void Linking.openURL(message.linkCard!.url)} style={styles.linkCardCta} accessibilityRole="button" accessibilityLabel={message.linkCard.buttonTitle ?? 'Visit now'} > )} {shouldRenderImage && ( setFullscreenMedia({ kind: 'image', uri: mediaUri })} accessibilityRole="imagebutton" accessibilityLabel="View image full screen" > )} {shouldRenderVideo && ( )} {(message.type === EnxMessageType.File || (message.type === EnxMessageType.Video && !shouldRenderVideo)) && !message.linkCard && ( message.media?.url && Linking.openURL(message.media.url)}> {message.type === EnxMessageType.Video ? '🎬' : '📄'} {message.media?.mimeType ?? 'application/octet-stream'} )} {!!message.text && !mediaOnlyBubble && ( )} {!!message.subtitle && !mediaOnlyBubble && ( )} {(extraActions ?? []).map((action) => ( { onActionTap?.(action); if (!onActionTap && action.url) void Linking.openURL(action.url); }} > ))} {choices.map((choice, i) => ( { if (!isMulti) { onSuggestionTap?.([choice.title], EnxSuggestionType.Single); } else { setChoices((prev) => prev.map((c, idx) => idx === i ? { ...c, isSelected: !c.isSelected } : c)); } }} > ))} {isMulti && choices.length > 0 && ( { const selected = choices.filter((c) => c.isSelected).map((c) => c.title); if (selected.length) onSuggestionTap?.(selected, EnxSuggestionType.Multiple); }} > )} {message.type === EnxMessageType.Calendar && ( <> setShowCalendarPicker(true)}> Select date {showCalendarPicker && ( {Platform.OS === 'ios' && ( setShowCalendarPicker(false)}> Cancel { setShowCalendarPicker(false); sendCalendarDate(selectedDate); }} > Done )} )} )} {!message.linkCard ? {time(message.timestamp)} : null} ); /** Image-only bot rows had no menu → bubble shrink-wrapped; `Image` width % then collapsed. Same width as menus. */ const growBotBubble = !isUser && (hasMenuBubble || shouldRenderImage || shouldRenderVideo); const closeFullscreenMedia = (): void => { setFullscreenMedia(null); setInlineVideoPaused(false); }; const mediaModalTopPad = Platform.OS === 'android' ? (StatusBar.currentHeight ?? 0) + 8 : 52; return ( <> {growBotBubble ? {bubble} : bubble} ← {fullscreenMedia?.kind === 'image' && ( )} {fullscreenMedia?.kind === 'video' && ( ); }; const styles = StyleSheet.create({ systemNoticeRow: { paddingHorizontal: 12, marginVertical: 6, alignItems: 'center', }, systemNoticeChip: { maxWidth: '88%', paddingHorizontal: 16, paddingVertical: 10, borderRadius: 12, backgroundColor: 'rgba(0,0,0,0.07)', }, systemNoticeText: { color: '#4b5563', fontSize: 14, lineHeight: 20, textAlign: 'center', }, row: { paddingHorizontal: 8, marginVertical: 4, flexDirection: 'row' }, rowLeft: { justifyContent: 'flex-start' }, rowRight: { justifyContent: 'flex-end' }, bubble: { maxWidth: '76%', borderRadius: 16, overflow: 'hidden' }, /** Menu-style bot messages fill up to 76% of the row (not shrink-wrapped to shortest label). */ bubbleMenu: { alignSelf: 'stretch', width: '100%' }, /** User image rows: same % width as bot so `Image` width % resolves (no shrink-wrap). */ bubbleUserImage: { width: '76%', maxWidth: '76%', alignSelf: 'flex-end' }, /** Bot menu rows: fixed generous width (no side avatar). */ botBubbleGrowSolo: { width: '76%', maxWidth: '76%' }, tailLeft: { borderBottomLeftRadius: 4 }, tailRight: { borderBottomRightRadius: 4 }, t: { alignSelf: 'flex-end', paddingHorizontal: 10, paddingTop: 6, paddingBottom: 8, color: '#6b7280', fontSize: 10 }, image: { width: '100%', height: 180, backgroundColor: '#d1d5db' }, imageModalRoot: { flex: 1, backgroundColor: '#000000' }, imageModalHeader: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, paddingBottom: 8, }, imageModalBackBtn: { paddingVertical: 10, paddingHorizontal: 12, justifyContent: 'center', alignItems: 'center' }, imageModalBackArrow: { color: '#ffffff', fontSize: 28, fontWeight: '300', lineHeight: 32 }, imageModalImg: { flex: 1, width: '100%' }, fullscreenVideo: { flex: 1, width: '100%', backgroundColor: '#000000' }, videoShell: { width: '100%', height: 200, backgroundColor: '#000000', position: 'relative', }, inlineVideo: { width: '100%', height: '100%' }, videoExpandHit: { position: 'absolute', top: 6, right: 6, zIndex: 10, paddingHorizontal: 10, paddingVertical: 6, borderRadius: 8, backgroundColor: 'rgba(0,0,0,0.55)', }, videoExpandIcon: { color: '#ffffff', fontSize: 18, fontWeight: '600', lineHeight: 22 }, file: { margin: 12, padding: 10, borderRadius: 10, backgroundColor: '#f3f4f6', flexDirection: 'row', alignItems: 'center' }, fileEmoji: { fontSize: 28 }, fileContent: { flex: 1, marginLeft: 10 }, fileName: { color: '#111827', fontWeight: '600', fontSize: 14 }, fileType: { color: '#6b7280', fontSize: 12, marginTop: 2 }, lineBtn: { borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: '#d1d5db', minHeight: 44, paddingHorizontal: 14, alignItems: 'center', justifyContent: 'center', }, calendarWrap: { borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: '#d1d5db', paddingVertical: 6, paddingHorizontal: 8 }, calendarActions: { flexDirection: 'row', justifyContent: 'flex-end', paddingHorizontal: 6, paddingBottom: 4 }, calendarActionBtn: { paddingHorizontal: 8, paddingVertical: 4, marginLeft: 8 }, calendarActionTxt: { color: '#374151', fontSize: 14 }, linkCard: { borderRadius: 12, overflow: 'hidden', backgroundColor: '#ffffff', borderWidth: StyleSheet.hairlineWidth, borderColor: '#e5e7eb', }, linkCardImage: { width: '100%', height: 152, backgroundColor: '#e5e7eb' }, linkCardBody: { paddingHorizontal: 12, paddingTop: 10, paddingBottom: 8 }, linkCardTime: { alignSelf: 'flex-end', fontSize: 11, color: '#9ca3af', marginBottom: 4 }, linkCardCta: { alignSelf: 'stretch', alignItems: 'center', marginHorizontal: -12, paddingHorizontal: 12, paddingTop: 12, paddingBottom: 8, borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: '#d1d5db', }, linkCardCtaMarkdown: { width: '100%', alignItems: 'center' }, });