index.tsx 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300
  1. import React, { useState, useCallback, useEffect, useRef } from 'react';
  2. import {
  3. View,
  4. TouchableOpacity,
  5. Image,
  6. Text,
  7. FlatList,
  8. Dimensions,
  9. Alert,
  10. ScrollView,
  11. Linking,
  12. ActivityIndicator,
  13. AppState,
  14. AppStateStatus,
  15. TextInput,
  16. Platform
  17. } from 'react-native';
  18. import {
  19. GiftedChat,
  20. Bubble,
  21. InputToolbar,
  22. IMessage,
  23. Send,
  24. BubbleProps,
  25. Composer,
  26. TimeProps,
  27. MessageProps,
  28. Actions,
  29. isSameUser,
  30. isSameDay,
  31. SystemMessage,
  32. MessageText
  33. } from 'react-native-gifted-chat';
  34. import { MaterialCommunityIcons } from '@expo/vector-icons';
  35. import { GestureHandlerRootView, Swipeable } from 'react-native-gesture-handler';
  36. import { Header, WarningModal } from 'src/components';
  37. import { Colors } from 'src/theme';
  38. import { useFocusEffect, useNavigation } from '@react-navigation/native';
  39. import { Audio } from 'expo-av';
  40. import ChatMessageBox from '../Components/ChatMessageBox';
  41. import ReplyMessageBar from '../Components/ReplyMessageBar';
  42. import { useSharedValue, withTiming } from 'react-native-reanimated';
  43. import { BlurView } from 'expo-blur';
  44. import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
  45. import Clipboard from '@react-native-clipboard/clipboard';
  46. import { trigger } from 'react-native-haptic-feedback';
  47. import ReactModal from 'react-native-modal';
  48. import { storage, StoreType } from 'src/storage';
  49. import {
  50. usePostGetGroupChatQuery,
  51. usePostSendGroupMessageMutation,
  52. usePostReactToGroupMessageMutation,
  53. usePostGroupMessagesReadMutation,
  54. usePostDeleteGroupMessageMutation,
  55. usePostGetPinnedGroupMessageQuery,
  56. usePostSetPinGroupMessageMutation,
  57. usePostGetGroupSettingsQuery,
  58. usePostGetGroupMembersQuery
  59. } from '@api/chat';
  60. import { CustomMessage, GroupMessage, Reaction } from '../types';
  61. import { API_HOST, APP_VERSION, WEBSOCKET_URL } from 'src/constants';
  62. import ReactionBar from '../Components/ReactionBar';
  63. import OptionsMenu from '../Components/OptionsMenu';
  64. import EmojiSelectorModal from '../Components/EmojiSelectorModal';
  65. import TypingIndicator from '../Components/TypingIndicator';
  66. import { styles } from '../ChatScreen/styles';
  67. import SendIcon from 'assets/icons/messages/send.svg';
  68. import { SheetManager } from 'react-native-actions-sheet';
  69. import { NAVIGATION_PAGES } from 'src/types';
  70. import { usePushNotification } from 'src/contexts/PushNotificationContext';
  71. import ReactionsListModal from '../Components/ReactionsListModal';
  72. import { dismissChatNotifications } from '../utils';
  73. import { useMessagesStore } from 'src/stores/unreadMessagesStore';
  74. import FileViewer from 'react-native-file-viewer';
  75. import * as FileSystem from 'expo-file-system';
  76. import ImageView from 'better-react-native-image-viewing';
  77. import * as MediaLibrary from 'expo-media-library';
  78. import BanIcon from 'assets/icons/messages/ban.svg';
  79. import AttachmentsModal from '../Components/AttachmentsModal';
  80. import RenderMessageVideo from '../Components/renderMessageVideo';
  81. import MessageLocation from '../Components/MessageLocation';
  82. import GroupIcon from 'assets/icons/messages/group-chat.svg';
  83. import { CACHED_ATTACHMENTS_DIR } from 'src/constants/constants';
  84. import GroupStatusModal from '../Components/GroupStatusModal';
  85. import PinIcon from 'assets/icons/messages/pin.svg';
  86. import MentionsList from '../Components/MentionsList';
  87. const options = {
  88. enableVibrateFallback: true,
  89. ignoreAndroidSystemSettings: false
  90. };
  91. const reactionEmojis = ['👍', '❤️', '😂', '😮', '😭'];
  92. const GroupChatScreen = ({ route }: { route: any }) => {
  93. const token = storage.get('token', StoreType.STRING) as string;
  94. const {
  95. group_token,
  96. name,
  97. avatar,
  98. userType = 'normal'
  99. }: {
  100. group_token: string;
  101. name: string;
  102. avatar: string | null;
  103. userType: 'normal' | 'not_exist' | 'blocked';
  104. } = route.params;
  105. const groupName =
  106. userType === 'blocked'
  107. ? 'Account is blocked'
  108. : userType === 'not_exist'
  109. ? 'Account does not exist'
  110. : name;
  111. const currentUserId = storage.get('uid', StoreType.STRING) as number;
  112. const insets = useSafeAreaInsets();
  113. const [groupAvatar, setGroupAvatar] = useState<string | null>(null);
  114. const [messages, setMessages] = useState<CustomMessage[] | null>();
  115. const navigation = useNavigation();
  116. const [prevThenMessageId, setPrevThenMessageId] = useState<number>(-1);
  117. const {
  118. data: chatData,
  119. refetch: refetch,
  120. isFetching: isFetching
  121. } = usePostGetGroupChatQuery(token, group_token, 50, prevThenMessageId, true);
  122. const [canSeeMembers, setCanSeeMembers] = useState(false);
  123. const { data: pinData, refetch: refetchPinned } = usePostGetPinnedGroupMessageQuery(
  124. token,
  125. group_token,
  126. true
  127. );
  128. const { data } = usePostGetGroupSettingsQuery(token, group_token, true);
  129. const { data: members, refetch: refetchMembers } = usePostGetGroupMembersQuery(
  130. token,
  131. group_token,
  132. canSeeMembers
  133. );
  134. const { mutateAsync: sendMessage } = usePostSendGroupMessageMutation();
  135. const [isSearchingMessage, setIsSearchingMessage] = useState<number | null>(null);
  136. const swipeableRowRef = useRef<Swipeable | null>(null);
  137. const messageContainerRef = useRef<FlatList<IMessage> | null>(null);
  138. const [selectedMedia, setSelectedMedia] = useState<any>(null);
  139. const [pinned, setPinned] = useState<any>(null);
  140. const [replyMessage, setReplyMessage] = useState<CustomMessage | null>(null);
  141. const [modalInfo, setModalInfo] = useState({
  142. visible: false,
  143. type: 'confirm',
  144. message: '',
  145. action: () => {},
  146. buttonTitle: '',
  147. title: ''
  148. });
  149. const [selectedMessage, setSelectedMessage] = useState<BubbleProps<CustomMessage> | null>(null);
  150. const [emojiSelectorVisible, setEmojiSelectorVisible] = useState(false);
  151. const [messagePosition, setMessagePosition] = useState<{
  152. x: number;
  153. y: number;
  154. width: number;
  155. height: number;
  156. isMine: boolean;
  157. } | null>(null);
  158. const [isModalVisible, setIsModalVisible] = useState(false);
  159. const [unreadMessageIndex, setUnreadMessageIndex] = useState<number | null>(null);
  160. const { mutateAsync: markMessagesAsRead } = usePostGroupMessagesReadMutation();
  161. const { mutateAsync: deleteMessage } = usePostDeleteGroupMessageMutation();
  162. const { mutateAsync: reactToMessage } = usePostReactToGroupMessageMutation();
  163. const { mutateAsync: pinMessage } = usePostSetPinGroupMessageMutation();
  164. const [highlightedMessageId, setHighlightedMessageId] = useState<number | null>(null);
  165. const [isRerendering, setIsRerendering] = useState<boolean>(false);
  166. const [isTyping, setIsTyping] = useState<string | null>(null);
  167. const messageRefs = useRef<{ [key: string]: any }>({});
  168. const flatList = useRef<FlatList | null>(null);
  169. const scrollY = useSharedValue(0);
  170. const { isSubscribed } = usePushNotification();
  171. const [isLoadingEarlier, setIsLoadingEarlier] = useState(false);
  172. const [hasMoreMessages, setHasMoreMessages] = useState(true);
  173. const updateUnreadMessagesCount = useMessagesStore((state) => state.updateUnreadMessagesCount);
  174. const [insetsColor, setInsetsColor] = useState(Colors.FILL_LIGHT);
  175. const [text, setText] = useState('');
  176. const [mentionList, setMentionList] = useState<any>([]);
  177. const [showMentions, setShowMentions] = useState(false);
  178. const [inputHeight, setInputHeight] = useState(45);
  179. const appState = useRef(AppState.currentState);
  180. const textInputRef = useRef<TextInput>(null);
  181. const socket = useRef<WebSocket | null>(null);
  182. const closeModal = () => {
  183. setModalInfo({ ...modalInfo, visible: false });
  184. };
  185. useEffect(() => {
  186. Audio.setAudioModeAsync({
  187. allowsRecordingIOS: false,
  188. staysActiveInBackground: false,
  189. playsInSilentModeIOS: true,
  190. shouldDuckAndroid: true,
  191. playThroughEarpieceAndroid: false
  192. });
  193. }, []);
  194. useEffect(() => {
  195. if (pinData && pinData?.message) {
  196. setPinned(pinData.message);
  197. }
  198. }, [pinData]);
  199. const onSendMedia = useCallback(
  200. async (files: { uri: string; type: 'image' | 'video' }[]) => {
  201. for (const file of files) {
  202. const tempMessage: CustomMessage = {
  203. _id: Date.now() + Math.random(),
  204. text: '',
  205. createdAt: new Date(),
  206. user: { _id: +currentUserId, name: 'Me', avatar: null as never },
  207. reactions: {},
  208. deleted: false,
  209. attachment: {
  210. id: -1,
  211. filename: file.type,
  212. filetype: file.type,
  213. attachment_link: file.uri,
  214. attachment_full_url: file.uri
  215. },
  216. pending: true,
  217. isSending: true,
  218. image: file.type === 'image' ? file.uri : undefined,
  219. video: file.type === 'video' ? file.uri : undefined
  220. };
  221. if (replyMessage) {
  222. tempMessage.replyMessage = {
  223. text: replyMessage.text,
  224. id: replyMessage._id,
  225. name:
  226. replyMessage.user._id !== +currentUserId ? (replyMessage.user.name as string) : 'Me'
  227. };
  228. }
  229. setMessages((previousMessages) => GiftedChat.append(previousMessages ?? [], [tempMessage]));
  230. const messageData = {
  231. token,
  232. to_group_token: group_token,
  233. text: '',
  234. reply_to_id: replyMessage ? (replyMessage._id as number) : -1,
  235. attachment: {
  236. uri: file.uri,
  237. type: file.type,
  238. name: file.uri.split('/').pop()
  239. }
  240. };
  241. const res = await sendMessage(messageData, {
  242. onSuccess: (res) => {
  243. const { attachment, message_id } = res;
  244. const newMessage = {
  245. _id: message_id,
  246. text: '',
  247. attachment,
  248. replyMessage: { ...tempMessage.replyMessage, sender: replyMessage?.user?._id },
  249. image: file.type === 'image' ? API_HOST + attachment.attachment_full_url : undefined,
  250. video: file.type === 'video' ? file.uri : undefined
  251. };
  252. setMessages((previousMessages) =>
  253. (previousMessages ?? []).map((msg) =>
  254. msg._id === tempMessage._id
  255. ? {
  256. ...msg,
  257. _id: res.message_id,
  258. isSending: false
  259. }
  260. : msg
  261. )
  262. );
  263. sendWebSocketMessage('new_message', newMessage as unknown as CustomMessage);
  264. }
  265. });
  266. clearReplyMessage();
  267. }
  268. },
  269. [replyMessage]
  270. );
  271. const onSendLocation = useCallback(
  272. async (coords: { latitude: number; longitude: number }) => {
  273. const tempMessage: CustomMessage = {
  274. _id: Date.now() + Math.random(),
  275. text: '',
  276. createdAt: new Date(),
  277. user: { _id: +currentUserId, name: 'Me', avatar: null as never },
  278. pending: true,
  279. deleted: false,
  280. reactions: {},
  281. attachment: {
  282. id: -1,
  283. filename: 'location.json',
  284. filetype: 'nomadmania/location',
  285. lat: coords.latitude,
  286. lng: coords.longitude
  287. }
  288. };
  289. if (replyMessage) {
  290. tempMessage.replyMessage = {
  291. text: replyMessage.text,
  292. id: replyMessage._id,
  293. name: replyMessage.user._id !== +currentUserId ? (replyMessage.user.name as string) : 'Me'
  294. };
  295. }
  296. setMessages((previousMessages) => GiftedChat.append(previousMessages ?? [], [tempMessage]));
  297. const locationData = JSON.stringify({ lat: coords.latitude, lng: coords.longitude });
  298. const fileUri = FileSystem.documentDirectory + 'location.json';
  299. await FileSystem.writeAsStringAsync(fileUri, locationData);
  300. const locationFile = {
  301. uri: fileUri,
  302. type: 'application/json',
  303. name: 'location.json'
  304. };
  305. const messageData = {
  306. token,
  307. to_group_token: group_token,
  308. text: tempMessage.text,
  309. reply_to_id: replyMessage ? (replyMessage._id as number) : -1,
  310. attachment: locationFile
  311. };
  312. sendMessage(messageData, {
  313. onSuccess: async (res) => {
  314. const { attachment, message_id } = res;
  315. const newMessage = {
  316. _id: message_id,
  317. text: '',
  318. attachment,
  319. replyMessage: { ...tempMessage.replyMessage, sender: replyMessage?.user?._id }
  320. };
  321. setMessages((previousMessages) =>
  322. (previousMessages ?? []).map((msg) =>
  323. msg._id === tempMessage._id ? { ...msg, _id: res.message_id } : msg
  324. )
  325. );
  326. sendWebSocketMessage('new_message', newMessage as unknown as CustomMessage);
  327. await FileSystem.deleteAsync(fileUri);
  328. },
  329. onError: async (err) => {
  330. await FileSystem.deleteAsync(fileUri);
  331. }
  332. });
  333. clearReplyMessage();
  334. },
  335. [replyMessage]
  336. );
  337. const onSendFile = useCallback(
  338. (files: { uri: string; type: string; name?: string }[]) => {
  339. const newMsgs = files.map((file) => {
  340. const msg: CustomMessage = {
  341. _id: Date.now() + Math.random(),
  342. text: '',
  343. createdAt: new Date(),
  344. user: { _id: +currentUserId, name: 'Me', avatar: null as never },
  345. deleted: false,
  346. reactions: {},
  347. isSending: true,
  348. attachment: {
  349. id: -1,
  350. filename: file.name ?? 'File',
  351. filetype: file.type,
  352. attachment_link: file.uri
  353. }
  354. };
  355. if (replyMessage) {
  356. msg.replyMessage = {
  357. text: replyMessage.text,
  358. id: replyMessage._id,
  359. name:
  360. replyMessage.user._id !== +currentUserId ? (replyMessage.user.name as string) : 'Me'
  361. };
  362. }
  363. if (file.type.includes('image')) {
  364. msg.image = file.uri;
  365. } else if (file.type.includes('video')) {
  366. msg.video = file.uri;
  367. }
  368. setMessages((previousMessages) => GiftedChat.append(previousMessages ?? [], [msg]));
  369. const messageData = {
  370. token,
  371. to_group_token: group_token,
  372. text: '',
  373. reply_to_id: replyMessage ? (replyMessage._id as number) : -1,
  374. attachment: {
  375. uri: file.uri,
  376. type: file.type,
  377. name: file.name || file.uri.split('/').pop()
  378. }
  379. };
  380. sendMessage(messageData, {
  381. onSuccess: (res) => {
  382. const { attachment, message_id } = res;
  383. const newMessage = {
  384. _id: message_id,
  385. text: '',
  386. attachment,
  387. replyMessage: { ...msg.replyMessage, sender: replyMessage?.user?._id },
  388. image: file.type === 'image' ? API_HOST + attachment.attachment_full_url : undefined,
  389. video: file.type === 'video' ? file.uri : undefined
  390. };
  391. setMessages((previousMessages) =>
  392. (previousMessages ?? []).map((prevMsg) =>
  393. prevMsg._id === msg._id
  394. ? {
  395. ...prevMsg,
  396. _id: res.message_id,
  397. attachment: res.attachment,
  398. isSending: false,
  399. image:
  400. res.attachment?.attachment_small_url && file.type?.startsWith('image')
  401. ? API_HOST + res.attachment.attachment_small_url
  402. : undefined,
  403. video:
  404. res.attachment?.attachment_link && file.type?.startsWith('video')
  405. ? API_HOST + res.attachment.attachment_link
  406. : undefined
  407. }
  408. : prevMsg
  409. )
  410. );
  411. sendWebSocketMessage('new_message', newMessage as unknown as CustomMessage);
  412. }
  413. });
  414. return msg;
  415. });
  416. clearReplyMessage();
  417. },
  418. [replyMessage]
  419. );
  420. async function openFileInApp(uri: string, fileName: string) {
  421. try {
  422. const dirExist = await FileSystem.getInfoAsync(CACHED_ATTACHMENTS_DIR);
  423. if (!dirExist.exists) {
  424. await FileSystem.makeDirectoryAsync(CACHED_ATTACHMENTS_DIR, { intermediates: true });
  425. }
  426. const fileUri = `${CACHED_ATTACHMENTS_DIR}${fileName}`;
  427. const fileExists = await FileSystem.getInfoAsync(fileUri);
  428. if (fileExists.exists && fileExists.size > 1024) {
  429. await FileViewer.open(fileUri, {
  430. showOpenWithDialog: true,
  431. showAppsSuggestions: true
  432. });
  433. return;
  434. }
  435. const { uri: localUri } = await FileSystem.downloadAsync(uri, fileUri, {
  436. headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS }
  437. });
  438. await FileViewer.open(localUri, {
  439. showOpenWithDialog: true,
  440. showAppsSuggestions: true
  441. });
  442. } catch (err) {
  443. console.warn('openFileInApp error:', err);
  444. Alert.alert('Cannot open file', 'No application found to open this file.');
  445. }
  446. }
  447. async function downloadFileToDevice(currentMessage: CustomMessage) {
  448. if (!currentMessage.image && !currentMessage.video) {
  449. return;
  450. }
  451. const fileUrl = currentMessage.video
  452. ? currentMessage.video
  453. : API_HOST + currentMessage.attachment?.attachment_full_url;
  454. const fileType = currentMessage.attachment?.filetype || '';
  455. const fileExt = fileType.split('/').pop() || '';
  456. const fileName = currentMessage.attachment?.filename?.split('.')[0] || 'file';
  457. const fileUri = `${FileSystem.cacheDirectory}${fileName}.${fileExt}`;
  458. try {
  459. const { status } = await MediaLibrary.requestPermissionsAsync();
  460. if (status !== 'granted') {
  461. return;
  462. }
  463. const downloadOptions = currentMessage.video
  464. ? { headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS } }
  465. : undefined;
  466. const { uri } = await FileSystem.downloadAsync(fileUrl, fileUri, downloadOptions);
  467. await MediaLibrary.createAssetAsync(uri);
  468. Alert.alert(
  469. 'Success',
  470. `${fileType.startsWith('video') ? 'Video' : 'Image'} saved to gallery.`
  471. );
  472. } catch (error) {
  473. Alert.alert('Error', 'Failed to download the file.');
  474. }
  475. }
  476. const renderMessageFile = (props: BubbleProps<CustomMessage>) => {
  477. const { currentMessage } = props;
  478. const leftMessage = currentMessage?.user?._id !== +currentUserId;
  479. if (!currentMessage?.attachment) return null;
  480. const { attachment_link, filename } = currentMessage.attachment;
  481. const fileName = filename ?? 'Attachment';
  482. const uri = API_HOST + attachment_link;
  483. return (
  484. <TouchableOpacity
  485. style={[
  486. styles.fileContainer,
  487. { backgroundColor: leftMessage ? 'rgba(15, 63, 79, 0.2)' : 'rgba(244, 244, 244, 0.2)' }
  488. ]}
  489. onPress={() => {
  490. openFileInApp(uri, fileName);
  491. }}
  492. onLongPress={() => handleLongPress(currentMessage, props)}
  493. disabled={currentMessage?.isSending}
  494. >
  495. {currentMessage?.isSending ? (
  496. <ActivityIndicator
  497. size="small"
  498. color={leftMessage ? Colors.DARK_BLUE : Colors.FILL_LIGHT}
  499. />
  500. ) : (
  501. <MaterialCommunityIcons
  502. name="file"
  503. size={32}
  504. color={leftMessage ? Colors.DARK_BLUE : Colors.FILL_LIGHT}
  505. />
  506. )}
  507. <Text
  508. style={[
  509. styles.fileNameText,
  510. { color: leftMessage ? Colors.DARK_BLUE : Colors.FILL_LIGHT }
  511. ]}
  512. >
  513. {fileName}
  514. </Text>
  515. </TouchableOpacity>
  516. );
  517. };
  518. const renderMessageLocation = (props: BubbleProps<CustomMessage>) => {
  519. const { currentMessage } = props;
  520. if (!currentMessage?.attachment) return null;
  521. const { lat, lng } = currentMessage.attachment;
  522. if (!lat || !lng) return null;
  523. return (
  524. <View
  525. style={[
  526. {
  527. alignItems: 'center',
  528. borderRadius: 8,
  529. marginVertical: 6,
  530. marginHorizontal: 6,
  531. width: 220
  532. }
  533. ]}
  534. >
  535. <MessageLocation props={props} lat={lat} lng={lng} onLongPress={handleLongPress} />
  536. </View>
  537. );
  538. };
  539. const onShareLiveLocation = useCallback(() => {}, []);
  540. useEffect(() => {
  541. if (data && data.settings) {
  542. setCanSeeMembers(data.settings.members_can_see_members === 1 || data.settings.admin === 1);
  543. }
  544. }, [data]);
  545. useEffect(() => {
  546. let unsubscribe: any;
  547. const setupNotificationHandler = async () => {
  548. unsubscribe = await dismissChatNotifications(
  549. group_token,
  550. isSubscribed,
  551. setModalInfo,
  552. navigation
  553. );
  554. };
  555. setupNotificationHandler();
  556. return () => {
  557. if (unsubscribe) unsubscribe();
  558. updateUnreadMessagesCount();
  559. };
  560. }, [group_token]);
  561. useEffect(() => {
  562. socket.current = new WebSocket(WEBSOCKET_URL);
  563. socket.current.onopen = () => {
  564. socket.current?.send(JSON.stringify({ token }));
  565. };
  566. socket.current.onmessage = (event) => {
  567. const data = JSON.parse(event.data);
  568. handleWebSocketMessage(data);
  569. };
  570. socket.current.onclose = () => {
  571. console.log('WebSocket connection closed chat screen');
  572. };
  573. return () => {
  574. if (socket.current) {
  575. socket.current.close();
  576. socket.current = null;
  577. }
  578. };
  579. }, [token]);
  580. useEffect(() => {
  581. const handleAppStateChange = async (nextAppState: AppStateStatus) => {
  582. const prevState = appState.current;
  583. appState.current = nextAppState;
  584. if (prevState.match(/inactive|background/) && nextAppState === 'active') {
  585. refetch();
  586. if (!socket.current || socket.current.readyState === WebSocket.CLOSED) {
  587. socket.current = new WebSocket(WEBSOCKET_URL);
  588. socket.current.onopen = () => {
  589. socket.current?.send(JSON.stringify({ token }));
  590. };
  591. socket.current.onmessage = (event) => {
  592. const data = JSON.parse(event.data);
  593. handleWebSocketMessage(data);
  594. };
  595. }
  596. await dismissChatNotifications(group_token, isSubscribed, setModalInfo, navigation);
  597. }
  598. };
  599. const subscription = AppState.addEventListener('change', handleAppStateChange);
  600. return () => {
  601. subscription.remove();
  602. if (socket.current) {
  603. socket.current.close();
  604. socket.current = null;
  605. }
  606. };
  607. }, [token]);
  608. const handleWebSocketMessage = (data: any) => {
  609. switch (data.action) {
  610. case 'new_message':
  611. if (data.group_token === group_token && data.message) {
  612. const newMessage = mapApiMessageToGiftedMessage(data.message);
  613. setMessages((previousMessages) => {
  614. const messageExists =
  615. previousMessages && previousMessages.some((msg) => msg._id === newMessage._id);
  616. if (!messageExists) {
  617. return GiftedChat.append(previousMessages ?? [], [
  618. {
  619. ...newMessage,
  620. user: {
  621. _id: data.uid,
  622. name: data.name,
  623. avatar: API_HOST + data.avatar
  624. }
  625. }
  626. ]);
  627. }
  628. return previousMessages;
  629. });
  630. }
  631. break;
  632. case 'new_reaction':
  633. if (data.group_token === group_token && data.reaction) {
  634. // todo: name
  635. updateMessageWithReaction(data.reaction);
  636. }
  637. break;
  638. case 'unreact':
  639. if (data.group_token === group_token && data.unreacted_message_id) {
  640. // todo: name
  641. removeReactionFromMessage(data.unreacted_message_id);
  642. }
  643. break;
  644. case 'delete_message':
  645. if (data.group_token === group_token && data.deleted_message_id) {
  646. removeDeletedMessage(data.deleted_message_id);
  647. }
  648. break;
  649. case 'is_typing':
  650. if (data.group_token === group_token && data.uid !== +currentUserId) {
  651. setIsTyping(data.name);
  652. }
  653. break;
  654. case 'stopped_typing':
  655. if (data.group_token === group_token) {
  656. setIsTyping(null);
  657. }
  658. break;
  659. case 'messages_read':
  660. if (data.group_token === group_token && data.read_messages_ids) {
  661. setMessages(
  662. (prevMessages) =>
  663. prevMessages?.map((msg) => {
  664. if (data.read_messages_ids.includes(msg._id)) {
  665. return { ...msg, received: true };
  666. }
  667. return msg;
  668. }) ?? []
  669. );
  670. }
  671. break;
  672. case 'messages_received':
  673. if (data.group_token === group_token && data.received_messages_ids) {
  674. setMessages(
  675. (prevMessages) =>
  676. prevMessages?.map((msg) => {
  677. if (data.received_messages_ids.includes(msg._id)) {
  678. return { ...msg, sent: true };
  679. }
  680. return msg;
  681. }) ?? []
  682. );
  683. }
  684. break;
  685. default:
  686. break;
  687. }
  688. };
  689. const updateMessageWithReaction = (reactionData: any) => {
  690. setMessages(
  691. (prevMessages) =>
  692. prevMessages?.map((msg) => {
  693. if (msg._id === reactionData.message_id) {
  694. const updatedReactions = [
  695. ...(Array.isArray(msg.reactions)
  696. ? msg.reactions?.filter((r: any) => r.uid !== reactionData.uid)
  697. : []),
  698. reactionData
  699. ];
  700. return { ...msg, reactions: updatedReactions };
  701. }
  702. return msg;
  703. }) ?? []
  704. );
  705. };
  706. const removeReactionFromMessage = (messageId: number) => {
  707. setMessages(
  708. (prevMessages) =>
  709. prevMessages?.map((msg) => {
  710. if (msg._id === messageId) {
  711. const updatedReactions = Array.isArray(msg.reactions)
  712. ? msg.reactions?.filter((r: any) => r.uid === +currentUserId)
  713. : [];
  714. return { ...msg, reactions: updatedReactions };
  715. }
  716. return msg;
  717. }) ?? []
  718. );
  719. };
  720. const removeDeletedMessage = (messageId: number) => {
  721. setMessages(
  722. (prevMessages) =>
  723. prevMessages?.map((msg) => {
  724. if (msg._id === messageId) {
  725. return {
  726. ...msg,
  727. deleted: true,
  728. text: 'This message was deleted',
  729. pending: false,
  730. sent: false,
  731. received: false
  732. };
  733. }
  734. return msg;
  735. }) ?? []
  736. );
  737. };
  738. useEffect(() => {
  739. const pingInterval = setInterval(() => {
  740. if (socket.current && socket.current.readyState === WebSocket.OPEN) {
  741. socket.current.send(
  742. JSON.stringify({ action: 'ping', conversation_with_group: group_token })
  743. );
  744. } else {
  745. socket.current = new WebSocket(WEBSOCKET_URL);
  746. socket.current.onopen = () => {
  747. socket.current?.send(JSON.stringify({ token }));
  748. };
  749. socket.current.onmessage = (event) => {
  750. const data = JSON.parse(event.data);
  751. handleWebSocketMessage(data);
  752. };
  753. return () => {
  754. if (socket.current) {
  755. socket.current.close();
  756. socket.current = null;
  757. }
  758. };
  759. }
  760. }, 50000);
  761. return () => clearInterval(pingInterval);
  762. }, []);
  763. const sendWebSocketMessage = (
  764. action: string,
  765. message: CustomMessage | null = null,
  766. reaction: string | null = null,
  767. readMessagesIds: number[] | null = null
  768. ) => {
  769. if (socket.current && socket.current.readyState === WebSocket.OPEN) {
  770. const data: any = {
  771. action,
  772. conversation_with_group: group_token
  773. };
  774. if (action === 'new_message' && message) {
  775. data.message = {
  776. id: message._id,
  777. text: message.text,
  778. sender: +currentUserId,
  779. sent_datetime: new Date().toISOString().replace('T', ' ').substring(0, 19),
  780. reply_to_id: message.replyMessage?.id ?? -1,
  781. reply_to: message.replyMessage ?? null,
  782. reactions: message.reactions ?? '{}',
  783. status: 2,
  784. attachement: message.attachment ? message.attachment : -1
  785. };
  786. }
  787. if (action === 'new_reaction' && message && reaction) {
  788. data.reaction = {
  789. message_id: message._id,
  790. reaction,
  791. uid: +currentUserId,
  792. datetime: new Date().toISOString()
  793. };
  794. }
  795. if (action === 'unreact' && message) {
  796. data.message_id = message._id;
  797. }
  798. if (action === 'delete_message' && message) {
  799. data.message_id = message._id;
  800. }
  801. if (action === 'messages_read' && readMessagesIds) {
  802. data.messages_ids = readMessagesIds;
  803. }
  804. socket.current.send(JSON.stringify(data));
  805. }
  806. };
  807. const handleTyping = (isTyping: boolean) => {
  808. if (isTyping) {
  809. sendWebSocketMessage('is_typing');
  810. } else {
  811. sendWebSocketMessage('stopped_typing');
  812. }
  813. };
  814. const mapApiMessageToGiftedMessage = (message: GroupMessage): CustomMessage => {
  815. return {
  816. _id: message.id,
  817. text: message.text,
  818. createdAt: new Date(message.sent_datetime + 'Z'),
  819. user: {
  820. _id: message.sender,
  821. name: message.sender !== +currentUserId ? message.sender_name : 'Me',
  822. avatar:
  823. message.sender !== +currentUserId && message.sender_avatar
  824. ? API_HOST + message.sender_avatar
  825. : message.sender === +currentUserId
  826. ? (null as never)
  827. : undefined
  828. },
  829. replyMessage:
  830. message.reply_to_id && message.reply_to_id > 0
  831. ? {
  832. text: message.reply_to.text,
  833. id: message.reply_to.id,
  834. name:
  835. message.reply_to.sender !== +currentUserId ? message.reply_to?.sender_name : 'Me'
  836. }
  837. : null,
  838. reactions: JSON.parse(message.reactions || '{}'),
  839. attachment: message.attachement !== -1 ? message.attachement : null,
  840. pending: message.status === 1,
  841. sent: message.status === 2,
  842. received: message.status === 3,
  843. deleted: message.status === 4,
  844. isSending: false,
  845. video:
  846. message.attachement !== -1 && message.attachement?.filetype?.startsWith('video')
  847. ? API_HOST + message.attachement?.attachment_link
  848. : null,
  849. image:
  850. message.attachement !== -1 && message.attachement?.filetype?.startsWith('image')
  851. ? API_HOST + message.attachement?.attachment_small_url
  852. : null,
  853. system: message.sender === -1
  854. };
  855. };
  856. useFocusEffect(
  857. useCallback(() => {
  858. refetch();
  859. }, [])
  860. );
  861. useFocusEffect(
  862. useCallback(() => {
  863. if (chatData?.groupAvatar) {
  864. setGroupAvatar(API_HOST + chatData.groupAvatar);
  865. }
  866. if (chatData?.messages) {
  867. const mappedMessages = chatData.messages.map(mapApiMessageToGiftedMessage);
  868. if (unreadMessageIndex === null && !isFetching) {
  869. const firstUnreadIndex = mappedMessages.findLastIndex(
  870. (msg) => !msg.received && !msg?.deleted && msg.user._id !== +currentUserId
  871. );
  872. if (firstUnreadIndex !== -1) {
  873. setUnreadMessageIndex(firstUnreadIndex);
  874. const unreadMarker: any = {
  875. _id: 'unreadMarker',
  876. text: 'Unread messages',
  877. system: true
  878. };
  879. mappedMessages.splice(firstUnreadIndex + 1, 0, unreadMarker);
  880. setTimeout(() => {
  881. if (flatList.current) {
  882. flatList.current.scrollToIndex({
  883. index: firstUnreadIndex,
  884. animated: true,
  885. viewPosition: 0.5
  886. });
  887. }
  888. }, 500);
  889. } else {
  890. setUnreadMessageIndex(0);
  891. }
  892. }
  893. setMessages((previousMessages) => {
  894. const newMessages = mappedMessages.filter(
  895. (newMsg) => !previousMessages?.some((oldMsg) => oldMsg._id === newMsg._id)
  896. );
  897. return prevThenMessageId !== -1 && previousMessages
  898. ? GiftedChat.prepend(previousMessages, newMessages)
  899. : mappedMessages;
  900. });
  901. if (mappedMessages.length < 50) {
  902. setHasMoreMessages(false);
  903. }
  904. if (mappedMessages.length === 0 && !modalInfo.visible) {
  905. setTimeout(() => {
  906. textInputRef.current?.focus();
  907. }, 500);
  908. }
  909. setIsLoadingEarlier(false);
  910. }
  911. }, [chatData])
  912. );
  913. useEffect(() => {
  914. if (messages) {
  915. if (isSearchingMessage) {
  916. const messageIndex = messages.findIndex((msg) => msg._id === isSearchingMessage);
  917. if (messageIndex !== -1 && flatList.current) {
  918. setIsSearchingMessage(null);
  919. }
  920. scrollToMessage(isSearchingMessage);
  921. }
  922. }
  923. }, [messages]);
  924. useEffect(() => {
  925. if (messages?.length === 0 && !modalInfo.visible) {
  926. setTimeout(() => {
  927. textInputRef.current?.focus();
  928. }, 500);
  929. }
  930. }, [modalInfo]);
  931. const loadEarlierMessages = async () => {
  932. if (!hasMoreMessages || (isLoadingEarlier && !isSearchingMessage) || !messages) return;
  933. setIsLoadingEarlier(true);
  934. const previousMessageId = messages[messages.length - 1]._id;
  935. setPrevThenMessageId(previousMessageId);
  936. };
  937. const sentToServer = useRef<Set<number>>(new Set());
  938. const handleViewableItemsChanged = ({ viewableItems }: { viewableItems: any[] }) => {
  939. const newViewableUnreadMessages = viewableItems
  940. .filter(
  941. (item) =>
  942. !item.item.received &&
  943. !item.item.deleted &&
  944. item.item._id !== 'unreadMarker' &&
  945. item.item.user._id !== +currentUserId &&
  946. !sentToServer.current.has(item.item._id)
  947. )
  948. .map((item) => item.item._id);
  949. if (newViewableUnreadMessages.length > 0) {
  950. markMessagesAsRead(
  951. {
  952. token,
  953. group_token,
  954. messages_id: newViewableUnreadMessages
  955. },
  956. {
  957. onSuccess: (res) => {
  958. newViewableUnreadMessages.forEach((id) => sentToServer.current.add(id));
  959. sendWebSocketMessage('messages_read', null, null, newViewableUnreadMessages);
  960. }
  961. }
  962. );
  963. }
  964. };
  965. const renderSystemMessage = (props: any) => {
  966. if (props.currentMessage._id === 'unreadMarker') {
  967. return (
  968. <View style={styles.unreadMessagesContainer}>
  969. <Text style={styles.unreadMessagesText}>{props.currentMessage.text}</Text>
  970. </View>
  971. );
  972. } else if (props.currentMessage.user._id === -1) {
  973. return (
  974. <SystemMessage
  975. currentMessage={props.currentMessage}
  976. containerStyle={{
  977. marginTop: 0,
  978. marginBottom: 0,
  979. paddingVertical: 2,
  980. paddingHorizontal: 12
  981. }}
  982. wrapperStyle={{
  983. backgroundColor: Colors.FILL_LIGHT,
  984. paddingHorizontal: 6,
  985. paddingVertical: 4,
  986. borderRadius: 10
  987. }}
  988. textStyle={{
  989. color: Colors.DARK_BLUE,
  990. fontStyle: 'italic',
  991. fontSize: 12,
  992. textAlign: 'center'
  993. }}
  994. />
  995. );
  996. }
  997. return null;
  998. };
  999. const clearReplyMessage = () => setReplyMessage(null);
  1000. const handleLongPress = (message: CustomMessage, props: BubbleProps<CustomMessage>) => {
  1001. const messageRef = messageRefs.current[message._id];
  1002. setSelectedMessage(props);
  1003. trigger('impactMedium', options);
  1004. const isMine = message.user._id === +currentUserId;
  1005. if (messageRef) {
  1006. messageRef.measureInWindow((x: number, y: number, width: number, height: number) => {
  1007. const screenHeight = Dimensions.get('window').height;
  1008. const spaceAbove = y - insets.top;
  1009. const spaceBelow = screenHeight - (y + height) - insets.bottom * 2;
  1010. let finalY = y;
  1011. scrollY.value = 0;
  1012. if (isNaN(y) || isNaN(height)) {
  1013. console.error("Invalid measurement values for 'y' or 'height'", { y, height });
  1014. return;
  1015. }
  1016. if (spaceBelow < 220) {
  1017. const extraShift = 220 - spaceBelow;
  1018. finalY -= extraShift;
  1019. }
  1020. if (spaceAbove < 50) {
  1021. const extraShift = 50 - spaceAbove;
  1022. finalY += extraShift;
  1023. }
  1024. if (spaceBelow < 220 || spaceAbove < 50) {
  1025. const targetY = screenHeight / 2 - height / 2;
  1026. scrollY.value = withTiming(finalY - finalY);
  1027. }
  1028. if (height > Dimensions.get('window').height - 200) {
  1029. finalY = 100;
  1030. }
  1031. finalY = isNaN(finalY) ? 0 : finalY;
  1032. setMessagePosition({ x, y: finalY, width, height, isMine });
  1033. setIsModalVisible(true);
  1034. });
  1035. }
  1036. };
  1037. const openEmojiSelector = () => {
  1038. SheetManager.show('emoji-selector');
  1039. trigger('impactLight', options);
  1040. };
  1041. const closeEmojiSelector = () => {
  1042. SheetManager.hide('emoji-selector');
  1043. };
  1044. const handleReactionPress = (emoji: string, messageId: number) => {
  1045. addReaction(messageId, emoji);
  1046. };
  1047. const handleDeleteMessage = (messageId: number) => {
  1048. deleteMessage(
  1049. {
  1050. token,
  1051. message_id: messageId,
  1052. group_token
  1053. },
  1054. {
  1055. onSuccess: () => {
  1056. setMessages(
  1057. (prevMessages) =>
  1058. prevMessages?.map((msg) => {
  1059. if (msg._id === messageId) {
  1060. return {
  1061. ...msg,
  1062. deleted: true,
  1063. text: 'This message was deleted',
  1064. pending: false,
  1065. sent: false,
  1066. received: false,
  1067. attachment: null,
  1068. image: undefined,
  1069. video: undefined
  1070. };
  1071. }
  1072. return msg;
  1073. }) ?? []
  1074. );
  1075. const messageToDelete = messages?.find((msg) => msg._id === messageId);
  1076. if (messageToDelete) {
  1077. sendWebSocketMessage('delete_message', messageToDelete, null, null);
  1078. }
  1079. }
  1080. }
  1081. );
  1082. };
  1083. const handlePinMessage = (messageId: number, pin: 0 | 1) => {
  1084. pinMessage(
  1085. {
  1086. token,
  1087. message_id: messageId,
  1088. group_token,
  1089. pin
  1090. },
  1091. {
  1092. onSuccess: () => {
  1093. refetchPinned();
  1094. if (pin === 0) {
  1095. setPinned(null);
  1096. }
  1097. }
  1098. }
  1099. );
  1100. };
  1101. const handleOptionPress = (option: string) => {
  1102. if (!selectedMessage) return;
  1103. switch (option) {
  1104. case 'reply':
  1105. setReplyMessage(selectedMessage.currentMessage);
  1106. setIsModalVisible(false);
  1107. break;
  1108. case 'copy':
  1109. Clipboard.setString(selectedMessage?.currentMessage?.text ?? '');
  1110. setIsModalVisible(false);
  1111. Alert.alert('Copied');
  1112. break;
  1113. case 'delete':
  1114. handleDeleteMessage(selectedMessage.currentMessage?._id);
  1115. setIsModalVisible(false);
  1116. break;
  1117. case 'download':
  1118. downloadFileToDevice(selectedMessage.currentMessage);
  1119. setIsModalVisible(false);
  1120. break;
  1121. case 'info':
  1122. SheetManager.show('group-status', {
  1123. payload: {
  1124. messageId: selectedMessage.currentMessage._id,
  1125. groupToken: group_token,
  1126. setInsetsColor
  1127. } as any
  1128. });
  1129. setIsModalVisible(false);
  1130. setInsetsColor(Colors.WHITE);
  1131. break;
  1132. case 'pin':
  1133. handlePinMessage(selectedMessage.currentMessage?._id, 1);
  1134. setIsModalVisible(false);
  1135. break;
  1136. default:
  1137. break;
  1138. }
  1139. closeEmojiSelector();
  1140. };
  1141. const openReactionList = (
  1142. reactions: { uid: number; name: string; reaction: string }[],
  1143. messageId: number
  1144. ) => {
  1145. SheetManager.show('reactions-list-modal', {
  1146. payload: {
  1147. users: reactions,
  1148. currentUserId: +currentUserId,
  1149. token,
  1150. messageId,
  1151. conversation_with_user: group_token,
  1152. setMessages,
  1153. sendWebSocketMessage,
  1154. isGroup: true,
  1155. groupToken: group_token
  1156. } as any
  1157. });
  1158. };
  1159. const renderTimeContainer = (time: TimeProps<CustomMessage>) => {
  1160. const createdAt = new Date(time.currentMessage.createdAt);
  1161. const formattedTime = createdAt.toLocaleTimeString([], {
  1162. hour: '2-digit',
  1163. minute: '2-digit',
  1164. hour12: true
  1165. });
  1166. const hasReactions =
  1167. time.currentMessage.reactions &&
  1168. Array.isArray(time.currentMessage.reactions) &&
  1169. time.currentMessage.reactions.length > 0;
  1170. return (
  1171. <View
  1172. style={[
  1173. styles.bottomContainer,
  1174. {
  1175. justifyContent: hasReactions ? 'space-between' : 'flex-end'
  1176. }
  1177. ]}
  1178. >
  1179. {hasReactions && (
  1180. <TouchableOpacity
  1181. style={[
  1182. styles.bottomCustomContainer,
  1183. {
  1184. backgroundColor:
  1185. time.position === 'left' ? 'rgba(0, 0, 0, 0.2)' : 'rgba(255, 255, 255, 0.2)'
  1186. }
  1187. ]}
  1188. onPress={() =>
  1189. Array.isArray(time.currentMessage.reactions) &&
  1190. openReactionList(
  1191. time.currentMessage.reactions.map((reaction) => ({
  1192. ...reaction,
  1193. name: reaction.uid !== +currentUserId ? reaction?.name : 'Me'
  1194. })),
  1195. time.currentMessage._id
  1196. )
  1197. }
  1198. >
  1199. {Object.entries(
  1200. (Array.isArray(time.currentMessage.reactions)
  1201. ? time.currentMessage.reactions
  1202. : []
  1203. ).reduce(
  1204. (acc: Record<string, { count: number }>, { reaction }: { reaction: string }) => {
  1205. if (!acc[reaction]) {
  1206. acc[reaction] = { count: 0 };
  1207. }
  1208. acc[reaction].count += 1;
  1209. return acc;
  1210. },
  1211. {}
  1212. )
  1213. ).map(([emoji, { count }]: any) => {
  1214. return (
  1215. <View key={emoji}>
  1216. <Text style={{}}>
  1217. {emoji}
  1218. {(count as number) > 1 ? ` ${count}` : ''}
  1219. </Text>
  1220. </View>
  1221. );
  1222. })}
  1223. </TouchableOpacity>
  1224. )}
  1225. <View style={styles.timeContainer}>
  1226. <Text style={styles.timeText}>{formattedTime}</Text>
  1227. {renderTicks(time.currentMessage)}
  1228. </View>
  1229. </View>
  1230. );
  1231. };
  1232. const renderSelectedMessage = () =>
  1233. selectedMessage && (
  1234. <View
  1235. style={{
  1236. maxHeight: '80%',
  1237. width: messagePosition?.width,
  1238. position: 'absolute',
  1239. top: messagePosition?.y,
  1240. left: messagePosition?.x
  1241. }}
  1242. >
  1243. <ScrollView>
  1244. <Bubble
  1245. {...selectedMessage}
  1246. wrapperStyle={{
  1247. right: { backgroundColor: Colors.DARK_BLUE },
  1248. left: { backgroundColor: Colors.FILL_LIGHT }
  1249. }}
  1250. textStyle={{
  1251. right: { color: Colors.WHITE },
  1252. left: { color: Colors.DARK_BLUE }
  1253. }}
  1254. renderTicks={() => null}
  1255. renderTime={renderTimeContainer}
  1256. renderCustomView={() =>
  1257. selectedMessage.currentMessage.attachment?.filetype === 'nomadmania/location'
  1258. ? renderMessageLocation(selectedMessage)
  1259. : selectedMessage.currentMessage.attachment &&
  1260. !selectedMessage.currentMessage.image &&
  1261. !selectedMessage.currentMessage.video
  1262. ? renderMessageFile(selectedMessage)
  1263. : renderReplyMessageView(selectedMessage)
  1264. }
  1265. />
  1266. </ScrollView>
  1267. </View>
  1268. );
  1269. const handleBackgroundPress = () => {
  1270. setIsModalVisible(false);
  1271. setSelectedMessage(null);
  1272. closeEmojiSelector();
  1273. };
  1274. useFocusEffect(
  1275. useCallback(() => {
  1276. navigation?.getParent()?.setOptions({
  1277. tabBarStyle: {
  1278. display: 'none'
  1279. }
  1280. });
  1281. }, [navigation])
  1282. );
  1283. const onSend = useCallback(
  1284. (newMessages: CustomMessage[] = []) => {
  1285. if (replyMessage) {
  1286. newMessages[0].replyMessage = {
  1287. text: transformMessageForServer(replyMessage.text),
  1288. id: replyMessage._id,
  1289. name: replyMessage.user._id !== +currentUserId ? (replyMessage.user.name as string) : 'Me'
  1290. };
  1291. }
  1292. const user = {
  1293. _id: +currentUserId,
  1294. name: 'Me',
  1295. avatar: null as never
  1296. };
  1297. const message = { ...newMessages[0], pending: true, isSending: true, user };
  1298. setMessages((previousMessages) =>
  1299. GiftedChat.append(previousMessages ?? [], [
  1300. { ...message, text: transformMessageForServer(newMessages[0].text) }
  1301. ])
  1302. );
  1303. sendMessage(
  1304. {
  1305. token,
  1306. to_group_token: group_token,
  1307. text: transformMessageForServer(message.text),
  1308. reply_to_id: replyMessage ? (replyMessage._id as number) : -1
  1309. },
  1310. {
  1311. onSuccess: (res) => {
  1312. const newMessage = {
  1313. _id: res.message_id,
  1314. text: message.text,
  1315. replyMessage: { ...message.replyMessage, sender: replyMessage?.user?._id }
  1316. };
  1317. setMessages((previousMessages) =>
  1318. (previousMessages ?? []).map((msg) =>
  1319. msg._id === message._id ? { ...msg, _id: res.message_id, isSending: false } : msg
  1320. )
  1321. );
  1322. sendWebSocketMessage('new_message', newMessage as unknown as CustomMessage);
  1323. }
  1324. }
  1325. );
  1326. clearReplyMessage();
  1327. },
  1328. [replyMessage]
  1329. );
  1330. const addReaction = (messageId: number, reaction: string) => {
  1331. if (!messages) return;
  1332. const updatedMessages = messages.map((msg: any) => {
  1333. if (msg._id === messageId) {
  1334. const updatedReactions: Reaction[] = [
  1335. ...(Array.isArray(msg.reactions)
  1336. ? msg.reactions?.filter((r: Reaction) => r.uid !== +currentUserId)
  1337. : []),
  1338. { datetime: new Date().toISOString(), reaction: reaction, uid: +currentUserId }
  1339. ];
  1340. return {
  1341. ...msg,
  1342. reactions: updatedReactions
  1343. };
  1344. }
  1345. return msg;
  1346. });
  1347. setMessages(updatedMessages);
  1348. reactToMessage(
  1349. { token, message_id: messageId, reaction: reaction, group_token: group_token },
  1350. {
  1351. onSuccess: () => {
  1352. const message = messages.find((msg) => msg._id === messageId);
  1353. if (message) {
  1354. sendWebSocketMessage('new_reaction', message, reaction);
  1355. }
  1356. }
  1357. }
  1358. );
  1359. setIsModalVisible(false);
  1360. };
  1361. const updateRowRef = useCallback(
  1362. (ref: any) => {
  1363. if (
  1364. ref &&
  1365. replyMessage &&
  1366. ref.props.children.props.currentMessage?._id === replyMessage._id
  1367. ) {
  1368. swipeableRowRef.current = ref;
  1369. }
  1370. },
  1371. [replyMessage]
  1372. );
  1373. const renderReplyMessageView = (props: BubbleProps<CustomMessage>) => {
  1374. if (!props.currentMessage) {
  1375. return null;
  1376. }
  1377. const { currentMessage } = props;
  1378. if (!currentMessage || !currentMessage?.replyMessage) {
  1379. return null;
  1380. }
  1381. return (
  1382. <TouchableOpacity
  1383. style={[
  1384. styles.replyMessageContainer,
  1385. {
  1386. backgroundColor:
  1387. currentMessage.user._id !== +currentUserId
  1388. ? 'rgba(255, 255, 255, 0.7)'
  1389. : 'rgba(0, 0, 0, 0.2)',
  1390. borderColor:
  1391. currentMessage.user._id !== +currentUserId ? Colors.DARK_BLUE : Colors.WHITE
  1392. }
  1393. ]}
  1394. onPress={() => {
  1395. if (currentMessage?.replyMessage?.id) {
  1396. scrollToMessage(currentMessage.replyMessage.id);
  1397. }
  1398. }}
  1399. >
  1400. <View style={styles.replyContent}>
  1401. <Text
  1402. style={[
  1403. styles.replyAuthorName,
  1404. {
  1405. color: currentMessage.user._id !== +currentUserId ? Colors.DARK_BLUE : Colors.WHITE
  1406. }
  1407. ]}
  1408. >
  1409. {currentMessage.replyMessage.name}
  1410. </Text>
  1411. <Text
  1412. numberOfLines={1}
  1413. style={[
  1414. styles.replyMessageText,
  1415. {
  1416. color: currentMessage.user._id !== +currentUserId ? Colors.DARK_BLUE : Colors.WHITE
  1417. }
  1418. ]}
  1419. >
  1420. {currentMessage.replyMessage.text}
  1421. </Text>
  1422. </View>
  1423. </TouchableOpacity>
  1424. );
  1425. };
  1426. const scrollToMessage = (messageId: number) => {
  1427. if (!messages) return;
  1428. const messageIndex = messages.findIndex((message) => message._id === messageId);
  1429. if (messageIndex !== -1 && flatList.current) {
  1430. setIsSearchingMessage(null);
  1431. flatList.current.scrollToIndex({
  1432. index: messageIndex,
  1433. animated: true,
  1434. viewPosition: 0.5
  1435. });
  1436. setHighlightedMessageId(messageId);
  1437. setMessages((previousMessages) =>
  1438. (previousMessages ?? []).map((msg) =>
  1439. msg._id === messageId
  1440. ? {
  1441. ...msg,
  1442. isRendering: msg?.isRendering ? false : true
  1443. }
  1444. : msg
  1445. )
  1446. );
  1447. }
  1448. if (hasMoreMessages && messageIndex === -1) {
  1449. setIsSearchingMessage(messageId);
  1450. loadEarlierMessages();
  1451. }
  1452. };
  1453. useEffect(() => {
  1454. if (highlightedMessageId && isRerendering) {
  1455. setTimeout(() => {
  1456. setHighlightedMessageId(null);
  1457. setIsRerendering(false);
  1458. }, 1500);
  1459. }
  1460. }, [highlightedMessageId, isRerendering]);
  1461. useEffect(() => {
  1462. if (replyMessage && swipeableRowRef.current) {
  1463. swipeableRowRef.current.close();
  1464. swipeableRowRef.current = null;
  1465. }
  1466. }, [replyMessage]);
  1467. const handleOpenImage = async (uri: string, fileName: string) => {
  1468. const dirExist = await FileSystem.getInfoAsync(CACHED_ATTACHMENTS_DIR);
  1469. if (!dirExist.exists) {
  1470. await FileSystem.makeDirectoryAsync(CACHED_ATTACHMENTS_DIR, { intermediates: true });
  1471. }
  1472. const fileUri = `${CACHED_ATTACHMENTS_DIR}${fileName}`;
  1473. const fileExists = await FileSystem.getInfoAsync(fileUri);
  1474. if (fileExists.exists && fileExists.size > 1024) {
  1475. setSelectedMedia(fileUri);
  1476. return;
  1477. }
  1478. setSelectedMedia(uri);
  1479. const { uri: localUri } = await FileSystem.downloadAsync(uri, fileUri, {
  1480. headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS }
  1481. });
  1482. };
  1483. const renderMessageImage = (props: any) => {
  1484. const { currentMessage } = props;
  1485. const leftMessage = currentMessage?.user?._id !== +currentUserId;
  1486. return (
  1487. <TouchableOpacity
  1488. onPress={() => {
  1489. if (!currentMessage.attachment.attachment_full_url?.startsWith('/')) {
  1490. setSelectedMedia(currentMessage.attachment.attachment_full_url);
  1491. return;
  1492. }
  1493. handleOpenImage(
  1494. API_HOST + currentMessage.attachment.attachment_full_url,
  1495. currentMessage.attachment?.filename
  1496. );
  1497. }}
  1498. onLongPress={() => handleLongPress(currentMessage, props)}
  1499. style={styles.imageContainer}
  1500. disabled={currentMessage.isSending}
  1501. >
  1502. <Image
  1503. source={{
  1504. uri: currentMessage.image,
  1505. headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS }
  1506. }}
  1507. style={styles.chatImage}
  1508. resizeMode="cover"
  1509. />
  1510. {currentMessage.isSending && (
  1511. <View
  1512. style={{
  1513. position: 'absolute',
  1514. top: 0,
  1515. left: 0,
  1516. right: 0,
  1517. bottom: 0,
  1518. justifyContent: 'center',
  1519. alignItems: 'center'
  1520. }}
  1521. >
  1522. <ActivityIndicator
  1523. size="large"
  1524. color={leftMessage ? Colors.DARK_BLUE : Colors.FILL_LIGHT}
  1525. />
  1526. </View>
  1527. )}
  1528. </TouchableOpacity>
  1529. );
  1530. };
  1531. const renderTicks = (message: CustomMessage) => {
  1532. if (message.user._id !== +currentUserId) return null;
  1533. if (message.isSending) {
  1534. return (
  1535. <View>
  1536. <ActivityIndicator
  1537. size={16}
  1538. color={Colors.LIGHT_GRAY}
  1539. style={{ transform: 'scale(0.8)' }}
  1540. />
  1541. </View>
  1542. );
  1543. }
  1544. return message.received ? (
  1545. <View>
  1546. <MaterialCommunityIcons name="check-all" size={16} color={Colors.WHITE} />
  1547. </View>
  1548. ) : message.sent ? (
  1549. <View>
  1550. <MaterialCommunityIcons name="check" size={16} color={Colors.WHITE} />
  1551. </View>
  1552. ) : message.pending ? (
  1553. <View>
  1554. <MaterialCommunityIcons name="check" size={16} color={Colors.LIGHT_GRAY} />
  1555. </View>
  1556. ) : null;
  1557. };
  1558. const renderBubble = (props: BubbleProps<CustomMessage>) => {
  1559. const { currentMessage } = props;
  1560. if (currentMessage.deleted) {
  1561. const text = currentMessage.text.length
  1562. ? props.currentMessage.text
  1563. : 'This message was deleted';
  1564. return (
  1565. <View>
  1566. <Bubble
  1567. {...props}
  1568. renderTime={() => null}
  1569. currentMessage={{
  1570. ...props.currentMessage,
  1571. text: text
  1572. }}
  1573. renderMessageText={() => (
  1574. <View style={{ paddingHorizontal: 12, paddingVertical: 6 }}>
  1575. <Text style={{ color: Colors.LIGHT_GRAY, fontStyle: 'italic', fontSize: 12 }}>
  1576. {text}
  1577. </Text>
  1578. </View>
  1579. )}
  1580. wrapperStyle={{
  1581. right: {
  1582. backgroundColor: Colors.DARK_BLUE
  1583. },
  1584. left: {
  1585. backgroundColor: Colors.FILL_LIGHT
  1586. }
  1587. }}
  1588. textStyle={{
  1589. left: {
  1590. color: Colors.DARK_BLUE
  1591. },
  1592. right: {
  1593. color: Colors.WHITE
  1594. }
  1595. }}
  1596. />
  1597. </View>
  1598. );
  1599. }
  1600. const isHighlighted = currentMessage._id === highlightedMessageId;
  1601. const backgroundColor = isHighlighted
  1602. ? Colors.ORANGE
  1603. : currentMessage.user._id === +currentUserId
  1604. ? Colors.DARK_BLUE
  1605. : Colors.FILL_LIGHT;
  1606. const messageToCompare = props.previousMessage;
  1607. const showUserName =
  1608. props.position === 'left' &&
  1609. currentMessage &&
  1610. messageToCompare &&
  1611. (!isSameUser(currentMessage, messageToCompare) ||
  1612. !isSameDay(currentMessage, messageToCompare));
  1613. return (
  1614. <View
  1615. key={`${currentMessage._id}-${isHighlighted ? 'highlighted' : 'normal'}`}
  1616. ref={(ref) => {
  1617. if (ref && currentMessage) {
  1618. messageRefs.current[currentMessage._id] = ref;
  1619. }
  1620. }}
  1621. collapsable={false}
  1622. >
  1623. <Bubble
  1624. {...props}
  1625. wrapperStyle={{
  1626. right: {
  1627. backgroundColor: backgroundColor
  1628. },
  1629. left: {
  1630. backgroundColor: backgroundColor
  1631. }
  1632. }}
  1633. textStyle={{
  1634. left: {
  1635. color: Colors.DARK_BLUE
  1636. },
  1637. right: {
  1638. color: Colors.FILL_LIGHT
  1639. }
  1640. }}
  1641. onLongPress={() => handleLongPress(currentMessage, props)}
  1642. renderTicks={() => null}
  1643. renderTime={renderTimeContainer}
  1644. renderCustomView={() => {
  1645. return (
  1646. <View>
  1647. {showUserName ? (
  1648. <Text
  1649. style={{
  1650. color: Colors.BLACK,
  1651. fontWeight: '600',
  1652. fontSize: 13,
  1653. paddingHorizontal: 10,
  1654. paddingTop: 8,
  1655. paddingBottom: 2
  1656. }}
  1657. >
  1658. {/* {'~ '} */}
  1659. {props.currentMessage.user.name}
  1660. </Text>
  1661. ) : null}
  1662. {currentMessage.attachment?.filetype === 'nomadmania/location'
  1663. ? renderMessageLocation(props)
  1664. : currentMessage.attachment && !currentMessage.image && !currentMessage.video
  1665. ? renderMessageFile(props)
  1666. : renderReplyMessageView(props)}
  1667. </View>
  1668. );
  1669. }}
  1670. />
  1671. </View>
  1672. );
  1673. };
  1674. const openAttachmentsModal = () => {
  1675. SheetManager.show('chat-attachments', {
  1676. payload: {
  1677. name: groupName,
  1678. uid: group_token,
  1679. setModalInfo,
  1680. closeOptions: () => {},
  1681. onSendMedia,
  1682. onSendLocation,
  1683. onShareLiveLocation,
  1684. onSendFile,
  1685. isGroup: true
  1686. } as any
  1687. });
  1688. };
  1689. const renderInputToolbar = (props: any) => {
  1690. if (!chatData?.can_send_messages) return null;
  1691. return (
  1692. <>
  1693. {showMentions && canSeeMembers ? (
  1694. <MentionsList
  1695. mentionList={mentionList}
  1696. inputHeight={inputHeight}
  1697. onMentionSelect={onMentionSelect}
  1698. />
  1699. ) : null}
  1700. <View
  1701. onLayout={(e) => {
  1702. setInputHeight(e.nativeEvent.layout.height);
  1703. }}
  1704. >
  1705. <InputToolbar
  1706. {...props}
  1707. renderActions={() =>
  1708. userType === 'normal' ? (
  1709. <Actions
  1710. icon={() => (
  1711. <MaterialCommunityIcons name="plus" size={28} color={Colors.DARK_BLUE} />
  1712. )}
  1713. onPressActionButton={openAttachmentsModal}
  1714. />
  1715. ) : null
  1716. }
  1717. containerStyle={{
  1718. backgroundColor: Colors.FILL_LIGHT
  1719. }}
  1720. />
  1721. </View>
  1722. </>
  1723. );
  1724. };
  1725. const renderScrollToBottom = () => {
  1726. return (
  1727. <TouchableOpacity
  1728. style={styles.scrollToBottom}
  1729. onPress={() => {
  1730. if (flatList.current) {
  1731. flatList.current.scrollToIndex({ index: 0, animated: true });
  1732. }
  1733. }}
  1734. >
  1735. <MaterialCommunityIcons name="chevron-down" size={24} color={Colors.WHITE} />
  1736. </TouchableOpacity>
  1737. );
  1738. };
  1739. const shouldUpdateMessage = (
  1740. props: MessageProps<IMessage>,
  1741. nextProps: MessageProps<IMessage>
  1742. ) => {
  1743. setIsRerendering(true);
  1744. const currentId = nextProps.currentMessage._id;
  1745. return currentId === highlightedMessageId;
  1746. };
  1747. const onInputTextChanged = (value: string) => {
  1748. handleTyping(value.length > 0);
  1749. setText(value);
  1750. const mentionMatch = value.match(/(^|\s)(@\w*)$/);
  1751. if (mentionMatch) {
  1752. setShowMentions(true);
  1753. const searchText = mentionMatch[2].slice(1).toLowerCase();
  1754. setMentionList(
  1755. (members?.settings ?? [])?.filter(
  1756. (m) => m.name.toLowerCase().includes(searchText) && m.uid !== +currentUserId
  1757. )
  1758. );
  1759. } else {
  1760. setShowMentions(false);
  1761. }
  1762. };
  1763. const onMentionSelect = (member: { uid: number; name: string }) => {
  1764. const words = text.split(' ');
  1765. words[words.length - 1] = `@${member.name} `;
  1766. setText(words.join(' '));
  1767. setShowMentions(false);
  1768. };
  1769. const transformMessageForServer = (text: string) => {
  1770. let transformedText = text;
  1771. members?.settings?.forEach((member) => {
  1772. const mentionRegex = new RegExp(`@${member.name}\\b`, 'g');
  1773. transformedText = transformedText.replace(mentionRegex, `@{${member.uid}}`);
  1774. });
  1775. return transformedText;
  1776. };
  1777. return (
  1778. <SafeAreaView
  1779. edges={['top']}
  1780. style={{
  1781. height: '100%'
  1782. }}
  1783. >
  1784. <View style={{ paddingHorizontal: '5%' }}>
  1785. <Header
  1786. label={groupName}
  1787. textColor={userType !== 'normal' ? Colors.RED : Colors.DARK_BLUE}
  1788. rightElement={
  1789. <TouchableOpacity
  1790. onPress={() =>
  1791. navigation.navigate(
  1792. ...([NAVIGATION_PAGES.GROUP_SETTINGS, { groupToken: group_token }] as never)
  1793. )
  1794. }
  1795. disabled={userType !== 'normal'}
  1796. >
  1797. {groupAvatar && userType === 'normal' ? (
  1798. <Image source={{ uri: groupAvatar, cache: 'reload' }} style={styles.avatar} />
  1799. ) : userType === 'normal' ? (
  1800. <GroupIcon fill={Colors.DARK_BLUE} width={30} height={30} />
  1801. ) : (
  1802. <BanIcon fill={Colors.RED} width={30} height={30} />
  1803. )}
  1804. </TouchableOpacity>
  1805. }
  1806. />
  1807. </View>
  1808. {pinned && (
  1809. <TouchableOpacity
  1810. style={{
  1811. height: 38,
  1812. flexDirection: 'row',
  1813. backgroundColor: Colors.FILL_LIGHT,
  1814. borderBottomWidth: 1,
  1815. borderBottomColor: Colors.DARK_LIGHT
  1816. }}
  1817. onPress={() => scrollToMessage(pinned.id)}
  1818. >
  1819. <View
  1820. style={{
  1821. height: 50,
  1822. width: 6,
  1823. backgroundColor: Colors.DARK_BLUE
  1824. }}
  1825. ></View>
  1826. <View
  1827. style={{
  1828. paddingLeft: 8,
  1829. height: '100%',
  1830. justifyContent: 'center'
  1831. }}
  1832. >
  1833. <PinIcon fill={Colors.DARK_BLUE} height={18} />
  1834. </View>
  1835. <View style={{ flex: 1, justifyContent: 'center' }}>
  1836. <Text style={{ color: Colors.DARK_BLUE, paddingLeft: 10 }} numberOfLines={1}>
  1837. {pinned.text}
  1838. </Text>
  1839. </View>
  1840. {data?.settings?.admin === 1 && (
  1841. <View style={{ alignItems: 'flex-end', justifyContent: 'center' }}>
  1842. <TouchableOpacity
  1843. style={{ paddingRight: 10 }}
  1844. onPress={() => handlePinMessage(pinned.id, 0)}
  1845. >
  1846. <MaterialCommunityIcons
  1847. name="close-circle-outline"
  1848. size={24}
  1849. color={Colors.DARK_BLUE}
  1850. />
  1851. </TouchableOpacity>
  1852. </View>
  1853. )}
  1854. </TouchableOpacity>
  1855. )}
  1856. <GestureHandlerRootView style={styles.container}>
  1857. {messages ? (
  1858. <GiftedChat
  1859. messages={messages as CustomMessage[]}
  1860. text={text}
  1861. listViewProps={{
  1862. ref: flatList,
  1863. showsVerticalScrollIndicator: false,
  1864. initialNumToRender: messages.length,
  1865. onViewableItemsChanged: handleViewableItemsChanged,
  1866. viewabilityConfig: { itemVisiblePercentThreshold: 50 },
  1867. onScrollToIndexFailed: (info: any) => {
  1868. const wait = new Promise((resolve) => setTimeout(resolve, 300));
  1869. wait.then(() => {
  1870. flatList.current?.scrollToIndex({
  1871. index: info.index,
  1872. animated: true,
  1873. viewPosition: 0.5
  1874. });
  1875. });
  1876. }
  1877. }}
  1878. renderSystemMessage={renderSystemMessage}
  1879. onSend={(newMessages: CustomMessage[]) => onSend(newMessages)}
  1880. user={{ _id: +currentUserId, name: 'Me' }}
  1881. renderBubble={renderBubble}
  1882. renderMessageImage={renderMessageImage}
  1883. showUserAvatar={true}
  1884. onPressAvatar={(user) => {
  1885. navigation.navigate(
  1886. ...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId: user._id }] as never)
  1887. );
  1888. }}
  1889. renderInputToolbar={renderInputToolbar}
  1890. renderCustomView={renderReplyMessageView}
  1891. isCustomViewBottom={false}
  1892. messageContainerRef={messageContainerRef}
  1893. minComposerHeight={34}
  1894. onInputTextChanged={onInputTextChanged}
  1895. textInputRef={textInputRef}
  1896. isTyping={isTyping ? true : false}
  1897. renderTypingIndicator={() => <TypingIndicator isTyping={isTyping} />}
  1898. renderSend={(props) => (
  1899. <View style={styles.sendBtn}>
  1900. {props.text?.trim() && (
  1901. <Send
  1902. {...props}
  1903. containerStyle={{
  1904. justifyContent: 'center'
  1905. }}
  1906. >
  1907. <SendIcon fill={Colors.DARK_BLUE} />
  1908. </Send>
  1909. )}
  1910. {!props.text?.trim() && <SendIcon fill={Colors.LIGHT_GRAY} />}
  1911. </View>
  1912. )}
  1913. renderMessageVideo={(props) => (
  1914. <RenderMessageVideo
  1915. props={props}
  1916. token={token}
  1917. currentUserId={+currentUserId}
  1918. onLongPress={handleLongPress}
  1919. />
  1920. )}
  1921. textInputProps={{
  1922. ...styles.composer,
  1923. selectionColor: Colors.LIGHT_GRAY
  1924. }}
  1925. placeholder=""
  1926. renderMessage={(props) => (
  1927. <ChatMessageBox
  1928. {...(props as MessageProps<CustomMessage>)}
  1929. updateRowRef={updateRowRef}
  1930. setReplyOnSwipeOpen={setReplyMessage}
  1931. />
  1932. )}
  1933. renderChatFooter={() => (
  1934. <ReplyMessageBar clearReply={clearReplyMessage} message={replyMessage} />
  1935. )}
  1936. maxComposerHeight={100}
  1937. renderComposer={(props) => <Composer {...props} />}
  1938. keyboardShouldPersistTaps="handled"
  1939. renderChatEmpty={() => (
  1940. <View style={styles.emptyChat}>
  1941. <Text
  1942. style={styles.emptyChatText}
  1943. >{`No messages yet.\nFeel free to start the conversation.`}</Text>
  1944. </View>
  1945. )}
  1946. shouldUpdateMessage={shouldUpdateMessage}
  1947. scrollToBottom={true}
  1948. scrollToBottomComponent={renderScrollToBottom}
  1949. scrollToBottomStyle={{ backgroundColor: 'transparent' }}
  1950. parsePatterns={(linkStyle) => [
  1951. {
  1952. type: 'url',
  1953. style: { color: Colors.ORANGE, textDecorationLine: 'underline' },
  1954. onPress: (url: string) => Linking.openURL(url),
  1955. onLongPress: (url: string) => {
  1956. Clipboard.setString(url ?? '');
  1957. Alert.alert('Link copied');
  1958. }
  1959. },
  1960. {
  1961. pattern: /@\{(\d+)\}/g,
  1962. renderText: (messageText: string) => {
  1963. const tagId = messageText.slice(2, messageText.length - 1);
  1964. const user = (members?.settings ?? [])?.find((m) => m.uid === +tagId);
  1965. if (user) {
  1966. return (
  1967. <Text
  1968. style={{ color: Colors.ORANGE }}
  1969. onPress={() =>
  1970. navigation.navigate(
  1971. ...([
  1972. NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW,
  1973. { userId: user.uid }
  1974. ] as never)
  1975. )
  1976. }
  1977. >
  1978. @{user.name}
  1979. </Text>
  1980. );
  1981. } else {
  1982. return messageText;
  1983. }
  1984. }
  1985. }
  1986. ]}
  1987. infiniteScroll={true}
  1988. loadEarlier={hasMoreMessages}
  1989. isLoadingEarlier={isLoadingEarlier}
  1990. onLoadEarlier={loadEarlierMessages}
  1991. renderLoadEarlier={() => (
  1992. <View style={{ paddingVertical: 20 }}>
  1993. <ActivityIndicator size="small" color={Colors.DARK_BLUE} />
  1994. </View>
  1995. )}
  1996. />
  1997. ) : (
  1998. <ActivityIndicator size="large" color={Colors.DARK_BLUE} />
  1999. )}
  2000. <ImageView
  2001. images={[
  2002. {
  2003. uri: selectedMedia,
  2004. cache: 'force-cache',
  2005. headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS }
  2006. }
  2007. ]}
  2008. imageIndex={0}
  2009. visible={!!selectedMedia}
  2010. onRequestClose={() => setSelectedMedia(null)}
  2011. backgroundColor={Colors.DARK_BLUE}
  2012. />
  2013. <ReactModal
  2014. isVisible={isModalVisible}
  2015. onBackdropPress={handleBackgroundPress}
  2016. style={styles.reactModalContainer}
  2017. animationIn="fadeIn"
  2018. animationOut="fadeOut"
  2019. useNativeDriver
  2020. backdropColor="transparent"
  2021. >
  2022. <BlurView
  2023. intensity={80}
  2024. style={styles.modalBackground}
  2025. experimentalBlurMethod="dimezisBlurView"
  2026. >
  2027. <TouchableOpacity
  2028. style={styles.modalBackground}
  2029. activeOpacity={1}
  2030. onPress={handleBackgroundPress}
  2031. >
  2032. <ReactionBar
  2033. messagePosition={messagePosition}
  2034. selectedMessage={selectedMessage}
  2035. reactionEmojis={reactionEmojis}
  2036. handleReactionPress={handleReactionPress}
  2037. openEmojiSelector={openEmojiSelector}
  2038. />
  2039. {renderSelectedMessage()}
  2040. <OptionsMenu
  2041. selectedMessage={selectedMessage}
  2042. handleOptionPress={handleOptionPress}
  2043. messagePosition={messagePosition}
  2044. isGroup={true}
  2045. isAdmin={data?.settings?.admin == 1}
  2046. />
  2047. <EmojiSelectorModal
  2048. visible={emojiSelectorVisible}
  2049. selectedMessage={selectedMessage}
  2050. addReaction={addReaction}
  2051. closeEmojiSelector={closeEmojiSelector}
  2052. />
  2053. </TouchableOpacity>
  2054. </BlurView>
  2055. </ReactModal>
  2056. <WarningModal
  2057. isVisible={modalInfo.visible}
  2058. onClose={closeModal}
  2059. type={modalInfo.type}
  2060. message={modalInfo.message}
  2061. buttonTitle={modalInfo.buttonTitle}
  2062. title={modalInfo.title}
  2063. action={() => {
  2064. modalInfo.action();
  2065. closeModal();
  2066. }}
  2067. />
  2068. <AttachmentsModal />
  2069. <ReactionsListModal />
  2070. <GroupStatusModal />
  2071. </GestureHandlerRootView>
  2072. <View
  2073. style={{
  2074. height: insets.bottom,
  2075. backgroundColor: insetsColor
  2076. }}
  2077. />
  2078. </SafeAreaView>
  2079. );
  2080. };
  2081. export default GroupChatScreen;