@cometchat/chat-uikit-react-native 5.2.3 → 5.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/package.json +1 -1
  2. package/src/CometChatConversations/CometChatConversations.tsx +167 -86
  3. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +312 -116
  4. package/src/CometChatMessageComposer/styles.tsx +2 -1
  5. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +83 -17
  6. package/src/CometChatMessageList/CometChatMessageList.tsx +675 -122
  7. package/src/CometChatMessageList/style.ts +4 -2
  8. package/src/CometChatSearch/CometChatSearch.tsx +2165 -0
  9. package/src/CometChatSearch/SearchConstants.ts +46 -0
  10. package/src/CometChatSearch/Skeleton.tsx +192 -0
  11. package/src/CometChatSearch/index.ts +1 -0
  12. package/src/CometChatSearch/style.ts +414 -0
  13. package/src/extensions/CollaborativeDocument/CollaborativeDocumentExtensionDecorator.tsx +43 -7
  14. package/src/extensions/CollaborativeWhiteboard/CollaborativeWhiteboardExtensionDecorator.tsx +45 -7
  15. package/src/extensions/Polls/Polls.tsx +36 -2
  16. package/src/extensions/Polls/PollsBubble.tsx +13 -9
  17. package/src/extensions/Polls/PollsDecorator.tsx +13 -1
  18. package/src/extensions/Stickers/StickersExtensionDecorator.tsx +50 -11
  19. package/src/extensions/Stickers/style.ts +0 -1
  20. package/src/index.ts +5 -0
  21. package/src/shared/base/Types.ts +8 -0
  22. package/src/shared/constants/UIKitConstants.ts +2 -0
  23. package/src/shared/events/CometChatMessageEvents/index.ts +8 -7
  24. package/src/shared/events/CometChatUIEventHandler/Listener.ts +4 -0
  25. package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +158 -27
  26. package/src/shared/framework/DataSource.ts +7 -0
  27. package/src/shared/framework/DataSourceDecorator.tsx +12 -0
  28. package/src/shared/framework/MessageDataSource.tsx +182 -1
  29. package/src/shared/helper/functions.js +0 -67
  30. package/src/shared/helper/helperFunctions.ts +72 -0
  31. package/src/shared/icons/components/documents.tsx +23 -0
  32. package/src/shared/icons/components/empty-search.tsx +52 -0
  33. package/src/shared/icons/components/message-blocked.tsx +1 -1
  34. package/src/shared/icons/components/unread.tsx +29 -0
  35. package/src/shared/icons/icon-mapping.tsx +7 -0
  36. package/src/shared/index.ts +2 -1
  37. package/src/shared/modals/CometChatMessageTemplate.ts +23 -0
  38. package/src/shared/resources/CometChatLocalizeNew/CometChatLocalizationHelper.ts +4 -4
  39. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +17 -1
  40. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +70 -34
  41. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +60 -24
  42. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +37 -1
  43. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +60 -24
  44. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +37 -1
  45. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +37 -1
  46. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +37 -1
  47. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +37 -1
  48. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +40 -4
  49. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +37 -1
  50. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +37 -1
  51. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +37 -1
  52. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +37 -1
  53. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +38 -2
  54. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +37 -1
  55. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +37 -1
  56. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +40 -4
  57. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +274 -23
  58. package/src/shared/utils/MessageUtils.tsx +0 -1
  59. package/src/shared/views/CometChatAudioBubble/style.ts +0 -2
  60. package/src/shared/views/CometChatFileBubble/style.ts +0 -4
  61. package/src/shared/views/CometChatImageBubble/CometChatImageLoader.tsx +1 -0
  62. package/src/shared/views/CometChatList/CometChatList.tsx +12 -0
  63. package/src/shared/views/CometChatList/Header.tsx +79 -49
  64. package/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx +14 -4
  65. package/src/shared/views/CometChatReportDialog/CometChatReportDialog.tsx +390 -0
  66. package/src/shared/views/CometChatReportDialog/index.ts +3 -0
  67. package/src/shared/views/CometChatReportDialog/style.ts +164 -0
  68. package/src/shared/views/CometChatStatusIndicator/private.png +0 -0
  69. package/src/shared/views/CometChatStatusIndicator/protected.png +0 -0
  70. package/src/shared/views/CometChatStatusIndicator/styles.ts +2 -2
  71. package/src/shared/views/CometChatSuggestionList/CometChatSuggestionList.tsx +18 -2
  72. package/src/shared/views/index.ts +6 -0
  73. package/src/theme/default/default.ts +3 -0
  74. package/src/theme/provider.tsx +23 -12
  75. package/src/theme/type.ts +2 -0
@@ -14,6 +14,7 @@ import React, {
14
14
  } from "react";
