@cometchat/chat-uikit-react-native 5.3.4 → 5.3.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cometchat/chat-uikit-react-native",
3
- "version": "5.3.4",
3
+ "version": "5.3.5",
4
4
  "description": "Ready-to-use Chat UI Components for React Native",
5
5
  "main": "src/index",
6
6
  "module": "src/index",
@@ -300,6 +300,9 @@ export const CometChatConversations = (props: ConversationInterface) => {
300
300
  const conversationListRef = React.useRef<CometChatListActionsInterface>(null);
301
301
  // Store the logged in user for comparison and event handling.
302
302
  const loggedInUser = React.useRef<CometChat.User>(undefined);
303
+ // Buffer receipts by messageId to handle race conditions where receipts arrive
304
+ // before the message becomes the conversation's last message (due to async updateLastMessage)
305
+ const pendingReceiptsMap = React.useRef<Map<string, { readAt?: number; deliveredAt?: number }>>(new Map());
303
306
  // State to control the confirmation dialog for deleting a conversation.
304
307
  const [confirmDelete, setConfirmDelete] = React.useState<string | undefined>(undefined);
305
308
  // State to control selection mode for conversation items.
@@ -445,6 +448,7 @@ export const CometChatConversations = (props: ConversationInterface) => {
445
448
  (conversationListRef.current?.getListItem(
446
449
  `${loggedInUser.current?.getUid()}_user_${uid}`
447
450
  ) as unknown as CometChat.Conversation);
451
+ if (!item) return;
448
452
  const user: CometChat.User = item.getConversationWith();
449
453
  if (user.getBlockedByMe() || user.getHasBlockedMe()) return;
450
454
  if (item) {
@@ -513,6 +517,31 @@ export const CometChatConversations = (props: ConversationInterface) => {
513
517
  if (!conver) return;
514
518
  let lastMessageId = conver.getLastMessage().getId();
515
519
  if (lastMessageId == newMessage.getId()) {
520
+ // Preserve the real-time user status from the existing conversation.
521
+ // The server-returned conversation may have stale user status/lastActiveAt.
522
+ const existingWith = conver.getConversationWith();
523
+ const newWith = conversation.getConversationWith();
524
+ if (existingWith instanceof CometChat.User && newWith instanceof CometChat.User) {
525
+ if (existingWith.getStatus() === "online" && newWith.getStatus() !== "online") {
526
+ newWith.setStatus("online");
527
+ const existingLastActive = existingWith.getLastActiveAt();
528
+ if (existingLastActive) {
529
+ newWith.setLastActiveAt(existingLastActive);
530
+ }
531
+ }
532
+ }
533
+ // Preserve receipt status from the existing conversation if the server-returned
534
+ // conversation has stale receipt info (due to async timing)
535
+ const existingLastMsg = conver.getLastMessage();
536
+ const newLastMsg = conversation.getLastMessage();
537
+ if (existingLastMsg && newLastMsg && existingLastMsg.getId() === newLastMsg.getId()) {
538
+ if (existingLastMsg.getReadAt?.() && !newLastMsg.getReadAt?.()) {
539
+ newLastMsg.setReadAt(existingLastMsg.getReadAt());
540
+ }
541
+ if (existingLastMsg.getDeliveredAt?.() && !newLastMsg.getDeliveredAt?.()) {
542
+ newLastMsg.setDeliveredAt(existingLastMsg.getDeliveredAt());
543
+ }
544
+ }
516
545
  conversationListRef.current!.updateList(CommonUtils.clone(conversation));
517
546
  }
518
547
  }
@@ -593,6 +622,29 @@ export const CometChatConversations = (props: ConversationInterface) => {
593
622
  .catch((err) => onError && onError(err));
594
623
  return;
595
624
  }
625
+ // Preserve receipt status if the existing last message is the same message
626
+ // (receipts may have arrived while this async operation was in flight)
627
+ const existingLastMessage = oldConversation.getLastMessage();
628
+ if (existingLastMessage && existingLastMessage.getId() === newMessage.getId()) {
629
+ if (existingLastMessage.getReadAt?.() && !newMessage.getReadAt?.()) {
630
+ newMessage.setReadAt(existingLastMessage.getReadAt());
631
+ }
632
+ if (existingLastMessage.getDeliveredAt?.() && !newMessage.getDeliveredAt?.()) {
633
+ newMessage.setDeliveredAt(existingLastMessage.getDeliveredAt());
634
+ }
635
+ }
636
+ // Also check if a receipt arrived BEFORE this message was set as lastMessage
637
+ // (race condition: receipt fires before updateLastMessage completes)
638
+ const newMsgId = String(newMessage.getId?.() ?? "");
639
+ const bufferedReceipt = pendingReceiptsMap.current.get(newMsgId);
640
+ if (bufferedReceipt) {
641
+ if (bufferedReceipt.readAt && !newMessage.getReadAt?.()) {
642
+ newMessage.setReadAt(bufferedReceipt.readAt);
643
+ }
644
+ if (bufferedReceipt.deliveredAt && !newMessage.getDeliveredAt?.()) {
645
+ newMessage.setDeliveredAt(bufferedReceipt.deliveredAt);
646
+ }
647
+ }
596
648
  // Update last message and unread count.
597
649
  oldConversation.setLastMessage(newMessage);
598
650
  if (newMessage.getSender().getUid() != loggedInUser.current?.getUid())
@@ -641,6 +693,17 @@ export const CometChatConversations = (props: ConversationInterface) => {
641
693
  * @param receipt - The message receipt.
642
694
  */
643
695
  const updateMessageReceipt = (receipt: CometChat.MessageReceipt) => {
696
+ const receiptMessageId = typeof (receipt as any).getMessageId === 'function' ? String((receipt as any).getMessageId()) : String((receipt as any)["messageId"] ?? "");
697
+
698
+ // Always buffer the receipt by messageId — this handles race conditions where
699
+ // the receipt arrives before updateLastMessage has set the message as lastMessage
700
+ if (receiptMessageId) {
701
+ const existing = pendingReceiptsMap.current.get(receiptMessageId) || {};
702
+ if (receipt.getReadAt()) existing.readAt = receipt.getReadAt();
703
+ if (receipt.getDeliveredAt()) existing.deliveredAt = receipt.getDeliveredAt();
704
+ pendingReceiptsMap.current.set(receiptMessageId, existing);
705
+ }
706
+
644
707
  const conv: CometChat.Conversation | boolean =
645
708
  receipt?.getReceiverType() === ReceiverTypeConstants.user
646
709
  ? (conversationListRef.current?.getListItem(
@@ -659,25 +722,44 @@ export const CometChatConversations = (props: ConversationInterface) => {
659
722
 
660
723
  if (
661
724
  conv &&
662
- conv.getConversationType() == ConversationTypeConstants.group &&
663
- conv.getLastMessage().getSender().getUid() !== loggedInUser.current!.getUid()
725
+ (conv as CometChat.Conversation).getConversationType() == ConversationTypeConstants.group &&
726
+ (conv as CometChat.Conversation).getLastMessage().getSender().getUid() !== loggedInUser.current!.getUid()
664
727
  ) {
665
728
  return;
666
729
  }
667
730
 
668
- if (
669
- conv &&
670
- conv?.getLastMessage &&
671
- (String(typeof conv.getLastMessage().getId === 'function' ? conv.getLastMessage().getId() : conv.getLastMessage().id) === String(receipt.getMessageId()))
672
- ) {
673
- let newConversation = CommonUtils.clone(conv);
674
- if (receipt.getReadAt()) {
675
- newConversation.getLastMessage().setReadAt(receipt.getReadAt());
731
+ if (conv && (conv as CometChat.Conversation)?.getLastMessage) {
732
+ let newConversation = CommonUtils.clone(conv as CometChat.Conversation);
733
+ const lastMessage = newConversation.getLastMessage();
734
+
735
+ // Only update if the last message was sent by the logged-in user (receipts are for outgoing messages)
736
+ if (lastMessage?.getSender?.()?.getUid?.() !== loggedInUser.current?.getUid()) {
737
+ return;
676
738
  }
677
- if (receipt.getDeliveredAt()) {
678
- newConversation.getLastMessage().setDeliveredAt(receipt.getDeliveredAt());
739
+
740
+ // Apply any buffered receipt for this specific message
741
+ const lastMsgId = String(lastMessage?.getId?.() ?? "");
742
+ const pending = pendingReceiptsMap.current.get(lastMsgId);
743
+
744
+ let updated = false;
745
+
746
+ // Apply read status — never downgrade (if already read, skip)
747
+ const readAtToApply = pending?.readAt || (receipt.getReadAt() && String(receiptMessageId) === lastMsgId ? receipt.getReadAt() : undefined);
748
+ if (readAtToApply && !lastMessage.getReadAt?.()) {
749
+ lastMessage.setReadAt(readAtToApply);
750
+ updated = true;
751
+ }
752
+
753
+ // Apply delivered status — never downgrade (if already read or delivered, skip delivered)
754
+ const deliveredAtToApply = pending?.deliveredAt || (receipt.getDeliveredAt() && String(receiptMessageId) === lastMsgId ? receipt.getDeliveredAt() : undefined);
755
+ if (deliveredAtToApply && !lastMessage.getDeliveredAt?.() && !lastMessage.getReadAt?.()) {
756
+ lastMessage.setDeliveredAt(deliveredAtToApply);
757
+ updated = true;
758
+ }
759
+
760
+ if (updated) {
761
+ conversationListRef.current?.updateList(newConversation);
679
762
  }
680
- conversationListRef.current?.updateList(newConversation);
681
763
  }
682
764
  };
683
765
 
@@ -1156,7 +1238,11 @@ export const CometChatConversations = (props: ConversationInterface) => {
1156
1238
  * @returns The updated conversation.
1157
1239
  */
1158
1240
  const updateUnreadMessageCount = (conversation: CometChat.Conversation) => {
1159
- const oldConversation: CometChat.Conversation = conversationListRef.current!.getListItem(
1241
+ if (!conversationListRef.current) {
1242
+ conversation.setUnreadMessageCount(1);
1243
+ return conversation;
1244
+ }
1245
+ const oldConversation: CometChat.Conversation = conversationListRef.current.getListItem(
1160
1246
  conversation["conversationId"]
1161
1247
  ) as unknown as CometChat.Conversation;
1162
1248
  if (oldConversation == undefined) {
@@ -1201,7 +1287,7 @@ export const CometChatConversations = (props: ConversationInterface) => {
1201
1287
  }
1202
1288
  conversation = updateUnreadMessageCount(conversation);
1203
1289
  conversation.setLastMessage(call);
1204
- conversationListRef.current!.updateList(conversation);
1290
+ conversationListRef.current?.updateList(conversation);
1205
1291
  })
1206
1292
  .catch((e) => {
1207
1293
  onError && onError(e);
@@ -1215,7 +1301,7 @@ export const CometChatConversations = (props: ConversationInterface) => {
1215
1301
  }
1216
1302
  conversation = updateUnreadMessageCount(conversation);
1217
1303
  conversation.setLastMessage(call);
1218
- conversationListRef.current!.updateList(conversation);
1304
+ conversationListRef.current?.updateList(conversation);
1219
1305
  })
1220
1306
  .catch((e) => {
1221
1307
  onError && onError(e);
@@ -1229,7 +1315,7 @@ export const CometChatConversations = (props: ConversationInterface) => {
1229
1315
  }
1230
1316
  conversation = updateUnreadMessageCount(conversation);
1231
1317
  conversation.setLastMessage(call);
1232
- conversationListRef.current!.updateList(conversation);
1318
+ conversationListRef.current?.updateList(conversation);
1233
1319
  })
1234
1320
  .catch((e) => {
1235
1321
  onError && onError(e);
@@ -1243,7 +1329,7 @@ export const CometChatConversations = (props: ConversationInterface) => {
1243
1329
  }
1244
1330
  conversation = updateUnreadMessageCount(conversation);
1245
1331
  conversation.setLastMessage(call);
1246
- conversationListRef.current!.updateList(conversation);
1332
+ conversationListRef.current?.updateList(conversation);
1247
1333
  })
1248
1334
  .catch((e) => {
1249
1335
  onError && onError(e);
@@ -1434,6 +1520,9 @@ export const CometChatConversations = (props: ConversationInterface) => {
1434
1520
  messageEventHandler(customInteractiveMessage);
1435
1521
  !disableSoundForMessages && CometChatSoundManager.play("incomingMessage");
1436
1522
  },
1523
+ onMessageModerated: (moderatedMessage: CometChat.BaseMessage) => {
1524
+ checkAndUpdateLastMessage(moderatedMessage);
1525
+ },
1437
1526
  });
1438
1527
  // Listen for additional group events.
1439
1528
  CometChatUIEventHandler.addGroupListener(groupListenerId, {
@@ -1114,7 +1114,13 @@ export const CometChatMessageList = memo(
1114
1114
  // as the user might want to keep messages unread for reference.
1115
1115
  if (messagesList.length === 0 && !navigatedFromSearch) {
1116
1116
  //marking most recent unread message as read
1117
- if (user) {
1117
+ // Use markAsRead on the latest message instead of markConversationAsRead
1118
+ // to avoid marking thread replies as read when user only opens the main chat.
1119
+ if (!parentMessageId && lastMessage) {
1120
+ CometChat.markAsRead(lastMessage).catch((e: any) => {
1121
+ console.log("Error marking message as read", e);
1122
+ });
1123
+ } else if (user) {
1118
1124
  CometChat.markConversationAsRead(user.getUid(), CometChat.RECEIVER_TYPE.USER).catch((e) => {
1119
1125
  console.log("Error marking user conversation as read", e);
1120
1126
  });
@@ -1146,7 +1152,8 @@ export const CometChatMessageList = memo(
1146
1152
  CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, {
1147
1153
  message,
1148
1154
  });
1149
- } else break;
1155
+ }
1156
+ else break;
1150
1157
  }
1151
1158
  }
1152
1159
  previousMessagesFetched = previousMessagesFetched.map(
@@ -1304,7 +1311,13 @@ export const CometChatMessageList = memo(
1304
1311
  if (startFromUnreadMessages && isInitialLoad && !navigatedFromSearch && !goToMessageId) {
1305
1312
  shouldSuppressHighlightRef.current = true;
1306
1313
  //marking most recent unread message as read
1307
- if (user) {
1314
+ // Use markAsRead on the latest message instead of markConversationAsRead
1315
+ // to avoid marking thread replies as read when user only opens the main chat.
1316
+ if (!parentMessageId && uniqueMessages[0]) {
1317
+ CometChat.markAsRead(uniqueMessages[0]).catch((e: any) => {
1318
+ console.log("Error marking message as read", e);
1319
+ });
1320
+ } else if (user) {
1308
1321
  CometChat.markConversationAsRead(user.getUid(), CometChat.RECEIVER_TYPE.USER).catch((e) => {
1309
1322
  console.log("Error marking user conversation as read", e);
1310
1323
  });
@@ -4444,7 +4457,13 @@ export const CometChatMessageList = memo(
4444
4457
  );
4445
4458
 
4446
4459
  if (indicatorItem) {
4447
- if (user) {
4460
+ // Use markAsRead on the indicator message instead of markConversationAsRead
4461
+ // to avoid marking thread replies as read when user only views the main chat.
4462
+ if (!parentMessageId && indicatorItem.item) {
4463
+ CometChat.markAsRead(indicatorItem.item).catch((e: any) => {
4464
+ console.log("Error marking message as read", e);
4465
+ });
4466
+ } else if (user) {
4448
4467
  CometChat.markConversationAsRead(user.getUid(), CometChat.RECEIVER_TYPE.USER).catch((e) => {
4449
4468
  console.log("Error marking user conversation as read", e);
4450
4469
  });
@@ -4456,7 +4475,7 @@ export const CometChatMessageList = memo(
4456
4475
  setUnreadCount(0);
4457
4476
  }
4458
4477
  }
4459
- }, [navigatedFromSearch, newMessageIndicatorId, unreadCount, user, group, hasManuallyMarkedUnread]);
4478
+ }, [navigatedFromSearch, newMessageIndicatorId, unreadCount, user, group, hasManuallyMarkedUnread, parentMessageId]);
4460
4479
 
4461
4480
 
4462
4481
 
@@ -56,9 +56,11 @@ export const LinkPreviewBubble = (props: LinkPreviewBubbleInterface) => {
56
56
 
57
57
  const _style = style;
58
58
 
59
- const [imageSource, setImageSource] = useState({
60
- uri: image.startsWith("https:") ? image : `https:${image.split("http:")[1]}`,
61
- });
59
+ const [imageSource, setImageSource] = useState(
60
+ image
61
+ ? { uri: image.startsWith("https:") ? image : `https:${image.split("http:")[1]}` }
62
+ : undefined
63
+ );
62
64
 
63
65
  const [imageHeight, setImageHeight] = useState<DimensionValue>();
64
66
  const [imageWidth, setImageWidth] = useState<DimensionValue>();
@@ -145,20 +147,22 @@ export const LinkPreviewBubble = (props: LinkPreviewBubbleInterface) => {
145
147
  onTouchEnd={handleTouchEnd}
146
148
  onTouchMove={onTouchMove}
147
149
  >
148
- <View
149
- style={style?.headerImageContainerStyle}
150
- onTouchStart={handleTouchStart}
151
- onTouchEnd={handleTouchEnd}
152
- onTouchMove={onTouchMove}
153
- >
154
- <Image
155
- source={imageSource}
156
- style={[{ height: imageHeight, width: imageWidth }, style?.headerImageStyle]}
157
- onError={(err) => {
158
- setImageSource(DefaultLinkPreview);
159
- }}
160
- />
161
- </View>
150
+ {imageSource ? (
151
+ <View
152
+ style={style?.headerImageContainerStyle}
153
+ onTouchStart={handleTouchStart}
154
+ onTouchEnd={handleTouchEnd}
155
+ onTouchMove={onTouchMove}
156
+ >
157
+ <Image
158
+ source={imageSource}
159
+ style={[{ height: imageHeight, width: imageWidth }, style?.headerImageStyle]}
160
+ onError={(err) => {
161
+ setImageSource(DefaultLinkPreview);
162
+ }}
163
+ />
164
+ </View>
165
+ ) : null}
162
166
 
163
167
  <View style={style?.bodyStyle?.containerStyle}>
164
168
  <View style={{ flexDirection: "row" }}>
@@ -168,7 +172,7 @@ export const LinkPreviewBubble = (props: LinkPreviewBubbleInterface) => {
168
172
  </Text>
169
173
  </View>
170
174
 
171
- {!faviconError && (
175
+ {!imageSource && !faviconError && (
172
176
  <View style={style?.bodyStyle?.faviconContainerStyle}>
173
177
  <Image
174
178
  source={faviconSource}
@@ -69,7 +69,7 @@ export class LinkPreviewExtensionDecorator extends DataSourceDecorator {
69
69
  ? theme.messageListStyles?.outgoingMessageBubbleStyles?.linkPreviewBubbleStyles
70
70
  : theme.messageListStyles?.incomingMessageBubbleStyles?.linkPreviewBubbleStyles;
71
71
  const { image, favicon, title, url, description } = linkData.links[0];
72
- const img = image.length === 0 ? favicon : image;
72
+ const img = image.length === 0 || image === favicon ? "" : image;
73
73
  return (
74
74
  <LinkPreviewBubble
75
75
  link={url}
@@ -48,7 +48,11 @@ export class ThumbnailGenerationExtensionDecorator extends DataSourceDecorator {
48
48
  let image: { uri: string } = { uri: "" };
49
49
  const thumbnailData = getExtensionData(message, ExtensionConstants.thumbnailGeneration);
50
50
  if (thumbnailData == undefined) {
51
- image = message.getType() === "image" ? { uri: (message?.getData() as any)?.url } : image;
51
+ if (message.getType() === "image") {
52
+ const data = message?.getData() as any;
53
+ const fallbackUrl = data?.url ?? data?.attachments?.[0]?.url ?? "";
54
+ image = { uri: fallbackUrl };
55
+ }
52
56
  } else {
53
57
  const attachmentData = thumbnailData["attachments"];
54
58
  if (attachmentData.length) {
@@ -12,7 +12,6 @@ export const MessageReceiptUtils = {
12
12
  // Moderation status (if available)
13
13
  const moderationStatus = getModerationStatus(message);
14
14
  if (moderationStatus === "disapproved") return MessageReceipt.ERROR;
15
- if (moderationStatus === "pending") return MessageReceipt.WAIT;
16
15
 
17
16
  // Explicit error markers
18
17
  const hasError = (message as any)?.error || (message as any)?.metadata?.error;
@@ -240,53 +240,68 @@ export function useAudioRecorder(): UseAudioRecorderReturn {
240
240
 
241
241
  /**
242
242
  * Duration timer effect - increments duration during recording state.
243
- * Replicates the EXACT logic from the old Timer component in CometChatMediaRecorder/Timer.tsx:
244
- * - Uses a local ref to track time in milliseconds
245
- * - Increments by 1000ms every second when recording (not paused)
246
- * - Freezes (stops incrementing) when paused - time value is preserved
247
- * - Resets to 0 when going back to idle state
248
- *
249
- * The old Timer component:
250
- * - Used `time` state in seconds, incremented by 1 every 1000ms
251
- * - We use milliseconds for consistency with the rest of the codebase
243
+ * Uses wall-clock time (Date.now()) for accurate duration tracking,
244
+ * combined with a preserved offset for pause/resume support.
252
245
  *
253
246
  * @validates Requirements 1.4, 3.1
254
247
  */
255
248
  const timerValueRef = useRef<number>(0);
249
+ const segmentStartTimeRef = useRef<number>(0);
250
+ /** Duration accumulated before the current active recording segment started. */
251
+ const offsetAtSegmentStartRef = useRef<number>(0);
252
+ /** Timestamp captured at the moment the user initiates a pause, before the async native call. */
253
+ const pauseRequestedAtRef = useRef<number>(0);
256
254
 
257
255
  useEffect(() => {
258
256
  if (reducerState.state === 'recording') {
259
- // Not paused -> start counting (increment every 1 second like old Timer)
260
- // This matches: intervalRef.current = setInterval(() => { setTime((prev) => prev + 1); }, 1000);
257
+ // Capture wall-clock start and the offset accumulated so far
258
+ segmentStartTimeRef.current = Date.now();
259
+ offsetAtSegmentStartRef.current = timerValueRef.current;
260
+ pauseRequestedAtRef.current = 0;
261
+
262
+ // Tick every 500ms, compute elapsed from Date.now() for accuracy
261
263
  durationTimerRef.current = setInterval(() => {
262
- timerValueRef.current += 1000; // Increment by 1000ms (1 second)
263
- dispatch({ type: 'UPDATE_DURATION', duration: timerValueRef.current });
264
- }, 1000);
264
+ const elapsed = Date.now() - segmentStartTimeRef.current;
265
+ const totalMs = offsetAtSegmentStartRef.current + elapsed;
266
+ timerValueRef.current = totalMs;
267
+ dispatch({ type: 'UPDATE_DURATION', duration: totalMs });
268
+ }, 500);
265
269
  } else if (reducerState.state === 'paused') {
266
- // Paused -> clear interval, so time is frozen (but value preserved in timerValueRef)
267
- // This matches the old Timer's behavior when paused=true
270
+ // Paused -> stop interval, snap to exact elapsed time
268
271
  if (durationTimerRef.current) {
269
272
  clearInterval(durationTimerRef.current);
270
273
  durationTimerRef.current = null;
271
274
  }
272
- // Note: timerValueRef.current is NOT reset here - time is frozen but preserved
275
+ if (segmentStartTimeRef.current > 0) {
276
+ // Use the timestamp from when pause was requested (before the async native call)
277
+ // to avoid overcounting the time the native call took to complete.
278
+ const pauseTime = pauseRequestedAtRef.current > 0
279
+ ? pauseRequestedAtRef.current
280
+ : Date.now();
281
+ const elapsed = pauseTime - segmentStartTimeRef.current;
282
+ timerValueRef.current = offsetAtSegmentStartRef.current + Math.max(0, elapsed);
283
+ dispatch({ type: 'UPDATE_DURATION', duration: timerValueRef.current });
284
+ segmentStartTimeRef.current = 0;
285
+ pauseRequestedAtRef.current = 0;
286
+ }
273
287
  } else if (reducerState.state === 'idle') {
274
- // Reset timer when going back to idle (like resetKey changing in old Timer)
288
+ // Reset everything
275
289
  timerValueRef.current = 0;
290
+ segmentStartTimeRef.current = 0;
291
+ offsetAtSegmentStartRef.current = 0;
292
+ pauseRequestedAtRef.current = 0;
276
293
  if (durationTimerRef.current) {
277
294
  clearInterval(durationTimerRef.current);
278
295
  durationTimerRef.current = null;
279
296
  }
280
297
  } else {
281
298
  // For other states (completed, playing, error), just stop the interval
282
- // but preserve the duration value
283
299
  if (durationTimerRef.current) {
284
300
  clearInterval(durationTimerRef.current);
285
301
  durationTimerRef.current = null;
286
302
  }
287
303
  }
288
304
 
289
- // Cleanup when unmounting or when effect re-runs
290
305
  return () => {
291
306
  if (durationTimerRef.current) {
292
307
  clearInterval(durationTimerRef.current);
@@ -502,8 +517,11 @@ export function useAudioRecorder(): UseAudioRecorderReturn {
502
517
  // Reset state for new recording
503
518
  pausedDurationRef.current = 0;
504
519
  recordingStartTimeRef.current = 0;
505
- // Reset timer value for new recording (like resetKey in old Timer)
520
+ // Reset timer value for new recording
506
521
  timerValueRef.current = 0;
522
+ segmentStartTimeRef.current = 0;
523
+ offsetAtSegmentStartRef.current = 0;
524
+ pauseRequestedAtRef.current = 0;
507
525
 
508
526
  return new Promise((resolve, reject) => {
509
527
  NativeModules.FileManager.startRecording((result: string) => {
@@ -552,6 +570,17 @@ export function useAudioRecorder(): UseAudioRecorderReturn {
552
570
  return;
553
571
  }
554
572
 
573
+ // Capture the exact moment pause was requested, before the async native call.
574
+ // This prevents the timer from overcounting while the native call completes.
575
+ pauseRequestedAtRef.current = Date.now();
576
+
577
+ // Stop the duration timer immediately so it doesn't keep ticking
578
+ // while the async native call completes.
579
+ if (durationTimerRef.current) {
580
+ clearInterval(durationTimerRef.current);
581
+ durationTimerRef.current = null;
582
+ }
583
+
555
584
  try {
556
585
  // Save current amplitudes for this segment
557
586
  const currentAmplitudes = [...reducerState.amplitudes];
@@ -1253,6 +1282,9 @@ export function useAudioRecorder(): UseAudioRecorderReturn {
1253
1282
  pausedDurationRef.current = 0;
1254
1283
  recordingStartTimeRef.current = 0;
1255
1284
  timerValueRef.current = 0;
1285
+ segmentStartTimeRef.current = 0;
1286
+ offsetAtSegmentStartRef.current = 0;
1287
+ pauseRequestedAtRef.current = 0;
1256
1288
  seekOperationIdRef.current = 0;
1257
1289
  isSeekingRef.current = false;
1258
1290
  pendingSeekRef.current = null;
@@ -251,8 +251,14 @@ export const CometChatList = React.forwardRef<CometChatListActionsInterface, Com
251
251
  const selectionEffectDidMountRef = useRef(false);
252
252
 
253
253
  const [list, setList] = useState<any[]>([]);
254
+ const listRef = useRef<any[]>([]);
254
255
  const [dataLoadingStatus, setDataLoadingStatus] = useState<string>(LOADING);
255
256
 
257
+ // Keep listRef in sync with list state for use in imperative methods
258
+ useEffect(() => {
259
+ listRef.current = list;
260
+ }, [list]);
261
+
256
262
  useEffect(() => {
257
263
  // Skip calling onSelection on initial mount; only trigger after a user-driven change
258
264
  if (!selectionEffectDidMountRef.current) {
@@ -382,13 +388,16 @@ export const CometChatList = React.forwardRef<CometChatListActionsInterface, Com
382
388
  * @param
383
389
  */
384
390
  const updateList = (item: any) => {
385
- let newList = [...list];
386
- let itemKey = newList.findIndex((u) => u[listItemKey] === item[listItemKey]);
387
- if (itemKey > -1) {
388
- newList.splice(itemKey, 1, item);
389
- if (newList.length === 0) setDataLoadingStatus(NO_DATA_FOUND);
390
- setList(newList);
391
- }
391
+ setList((prevList) => {
392
+ let newList = [...prevList];
393
+ let itemKey = newList.findIndex((u) => u[listItemKey] === item[listItemKey]);
394
+ if (itemKey > -1) {
395
+ newList.splice(itemKey, 1, item);
396
+ if (newList.length === 0) setDataLoadingStatus(NO_DATA_FOUND);
397
+ return newList;
398
+ }
399
+ return prevList;
400
+ });
392
401
  };
393
402
 
394
403
  /**
@@ -396,12 +405,14 @@ export const CometChatList = React.forwardRef<CometChatListActionsInterface, Com
396
405
  * @param item
397
406
  */
398
407
  const updateAndMoveToFirst = (item: any) => {
399
- let newList = [...list];
400
- let itemKey = newList.findIndex((u) => u[listItemKey] === item[listItemKey]);
401
- if (itemKey > -1) {
402
- newList.splice(itemKey, 1);
403
- }
404
- setList([item, ...newList]);
408
+ setList((prevList) => {
409
+ let newList = [...prevList];
410
+ let itemKey = newList.findIndex((u) => u[listItemKey] === item[listItemKey]);
411
+ if (itemKey > -1) {
412
+ newList.splice(itemKey, 1);
413
+ }
414
+ return [item, ...newList];
415
+ });
405
416
  };
406
417
 
407
418
  const addItemToList = (item: any, position?: number) => {
@@ -431,14 +442,14 @@ export const CometChatList = React.forwardRef<CometChatListActionsInterface, Com
431
442
  };
432
443
 
433
444
  const getListItem = (itemId: string | number): any => {
434
- return list.find((item: any) => item[listItemKey] === itemId);
445
+ return listRef.current.find((item: any) => item[listItemKey] === itemId);
435
446
  };
436
447
 
437
448
  /**
438
449
  * Get all list items
439
450
  */
440
451
  const getAllListItems = (): any[] => {
441
- return list;
452
+ return listRef.current;
442
453
  };
443
454
 
444
455
  /**