123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163 |
- import React, { useState, useCallback, useEffect, useRef } from 'react';
- import {
- View,
- TouchableOpacity,
- Image,
- Text,
- FlatList,
- Dimensions,
- Alert,
- ScrollView,
- Linking,
- ActivityIndicator,
- AppState,
- AppStateStatus,
- TextInput,
- Platform
- } from 'react-native';
- import {
- GiftedChat,
- Bubble,
- InputToolbar,
- IMessage,
- Send,
- BubbleProps,
- Composer,
- TimeProps,
- MessageProps,
- Actions
- } from 'react-native-gifted-chat';
- import { MaterialCommunityIcons } from '@expo/vector-icons';
- import { GestureHandlerRootView, Swipeable } from 'react-native-gesture-handler';
- import { AvatarWithInitials, Header, WarningModal } from 'src/components';
- import { Colors } from 'src/theme';
- import { useFocusEffect, useNavigation } from '@react-navigation/native';
- import { Audio } from 'expo-av';
- import ChatMessageBox from '../Components/ChatMessageBox';
- import ReplyMessageBar from '../Components/ReplyMessageBar';
- import { useSharedValue, withTiming } from 'react-native-reanimated';
- import { BlurView } from 'expo-blur';
- import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
- import Clipboard from '@react-native-clipboard/clipboard';
- import { trigger } from 'react-native-haptic-feedback';
- import ReactModal from 'react-native-modal';
- import { storage, StoreType } from 'src/storage';
- import {
- usePostDeleteMessageMutation,
- usePostGetChatWithQuery,
- usePostMessagesReadMutation,
- usePostReactToMessageMutation,
- usePostSendMessageMutation,
- usePostEditMessageMutation,
- usePostCanSendMessageQuery
- } from '@api/chat';
- import { CustomMessage, Message, Reaction } from '../types';
- import { API_HOST, APP_VERSION, WEBSOCKET_URL } from 'src/constants';
- import ReactionBar from '../Components/ReactionBar';
- import OptionsMenu from '../Components/OptionsMenu';
- import EmojiSelectorModal from '../Components/EmojiSelectorModal';
- import { styles } from './styles';
- import SendIcon from 'assets/icons/messages/send.svg';
- import { SheetManager } from 'react-native-actions-sheet';
- import { NAVIGATION_PAGES } from 'src/types';
- import { usePushNotification } from 'src/contexts/PushNotificationContext';
- import ReactionsListModal from '../Components/ReactionsListModal';
- import { dismissChatNotifications, isMessageEdited } from '../utils';
- import { useMessagesStore } from 'src/stores/unreadMessagesStore';
- import FileViewer from 'react-native-file-viewer';
- import * as FileSystem from 'expo-file-system';
- import ImageView from 'better-react-native-image-viewing';
- import * as MediaLibrary from 'expo-media-library';
- import BanIcon from 'assets/icons/messages/ban.svg';
- import AttachmentsModal from '../Components/AttachmentsModal';
- import RenderMessageVideo from '../Components/renderMessageVideo';
- import MessageLocation from '../Components/MessageLocation';
- import { CACHED_ATTACHMENTS_DIR } from 'src/constants/constants';
- const options = {
- enableVibrateFallback: true,
- ignoreAndroidSystemSettings: false
- };
- const reactionEmojis = ['👍', '❤️', '😂', '😮', '😭'];
- const ChatScreen = ({ route }: { route: any }) => {
- const token = storage.get('token', StoreType.STRING) as string;
- const {
- id,
- name,
- avatar,
- userType = 'normal'
- }: {
- id: number;
- name: string;
- avatar: string | null;
- userType: 'normal' | 'not_exist' | 'blocked';
- } = route.params;
- const userName =
- userType === 'blocked'
- ? 'Account is blocked'
- : userType === 'not_exist'
- ? 'Account does not exist'
- : name;
- const currentUserId = storage.get('uid', StoreType.STRING) as number;
- const insets = useSafeAreaInsets();
- const [messages, setMessages] = useState<CustomMessage[] | null>();
- const navigation = useNavigation();
- const [prevThenMessageId, setPrevThenMessageId] = useState<number>(-1);
- const { data: canSendMessage } = usePostCanSendMessageQuery(token, id, true);
- const {
- data: chatData,
- refetch,
- isFetching
- } = usePostGetChatWithQuery(token, id, 50, prevThenMessageId, true);
- const { mutateAsync: sendMessage } = usePostSendMessageMutation();
- const swipeableRowRef = useRef<Swipeable | null>(null);
- const messageContainerRef = useRef<FlatList<IMessage> | null>(null);
- const [selectedMedia, setSelectedMedia] = useState<any>(null);
- const [replyMessage, setReplyMessage] = useState<CustomMessage | null>(null);
- const [modalInfo, setModalInfo] = useState<any>({
- visible: false,
- type: 'confirm',
- message: '',
- action: () => {},
- buttonTitle: '',
- title: ''
- });
- const [selectedMessage, setSelectedMessage] = useState<BubbleProps<CustomMessage> | null>(null);
- const [emojiSelectorVisible, setEmojiSelectorVisible] = useState(false);
- const [messagePosition, setMessagePosition] = useState<{
- x: number;
- y: number;
- width: number;
- height: number;
- isMine: boolean;
- } | null>(null);
- const [isModalVisible, setIsModalVisible] = useState(false);
- const [unreadMessageIndex, setUnreadMessageIndex] = useState<number | null>(null);
- const { mutateAsync: markMessagesAsRead } = usePostMessagesReadMutation();
- const { mutateAsync: deleteMessage } = usePostDeleteMessageMutation();
- const { mutateAsync: reactToMessage } = usePostReactToMessageMutation();
- const { mutateAsync: editMessage } = usePostEditMessageMutation();
- const [highlightedMessageId, setHighlightedMessageId] = useState<number | null>(null);
- const [isRerendering, setIsRerendering] = useState<boolean>(false);
- const [isTyping, setIsTyping] = useState<boolean>(false);
- const messageRefs = useRef<{ [key: string]: any }>({});
- const flatList = useRef<FlatList | null>(null);
- const scrollY = useSharedValue(0);
- const { isSubscribed } = usePushNotification();
- const [isLoadingEarlier, setIsLoadingEarlier] = useState(false);
- const [hasMoreMessages, setHasMoreMessages] = useState(true);
- const updateUnreadMessagesCount = useMessagesStore((state) => state.updateUnreadMessagesCount);
- const [text, setText] = useState('');
- const [editingMessage, setEditingMessage] = useState<CustomMessage | null>(null);
- const appState = useRef(AppState.currentState);
- const textInputRef = useRef<TextInput>(null);
- const socket = useRef<WebSocket | null>(null);
- const closeModal = () => {
- setModalInfo({ ...modalInfo, visible: false });
- };
- useEffect(() => {
- if (!Audio || !Audio.setAudioModeAsync) {
- return;
- }
- Audio.setAudioModeAsync({
- allowsRecordingIOS: false,
- staysActiveInBackground: false,
- playsInSilentModeIOS: true,
- shouldDuckAndroid: true,
- playThroughEarpieceAndroid: false
- });
- }, []);
- useEffect(() => {
- if (canSendMessage && canSendMessage.need_authentication_or_friend === 1) {
- setModalInfo({
- visible: true,
- type: 'success',
- message: (
- <Text>
- Only legit NomadManias and friends can send messages.{'\n'}Befriend this traveller first
- or{' '}
- <Text
- style={{
- color: Colors.ORANGE,
- textDecorationLine: 'underline',
- textDecorationColor: Colors.ORANGE
- }}
- onPress={() =>
- Linking.openURL('https://nomadmania.com/badges/').catch((err) =>
- console.error('Failed to open auth URL:', err)
- )
- }
- >
- become Legit
- </Text>
- !
- </Text>
- ),
- action: () => {},
- buttonTitle: 'OK',
- title: 'Oops!'
- });
- }
- }, [canSendMessage]);
- const onSendMedia = useCallback(
- async (files: { uri: string; type: 'image' | 'video' }[]) => {
- for (const file of files) {
- const tempMessage: CustomMessage = {
- _id: Date.now() + Math.random(),
- text: '',
- createdAt: new Date(),
- user: { _id: +currentUserId, name: 'Me' },
- reactions: {},
- deleted: false,
- attachment: {
- id: -1,
- filename: file.type,
- filetype: file.type,
- attachment_link: file.uri,
- attachment_full_url: file.uri
- },
- pending: true,
- isSending: true,
- edited: false,
- image: file.type === 'image' ? file.uri : undefined,
- video: file.type === 'video' ? file.uri : undefined
- };
- if (replyMessage) {
- tempMessage.replyMessage = {
- text: replyMessage.text,
- id: replyMessage._id,
- name: replyMessage.user._id === id ? userName : 'Me'
- };
- }
- setMessages((previousMessages) => GiftedChat.append(previousMessages ?? [], [tempMessage]));
- const messageData = {
- token,
- to_uid: id,
- text: '',
- reply_to_id: replyMessage ? (replyMessage._id as number) : -1,
- attachment: {
- uri: file.uri,
- type: file.type,
- name: file.uri.split('/').pop()
- }
- };
- const res = await sendMessage(messageData, {
- onSuccess: (res) => {
- const { attachment, message_id } = res;
- const newMessage = {
- _id: message_id,
- text: '',
- attachment,
- replyMessage: { ...tempMessage.replyMessage, sender: replyMessage?.user?._id },
- image: file.type === 'image' ? API_HOST + attachment.attachment_full_url : undefined,
- video: file.type === 'video' ? file.uri : undefined
- };
- setMessages((previousMessages) =>
- (previousMessages ?? []).map((msg) =>
- msg._id === tempMessage._id
- ? {
- ...msg,
- _id: res.message_id,
- isSending: false
- }
- : msg
- )
- );
- sendWebSocketMessage('new_message', newMessage as unknown as CustomMessage);
- }
- });
- clearReplyMessage();
- }
- },
- [replyMessage]
- );
- const onSendLocation = useCallback(
- async (coords: { latitude: number; longitude: number }) => {
- const tempMessage: CustomMessage = {
- _id: Date.now() + Math.random(),
- text: '',
- createdAt: new Date(),
- user: { _id: +currentUserId, name: 'Me' },
- pending: true,
- deleted: false,
- edited: false,
- reactions: {},
- attachment: {
- id: -1,
- filename: 'location.json',
- filetype: 'nomadmania/location',
- lat: coords.latitude,
- lng: coords.longitude
- }
- };
- if (replyMessage) {
- tempMessage.replyMessage = {
- text: replyMessage.text,
- id: replyMessage._id,
- name: replyMessage.user._id === id ? userName : 'Me'
- };
- }
- setMessages((previousMessages) => GiftedChat.append(previousMessages ?? [], [tempMessage]));
- const locationData = JSON.stringify({ lat: coords.latitude, lng: coords.longitude });
- const fileUri = FileSystem.documentDirectory + 'location.json';
- await FileSystem.writeAsStringAsync(fileUri, locationData);
- const locationFile = {
- uri: fileUri,
- type: 'application/json',
- name: 'location.json'
- };
- const messageData = {
- token,
- to_uid: id,
- text: tempMessage.text,
- reply_to_id: replyMessage ? (replyMessage._id as number) : -1,
- attachment: locationFile
- };
- sendMessage(messageData, {
- onSuccess: async (res) => {
- const { attachment, message_id } = res;
- const newMessage = {
- _id: message_id,
- text: '',
- attachment,
- replyMessage: { ...tempMessage.replyMessage, sender: replyMessage?.user?._id }
- };
- setMessages((previousMessages) =>
- (previousMessages ?? []).map((msg) =>
- msg._id === tempMessage._id ? { ...msg, _id: res.message_id } : msg
- )
- );
- sendWebSocketMessage('new_message', newMessage as unknown as CustomMessage);
- await FileSystem.deleteAsync(fileUri);
- },
- onError: async (err) => {
- await FileSystem.deleteAsync(fileUri);
- }
- });
- clearReplyMessage();
- },
- [replyMessage]
- );
- const onSendFile = useCallback(
- (files: { uri: string; type: string; name?: string }[]) => {
- const newMsgs = files.map((file) => {
- const msg: CustomMessage = {
- _id: Date.now() + Math.random(),
- text: '',
- createdAt: new Date(),
- user: { _id: +currentUserId, name: 'Me' },
- deleted: false,
- reactions: {},
- isSending: true,
- edited: false,
- attachment: {
- id: -1,
- filename: file.name ?? 'File',
- filetype: file.type,
- attachment_link: file.uri
- }
- };
- if (replyMessage) {
- msg.replyMessage = {
- text: replyMessage.text,
- id: replyMessage._id,
- name: replyMessage.user._id === id ? userName : 'Me'
- };
- }
- if (file.type.includes('image')) {
- msg.image = file.uri;
- } else if (file.type.includes('video')) {
- msg.video = file.uri;
- }
- setMessages((previousMessages) => GiftedChat.append(previousMessages ?? [], [msg]));
- const messageData = {
- token,
- to_uid: id,
- text: '',
- reply_to_id: replyMessage ? (replyMessage._id as number) : -1,
- attachment: {
- uri: file.uri,
- type: file.type,
- name: file.name || file.uri.split('/').pop()
- }
- };
- sendMessage(messageData, {
- onSuccess: (res) => {
- const { attachment, message_id } = res;
- const newMessage = {
- _id: message_id,
- text: '',
- attachment,
- replyMessage: { ...msg.replyMessage, sender: replyMessage?.user?._id },
- image: file.type === 'image' ? API_HOST + attachment.attachment_full_url : undefined,
- video: file.type === 'video' ? file.uri : undefined
- };
- setMessages((previousMessages) =>
- (previousMessages ?? []).map((prevMsg) =>
- prevMsg._id === msg._id
- ? {
- ...prevMsg,
- _id: res.message_id,
- attachment: res.attachment,
- isSending: false,
- image:
- res.attachment?.attachment_small_url && file.type?.startsWith('image')
- ? API_HOST + res.attachment.attachment_small_url
- : undefined,
- video:
- res.attachment?.attachment_link && file.type?.startsWith('video')
- ? API_HOST + res.attachment.attachment_link
- : undefined
- }
- : prevMsg
- )
- );
- sendWebSocketMessage('new_message', newMessage as unknown as CustomMessage);
- }
- });
- return msg;
- });
- clearReplyMessage();
- },
- [replyMessage]
- );
- async function openFileInApp(uri: string, fileName: string) {
- try {
- const dirExist = await FileSystem.getInfoAsync(CACHED_ATTACHMENTS_DIR);
- if (!dirExist.exists) {
- await FileSystem.makeDirectoryAsync(CACHED_ATTACHMENTS_DIR, { intermediates: true });
- }
- const fileUri = `${CACHED_ATTACHMENTS_DIR}${fileName}`;
- const fileExists = await FileSystem.getInfoAsync(fileUri);
- if (fileExists.exists && fileExists.size > 1024) {
- await FileViewer.open(fileUri, {
- showOpenWithDialog: true,
- showAppsSuggestions: true
- });
- return;
- }
- const { uri: localUri } = await FileSystem.downloadAsync(uri, fileUri, {
- headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS }
- });
- await FileViewer.open(localUri, {
- showOpenWithDialog: true,
- showAppsSuggestions: true
- });
- } catch (err) {
- console.warn('openFileInApp error:', err);
- Alert.alert('Cannot open file', 'No application found to open this file.');
- }
- }
- async function downloadFileToDevice(currentMessage: CustomMessage) {
- if (!currentMessage.image && !currentMessage.video) {
- return;
- }
- const fileUrl = currentMessage.video
- ? currentMessage.video
- : API_HOST + currentMessage.attachment?.attachment_full_url;
- const fileType = currentMessage.attachment?.filetype || '';
- const fileExt = fileType.split('/').pop() || '';
- const fileName = currentMessage.attachment?.filename?.split('.')[0] || 'file';
- const fileUri = `${FileSystem.cacheDirectory}${fileName}.${fileExt}`;
- try {
- const { status } = await MediaLibrary.requestPermissionsAsync();
- if (status !== 'granted') {
- return;
- }
- const downloadOptions = currentMessage.video
- ? { headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS } }
- : undefined;
- const { uri } = await FileSystem.downloadAsync(fileUrl, fileUri, downloadOptions);
- await MediaLibrary.createAssetAsync(uri);
- Alert.alert(
- 'Success',
- `${fileType.startsWith('video') ? 'Video' : 'Image'} saved to gallery.`
- );
- } catch (error) {
- Alert.alert('Error', 'Failed to download the file.');
- }
- }
- const renderMessageFile = (props: BubbleProps<CustomMessage>) => {
- const { currentMessage } = props;
- const leftMessage = currentMessage?.user?._id !== +currentUserId;
- if (!currentMessage?.attachment) return null;
- const { attachment_link, filename } = currentMessage.attachment;
- const fileName = filename ?? 'Attachment';
- const uri = API_HOST + attachment_link;
- return (
- <TouchableOpacity
- style={[
- styles.fileContainer,
- { backgroundColor: leftMessage ? 'rgba(15, 63, 79, 0.2)' : 'rgba(244, 244, 244, 0.2)' }
- ]}
- onPress={() => {
- openFileInApp(uri, fileName);
- }}
- onLongPress={() => handleLongPress(currentMessage, props)}
- disabled={currentMessage?.isSending}
- >
- {currentMessage?.isSending ? (
- <ActivityIndicator
- size="small"
- color={leftMessage ? Colors.DARK_BLUE : Colors.FILL_LIGHT}
- />
- ) : (
- <MaterialCommunityIcons
- name="file"
- size={32}
- color={leftMessage ? Colors.DARK_BLUE : Colors.FILL_LIGHT}
- />
- )}
- <Text
- style={[
- styles.fileNameText,
- { color: leftMessage ? Colors.DARK_BLUE : Colors.FILL_LIGHT }
- ]}
- >
- {fileName}
- </Text>
- </TouchableOpacity>
- );
- };
- const renderMessageLocation = (props: BubbleProps<CustomMessage>) => {
- const { currentMessage } = props;
- if (!currentMessage?.attachment) return null;
- const { lat, lng } = currentMessage.attachment;
- if (!lat || !lng) return null;
- return (
- <View
- style={[
- {
- alignItems: 'center',
- borderRadius: 8,
- marginVertical: 6,
- marginHorizontal: 6,
- width: 220
- }
- ]}
- >
- <MessageLocation props={props} lat={lat} lng={lng} onLongPress={handleLongPress} />
- </View>
- );
- };
- const onShareLiveLocation = useCallback(() => {
- const liveMsg: IMessage = {
- _id: 'live-loc-' + Date.now(),
- text: 'Sharing live location...',
- createdAt: new Date(),
- user: { _id: +currentUserId, name: 'Me' },
- system: false
- };
- // setMessages((prev) => GiftedChat.append(prev, [liveMsg]));
- }, []);
- useEffect(() => {
- let unsubscribe: any;
- const setupNotificationHandler = async () => {
- unsubscribe = await dismissChatNotifications(id, isSubscribed, setModalInfo, navigation);
- };
- setupNotificationHandler();
- return () => {
- if (unsubscribe) unsubscribe();
- updateUnreadMessagesCount();
- };
- }, [id]);
- useEffect(() => {
- socket.current = new WebSocket(WEBSOCKET_URL);
- socket.current.onopen = () => {
- socket.current?.send(JSON.stringify({ token }));
- };
- socket.current.onmessage = (event) => {
- const data = JSON.parse(event.data);
- handleWebSocketMessage(data);
- };
- socket.current.onclose = () => {
- console.log('WebSocket connection closed chat screen');
- };
- return () => {
- if (socket.current) {
- socket.current.close();
- socket.current = null;
- }
- };
- }, [token]);
- useEffect(() => {
- const handleAppStateChange = async (nextAppState: AppStateStatus) => {
- const prevState = appState.current;
- appState.current = nextAppState;
- if (prevState.match(/inactive|background/) && nextAppState === 'active') {
- refetch();
- if (!socket.current || socket.current.readyState === WebSocket.CLOSED) {
- socket.current = new WebSocket(WEBSOCKET_URL);
- socket.current.onopen = () => {
- socket.current?.send(JSON.stringify({ token }));
- };
- socket.current.onmessage = (event) => {
- const data = JSON.parse(event.data);
- handleWebSocketMessage(data);
- };
- }
- await dismissChatNotifications(id, isSubscribed, setModalInfo, navigation);
- }
- };
- const subscription = AppState.addEventListener('change', handleAppStateChange);
- return () => {
- subscription.remove();
- if (socket.current) {
- socket.current.close();
- socket.current = null;
- }
- };
- }, [token]);
- const handleWebSocketMessage = (data: any) => {
- switch (data.action) {
- case 'new_message':
- if (data.conversation_with === id && data.message) {
- const newMessage = mapApiMessageToGiftedMessage(data.message);
- setMessages((previousMessages) => {
- const messageExists =
- previousMessages && previousMessages.some((msg) => msg._id === newMessage._id);
- if (!messageExists) {
- return GiftedChat.append(previousMessages ?? [], [newMessage]);
- }
- return previousMessages;
- });
- }
- break;
- case 'new_reaction':
- if (data.conversation_with === id && data.reaction) {
- updateMessageWithReaction(data.reaction);
- }
- break;
- case 'unreact':
- if (data.conversation_with === id && data.unreacted_message_id) {
- removeReactionFromMessage(data.unreacted_message_id);
- }
- break;
- case 'delete_message':
- if (data.conversation_with === id && data.deleted_message_id) {
- removeDeletedMessage(data.deleted_message_id);
- }
- break;
- case 'is_typing':
- if (data.conversation_with === id) {
- setIsTyping(true);
- }
- break;
- case 'stopped_typing':
- if (data.conversation_with === id) {
- setIsTyping(false);
- }
- break;
- case 'messages_read':
- if (data.conversation_with === id && data.read_messages_ids) {
- setMessages(
- (prevMessages) =>
- prevMessages?.map((msg) => {
- if (data.read_messages_ids.includes(msg._id)) {
- return { ...msg, received: true };
- }
- return msg;
- }) ?? []
- );
- }
- break;
- case 'messages_received':
- if (data.conversation_with === id && data.received_messages_ids) {
- setMessages(
- (prevMessages) =>
- prevMessages?.map((msg) => {
- if (data.received_messages_ids.includes(msg._id)) {
- return { ...msg, sent: true };
- }
- return msg;
- }) ?? []
- );
- }
- break;
- case 'edited_message':
- if (data.conversation_with === id && data.message) {
- setMessages(
- (prevMessages) =>
- prevMessages?.map((msg) => {
- if (msg._id === data.message.id) {
- return { ...msg, text: data.message.text, edited: true };
- }
- return msg;
- }) ?? []
- );
- }
- break;
- default:
- break;
- }
- };
- const updateMessageWithReaction = (reactionData: any) => {
- setMessages(
- (prevMessages) =>
- prevMessages?.map((msg) => {
- if (msg._id === reactionData.message_id) {
- const updatedReactions = [
- ...(Array.isArray(msg.reactions)
- ? msg.reactions?.filter((r: any) => r.uid !== reactionData.uid)
- : []),
- reactionData
- ];
- return { ...msg, reactions: updatedReactions };
- }
- return msg;
- }) ?? []
- );
- };
- const removeReactionFromMessage = (messageId: number) => {
- setMessages(
- (prevMessages) =>
- prevMessages?.map((msg) => {
- if (msg._id === messageId) {
- const updatedReactions = Array.isArray(msg.reactions)
- ? msg.reactions?.filter((r: any) => r.uid !== id)
- : [];
- return { ...msg, reactions: updatedReactions };
- }
- return msg;
- }) ?? []
- );
- };
- const removeDeletedMessage = (messageId: number) => {
- setMessages(
- (prevMessages) =>
- prevMessages?.map((msg) => {
- if (msg._id === messageId) {
- return {
- ...msg,
- deleted: true,
- text: 'This message was deleted',
- pending: false,
- sent: false,
- received: false
- };
- }
- return msg;
- }) ?? []
- );
- };
- useEffect(() => {
- const pingInterval = setInterval(() => {
- if (socket.current && socket.current.readyState === WebSocket.OPEN) {
- socket.current.send(JSON.stringify({ action: 'ping', conversation_with: id }));
- } else {
- socket.current = new WebSocket(WEBSOCKET_URL);
- socket.current.onopen = () => {
- socket.current?.send(JSON.stringify({ token }));
- };
- socket.current.onmessage = (event) => {
- const data = JSON.parse(event.data);
- handleWebSocketMessage(data);
- };
- return () => {
- if (socket.current) {
- socket.current.close();
- socket.current = null;
- }
- };
- }
- }, 50000);
- return () => clearInterval(pingInterval);
- }, []);
- const sendWebSocketMessage = (
- action: string,
- message: CustomMessage | null = null,
- reaction: string | null = null,
- readMessagesIds: number[] | null = null
- ) => {
- if (socket.current && socket.current.readyState === WebSocket.OPEN) {
- const data: any = {
- action,
- conversation_with: id
- };
- if (action === 'new_message' && message) {
- data.message = {
- id: message._id,
- text: message.text,
- sender: +currentUserId,
- sent_datetime: new Date().toISOString().replace('T', ' ').substring(0, 19),
- reply_to_id: message.replyMessage?.id ?? -1,
- reply_to: message.replyMessage ?? null,
- reactions: message.reactions ?? '{}',
- status: 2,
- attachement: message.attachment ? message.attachment : -1
- };
- }
- if (action === 'new_reaction' && message && reaction) {
- data.reaction = {
- message_id: message._id,
- reaction,
- uid: +currentUserId,
- datetime: new Date().toISOString()
- };
- }
- if (action === 'unreact' && message) {
- data.message_id = message._id;
- }
- if (action === 'delete_message' && message) {
- data.message_id = message._id;
- }
- if (action === 'messages_read' && readMessagesIds) {
- data.messages_ids = readMessagesIds;
- }
- if (action === 'edited_message' && message) {
- data.message = {
- id: message._id,
- text: message.text
- };
- }
- socket.current.send(JSON.stringify(data));
- }
- };
- const handleTyping = (isTyping: boolean) => {
- if (isTyping) {
- sendWebSocketMessage('is_typing');
- } else {
- sendWebSocketMessage('stopped_typing');
- }
- };
- const mapApiMessageToGiftedMessage = (message: Message): CustomMessage => {
- return {
- _id: message.id,
- text: message.text,
- createdAt: new Date(message.sent_datetime + 'Z'),
- user: {
- _id: message.sender,
- name: message.sender === id ? userName : 'Me'
- },
- replyMessage:
- message.reply_to_id !== -1
- ? {
- text: message.reply_to.text,
- id: message.reply_to.id,
- name: message.reply_to.sender === id ? userName : 'Me'
- }
- : null,
- reactions: JSON.parse(message.reactions || '{}'),
- attachment: message.attachement !== -1 ? message.attachement : null,
- pending: message.status === 1,
- sent: message.status === 2,
- received: message.status === 3,
- deleted: message.status === 4,
- edited: isMessageEdited(message.edits),
- isSending: false,
- video:
- message.attachement !== -1 && message.attachement?.filetype?.startsWith('video')
- ? API_HOST + message.attachement?.attachment_link
- : null,
- image:
- message.attachement !== -1 && message.attachement?.filetype?.startsWith('image')
- ? API_HOST + message.attachement?.attachment_small_url
- : null
- };
- };
- useFocusEffect(
- useCallback(() => {
- refetch();
- }, [])
- );
- useFocusEffect(
- useCallback(() => {
- if (chatData?.messages) {
- const mappedMessages = chatData.messages.map(mapApiMessageToGiftedMessage);
- if (unreadMessageIndex === null && !isFetching) {
- const firstUnreadIndex = mappedMessages.findLastIndex(
- (msg) => !msg.received && !msg?.deleted && msg.user._id === id
- );
- if (firstUnreadIndex !== -1) {
- setUnreadMessageIndex(firstUnreadIndex);
- const unreadMarker: any = {
- _id: 'unreadMarker',
- text: 'Unread messages',
- system: true
- };
- mappedMessages.splice(firstUnreadIndex + 1, 0, unreadMarker);
- setTimeout(() => {
- if (flatList.current) {
- flatList.current.scrollToIndex({
- index: firstUnreadIndex,
- animated: true,
- viewPosition: 0.5
- });
- }
- }, 500);
- } else {
- setUnreadMessageIndex(0);
- }
- }
- setMessages((previousMessages) => {
- const newMessages = mappedMessages.filter(
- (newMsg) => !previousMessages?.some((oldMsg) => oldMsg._id === newMsg._id)
- );
- return prevThenMessageId !== -1 && previousMessages
- ? GiftedChat.prepend(previousMessages, newMessages)
- : mappedMessages;
- });
- if (mappedMessages.length < 50) {
- setHasMoreMessages(false);
- }
- if (
- mappedMessages.length === 0 &&
- !modalInfo.visible &&
- !canSendMessage?.need_authentication_or_friend
- ) {
- setTimeout(() => {
- textInputRef.current?.focus();
- }, 500);
- }
- setIsLoadingEarlier(false);
- }
- }, [chatData])
- );
- useEffect(() => {
- if (
- messages?.length === 0 &&
- !modalInfo.visible &&
- !canSendMessage?.need_authentication_or_friend
- ) {
- setTimeout(() => {
- textInputRef.current?.focus();
- }, 500);
- }
- }, [modalInfo]);
- const loadEarlierMessages = async () => {
- if (!hasMoreMessages || isLoadingEarlier || !messages) return;
- setIsLoadingEarlier(true);
- const previousMessageId = messages[messages.length - 1]._id;
- setPrevThenMessageId(previousMessageId);
- };
- const sentToServer = useRef<Set<number>>(new Set());
- const handleViewableItemsChanged = ({ viewableItems }: { viewableItems: any[] }) => {
- const newViewableUnreadMessages = viewableItems
- .filter(
- (item) =>
- !item.item.received &&
- !item.item.deleted &&
- !item.item.system &&
- item.item.user._id === id &&
- !sentToServer.current.has(item.item._id)
- )
- .map((item) => item.item._id);
- if (newViewableUnreadMessages.length > 0) {
- markMessagesAsRead(
- {
- token,
- from_user: id,
- messages_id: newViewableUnreadMessages
- },
- {
- onSuccess: () => {
- newViewableUnreadMessages.forEach((id) => sentToServer.current.add(id));
- sendWebSocketMessage('messages_read', null, null, newViewableUnreadMessages);
- }
- }
- );
- }
- };
- const renderSystemMessage = (props: any) => {
- if (props.currentMessage._id === 'unreadMarker') {
- return (
- <View style={styles.unreadMessagesContainer}>
- <Text style={styles.unreadMessagesText}>{props.currentMessage.text}</Text>
- </View>
- );
- }
- return null;
- };
- const clearReplyMessage = () => setReplyMessage(null);
- const clearEditMessage = () => {
- setEditingMessage(null);
- setText('');
- };
- const onInputTextChanged = (value: string) => {
- handleTyping(value.length > 0);
- setText(value);
- };
- const handleLongPress = (message: CustomMessage, props: BubbleProps<CustomMessage>) => {
- const messageRef = messageRefs.current[message._id];
- setSelectedMessage(props);
- trigger('impactMedium', options);
- const isMine = message.user._id === +currentUserId;
- if (messageRef) {
- messageRef.measureInWindow((x: number, y: number, width: number, height: number) => {
- const screenHeight = Dimensions.get('window').height;
- const spaceAbove = y - insets.top;
- const spaceBelow = screenHeight - (y + height) - insets.bottom * 2;
- let finalY = y;
- scrollY.value = 0;
- if (isNaN(y) || isNaN(height)) {
- console.error("Invalid measurement values for 'y' or 'height'", { y, height });
- return;
- }
- if (spaceBelow < 180) {
- const extraShift = 180 - spaceBelow;
- finalY -= extraShift;
- }
- if (spaceAbove < 50) {
- const extraShift = 50 - spaceAbove;
- finalY += extraShift;
- }
- if (spaceBelow < 180 || spaceAbove < 50) {
- const targetY = screenHeight / 2 - height / 2;
- scrollY.value = withTiming(finalY - finalY);
- }
- if (height > Dimensions.get('window').height - 200) {
- finalY = 100;
- }
- finalY = isNaN(finalY) ? 0 : finalY;
- setMessagePosition({ x, y: finalY, width, height, isMine });
- setIsModalVisible(true);
- });
- }
- };
- const openEmojiSelector = () => {
- SheetManager.show('emoji-selector');
- trigger('impactLight', options);
- };
- const closeEmojiSelector = () => {
- SheetManager.hide('emoji-selector');
- };
- const handleReactionPress = (emoji: string, messageId: number) => {
- addReaction(messageId, emoji);
- };
- const handleDeleteMessage = (messageId: number) => {
- deleteMessage(
- {
- token,
- message_id: messageId,
- conversation_with_user: id
- },
- {
- onSuccess: () => {
- setMessages(
- (prevMessages) =>
- prevMessages?.map((msg) => {
- if (msg._id === messageId) {
- return {
- ...msg,
- deleted: true,
- text: 'This message was deleted',
- pending: false,
- sent: false,
- received: false,
- attachment: null,
- image: undefined,
- video: undefined
- };
- }
- return msg;
- }) ?? []
- );
- const messageToDelete = messages?.find((msg) => msg._id === messageId);
- if (messageToDelete) {
- sendWebSocketMessage('delete_message', messageToDelete, null, null);
- }
- }
- }
- );
- };
- const handleOptionPress = (option: string) => {
- if (!selectedMessage) return;
- switch (option) {
- case 'reply':
- setReplyMessage(selectedMessage.currentMessage);
- setIsModalVisible(false);
- break;
- case 'copy':
- Clipboard.setString(selectedMessage?.currentMessage?.text ?? '');
- setIsModalVisible(false);
- Alert.alert('Copied');
- break;
- case 'delete':
- handleDeleteMessage(selectedMessage.currentMessage?._id);
- setIsModalVisible(false);
- break;
- case 'download':
- downloadFileToDevice(selectedMessage.currentMessage);
- setIsModalVisible(false);
- break;
- case 'edit':
- handleEditMessage(selectedMessage.currentMessage);
- setIsModalVisible(false);
- break;
- default:
- break;
- }
- closeEmojiSelector();
- };
- const openReactionList = (
- reactions: { uid: number; name: string; reaction: string }[],
- messageId: number
- ) => {
- SheetManager.show('reactions-list-modal', {
- payload: {
- users: reactions,
- currentUserId: +currentUserId,
- token,
- messageId,
- conversation_with_user: id,
- setMessages,
- sendWebSocketMessage
- } as any
- });
- };
- const renderTimeContainer = (time: TimeProps<CustomMessage>) => {
- const createdAt = new Date(time.currentMessage.createdAt);
- const formattedTime = createdAt.toLocaleTimeString([], {
- hour: '2-digit',
- minute: '2-digit',
- hour12: true
- });
- const hasReactions =
- time.currentMessage.reactions &&
- Array.isArray(time.currentMessage.reactions) &&
- time.currentMessage.reactions.length > 0;
- return (
- <View
- style={[
- styles.bottomContainer,
- {
- justifyContent: hasReactions ? 'space-between' : 'flex-end'
- }
- ]}
- >
- {hasReactions && (
- <TouchableOpacity
- style={[
- styles.bottomCustomContainer,
- {
- backgroundColor:
- time.position === 'left' ? 'rgba(0, 0, 0, 0.2)' : 'rgba(255, 255, 255, 0.2)'
- }
- ]}
- onPress={() =>
- Array.isArray(time.currentMessage.reactions) &&
- openReactionList(
- time.currentMessage.reactions.map((reaction) => ({
- ...reaction,
- name: reaction.uid === id ? userName : 'Me'
- })),
- time.currentMessage._id
- )
- }
- >
- {Object.entries(
- (Array.isArray(time.currentMessage.reactions)
- ? time.currentMessage.reactions
- : []
- ).reduce(
- (acc: Record<string, { count: number }>, { reaction }: { reaction: string }) => {
- if (!acc[reaction]) {
- acc[reaction] = { count: 0 };
- }
- acc[reaction].count += 1;
- return acc;
- },
- {}
- )
- ).map(([emoji, { count }]: any) => {
- return (
- <View key={emoji}>
- <Text style={{}}>
- {emoji}
- {(count as number) > 1 ? ` ${count}` : ''}
- </Text>
- </View>
- );
- })}
- </TouchableOpacity>
- )}
- <View style={styles.timeContainer}>
- {time.currentMessage.edited && <Text style={styles.timeText}>Edited</Text>}
- <Text style={[styles.timeText, time.currentMessage.edited ? { paddingLeft: 0 } : {}]}>
- {formattedTime}
- </Text>
- {renderTicks(time.currentMessage)}
- </View>
- </View>
- );
- };
- const renderSelectedMessage = () =>
- selectedMessage && (
- <View
- style={{
- maxHeight: '80%',
- width: messagePosition?.width,
- position: 'absolute',
- top: messagePosition?.y,
- left: messagePosition?.x
- }}
- >
- <ScrollView>
- <Bubble
- {...selectedMessage}
- wrapperStyle={{
- right: { backgroundColor: Colors.DARK_BLUE },
- left: { backgroundColor: Colors.FILL_LIGHT }
- }}
- textStyle={{
- right: { color: Colors.WHITE },
- left: { color: Colors.DARK_BLUE }
- }}
- renderTicks={() => null}
- renderTime={renderTimeContainer}
- renderCustomView={() =>
- selectedMessage.currentMessage.attachment?.filetype === 'nomadmania/location'
- ? renderMessageLocation(selectedMessage)
- : selectedMessage.currentMessage.attachment &&
- !selectedMessage.currentMessage.image &&
- !selectedMessage.currentMessage.video
- ? renderMessageFile(selectedMessage)
- : renderReplyMessageView(selectedMessage)
- }
- />
- </ScrollView>
- </View>
- );
- const handleBackgroundPress = () => {
- setIsModalVisible(false);
- setSelectedMessage(null);
- closeEmojiSelector();
- };
- useFocusEffect(
- useCallback(() => {
- navigation?.getParent()?.setOptions({
- tabBarStyle: {
- display: 'none'
- }
- });
- }, [navigation])
- );
- const handleEditMessage = (message: CustomMessage) => {
- setReplyMessage(null);
- setEditingMessage(message);
- setText(message.text);
- textInputRef.current?.focus();
- };
- const onSend = useCallback(
- (newMessages: CustomMessage[] = []) => {
- if (editingMessage) {
- if (editingMessage.text !== newMessages[0].text) {
- setMessages((prevMessages) =>
- (prevMessages ?? []).map((msg) =>
- msg._id === editingMessage._id ? { ...msg, text: newMessages[0].text } : msg
- )
- );
- editMessage(
- {
- token,
- to_uid: id,
- message_id: editingMessage._id,
- text: newMessages[0].text
- },
- {
- onSuccess: (res) => {
- const editedMessage = {
- _id: editingMessage._id,
- text: newMessages[0].text
- };
- setMessages((previousMessages) =>
- (previousMessages ?? []).map((msg) =>
- msg._id === editingMessage._id
- ? { ...msg, isSending: false, edited: true }
- : msg
- )
- );
- sendWebSocketMessage('edited_message', editedMessage as unknown as CustomMessage);
- }
- }
- );
- }
- clearEditMessage();
- clearReplyMessage();
- return;
- }
- if (replyMessage) {
- newMessages[0].replyMessage = {
- text: replyMessage.text,
- id: replyMessage._id,
- name: replyMessage.user._id === id ? userName : 'Me'
- };
- }
- const message = { ...newMessages[0], pending: true, isSending: true };
- setMessages((previousMessages) => GiftedChat.append(previousMessages ?? [], [message]));
- sendMessage(
- {
- token,
- to_uid: id,
- text: message.text,
- reply_to_id: replyMessage ? (replyMessage._id as number) : -1
- },
- {
- onSuccess: (res) => {
- if (res.need_authentication_or_friend === 1) {
- setModalInfo({
- visible: true,
- type: 'success',
- message: (
- <Text>
- Only legit NomadManias and friends can send messages.{'\n'}Befriend this
- traveller first or{' '}
- <Text
- style={{
- color: Colors.ORANGE,
- textDecorationLine: 'underline',
- textDecorationColor: Colors.ORANGE
- }}
- onPress={() =>
- Linking.openURL('https://nomadmania.com/badges/').catch((err) =>
- console.error('Failed to open auth URL:', err)
- )
- }
- >
- become Legit
- </Text>
- !
- </Text>
- ),
- action: () => {},
- buttonTitle: 'OK',
- title: 'Oops!'
- });
- setMessages((messages ?? []).filter((msg) => msg._id === message._id));
- return;
- }
- const newMessage = {
- _id: res.message_id,
- text: message.text,
- replyMessage: { ...message.replyMessage, sender: replyMessage?.user?._id }
- };
- setMessages((previousMessages) =>
- (previousMessages ?? []).map((msg) =>
- msg._id === message._id ? { ...msg, _id: res.message_id, isSending: false } : msg
- )
- );
- sendWebSocketMessage('new_message', newMessage as unknown as CustomMessage);
- }
- }
- );
- clearReplyMessage();
- },
- [replyMessage, editingMessage]
- );
- const addReaction = (messageId: number, reaction: string) => {
- if (!messages) return;
- const updatedMessages = messages.map((msg: any) => {
- if (msg._id === messageId) {
- const updatedReactions: Reaction[] = [
- ...(Array.isArray(msg.reactions)
- ? msg.reactions?.filter((r: Reaction) => r.uid !== +currentUserId)
- : []),
- { datetime: new Date().toISOString(), reaction: reaction, uid: +currentUserId }
- ];
- return {
- ...msg,
- reactions: updatedReactions
- };
- }
- return msg;
- });
- setMessages(updatedMessages);
- reactToMessage(
- { token, message_id: messageId, reaction: reaction, conversation_with_user: id },
- {
- onSuccess: () => {
- const message = messages.find((msg) => msg._id === messageId);
- if (message) {
- sendWebSocketMessage('new_reaction', message, reaction);
- }
- }
- }
- );
- setIsModalVisible(false);
- };
- const updateRowRef = useCallback(
- (ref: any) => {
- if (
- ref &&
- replyMessage &&
- ref.props.children.props.currentMessage?._id === replyMessage._id
- ) {
- swipeableRowRef.current = ref;
- }
- },
- [replyMessage]
- );
- const renderReplyMessageView = (props: BubbleProps<CustomMessage>) => {
- if (!props.currentMessage) {
- return null;
- }
- const { currentMessage } = props;
- if (!currentMessage || !currentMessage?.replyMessage) {
- return null;
- }
- return (
- <TouchableOpacity
- style={[
- styles.replyMessageContainer,
- {
- backgroundColor:
- currentMessage.user._id === id ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.2)',
- borderColor: currentMessage.user._id === id ? Colors.DARK_BLUE : Colors.WHITE
- }
- ]}
- onPress={() => {
- if (currentMessage?.replyMessage?.id) {
- scrollToMessage(currentMessage.replyMessage.id);
- }
- }}
- >
- <View style={styles.replyContent}>
- <Text
- style={[
- styles.replyAuthorName,
- { color: currentMessage.user._id === id ? Colors.DARK_BLUE : Colors.WHITE }
- ]}
- >
- {currentMessage.replyMessage.name}
- </Text>
- <Text
- numberOfLines={1}
- style={[
- styles.replyMessageText,
- { color: currentMessage.user._id === id ? Colors.DARK_BLUE : Colors.WHITE }
- ]}
- >
- {currentMessage.replyMessage.text}
- </Text>
- </View>
- </TouchableOpacity>
- );
- };
- const scrollToMessage = (messageId: number) => {
- if (!messages) return;
- const messageIndex = messages.findIndex((message) => message._id === messageId);
- if (messageIndex !== -1 && flatList.current) {
- flatList.current.scrollToIndex({
- index: messageIndex,
- animated: true,
- viewPosition: 0.5
- });
- setHighlightedMessageId(messageId);
- }
- };
- useEffect(() => {
- if (highlightedMessageId && isRerendering) {
- setTimeout(() => {
- setHighlightedMessageId(null);
- setIsRerendering(false);
- }, 1500);
- }
- }, [highlightedMessageId, isRerendering]);
- useEffect(() => {
- if (replyMessage && swipeableRowRef.current) {
- swipeableRowRef.current.close();
- swipeableRowRef.current = null;
- }
- }, [replyMessage]);
- const handleOpenImage = async (uri: string, fileName: string) => {
- const dirExist = await FileSystem.getInfoAsync(CACHED_ATTACHMENTS_DIR);
- if (!dirExist.exists) {
- await FileSystem.makeDirectoryAsync(CACHED_ATTACHMENTS_DIR, { intermediates: true });
- }
- const fileUri = `${CACHED_ATTACHMENTS_DIR}${fileName}`;
- const fileExists = await FileSystem.getInfoAsync(fileUri);
- if (fileExists.exists && fileExists.size > 1024) {
- setSelectedMedia(fileUri);
- return;
- }
- setSelectedMedia(uri);
- const { uri: localUri } = await FileSystem.downloadAsync(uri, fileUri, {
- headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS }
- });
- };
- const renderMessageImage = (props: any) => {
- const { currentMessage } = props;
- const leftMessage = currentMessage?.user?._id !== +currentUserId;
- return (
- <TouchableOpacity
- onPress={() => {
- if (!currentMessage.attachment.attachment_full_url?.startsWith('/')) {
- setSelectedMedia(currentMessage.attachment.attachment_full_url);
- return;
- }
- handleOpenImage(
- API_HOST + currentMessage.attachment.attachment_full_url,
- currentMessage.attachment?.filename
- );
- }}
- onLongPress={() => handleLongPress(currentMessage, props)}
- style={styles.imageContainer}
- disabled={currentMessage.isSending}
- >
- <Image
- key={currentMessage.image}
- source={{
- uri: currentMessage.image,
- headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS }
- }}
- style={styles.chatImage}
- resizeMode="cover"
- />
- {currentMessage.isSending && (
- <View
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- justifyContent: 'center',
- alignItems: 'center'
- }}
- >
- <ActivityIndicator
- size="large"
- color={leftMessage ? Colors.DARK_BLUE : Colors.FILL_LIGHT}
- />
- </View>
- )}
- </TouchableOpacity>
- );
- };
- const renderTicks = (message: CustomMessage) => {
- if (message.user._id === id) return null;
- if (message.isSending) {
- return (
- <View>
- <ActivityIndicator
- size={16}
- color={Colors.LIGHT_GRAY}
- style={{ transform: 'scale(0.8)' }}
- />
- </View>
- );
- }
- return message.received ? (
- <View>
- <MaterialCommunityIcons name="check-all" size={16} color={Colors.WHITE} />
- </View>
- ) : message.sent ? (
- <View>
- <MaterialCommunityIcons name="check" size={16} color={Colors.WHITE} />
- </View>
- ) : message.pending ? (
- <View>
- <MaterialCommunityIcons name="check" size={16} color={Colors.LIGHT_GRAY} />
- </View>
- ) : null;
- };
- const renderBubble = (props: BubbleProps<CustomMessage>) => {
- const { currentMessage } = props;
- if (currentMessage.deleted) {
- const text = currentMessage.text.length
- ? props.currentMessage.text
- : 'This message was deleted';
- return (
- <View>
- <Bubble
- {...props}
- renderTime={() => null}
- currentMessage={{
- ...props.currentMessage,
- text: text
- }}
- renderMessageText={() => (
- <View style={{ paddingHorizontal: 12, paddingVertical: 6 }}>
- <Text style={{ color: Colors.LIGHT_GRAY, fontStyle: 'italic', fontSize: 12 }}>
- {text}
- </Text>
- </View>
- )}
- wrapperStyle={{
- right: {
- backgroundColor: Colors.DARK_BLUE
- },
- left: {
- backgroundColor: Colors.FILL_LIGHT
- }
- }}
- textStyle={{
- left: {
- color: Colors.DARK_BLUE
- },
- right: {
- color: Colors.WHITE
- }
- }}
- />
- </View>
- );
- }
- const isHighlighted = currentMessage._id === highlightedMessageId;
- const backgroundColor = isHighlighted
- ? Colors.ORANGE
- : currentMessage.user._id === +currentUserId
- ? Colors.DARK_BLUE
- : Colors.FILL_LIGHT;
- return (
- <View
- key={`${currentMessage._id}-${isHighlighted ? 'highlighted' : 'normal'}`}
- ref={(ref) => {
- if (ref && currentMessage) {
- messageRefs.current[currentMessage._id] = ref;
- }
- }}
- collapsable={false}
- >
- <Bubble
- {...props}
- wrapperStyle={{
- right: {
- backgroundColor: backgroundColor
- },
- left: {
- backgroundColor: backgroundColor
- }
- }}
- textStyle={{
- left: {
- color: Colors.DARK_BLUE
- },
- right: {
- color: Colors.FILL_LIGHT
- }
- }}
- onLongPress={() => handleLongPress(currentMessage, props)}
- renderTicks={() => null}
- renderTime={renderTimeContainer}
- renderCustomView={() =>
- currentMessage.attachment?.filetype === 'nomadmania/location'
- ? renderMessageLocation(props)
- : currentMessage.attachment && !currentMessage.image && !currentMessage.video
- ? renderMessageFile(props)
- : renderReplyMessageView(props)
- }
- />
- </View>
- );
- };
- const openAttachmentsModal = () => {
- SheetManager.show('chat-attachments', {
- payload: {
- name: userName,
- uid: id,
- setModalInfo,
- closeOptions: () => {},
- onSendMedia,
- onSendLocation,
- onShareLiveLocation,
- onSendFile
- } as any
- });
- };
- const renderInputToolbar = (props: any) => (
- <InputToolbar
- {...props}
- renderActions={() =>
- userType === 'normal' && !editingMessage ? (
- <Actions
- icon={() => <MaterialCommunityIcons name="plus" size={28} color={Colors.DARK_BLUE} />}
- onPressActionButton={openAttachmentsModal}
- />
- ) : null
- }
- containerStyle={{
- backgroundColor: Colors.FILL_LIGHT
- }}
- />
- );
- const renderScrollToBottom = () => {
- return (
- <TouchableOpacity
- style={styles.scrollToBottom}
- onPress={() => {
- if (flatList.current) {
- flatList.current.scrollToIndex({ index: 0, animated: true });
- }
- }}
- >
- <MaterialCommunityIcons name="chevron-down" size={24} color={Colors.WHITE} />
- </TouchableOpacity>
- );
- };
- const shouldUpdateMessage = (
- props: MessageProps<IMessage>,
- nextProps: MessageProps<IMessage>
- ) => {
- setIsRerendering(true);
- const currentId = nextProps.currentMessage._id;
- return currentId === highlightedMessageId;
- };
- return (
- <SafeAreaView
- edges={['top']}
- style={{
- height: '100%'
- }}
- >
- <View style={{ paddingHorizontal: '5%' }}>
- <Header
- label={userName}
- textColor={userType !== 'normal' ? Colors.RED : Colors.DARK_BLUE}
- rightElement={
- <TouchableOpacity
- onPress={() =>
- navigation.navigate(
- ...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId: id }] as never)
- )
- }
- disabled={userType !== 'normal'}
- >
- {avatar && userType === 'normal' ? (
- <Image source={{ uri: API_HOST + avatar }} style={styles.avatar} />
- ) : userType === 'normal' ? (
- <AvatarWithInitials
- text={
- name
- .split(/ (.+)/)
- .map((n) => n[0])
- .join('') ?? ''
- }
- flag={API_HOST + 'flag.png'}
- size={30}
- fontSize={12}
- />
- ) : (
- <BanIcon fill={Colors.RED} width={30} height={30} />
- )}
- </TouchableOpacity>
- }
- />
- </View>
- <GestureHandlerRootView style={styles.container}>
- {messages ? (
- <GiftedChat
- messages={messages as CustomMessage[]}
- text={text}
- listViewProps={{
- ref: flatList,
- showsVerticalScrollIndicator: false,
- initialNumToRender: 30,
- onViewableItemsChanged: handleViewableItemsChanged,
- viewabilityConfig: { itemVisiblePercentThreshold: 50 },
- onScrollToIndexFailed: (info: any) => {
- const wait = new Promise((resolve) => setTimeout(resolve, 300));
- wait.then(() => {
- flatList.current?.scrollToIndex({
- index: info.index,
- animated: true,
- viewPosition: 0.5
- });
- });
- }
- }}
- renderSystemMessage={renderSystemMessage}
- onSend={(newMessages: CustomMessage[]) => onSend(newMessages)}
- user={{ _id: +currentUserId, name: 'Me' }}
- renderBubble={renderBubble}
- renderMessageImage={renderMessageImage}
- renderInputToolbar={renderInputToolbar}
- renderCustomView={renderReplyMessageView}
- isCustomViewBottom={false}
- messageContainerRef={messageContainerRef}
- minComposerHeight={34}
- onInputTextChanged={onInputTextChanged}
- textInputRef={textInputRef}
- isTyping={isTyping}
- renderSend={(props) =>
- editingMessage ? (
- <View style={[styles.sendBtn, { paddingHorizontal: 8 }]}>
- {props.text?.trim() && (
- <Send
- {...props}
- containerStyle={{
- justifyContent: 'center'
- }}
- >
- <View style={styles.editBtn}>
- <MaterialCommunityIcons name="check" size={22} color={Colors.WHITE} />
- </View>
- </Send>
- )}
- {!props.text?.trim() && (
- <View style={[styles.editBtn, { backgroundColor: Colors.LIGHT_GRAY }]}>
- <MaterialCommunityIcons name="check" size={22} color={Colors.WHITE} />
- </View>
- )}
- </View>
- ) : (
- <View style={styles.sendBtn}>
- {props.text?.trim() && (
- <Send
- {...props}
- containerStyle={{
- justifyContent: 'center'
- }}
- >
- <SendIcon fill={Colors.DARK_BLUE} />
- </Send>
- )}
- {!props.text?.trim() && <SendIcon fill={Colors.LIGHT_GRAY} />}
- </View>
- )
- }
- renderMessageVideo={(props) => (
- <RenderMessageVideo
- props={props}
- token={token}
- currentUserId={+currentUserId}
- onLongPress={handleLongPress}
- />
- )}
- textInputProps={{
- ...styles.composer,
- selectionColor: Colors.LIGHT_GRAY
- }}
- placeholder=""
- renderMessage={(props) => (
- <ChatMessageBox
- {...(props as MessageProps<CustomMessage>)}
- updateRowRef={updateRowRef}
- setReplyOnSwipeOpen={setReplyMessage}
- />
- )}
- renderChatFooter={() => (
- <ReplyMessageBar
- clearReply={clearReplyMessage}
- clearEditMessage={clearEditMessage}
- message={replyMessage}
- editingMessage={editingMessage}
- />
- )}
- renderAvatar={null}
- maxComposerHeight={100}
- renderComposer={(props) => <Composer {...props} />}
- keyboardShouldPersistTaps="handled"
- renderChatEmpty={() => (
- <View style={styles.emptyChat}>
- <Text
- style={styles.emptyChatText}
- >{`No messages yet.\nFeel free to start the conversation.`}</Text>
- </View>
- )}
- shouldUpdateMessage={shouldUpdateMessage}
- scrollToBottom={true}
- scrollToBottomComponent={renderScrollToBottom}
- scrollToBottomStyle={{ backgroundColor: 'transparent' }}
- parsePatterns={(linkStyle) => [
- {
- type: 'url',
- style: { color: Colors.ORANGE, textDecorationLine: 'underline' },
- onPress: (url: string) => Linking.openURL(url),
- onLongPress: (url: string) => {
- Clipboard.setString(url ?? '');
- Alert.alert('Link copied');
- }
- }
- ]}
- infiniteScroll={true}
- loadEarlier={hasMoreMessages}
- isLoadingEarlier={isLoadingEarlier}
- onLoadEarlier={loadEarlierMessages}
- renderLoadEarlier={() => (
- <View style={{ paddingVertical: 20 }}>
- <ActivityIndicator size="small" color={Colors.DARK_BLUE} />
- </View>
- )}
- />
- ) : (
- <ActivityIndicator size="large" color={Colors.DARK_BLUE} />
- )}
- <ImageView
- images={[
- {
- uri: selectedMedia,
- cache: 'force-cache',
- headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS }
- }
- ]}
- imageIndex={0}
- visible={!!selectedMedia}
- onRequestClose={() => setSelectedMedia(null)}
- backgroundColor={Colors.DARK_BLUE}
- />
- <ReactModal
- isVisible={isModalVisible}
- onBackdropPress={handleBackgroundPress}
- style={styles.reactModalContainer}
- animationIn="fadeIn"
- animationOut="fadeOut"
- useNativeDriver
- backdropColor="transparent"
- >
- <BlurView
- intensity={80}
- style={styles.modalBackground}
- experimentalBlurMethod="dimezisBlurView"
- >
- <TouchableOpacity
- style={styles.modalBackground}
- activeOpacity={1}
- onPress={handleBackgroundPress}
- >
- <ReactionBar
- messagePosition={messagePosition}
- selectedMessage={selectedMessage}
- reactionEmojis={reactionEmojis}
- handleReactionPress={handleReactionPress}
- openEmojiSelector={openEmojiSelector}
- />
- {renderSelectedMessage()}
- <OptionsMenu
- selectedMessage={selectedMessage}
- handleOptionPress={handleOptionPress}
- messagePosition={messagePosition}
- />
- <EmojiSelectorModal
- visible={emojiSelectorVisible}
- selectedMessage={selectedMessage}
- addReaction={addReaction}
- closeEmojiSelector={closeEmojiSelector}
- />
- </TouchableOpacity>
- </BlurView>
- </ReactModal>
- <WarningModal
- isVisible={modalInfo.visible}
- onClose={closeModal}
- type={modalInfo.type}
- message={modalInfo.message}
- buttonTitle={modalInfo.buttonTitle}
- title={modalInfo.title}
- action={() => {
- modalInfo.action();
- closeModal();
- }}
- />
- <AttachmentsModal />
- <ReactionsListModal />
- </GestureHandlerRootView>
- <View
- style={{
- height: insets.bottom,
- backgroundColor: Colors.FILL_LIGHT
- }}
- />
- </SafeAreaView>
- );
- };
- export default ChatScreen;
|