15
15
  import {
16
16
  ActivityIndicator,
17
+ Animated,
17
18
  Dimensions,
18
19
  FlatList,
19
20
  Keyboard,
@@ -27,6 +28,13 @@ import {
27
28
  View,
28
29
  ViewStyle,
29
30
  } from "react-native";
31
+ import {
32
+ PanGestureHandler,
33
+ State,
34
+ PanGestureHandlerGestureEvent,
35
+ PanGestureHandlerStateChangeEvent,
36
+ } from "react-native-gesture-handler";
37
+ import { CometChatMessageEvents } from "../shared/events/CometChatMessageEvents";
30
38
  import { CometChatMessageInformation } from "../CometChatMessageInformation/CometChatMessageInformation";
31
39
  import {
32
40
  CometChatActionSheet,
@@ -64,7 +72,7 @@ import { Icon } from "../shared/icons/Icon";
64
72
  import { CometChatMessageTemplate } from "../shared/modals/CometChatMessageTemplate";
65
73
  import { getUnixTimestamp, messageStatus } from "../shared/utils/CometChatMessageHelper";
66
74
  import { CommonUtils } from "../shared/utils/CommonUtils";
67
- import { CometChatConfirmDialog, CometChatReceipt } from "../shared/views";
75
+ import { CometChatConfirmDialog, CometChatReceipt, CometChatReportDialog } from "../shared/views";
68
76
  import { CometChatAvatar } from "../shared/views/CometChatAvatar";
69
77
  import { CometChatBadge } from "../shared/views/CometChatBadge";
70
78
  import { CometChatDate } from "../shared/views/CometChatDate";
@@ -318,6 +326,10 @@ export interface CometChatMessageListProps {
318
326
  * @param messageList - Array of CometChat.BaseMessage
319
327
  */
320
328
  onEmpty?: () => void;
329
+ /**
330
+ * Flag to hide the reply option
331
+ */
332
+ hideReplyOption?: boolean;
321
333
  /**
322
334
  * Flag to hide the reply in thread option
323
335
  */
@@ -354,6 +366,14 @@ export interface CometChatMessageListProps {
354
366
  * Flag to hide the message info option
355
367
  */
356
368
  hideMessageInfoOption?: boolean;
369
+ /**
370
+ * Flag to hide the "Flag Message" option from the actions menu
371
+ */
372
+ hideFlagMessageOption?: boolean;
373
+ /**
374
+ * Flag to hide the remark text area in the flag dialog
375
+ */
376
+ hideFlagRemarkField?: boolean;
357
377
  /**
358
378
  * Flag to hide group action messages
359
379
  */
@@ -394,6 +414,16 @@ export interface CometChatMessageListProps {
394
414
  * Controls the speed of AI message streaming (only applies to @agentic users)
395
415
  */
396
416
  streamingSpeed?: number;
417
+ /**
418
+ * Message ID to navigate to and highlight in the message list.
419
+ * When provided, the message list will fetch messages around this ID and scroll to it.
420
+ */
421
+ goToMessageId?: string;
422
+ /**
423
+ * Search keyword to highlight in message text.
424
+ * When provided, matching text in messages will be highlighted.
425
+ */
426
+ searchKeyword?: string;
397
427
  }
398
428
 
399
429
  /**
@@ -488,6 +518,7 @@ export const CometChatMessageList = memo(
488
518
  addTemplates = [],
489
519
  onLoad,
490
520
  onEmpty,
521
+ hideReplyOption: propHideReplyOption = false,
491
522
  hideReplyInThreadOption: propHideReplyInThreadOption = false,
492
523
  hideShareMessageOption: propHideShareMessageOption = false,
493
524
  hideEditMessageOption: propHideEditMessageOption = false,
@@ -507,6 +538,10 @@ export const CometChatMessageList = memo(
507
538
  onSuggestedMessageClick,
508
539
  aiAssistantTools,
509
540
  streamingSpeed = 30,
541
+ goToMessageId,
542
+ searchKeyword,
543
+ hideFlagRemarkField,
544
+ hideFlagMessageOption: propHideFlagMessageOption = false,
510
545
  } = props;
511
546
 
512
547
  // Helper function to check if user is agentic
@@ -515,6 +550,7 @@ export const CometChatMessageList = memo(
515
550
  }, [user]);
516
551
 
517
552
  // hiding props for @agentic users
553
+ const hideReplyOption = isAgenticUser() ? true : propHideReplyOption;
518
554
  const hideReplyInThreadOption = isAgenticUser() ? true : propHideReplyInThreadOption;
519
555
  const hideShareMessageOption = isAgenticUser() ? true : propHideShareMessageOption;
520
556
  const hideEditMessageOption = isAgenticUser() ? true : propHideEditMessageOption;
@@ -525,6 +561,7 @@ export const CometChatMessageList = memo(
525
561
  const hideCopyMessageOption = isAgenticUser() ? true : propHideCopyMessageOption;
526
562
  const hideMessageInfoOption = isAgenticUser() ? true : propHideMessageInfoOption;
527
563
  const hideGroupActionMessages = isAgenticUser() ? true : propHideGroupActionMessages;
564
+ const hideFlagMessageOption = isAgenticUser() ? true : propHideFlagMessageOption;
528
565
 
529
566
  const callListenerId = "call_" + new Date().getTime();
530
567
  const effectiveHideModeration = hideModerationStatus;
@@ -632,14 +669,24 @@ export const CometChatMessageList = memo(
632
669
  outgoing: deepMerge(outgoingBubbleStyles, outgoingBubbleStyles.imageBubbleStyles ?? {}),
633
670
  });
634
671
 
672
+ const fileIncoming = deepMerge(incomingBubbleStyles, incomingBubbleStyles.fileBubbleStyles ?? {});
673
+ if (fileIncoming.containerStyle) fileIncoming.containerStyle.height = undefined;
674
+ const fileOutgoing = deepMerge(outgoingBubbleStyles, outgoingBubbleStyles.fileBubbleStyles ?? {});
675
+ if (fileOutgoing.containerStyle) fileOutgoing.containerStyle.height = undefined;
676
+
635
677
  styleCache.set(MessageTypeConstants.file, {
636
- incoming: deepMerge(incomingBubbleStyles, incomingBubbleStyles.fileBubbleStyles ?? {}),
637
- outgoing: deepMerge(outgoingBubbleStyles, outgoingBubbleStyles.fileBubbleStyles ?? {}),
678
+ incoming: fileIncoming,
679
+ outgoing: fileOutgoing,
638
680
  });
639
681
 
682
+ const audioIncoming = deepMerge(incomingBubbleStyles, incomingBubbleStyles.audioBubbleStyles ?? {});
683
+ if (audioIncoming.containerStyle) audioIncoming.containerStyle.height = undefined;
684
+ const audioOutgoing = deepMerge(outgoingBubbleStyles, outgoingBubbleStyles.audioBubbleStyles ?? {});
685
+ if (audioOutgoing.containerStyle) audioOutgoing.containerStyle.height = undefined;
686
+
640
687
  styleCache.set(MessageTypeConstants.audio, {
641
- incoming: deepMerge(incomingBubbleStyles, incomingBubbleStyles.audioBubbleStyles ?? {}),
642
- outgoing: deepMerge(outgoingBubbleStyles, outgoingBubbleStyles.audioBubbleStyles ?? {}),
688
+ incoming: audioIncoming,
689
+ outgoing: audioOutgoing,
643
690
  });
644
691
 
645
692
  styleCache.set(MessageTypeConstants.messageDeleted, {
@@ -776,11 +823,17 @@ export const CometChatMessageList = memo(
776
823
  const [loadingMessages, setLoadingMessages] = useState(false);
777
824
  /** this is required to prevent duplicate api calls. Cannot use state for this since this is being used in scrollHandler **/
778
825
  const loadingMessagesRef = useRef(false);
826
+ const loadingPrevMessagesRef = useRef(false);
827
+ // State for showing loading when navigating to far messages
828
+ const [navigationLoading, setNavigationLoading] = useState(false);
829
+ // State for showing bottom loading indicator when fetching next messages
830
+ const [bottomLoading, setBottomLoading] = useState(false);
779
831
  const [unreadCount, setUnreadCount] = useState(0);
780
832
  const [showMessageOptions, setShowMessageOptions] = useState<any[]>([]);
781
833
  const [ExtensionsComponent, setExtensionsComponent] = useState<JSX.Element | null>(null);
782
834
  const [CustomListHeader, setCustomListHeader] = useState<any>(null);
783
835
  const [messageInfo, setMessageInfo] = useState(false);
836
+ const [showReportDialog, setShowReportDialog] = useState(false);
784
837
  const [ongoingCallView, setOngoingCallView] = useState(null);
785
838
  const [selectedMessage, setSelectedMessage] = useState<any>(null);
786
839
  const [showEmojiKeyboard, setShowEmojiKeyboard] = useState(false);
@@ -790,12 +843,21 @@ export const CometChatMessageList = memo(
790
843
  const [showDeleteModal, setShowDeleteModal] = useState(false);
791
844
 
792
845
  const infoObject = useRef<CometChat.BaseMessage | null>(undefined);
846
+ const [highlightedMessageId, setHighlightedMessageId] = useState<string | null>(null);
847
+ const [scrollTargetId, setScrollTargetId] = useState<string | null>(null);
848
+ const highlightAnimatedValue = useRef(new Animated.Value(0)).current;
849
+ const [isListLayoutComplete, setIsListLayoutComplete] = useState<boolean>(false);
850
+ const reportedMessageRef = useRef<CometChat.BaseMessage | null>(null);
851
+ const pendingReportRef = useRef<boolean>(false);
793
852
  const bottomSheetRef = useRef<any>(null);
794
853
  const conversationId = useRef<string | null>(null);
795
854
  const streamSubscriptionRef = useRef<any>(null);
796
- let lastID = useRef(0);
797
- let reachedFirstMessage = useRef<boolean>(false);
855
+ const lastID = useRef(0);
856
+ const reachedFirstMessage = useRef<boolean>(false);
798
857
  const agenticParentMessageIdRef = useRef<string | undefined>(undefined);
858
+ const [hasTargetMessageId, setHasTargetMessageId] = useState(false);
859
+ const hasReachedBottomRef = useRef(true);
860
+ const fetchingAroundIdRef = useRef<string | null>(null); // Track which message ID we're currently fetching
799
861
  const markUnreadMessageAsRead = () => {
800
862
  CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, {
801
863
  message: messagesContentListRef.current[0],
@@ -803,20 +865,59 @@ export const CometChatMessageList = memo(
803
865
  CometChat.markAsRead(messagesContentListRef.current[0]);
804
866
  setUnreadCount(0);
805
867
  };
868
+ const prevMsgListLengthRef = useRef<number>(0);
869
+ const aMessageWasSentByMeRef = useRef<boolean>(false);
870
+ const latestMessageRef = useRef<any | null>(null);
806
871
 
807
- const newMsgIndicatorPressed = useCallback(() => {
808
- messagesContentListRef.current = [
809
- ...temporaryMessageListRef.current,
810
- ...messagesContentListRef.current,
811
- ];
812
- onLoad && onLoad([...messagesContentListRef.current].reverse());
813
- setMessagesList((prev) => [...temporaryMessageListRef.current, ...prev]);
814
- temporaryMessageListRef.current = [];
815
- scrollToBottom();
816
- markUnreadMessageAsRead();
817
- }, [onLoad]);
872
+ useEffect(() => {
873
+ if (messagesList.length === prevMsgListLengthRef.current + 1 && aMessageWasSentByMeRef.current) {
874
+ aMessageWasSentByMeRef.current = false;
875
+ setTimeout(() => {
876
+ messageListRef.current?.scrollToOffset({ offset: 0, animated: true });
877
+ }, 100);
878
+ }
879
+ prevMsgListLengthRef.current = messagesList.length;
880
+ }, [messagesList]);
881
+
882
+
883
+
884
+ const newMsgIndicatorPressed = useCallback(async () => {
885
+ if (hasTargetMessageId) {
886
+ try {
887
+ messageRequest.current = msgRequestBuilder.current?.build() || null;
888
+ messagesContentListRef.current = [];
889
+ setMessagesList([]);
890
+ setListState("loading");
891
+ reachedFirstMessage.current = false;
892
+ msgRequestBuilder.current?.setMessageId(0);
893
+ messageRequest.current = msgRequestBuilder.current?.build() || null;
894
+ await getPreviousMessages();
895
+ setTimeout(() => {
896
+ scrollToBottom();
897
+ setHideScrollToBottomButton(true);
898
+ }, 100);
899
+ } catch (error) {
900
+ setListState("");
901
+ }
902
+ } else {
903
+ messagesContentListRef.current = [
904
+ ...temporaryMessageListRef.current,
905
+ ...messagesContentListRef.current,
906
+ ];
907
+ onLoad && onLoad([...messagesContentListRef.current].reverse());
908
+ setMessagesList((prev) => [...temporaryMessageListRef.current, ...prev]);
909
+ temporaryMessageListRef.current = [];
910
+ scrollToBottom();
911
+ setHideScrollToBottomButton(true);
912
+ markUnreadMessageAsRead();
913
+ }
914
+ }, [onLoad, hasTargetMessageId]);
818
915
 
819
916
  const getPreviousMessages = async () => {
917
+ if (loadingPrevMessagesRef.current) {
918
+ return;
919
+ }
920
+ loadingPrevMessagesRef.current = true;
820
921
  // For agent chats (non-thread), don't fetch previous messages
821
922
  if (isAgenticUser() && !parentMessageId) {
822
923
  return;
@@ -893,7 +994,7 @@ export const CometChatMessageList = memo(
893
994
  ...messagesContentListRef.current,
894
995
  ...previousMessagesFetched,
895
996
  ];
896
- setMessagesList((prev) => [...prev, ...previousMessagesFetched]);
997
+ setMessagesList(messagesContentListRef.current);
897
998
  }
898
999
  if (messagesContentListRef.current.length == 0) {
899
1000
  onEmpty && onEmpty();
@@ -912,9 +1013,152 @@ export const CometChatMessageList = memo(
912
1013
  loadingMessagesRef.current = false;
913
1014
  }
914
1015
  onError && onError(e);
1016
+ }).finally(() => {
1017
+ loadingPrevMessagesRef.current = false;
915
1018
  });
916
1019
  };
917
1020
 
1021
+ const highlightMessage = (messageId: string) => {
1022
+ setHighlightedMessageId(messageId);
1023
+ highlightAnimatedValue.setValue(0);
1024
+ Animated.sequence([
1025
+ Animated.timing(highlightAnimatedValue, {
1026
+ toValue: 1,
1027
+ duration: 300,
1028
+ useNativeDriver: false,
1029
+ }),
1030
+ Animated.delay(2000), // Hold highlighted state for 2 seconds
1031
+ Animated.timing(highlightAnimatedValue, {
1032
+ toValue: 0,
1033
+ duration: 500,
1034
+ useNativeDriver: false,
1035
+ }),
1036
+ ]).start(() => {
1037
+ setHighlightedMessageId(null);
1038
+ });
1039
+ };
1040
+
1041
+ const getMessagesAroundId = async (messageId: string) => {
1042
+ if (fetchingAroundIdRef.current === messageId) {
1043
+ return;
1044
+ }
1045
+
1046
+ if (isAgenticUser() && !parentMessageId) {
1047
+ return;
1048
+ }
1049
+
1050
+ fetchingAroundIdRef.current = messageId; // Mark this message as being fetched
1051
+
1052
+ // Check if message exists in current list
1053
+ const messageExists = messagesContentListRef.current.find(msg =>
1054
+ String(msg.getId()) === String(messageId)
1055
+ );
1056
+
1057
+ if (messageExists) {
1058
+ setHasTargetMessageId(true);
1059
+ } else {
1060
+ // Message is far, show navigation loading
1061
+ setNavigationLoading(true);
1062
+ setHasTargetMessageId(true);
1063
+ }
1064
+
1065
+ try {
1066
+ const targetMessageId = Number(messageId);
1067
+ msgRequestBuilder.current?.setMessageId(targetMessageId);
1068
+ messageRequest.current = msgRequestBuilder.current?.build() || null;
1069
+
1070
+ // Get the target message first to ensure it exists
1071
+ const targetMessage = await CometChat.getMessageDetails(targetMessageId);
1072
+ if (!targetMessage) {
1073
+ setListState("");
1074
+ return;
1075
+ }
1076
+
1077
+ // Create request builder for next messages (messages after the target)
1078
+ let nextMessagesRequest = new CometChat.MessagesRequestBuilder()
1079
+ .setLimit(15)
1080
+ .setMessageId(targetMessageId);
1081
+
1082
+ if (user) {
1083
+ nextMessagesRequest = nextMessagesRequest.setUID(user.getUid());
1084
+ }
1085
+
1086
+ if (group) {
1087
+ nextMessagesRequest = nextMessagesRequest.setGUID(group.getGuid());
1088
+ }
1089
+
1090
+ if (parentMessageId) {
1091
+ nextMessagesRequest = nextMessagesRequest.setParentMessageId(Number(parentMessageId));
1092
+ }
1093
+
1094
+ // Fetch messages before and after the target message
1095
+ const nextMessages = await nextMessagesRequest.build().fetchNext();
1096
+
1097
+ // Combine messages: previous (reversed) + target + next
1098
+ const allMessages = [
1099
+ // ...previousMessages,
1100
+ targetMessage,
1101
+ ...nextMessages
1102
+ ].reverse();
1103
+
1104
+ // Remove duplicates and sort by timestamp (newest at top for FlatList)
1105
+ const uniqueMessages = allMessages
1106
+ // .filter((message, index, array) =>
1107
+ // array.findIndex(m => m.getId() === message.getId()) === index
1108
+ // )
1109
+ // .sort((a, b) => b.getSentAt() - a.getSentAt());
1110
+
1111
+ if (uniqueMessages.length > 0) {
1112
+ messagesContentListRef.current = uniqueMessages;
1113
+ setMessagesList(uniqueMessages);
1114
+ onLoad && onLoad([...uniqueMessages].reverse());
1115
+
1116
+ // Reset layout state and set up for scrolling to target message
1117
+ setScrollTargetId(messageId);
1118
+ }
1119
+
1120
+ setListState("");
1121
+ } catch (error) {
1122
+ console.log("Error fetching messages around ID:", error);
1123
+ setListState("error");
1124
+ onError && onError(error as CometChat.CometChatException);
1125
+ } finally {
1126
+ setNavigationLoading(false);
1127
+ fetchingAroundIdRef.current = null;
1128
+ }
1129
+ };
1130
+
1131
+ const scrollToMessage = (messageId: string) => {
1132
+ if (messageListRef.current && messagesContentListRef.current.length > 0) {
1133
+ const targetIndex = messagesContentListRef.current.findIndex(
1134
+ (msg) => String(msg.getId()) === messageId
1135
+ );
1136
+
1137
+ if (targetIndex !== -1) {
1138
+ // Message exists in list, just scroll to it without refetching
1139
+ try {
1140
+ messageListRef.current?.scrollToIndex({
1141
+ index: targetIndex,
1142
+ animated: true,
1143
+ viewPosition: 0.5, // Center the message
1144
+ });
1145
+ highlightMessage(messageId);
1146
+ } catch (scrollError) {
1147
+ console.error('Error during scrollToIndex execution:', scrollError);
1148
+ // Fallback to offset scroll if scrollToIndex fails
1149
+ const approximateOffset = targetIndex * 120;
1150
+ messageListRef.current?.scrollToOffset({
1151
+ offset: approximateOffset,
1152
+ animated: true,
1153
+ });
1154
+ highlightMessage(messageId);
1155
+ }
1156
+ } else {
1157
+ getMessagesAroundId(messageId);
1158
+ }
1159
+ }
1160
+ };
1161
+
918
1162
  const getUpdatedPreviousMessages = () => {
919
1163
  // For agent chats (non-thread), don't fetch updated previous messages
920
1164
  if (isAgenticUser() && !parentMessageId) {
@@ -1008,6 +1252,7 @@ export const CometChatMessageList = memo(
1008
1252
  const isAgenticUserCheck = isAgenticUser();
1009
1253
  const options = {
1010
1254
  textFormatters: textFormatters || [],
1255
+ hideReplyOption: isAgenticUserCheck || hideReplyOption,
1011
1256
  hideReplyInThreadOption: isAgenticUserCheck || hideReplyInThreadOption,
1012
1257
  hideShareMessageOption: isAgenticUserCheck || hideShareMessageOption,
1013
1258
  hideEditMessageOption: isAgenticUserCheck || hideEditMessageOption,
@@ -1017,7 +1262,11 @@ export const CometChatMessageList = memo(
1017
1262
  hideMessagePrivatelyOption: isAgenticUserCheck || hideMessagePrivatelyOption,
1018
1263
  hideCopyMessageOption: isAgenticUserCheck || hideCopyMessageOption,
1019
1264
  hideMessageInfoOption: isAgenticUserCheck || hideMessageInfoOption,
1265
+ hideFlagMessageOption: isAgenticUserCheck || hideFlagMessageOption,
1020
1266
  hideGroupActionMessages,
1267
+ onReplyClick: (messageId: string) => {
1268
+ scrollToMessage(messageId);
1269
+ },
1021
1270
  };
1022
1271
  let _formatters = textFormatters || [];
1023
1272
  let tempTemplates: CometChatMessageTemplate[] =
@@ -1200,6 +1449,20 @@ export const CometChatMessageList = memo(
1200
1449
  }
1201
1450
  }, [parentMessageId, isAgenticUser]);
1202
1451
 
1452
+ // Handle scrolling to highlighted message when FlatList layout is complete
1453
+ useEffect(() => {
1454
+ let timer: any;
1455
+ if (scrollTargetId && messagesList.length > 0) {
1456
+ timer = setTimeout(() => {
1457
+ scrollToMessage(scrollTargetId);
1458
+ setScrollTargetId(null);
1459
+ }, 100);
1460
+ }
1461
+ return () => {
1462
+ if (timer) clearTimeout(timer);
1463
+ };
1464
+ }, [scrollTargetId, messagesList.length]);
1465
+
1203
1466
  function checkSameConversation(message: CometChat.BaseMessage): boolean {
1204
1467
  if ((message as any).isStreamMessage) {
1205
1468
  if (isAgenticUser()) {
@@ -1304,10 +1567,8 @@ export const CometChatMessageList = memo(
1304
1567
 
1305
1568
  const isAtBottom = () => {
1306
1569
  //0 or null
1307
- if (!currentScrollPosition.current.y) {
1308
- return true;
1309
- }
1310
- return false;
1570
+ const atBottom = !currentScrollPosition.current.y || currentScrollPosition.current.y === 0;
1571
+ return atBottom;
1311
1572
  };
1312
1573
 
1313
1574
  const bottomHandler = (
@@ -1357,7 +1618,7 @@ export const CometChatMessageList = memo(
1357
1618
  }
1358
1619
  };
1359
1620
 
1360
- const addToMessageList = (newMessage: CometChat.BaseMessage) => {
1621
+ const addToMessageList = async (newMessage: CometChat.BaseMessage) => {
1361
1622
  if (isAgenticUser() && !conversationId.current) {
1362
1623
  if (newMessage.getConversationId()) {
1363
1624
  conversationId.current = newMessage.getConversationId();
@@ -1376,28 +1637,30 @@ export const CometChatMessageList = memo(
1376
1637
  // ----------------------------------------------------------------------------------
1377
1638
  // Fix: Before inserting, check for an existing message with matching id OR muid.
1378
1639
  // If found, update it in place instead of inserting again.
1379
- try {
1380
- const incomingId = (newMessage as any)?.getId?.();
1381
- const incomingMuid = (newMessage as any)?.muid || (newMessage as any)?.getMuid?.();
1382
- const existingIndex = messagesContentListRef.current.findIndex((m: any) => {
1383
- const mid = m?.getId?.();
1384
- const mmuid = m?.muid || m?.getMuid?.();
1385
- return (
1386
- (incomingId && mid && String(mid) === String(incomingId)) ||
1387
- (incomingMuid && mmuid && String(mmuid) === String(incomingMuid))
1388
- );
1389
- });
1390
- if (existingIndex !== -1) {
1391
- // Update existing message instead of duplicating.
1392
- const updatedList = [...messagesContentListRef.current];
1393
- updatedList[existingIndex] = CommonUtils.clone(newMessage);
1394
- messagesContentListRef.current = updatedList;
1395
- onLoad && onLoad([...messagesContentListRef.current].reverse());
1396
- setMessagesList(updatedList);
1397
- return; // prevent duplicate insert
1640
+ if (!isAgenticUser) {
1641
+ try {
1642
+ const incomingId = (newMessage as any)?.getId?.();
1643
+ const incomingMuid = (newMessage as any)?.muid || (newMessage as any)?.getMuid?.();
1644
+ const existingIndex = messagesContentListRef.current.findIndex((m: any) => {
1645
+ const mid = m?.getId?.();
1646
+ const mmuid = m?.muid || m?.getMuid?.();
1647
+ return (
1648
+ (incomingId && mid && String(mid) === String(incomingId)) ||
1649
+ (incomingMuid && mmuid && String(mmuid) === String(incomingMuid))
1650
+ );
1651
+ });
1652
+ if (existingIndex !== -1) {
1653
+ // Update existing message instead of duplicating.
1654
+ const updatedList = [...messagesContentListRef.current];
1655
+ updatedList[existingIndex] = CommonUtils.clone(newMessage);
1656
+ messagesContentListRef.current = updatedList;
1657
+ onLoad && onLoad([...messagesContentListRef.current].reverse());
1658
+ setMessagesList(updatedList);
1659
+ return; // prevent duplicate insert
1660
+ }
1661
+ } catch (e) {
1662
+ console.log("Error in message de-duplication:", e);
1398
1663
  }
1399
- } catch (e) {
1400
- console.log('Error in message de-duplication:', e);
1401
1664
  }
1402
1665
 
1403
1666
  const isStreamMessage = (newMessage as any).isStreamMessage;
@@ -1424,8 +1687,20 @@ export const CometChatMessageList = memo(
1424
1687
  return;
1425
1688
  }
1426
1689
  }
1690
+ if (latestMessageRef.current !== null &&
1691
+ messagesContentListRef.current[0]?.id !== latestMessageRef.current.id
1692
+ && messagesContentListRef.current[0]?.muid !== latestMessageRef.current.muid
1693
+ ) {
1694
+ reachedFirstMessage.current = false;
1695
+ msgRequestBuilder.current?.setMessageId(0);
1696
+ messageRequest.current = msgRequestBuilder.current?.build() || null;
1697
+ messagesContentListRef.current = [];
1698
+ await getPreviousMessages();
1699
+ }
1427
1700
  messagesContentListRef.current = [newMessage, ...messagesContentListRef.current];
1428
1701
  onLoad && onLoad([...messagesContentListRef.current].reverse());
1702
+ latestMessageRef.current = newMessage;
1703
+ aMessageWasSentByMeRef.current = true;
1429
1704
  setMessagesList((prev) => [newMessage, ...prev]);
1430
1705
  };
1431
1706
 
@@ -1572,7 +1847,12 @@ export const CometChatMessageList = memo(
1572
1847
  messageRequest.current = msgRequestBuilder.current?.build() || null;
1573
1848
  }
1574
1849
  if (!isAgenticUser() || (isAgenticUser() && parentMessageId)) {
1575
- getPreviousMessages();
1850
+ if (goToMessageId) {
1851
+ getMessagesAroundId(goToMessageId);
1852
+ } else {
1853
+ getPreviousMessages();
1854
+ }
1855
+ fetchLatestMessage();
1576
1856
  }
1577
1857
  })
1578
1858
  .catch((e: any) => {
@@ -1589,6 +1869,28 @@ export const CometChatMessageList = memo(
1589
1869
  };
1590
1870
  }, []);
1591
1871
 
1872
+
1873
+ const fetchLatestMessage = useCallback(() => {
1874
+ const messageRequestBuilder = new CometChat.MessagesRequestBuilder()
1875
+ .setLimit(1)
1876
+ .setMessageId(0);
1877
+
1878
+ if (user) {
1879
+ messageRequestBuilder.setUID(user.getUid());
1880
+ }
1881
+ if (group) {
1882
+ messageRequestBuilder.setGUID(group.getGuid());
1883
+ }
1884
+ messageRequestBuilder
1885
+ .build()
1886
+ .fetchPrevious()
1887
+ .then((messages) => {
1888
+ if (messages[0]) {
1889
+ latestMessageRef.current = messages[0];
1890
+ }
1891
+ });
1892
+ }, []);
1893
+
1592
1894
  // Callback to add stream message and register queue completion callback
1593
1895
  const createStreamMessage = useCallback(
1594
1896
  (userMessage: CometChat.BaseMessage) => {
@@ -1819,7 +2121,7 @@ export const CometChatMessageList = memo(
1819
2121
  messageEdited(editedMessage);
1820
2122
  },
1821
2123
  onMessageModerated: (moderatedMessage: any) => {
1822
- messageEdited(moderatedMessage);
2124
+ !isAgenticUser() && messageEdited(moderatedMessage);
1823
2125
  },
1824
2126
  onFormMessageReceived: (formMessage: any) => {
1825
2127
  newMessage(formMessage);
@@ -2244,9 +2546,7 @@ export const CometChatMessageList = memo(
2244
2546
  else messageState = MessageReceipt.ERROR;
2245
2547
 
2246
2548
  // Moderation overrides
2247
- if (moderationStatus === "pending") {
2248
- messageState = MessageReceipt.WAIT; // show wait icon until approved/disapproved
2249
- } else if (moderationStatus === "disapproved") {
2549
+ if (moderationStatus === "disapproved") {
2250
2550
  messageState = MessageReceipt.ERROR;
2251
2551
  }
2252
2552
  // Determine if message has been edited.
@@ -2357,11 +2657,6 @@ export const CometChatMessageList = memo(
2357
2657
  messageObject?.getReactions &&
2358
2658
  messageObject?.getReactions() &&
2359
2659
  messageObject?.getReactions().length > 0;
2360
- const moderationStatus = getModerationStatus(messageObject);
2361
- const isOutgoing = messageObject.getSender()?.getUid() === loggedInUser.current?.getUid();
2362
- if (isOutgoing && moderationStatus && moderationStatus !== "unmoderated") {
2363
- return null;
2364
- }
2365
2660
  return hasReaction
2366
2661
  ? (params: { maxContentWidth?: number }) => {
2367
2662
  return (
@@ -2400,6 +2695,17 @@ export const CometChatMessageList = memo(
2400
2695
  setShowMessageOptions([]);
2401
2696
  };
2402
2697
 
2698
+ const openReportDialog = (message: any) => {
2699
+ reportedMessageRef.current = message;
2700
+ // On iOS wait for BottomSheet modal dismiss animation completion to avoid flashing
2701
+ if (Platform.OS === "ios") {
2702
+ pendingReportRef.current = true;
2703
+ } else {
2704
+ setShowReportDialog(true);
2705
+ }
2706
+ setShowMessageOptions([]);
2707
+ };
2708
+
2403
2709
  const openThreadView = (...params: any[]) => {
2404
2710
  if (onThreadRepliesPress) {
2405
2711
  onThreadRepliesPress(params[0], () => (
@@ -2431,8 +2737,8 @@ export const CometChatMessageList = memo(
2431
2737
  let _style = getCurrentBubbleStyle(item);
2432
2738
  const moderationStatus = getModerationStatus(item);
2433
2739
  const isOutgoing = item.getSender()?.getUid() === loggedInUser.current?.getUid();
2434
- if (isOutgoing && moderationStatus && moderationStatus !== "unmoderated") {
2435
- return undefined; // hide thread view if moderated
2740
+ if (isOutgoing && moderationStatus === "disapproved") {
2741
+ return undefined; // hide thread view if disapproved
2436
2742
  }
2437
2743
  return !isThreaded ? undefined : (
2438
2744
  <TouchableOpacity
@@ -2509,12 +2815,28 @@ export const CometChatMessageList = memo(
2509
2815
  ? template.options(loggedInUser.current, item, mergedTheme, group)
2510
2816
  : []
2511
2817
  : [];
2818
+ if (hideFlagMessageOption) {
2819
+ options = options.filter((opt: any) => opt.id !== MessageOptionConstants.reportMessage);
2820
+ }
2512
2821
  let optionsWithPressHandling = options.map((option) => {
2513
2822
  if (!option.onPress)
2514
2823
  switch (option.id) {
2515
2824
  case MessageOptionConstants.messageInformation:
2516
2825
  option.onPress = openMessageInfo.bind(this, item);
2517
2826
  break;
2827
+ case MessageOptionConstants.replyMessage:
2828
+ option.onPress = () => {
2829
+ // Trigger swipe-to-reply functionality
2830
+ CometChatMessageEvents.emit(CometChatMessageEvents.ccReplyToMessage, {
2831
+ message: item,
2832
+ status: messageStatus.inprogress,
2833
+ });
2834
+ setShowMessageOptions([]);
2835
+ };
2836
+ break;
2837
+ case MessageOptionConstants.reportMessage:
2838
+ option.onPress = openReportDialog.bind(this, item);
2839
+ break;
2518
2840
  case MessageOptionConstants.replyInThread:
2519
2841
  option.onPress = openThreadView.bind(this, item);
2520
2842
  break;
@@ -2649,7 +2971,7 @@ export const CometChatMessageList = memo(
2649
2971
  if (effectiveHideModeration) {
2650
2972
  return hasTemplate?.BottomView && hasTemplate?.BottomView(message, bubbleAlignment);
2651
2973
  } else {
2652
- if (isOutgoing && moderationStatus === "disapproved") {
2974
+ if (isOutgoing && moderationStatus === "disapproved" && !isAgenticUser()) {
2653
2975
  return (
2654
2976
  <ModerationBottomView
2655
2977
  status={moderationStatus}
@@ -2670,6 +2992,10 @@ export const CometChatMessageList = memo(
2670
2992
  : getStatusInfoView(message, bubbleAlignment, currentIndex);
2671
2993
  }, [hasTemplate, message, bubbleAlignment, currentIndex, getStatusInfoView]);
2672
2994
 
2995
+ const ReplyView = useMemo(() => {
2996
+ return hasTemplate?.ReplyView?.(message, bubbleAlignment) || null;
2997
+ }, [hasTemplate, message, bubbleAlignment]);
2998
+
2673
2999
  if (hasTemplate) {
2674
3000
  if (hasTemplate?.BubbleView) return hasTemplate?.BubbleView(message);
2675
3001
 
@@ -2691,25 +3017,121 @@ export const CometChatMessageList = memo(
2691
3017
  Keyboard.dismiss();
2692
3018
  }, []);
2693
3019
 
3020
+ // Swipe-to-reply functionality
3021
+ const onReply = useCallback(() => {
3022
+ if (message.getDeletedBy() != null) return;
3023
+ if (!message.getId()) return;
3024
+
3025
+ CometChatMessageEvents.emit(CometChatMessageEvents.ccReplyToMessage, {
3026
+ message: message,
3027
+ status: messageStatus.inprogress,
3028
+ });
3029
+ }, [message]);
3030
+
3031
+ const swipeAnimatedValue = useRef(new Animated.Value(0)).current;
3032
+ const replyIconOpacity = useRef(new Animated.Value(0)).current;
3033
+
3034
+ const handlePanGesture = useCallback((event: PanGestureHandlerGestureEvent) => {
3035
+ const { translationX, velocityX } = event.nativeEvent;
3036
+
3037
+ // Only allow swiping from left to right for replies
3038
+ if (translationX <= 0) return;
3039
+
3040
+ const swipeThreshold = 80; // Threshold to trigger reply
3041
+ const maxSwipeDistance = 120; // Maximum swipe distance
3042
+
3043
+ // Calculate progress (0 to 1)
3044
+ const progress = Math.min(translationX / maxSwipeDistance, 1);
3045
+
3046
+ // Update animated values
3047
+ swipeAnimatedValue.setValue(Math.min(translationX, maxSwipeDistance));
3048
+ replyIconOpacity.setValue(progress);
3049
+ }, []);
3050
+
3051
+ const handlePanStateChange = useCallback((event: PanGestureHandlerStateChangeEvent) => {
3052
+ const { state, translationX, velocityX } = event.nativeEvent;
3053
+
3054
+ if (state === State.END) {
3055
+ const swipeThreshold = 80;
3056
+
3057
+ // Reset animations
3058
+ Animated.parallel([
3059
+ Animated.spring(swipeAnimatedValue, {
3060
+ toValue: 0,
3061
+ useNativeDriver: true,
3062
+ }),
3063
+ Animated.spring(replyIconOpacity, {
3064
+ toValue: 0,
3065
+ useNativeDriver: true,
3066
+ }),
3067
+ ]).start();
3068
+
3069
+ const moderationStatus = getModerationStatus(message);
3070
+ const isOutgoing = message.getSender()?.getUid() === loggedInUser.current?.getUid();
3071
+ if (isOutgoing && moderationStatus && moderationStatus !== "approved" && moderationStatus !== "unmoderated") return;
3072
+
3073
+ // Trigger reply if threshold is met
3074
+ if (translationX > swipeThreshold || velocityX > 500) {
3075
+ onReply();
3076
+ }
3077
+ }
3078
+ }, [onReply, message]);
3079
+
2694
3080
  return (
2695
- <TouchableOpacity
2696
- activeOpacity={1}
2697
- onPress={Platform.OS === "ios" ? onPress : undefined}
2698
- onLongPress={() => (showOptions ? onLongPress() : undefined)}
2699
- >
2700
- <CometChatMessageBubble
2701
- id={`${message.getId()}`}
2702
- LeadingView={LeadingView}
2703
- HeaderView={HeaderView}
2704
- FooterView={FooterView}
2705
- alignment={isThreaded ? "left" : bubbleAlignment}
2706
- ContentView={ContentView}
2707
- ThreadView={ThreadedView}
2708
- BottomView={BottomView}
2709
- StatusInfoView={StatusInfoView}
2710
- style={getCurrentBubbleStyle(message)}
2711
- />
2712
- </TouchableOpacity>
3081
+ message.getCategory() === MessageCategoryConstants.action ? (
3082
+ <View style={{ position: 'relative' }}>
3083
+ <TouchableOpacity
3084
+ activeOpacity={1}
3085
+ onPress={Platform.OS === "ios" ? onPress : undefined}
3086
+ onLongPress={() => (showOptions ? onLongPress() : undefined)}
3087
+ >
3088
+ <CometChatMessageBubble
3089
+ id={`${message.getId()}`}
3090
+ LeadingView={LeadingView}
3091
+ HeaderView={HeaderView}
3092
+ FooterView={FooterView}
3093
+ ReplyView={ReplyView}
3094
+ alignment={isThreaded ? "left" : bubbleAlignment}
3095
+ ContentView={ContentView}
3096
+ ThreadView={ThreadedView}
3097
+ BottomView={BottomView}
3098
+ StatusInfoView={StatusInfoView}
3099
+ style={getCurrentBubbleStyle(message)}
3100
+ />
3101
+ </TouchableOpacity>
3102
+ </View>
3103
+ ) : (
3104
+ <PanGestureHandler
3105
+ onGestureEvent={handlePanGesture}
3106
+ onHandlerStateChange={handlePanStateChange}
3107
+ activeOffsetX={[-10, 10]}
3108
+ failOffsetY={[-50, 50]}
3109
+ >
3110
+ <Animated.View style={{ transform: [{ translateX: swipeAnimatedValue }] }}>
3111
+ <View style={{ position: 'relative' }}>
3112
+ <TouchableOpacity
3113
+ activeOpacity={1}
3114
+ onPress={Platform.OS === "ios" ? onPress : undefined}
3115
+ onLongPress={() => (showOptions ? onLongPress() : undefined)}
3116
+ >
3117
+ <CometChatMessageBubble
3118
+ id={`${message.getId()}`}
3119
+ LeadingView={LeadingView}
3120
+ HeaderView={HeaderView}
3121
+ FooterView={FooterView}
3122
+ ReplyView={ReplyView}
3123
+ alignment={isThreaded ? "left" : bubbleAlignment}
3124
+ ContentView={ContentView}
3125
+ ThreadView={ThreadedView}
3126
+ BottomView={BottomView}
3127
+ StatusInfoView={StatusInfoView}
3128
+ style={getCurrentBubbleStyle(message)}
3129
+ />
3130
+ </TouchableOpacity>
3131
+ </View>
3132
+ </Animated.View>
3133
+ </PanGestureHandler>
3134
+ )
2713
3135
  );
2714
3136
  } else {
2715
3137
  return null;
@@ -2724,6 +3146,7 @@ export const CometChatMessageList = memo(
2724
3146
  getFooterView,
2725
3147
  getLeadingView,
2726
3148
  getAlignment,
3149
+ highlightedMessageId,
2727
3150
  ]
2728
3151
  );
2729
3152
 
@@ -2839,30 +3262,6 @@ export const CometChatMessageList = memo(
2839
3262
  });
2840
3263
  }, [messagesList]);
2841
3264
 
2842
- const showDateSeparatorAtIndex = useMemo(() => {
2843
- const n = messagesList.length;
2844
- const flags = new Array<boolean>(n).fill(false);
2845
- // helper to find next non-null key to the right
2846
- const nextNonNullKey = (startIdx: number) => {
2847
- for (let j = startIdx; j < n; j++) {
2848
- if (messageDayKeys[j] != null) return messageDayKeys[j];
2849
- }
2850
- return null;
2851
- };
2852
-
2853
- for (let i = 0; i < n; i++) {
2854
- const currKey = messageDayKeys[i] ?? nextNonNullKey(i);
2855
- const nextKey = i + 1 < n ? (messageDayKeys[i + 1] ?? nextNonNullKey(i + 1)) : null;
2856
- if (currKey != null && currKey !== nextKey) {
2857
- flags[i] = true;
2858
- } else if (i === n - 1 && currKey != null) {
2859
- // last message in list show header
2860
- flags[i] = true;
2861
- }
2862
- }
2863
- return flags;
2864
- }, [messageDayKeys, messagesList.length]);
2865
-
2866
3265
  const isSameLocalDay = (ms?: number) => {
2867
3266
  if (!ms) return false;
2868
3267
  const a = new Date(ms);
@@ -2902,7 +3301,14 @@ export const CometChatMessageList = memo(
2902
3301
  [mergedTheme, isAgenticUser, messagesList, getSentAtTimestamp, dateSeparatorPattern]
2903
3302
  );
2904
3303
 
2905
- const keyExtractor = useCallback((item: any) => `${item?.getId()}_${item.getMuid()}`, []);
3304
+ const keyExtractor = useCallback((item: any) => {
3305
+ const id = item?.getId();
3306
+ const muid = item?.getMuid();
3307
+ if (!id && !muid) {
3308
+ console.log("item has no id or muid", item);
3309
+ }
3310
+ return `${id}_${muid}`;
3311
+ }, []);
2906
3312
 
2907
3313
  const itemSeparator = useCallback(() => <View style={{ height: 8 }} />, []);
2908
3314
 
@@ -3125,6 +3531,67 @@ export const CometChatMessageList = memo(
3125
3531
  );
3126
3532
  }, []);
3127
3533
 
3534
+ const fetchNextMessages = async () => {
3535
+ if (loadingMessagesRef.current || !hasTargetMessageId) return;
3536
+
3537
+ if (messagesContentListRef.current.length === 0) return;
3538
+
3539
+ const newestMessage = messagesContentListRef.current[0];
3540
+ const newestMessageId = newestMessage.getId();
3541
+ setBottomLoading(true);
3542
+ loadingMessagesRef.current = true;
3543
+
3544
+ try {
3545
+ let nextMessagesRequest = new CometChat.MessagesRequestBuilder()
3546
+ .setLimit(30)
3547
+ .setMessageId(newestMessageId);
3548
+
3549
+ if (user) {
3550
+ nextMessagesRequest = nextMessagesRequest.setUID(user.getUid());
3551
+ }
3552
+ if (group) {
3553
+ nextMessagesRequest = nextMessagesRequest.setGUID(group.getGuid());
3554
+ }
3555
+ if (parentMessageId) {
3556
+ nextMessagesRequest = nextMessagesRequest.setParentMessageId(Number(parentMessageId));
3557
+ }
3558
+
3559
+ const nextMessages = await nextMessagesRequest.build().fetchNext();
3560
+ if (nextMessages.length > 0) {
3561
+ const existingIds = new Set(messagesContentListRef.current.map(m => m.getId()));
3562
+ const uniqueNewMessages = nextMessages.filter(m => !existingIds.has(m.getId()));
3563
+
3564
+ if (uniqueNewMessages.length > 0) {
3565
+ const reversedNewMessages = uniqueNewMessages.reverse();
3566
+ messagesContentListRef.current = [
3567
+ ...reversedNewMessages,
3568
+ ...messagesContentListRef.current
3569
+ ];
3570
+
3571
+ setMessagesList(messagesContentListRef.current);
3572
+ onLoad && onLoad([...messagesContentListRef.current].reverse());
3573
+ }
3574
+ } else {
3575
+ setHasTargetMessageId(false);
3576
+ hasReachedBottomRef.current = true;
3577
+ }
3578
+ } catch (error) {
3579
+ console.error('[fetchNextMessages] Error:', error);
3580
+ } finally {
3581
+ setBottomLoading(false);
3582
+ loadingMessagesRef.current = false;
3583
+ }
3584
+ };
3585
+
3586
+ const renderFooter = () => {
3587
+ if (!bottomLoading) return null;
3588
+ return (
3589
+ <View style={{ padding: 10, alignItems: "center" }}>
3590
+ <ActivityIndicator size='small' color={mergedTheme.color.primary} />
3591
+ </View>
3592
+ );
3593
+ };
3594
+
3128
3595
  const handleScroll = (event: any) => {
3129
3596
  if (loadingMessagesRef.current) {
3130
3597
  return;
@@ -3141,7 +3608,9 @@ export const CometChatMessageList = memo(
3141
3608
  Math.floor(contentOffset.y) >= Math.floor(contentSize.height - layoutMeasurement.height)
3142
3609
  ) {
3143
3610
  getPreviousMessages();
3144
- //messageListRef.current?.scrollToOffset({offset: contentOffset.y})
3611
+ }
3612
+ if (hasTargetMessageId && contentOffset.y <= 50) {
3613
+ fetchNextMessages();
3145
3614
  }
3146
3615
  scrollHandler(event);
3147
3616
  };
@@ -3187,8 +3656,12 @@ export const CometChatMessageList = memo(
3187
3656
  };
3188
3657
 
3189
3658
  const scrollToBottom = useCallback((scrollToFirstUnread = false) => {
3190
- messageListRef.current?.scrollToOffset({ offset: 0 });
3191
- }, []);
3659
+ messageListRef.current?.scrollToOffset({ offset: 0 });
3660
+ // Clear navigation flags
3661
+ setHasTargetMessageId(false);
3662
+ setHighlightedMessageId(null);
3663
+ hasReachedBottomRef.current = true;
3664
+ }, [hasTargetMessageId, messagesList.length]);
3192
3665
 
3193
3666
  // const windowSize = useMemo(() => {
3194
3667
  // return messagesList.length > 50 ? messagesList.length / 2 : 21;
@@ -3197,27 +3670,59 @@ export const CometChatMessageList = memo(
3197
3670
  const memoizedRenderItem = useCallback(
3198
3671
  ({ item, index, separators }: any) => {
3199
3672
  // index here is FlatList's index in messagesList (newest-first)
3200
- const showSeparator = showDateSeparatorAtIndex[index];
3673
+ let showSeparator = false;
3674
+ const nextItem = messagesContentListRef.current[index + 1];
3675
+ {
3676
+ const currentItemMs = sentAtToMs(item);
3677
+ const nextItemMs = sentAtToMs(nextItem);
3678
+ if (currentItemMs && nextItemMs) {
3679
+ showSeparator = new Date(currentItemMs).getDate() !== new Date(nextItemMs).getDate();
3680
+ }
3681
+ if (index === messagesContentListRef.current.length - 1 && messagesContentListRef.current.length < 30) {
3682
+ showSeparator = true;
3683
+ }
3684
+ }
3201
3685
  const ms = sentAtToMs(item) ?? Date.now();
3686
+ const isHighlighted = highlightedMessageId === String(item.getId());
3687
+
3688
+ const separatorHeight = showSeparator ? 40 : 0;
3689
+
3690
+ const animatedBackgroundStyle = {
3691
+ backgroundColor: highlightAnimatedValue.interpolate({
3692
+ inputRange: [0, 1],
3693
+ outputRange: ['transparent', String(mergedTheme.color.extendedPrimary200)],
3694
+ }),
3695
+ position: 'absolute' as 'absolute',
3696
+ left: 0,
3697
+ right: 0,
3698
+ top: separatorHeight,
3699
+ bottom: 0,
3700
+ zIndex: 1,
3701
+ };
3202
3702
 
3203
3703
  return (
3204
- <View style={{ flex: 1, paddingHorizontal: 16, paddingVertical: 8 }}>
3205
- {showSeparator && (
3206
- <View style={{ alignItems: "center", marginBottom: 8 }}>
3207
- <CometChatDateSeparator
3208
- timeStamp={ms}
3209
- pattern={"dayDateFormat"}
3210
- customDateString={getDayHeaderString(ms)}
3211
- style={mergedTheme.messageListStyles.dateSeparatorStyle}
3212
- />
3213
- </View>
3704
+ <View style={{ flex: 1, paddingHorizontal: 16, paddingVertical: 8, position: 'relative' }}>
3705
+ {isHighlighted && (
3706
+ <Animated.View style={animatedBackgroundStyle} />
3214
3707
  )}
3215
- <RenderMessageItem item={item} theme={mergedTheme} idx={index} />
3216
- {itemSeparator()}
3708
+ <View style={{ position: 'relative', zIndex: 2 }}>
3709
+ {showSeparator && (
3710
+ <View style={{ alignItems: "center", marginBottom: 8 }}>
3711
+ <CometChatDateSeparator
3712
+ timeStamp={ms}
3713
+ pattern={"dayDateFormat"}
3714
+ customDateString={getDayHeaderString(ms)}
3715
+ style={mergedTheme.messageListStyles.dateSeparatorStyle}
3716
+ />
3717
+ </View>
3718
+ )}
3719
+ <RenderMessageItem item={item} theme={mergedTheme} idx={index} />
3720
+ {itemSeparator()}
3721
+ </View>
3217
3722
  </View>
3218
3723
  );
3219
3724
  },
3220
- [mergedTheme, showDateSeparatorAtIndex, dateSeparatorPattern, messageDayKeys]
3725
+ [mergedTheme, highlightedMessageId]
3221
3726
  );
3222
3727
 
3223
3728
  return (
@@ -3226,7 +3731,7 @@ export const CometChatMessageList = memo(
3226
3731
  getLoadingStateView()
3227
3732
  ) : listState == "error" ? (
3228
3733
  getErrorStateView()
3229
- ) : listState == "" || listState == "loaded" ? (
3734
+ ) : (
3230
3735
  messagesList.length == 0 ? (
3231
3736
  getEmptyStateView()
3232
3737
  ) : (
@@ -3249,6 +3754,9 @@ export const CometChatMessageList = memo(
3249
3754
  <ActivityIndicator size='small' color={mergedTheme.color.primary} />
3250
3755
  </View>
3251
3756
  )}
3757
+
3758
+ {/* Navigation loading for far message fetching */}
3759
+ {navigationLoading && getLoadingStateView()}
3252
3760
 
3253
3761
  <FlatList
3254
3762
  showsVerticalScrollIndicator={false}
@@ -3256,11 +3764,30 @@ export const CometChatMessageList = memo(
3256
3764
  onMomentumScrollEnd={handleScroll}
3257
3765
  onScroll={shouldShowScrollToBottomButton}
3258
3766
  inverted={true}
3767
+ maintainVisibleContentPosition={{
3768
+ minIndexForVisible: 0,
3769
+ }}
3770
+ onEndReached={getPreviousMessages}
3771
+ onEndReachedThreshold={0.5}
3772
+ onStartReached={fetchNextMessages}
3773
+ onStartReachedThreshold={0.5}
3259
3774
  scrollEventThrottle={16}
3260
3775
  keyboardShouldPersistTaps={Platform.OS === "ios" ? "handled" : "always"}
3261
3776
  data={messagesList}
3262
3777
  keyExtractor={keyExtractor}
3263
3778
  renderItem={memoizedRenderItem}
3779
+ onLayout={() => {
3780
+ setIsListLayoutComplete(true);
3781
+ }}
3782
+ ListHeaderComponent={renderFooter}
3783
+ onScrollToIndexFailed={(error) => {
3784
+ const averageItemLength = error.averageItemLength || 120;
3785
+ const targetOffset = error.index * averageItemLength;
3786
+ messageListRef.current?.scrollToOffset({
3787
+ offset: targetOffset,
3788
+ animated: true,
3789
+ });
3790
+ }}
3264
3791
  /**Please do not push changes to windowSize without testing infinite scroll and UI interactions and response time**/
3265
3792
  /**Test the same on release mode. Dev mode could be laggy**/
3266
3793
  windowSize={33}
@@ -3283,7 +3810,7 @@ export const CometChatMessageList = memo(
3283
3810
  )}
3284
3811
  </View>
3285
3812
  )
3286
- ) : null}
3813
+ )}
3287
3814
 
3288
3815
  {!hideScrollToBottomButton && (
3289
3816
  <Pressable
@@ -3330,6 +3857,24 @@ export const CometChatMessageList = memo(
3330
3857
  }}
3331
3858
  />
3332
3859
 
3860
+ <CometChatReportDialog
3861
+ isOpen={showReportDialog}
3862
+ message={reportedMessageRef.current || undefined}
3863
+ onCancel={() => {
3864
+ setShowReportDialog(false);
3865
+ reportedMessageRef.current = null;
3866
+ }}
3867
+ hideFlagRemarkField={hideFlagRemarkField}
3868
+ onReport={(payload) => {
3869
+ console.log("Report submitted", {
3870
+ messageId: payload.message?.getId?.(),
3871
+ payload,
3872
+ });
3873
+ setShowReportDialog(false);
3874
+ reportedMessageRef.current = null;
3875
+ }}
3876
+ />
3877
+
3333
3878
  <CometChatBottomSheet
3334
3879
  ref={bottomSheetRef}
3335
3880
  onClose={() => {
@@ -3339,8 +3884,16 @@ export const CometChatMessageList = memo(
3339
3884
  setMessageInfo(false);
3340
3885
  }}
3341
3886
  onDismiss={() => {
3342
- // console.log(deleteItem.current, "CometChatBottomSheet onDismiss")
3343
- Platform.OS === "ios" && deleteItem.current && setShowDeleteModal(true);
3887
+ // iOS: Open any deferred modals only after dismiss animation completes
3888
+ if (Platform.OS === "ios") {
3889
+ if (deleteItem.current) {
3890
+ setShowDeleteModal(true);
3891
+ }
3892
+ if (pendingReportRef.current) {
3893
+ pendingReportRef.current = false;
3894
+ setShowReportDialog(true);
3895
+ }
3896
+ }
3344
3897
  }}
3345
3898
  isOpen={showMessageOptions.length > 0 || Boolean(ExtensionsComponent) || messageInfo}
3346
3899
  style={{