@cometchat/chat-uikit-react-native 5.5.4 → 5.7.0

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 (215) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/CometChatKeyboardModule.kt +101 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/CometchatUiKitPackage.java +1 -0
  3. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +78 -3
  4. package/android/src/main/java/com/reactnativecometchatuikit/KeyboardDirectionWatcher.kt +64 -0
  5. package/android/src/main/java/com/reactnativecometchatuikit/KeyboardLanguageDirection.kt +44 -0
  6. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +287 -49
  7. package/android/src/main/java/com/reactnativecometchatuikit/SafeFileName.java +78 -0
  8. package/ios/CCLocalFileGuard.h +19 -0
  9. package/ios/CCLocalFileGuard.m +34 -0
  10. package/ios/CometChatKeyboardModule.m +9 -0
  11. package/ios/CometChatKeyboardModule.swift +71 -0
  12. package/ios/FileManager.m +70 -6
  13. package/ios/KeyboardLanguageDirection.swift +24 -0
  14. package/ios/RichTextEditorView.swift +253 -51
  15. package/ios/RichTextEditorViewManager.m +1 -0
  16. package/ios/VideoManager.m +1 -1
  17. package/package.json +18 -3
  18. package/src/CometChatAIAssistantChatHistory/CometChatAIAssistantChatHistory.tsx +41 -57
  19. package/src/CometChatAIAssistantChatHistory/Skeleton.tsx +4 -1
  20. package/src/CometChatAIAssistantChatHistory/style.ts +5 -2
  21. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +145 -63
  22. package/src/CometChatCompactMessageComposer/styles.ts +7 -7
  23. package/src/CometChatConversations/CometChatConversations.tsx +276 -147
  24. package/src/CometChatConversations/Skeleton.tsx +4 -1
  25. package/src/CometChatConversations/style.ts +1 -1
  26. package/src/CometChatGroupMembers/CometChatGroupMembers.tsx +39 -18
  27. package/src/CometChatGroupMembers/Skeleton.tsx +4 -1
  28. package/src/CometChatGroupMembers/style.ts +6 -4
  29. package/src/CometChatGroups/CometChatGroups.tsx +74 -58
  30. package/src/CometChatGroups/GroupsStyle.ts +1 -1
  31. package/src/CometChatGroups/Skeleton.tsx +4 -1
  32. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +190 -96
  33. package/src/CometChatMessageComposer/styles.tsx +1 -1
  34. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +28 -15
  35. package/src/CometChatMessageHeader/listners.ts +76 -56
  36. package/src/CometChatMessageInformation/CometChatMessageInformation.tsx +8 -1
  37. package/src/CometChatMessageInformation/Skeleton.tsx +4 -1
  38. package/src/CometChatMessageList/CometChatMessageList.tsx +1465 -313
  39. package/src/CometChatMessageList/SwipeToReplyView.tsx +61 -0
  40. package/src/CometChatMessageList/style.ts +32 -32
  41. package/src/CometChatMessageList/swipeToReply.ts +25 -0
  42. package/src/CometChatNotificationFeed/CometChatNotificationFeed.tsx +81 -10
  43. package/src/CometChatNotificationFeed/style.ts +1 -1
  44. package/src/CometChatNotificationFeed/utils.ts +17 -18
  45. package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +82 -3
  46. package/src/CometChatPinnedMessages/style.ts +5 -5
  47. package/src/CometChatRichTextEditor/RichTextEditorViewNativeComponent.ts +2 -0
  48. package/src/CometChatRichTextEditor/index.tsx +3 -0
  49. package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +83 -15
  50. package/src/CometChatSavedMessages/style.ts +3 -3
  51. package/src/CometChatSearch/CometChatSearch.tsx +391 -136
  52. package/src/CometChatSearch/Skeleton.tsx +4 -1
  53. package/src/CometChatSearch/searchLabels.ts +26 -0
  54. package/src/CometChatSearch/style.ts +7 -7
  55. package/src/CometChatThreadHeader/CometChatThreadHeader.tsx +34 -8
  56. package/src/CometChatThreadHeader/Header.tsx +2 -2
  57. package/src/CometChatUsers/CometChatUsers.tsx +10 -1
  58. package/src/CometChatUsers/Skeleton.tsx +4 -1
  59. package/src/CometChatUsers/style.ts +1 -1
  60. package/src/calls/CometChatCallButtons/CometChatCallButtons.tsx +27 -1
  61. package/src/calls/CometChatCallLogs/CometChatCallLogs.tsx +16 -4
  62. package/src/calls/CometChatCallLogs/Skeleton.tsx +4 -1
  63. package/src/calls/CometChatIncomingCall/CometChatIncomingCall.tsx +11 -3
  64. package/src/calls/CometChatOutgoingCall/CometChatOutgoingCall.tsx +10 -2
  65. package/src/extensions/CollaborativeBubble/style.ts +4 -4
  66. package/src/extensions/CollaborativeDocument/CollaborativeDocumentExtensionDecorator.tsx +1 -1
  67. package/src/extensions/CollaborativeWhiteboard/CollaborativeWhiteboardExtensionDecorator.tsx +1 -1
  68. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +11 -6
  69. package/src/extensions/LinkPreview/style.ts +6 -6
  70. package/src/extensions/Polls/Header.tsx +1 -1
  71. package/src/extensions/Polls/Polls.tsx +25 -12
  72. package/src/extensions/Polls/PollsBubble.tsx +10 -6
  73. package/src/extensions/Polls/style.ts +4 -4
  74. package/src/extensions/Stickers/CometChatStickerKeyboard/CometChatStickerKeyboard.tsx +2 -2
  75. package/src/extensions/Stickers/CometChatStickerKeyboard/Skeleton.tsx +1 -1
  76. package/src/extensions/Stickers/CometChatStickerKeyboard/style.ts +1 -1
  77. package/src/extensions/Stickers/StickersExtensionDecorator.tsx +4 -2
  78. package/src/index.ts +11 -1
  79. package/src/shared/CometChatUiKit/CometChatUIKit.ts +102 -2
  80. package/src/shared/CometChatUiKit/UIKitSettings.ts +28 -0
  81. package/src/shared/events/CometChatUIEventHandler/Listener.ts +10 -0
  82. package/src/shared/events/index.ts +4 -0
  83. package/src/shared/events/offline.ts +28 -0
  84. package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +18 -13
  85. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +15 -7
  86. package/src/shared/formatters/CometChatTextFormatter.ts +11 -0
  87. package/src/shared/formatters/CometChatUrlsFormatter/index.tsx +7 -4
  88. package/src/shared/framework/MessageDataSource.tsx +51 -108
  89. package/src/shared/helper/LocalizedDateHelper.ts +64 -4
  90. package/src/shared/helper/helperFunctions.ts +71 -4
  91. package/src/shared/helper/keyboardDirection.ts +54 -0
  92. package/src/shared/helper/layoutDirection.ts +205 -0
  93. package/src/shared/helper/pluralRules.ts +67 -0
  94. package/src/shared/helper/textDirection.ts +118 -0
  95. package/src/shared/icons/Icon.tsx +37 -2
  96. package/src/shared/icons/components/format-list-numbered-rtl.tsx +15 -0
  97. package/src/shared/index.ts +2 -0
  98. package/src/shared/offline/OfflineHub.ts +651 -0
  99. package/src/shared/offline/OfflineMediaBubble.tsx +49 -0
  100. package/src/shared/offline/OfflineViews.tsx +222 -0
  101. package/src/shared/offline/conversationPins.ts +137 -0
  102. package/src/shared/offline/conversations.ts +325 -0
  103. package/src/shared/offline/frameProbe.ts +24 -0
  104. package/src/shared/offline/gate.ts +94 -0
  105. package/src/shared/offline/groupActions.ts +81 -0
  106. package/src/shared/offline/identity.ts +162 -0
  107. package/src/shared/offline/index.ts +76 -0
  108. package/src/shared/offline/media.ts +247 -0
  109. package/src/shared/offline/notices.ts +84 -0
  110. package/src/shared/offline/reconcile.ts +296 -0
  111. package/src/shared/offline/searchOutcome.ts +62 -0
  112. package/src/shared/offline/send.ts +430 -0
  113. package/src/shared/offline/stateContract.ts +85 -0
  114. package/src/shared/offline/threadReplies.ts +125 -0
  115. package/src/shared/offline/twoPhase.ts +372 -0
  116. package/src/shared/offline/unsentActions.ts +168 -0
  117. package/src/shared/offline/useOfflineMediaUri.ts +87 -0
  118. package/src/shared/offline/useOfflineReconnect.ts +25 -0
  119. package/src/shared/offline/useOfflineSessionEnded.ts +22 -0
  120. package/src/shared/offline/useOfflineUploadTray.ts +76 -0
  121. package/src/shared/offline/usePresenceHidden.ts +33 -0
  122. package/src/shared/resources/CometChatLocalizeNew/CometChatLocalizationHelper.ts +2 -0
  123. package/src/shared/resources/CometChatLocalizeNew/resources/ar/translation.json +720 -0
  124. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +74 -3
  125. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +75 -4
  126. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +74 -3
  127. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +75 -4
  128. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +74 -3
  129. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +74 -3
  130. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +74 -3
  131. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +74 -3
  132. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +74 -3
  133. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +82 -3
  134. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +74 -3
  135. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +74 -3
  136. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +74 -3
  137. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +90 -3
  138. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +74 -3
  139. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +74 -3
  140. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +74 -3
  141. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +74 -3
  142. package/src/shared/services/UploadQueueService.ts +106 -1
  143. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +13 -12
  144. package/src/shared/utils/CometChatMessagePreview/style.ts +1 -1
  145. package/src/shared/utils/MessageReceiptUtils.ts +8 -0
  146. package/src/shared/utils/MessageUtils.tsx +14 -14
  147. package/src/shared/utils/PermissionUtil.ts +16 -5
  148. package/src/shared/utils/SavedMessagesHelper.ts +18 -1
  149. package/src/shared/utils/attachmentLimits.ts +3 -2
  150. package/src/shared/utils/catchUpCursor.ts +36 -0
  151. package/src/shared/utils/conversationUtils.ts +3 -5
  152. package/src/shared/utils/failedMessageRetry.ts +73 -0
  153. package/src/shared/utils/fileIconFontSize.ts +10 -0
  154. package/src/shared/utils/fileSizeLabel.ts +16 -0
  155. package/src/shared/utils/groupActionText.ts +75 -0
  156. package/src/shared/utils/messageIdentity.ts +38 -0
  157. package/src/shared/views/CometChatAIAssistantMessageBubble/CometChatAIAssistantMessageBubble.tsx +12 -8
  158. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreview.style.ts +1 -1
  159. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreviewItem.tsx +5 -3
  160. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTile.tsx +22 -17
  161. package/src/shared/views/CometChatAttachmentViewer/CometChatAttachmentViewer.tsx +45 -12
  162. package/src/shared/views/CometChatAudioBubble/CometChatAudioBubble.tsx +16 -10
  163. package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +20 -8
  164. package/src/shared/views/CometChatBadge/CometChatBadge.tsx +8 -4
  165. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +6 -2
  166. package/src/shared/views/CometChatComposerErrorBanner.tsx +3 -1
  167. package/src/shared/views/CometChatConfirmDialog/CometChatConfirmDialog.tsx +8 -3
  168. package/src/shared/views/CometChatConversationStarter/CometChatConversationStarter.tsx +2 -2
  169. package/src/shared/views/CometChatEmojiKeyboard/CometChatEmojiKeyboard.tsx +5 -3
  170. package/src/shared/views/CometChatEmojiKeyboard/emojis.ts +8 -8
  171. package/src/shared/views/CometChatEmojiKeyboard/style.ts +2 -2
  172. package/src/shared/views/CometChatFileBubble/CometChatFileBubble.tsx +13 -27
  173. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +65 -15
  174. package/src/shared/views/CometChatImageViewerModal/ImageViewerModal.tsx +7 -3
  175. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +56 -25
  176. package/src/shared/views/CometChatInlineAudioRecorder/CometChatInlineAudioRecorder.tsx +41 -21
  177. package/src/shared/views/CometChatInlineAudioRecorder/useAudioRecorder.ts +7 -3
  178. package/src/shared/views/CometChatLinkConfirmPopup/CometChatLinkConfirmPopup.tsx +7 -3
  179. package/src/shared/views/CometChatList/CometChatList.tsx +478 -21
  180. package/src/shared/views/CometChatList/Header.tsx +5 -2
  181. package/src/shared/views/CometChatList/sectionLetter.ts +44 -0
  182. package/src/shared/views/CometChatList/styles.ts +7 -7
  183. package/src/shared/views/CometChatListItem/CometChatListItem.tsx +6 -4
  184. package/src/shared/views/CometChatMediaRecorder/CometChatAudioPlayer.tsx +16 -10
  185. package/src/shared/views/CometChatMediaRecorder/Timer.tsx +5 -1
  186. package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +43 -16
  187. package/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx +24 -4
  188. package/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx +19 -2
  189. package/src/shared/views/CometChatNewMessageIndicator/CometChatNewMessageIndicator.tsx +3 -2
  190. package/src/shared/views/CometChatReactionList/CometChatReactionList.tsx +59 -12
  191. package/src/shared/views/CometChatReactionList/ReactionListStyle.tsx +2 -2
  192. package/src/shared/views/CometChatReactionList/Skeleton.tsx +4 -1
  193. package/src/shared/views/CometChatReactions/CometChatReactions.tsx +6 -2
  194. package/src/shared/views/CometChatReportDialog/CometChatReportDialog.tsx +7 -3
  195. package/src/shared/views/CometChatReportDialog/style.ts +1 -1
  196. package/src/shared/views/CometChatSmartReplies/CometChatSmartReplies.tsx +1 -1
  197. package/src/shared/views/CometChatStatusIndicator/CometChatStatusIndicator.tsx +4 -0
  198. package/src/shared/views/CometChatStreamMessageBubble/CometChatStreamMessageBubble.tsx +20 -13
  199. package/src/shared/views/CometChatSuggestionList/CometChatSuggestionList.tsx +3 -2
  200. package/src/shared/views/CometChatSuggestionList/Skeleton.tsx +1 -1
  201. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +29 -3
  202. package/src/shared/views/CometChatTooltipMenu/CometChatTooltipMenu.tsx +20 -30
  203. package/src/shared/views/CometChatTooltipMenu/tooltipPosition.ts +43 -0
  204. package/src/shared/views/CometChatVideoBubble/style.ts +2 -2
  205. package/src/shared/views/CometChatVideoPlayer/CometChatVideoPlayer.tsx +4 -1
  206. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +58 -24
  207. package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +24 -12
  208. package/src/shared/views/SenderLabel.tsx +41 -0
  209. package/src/theme/default/default.ts +1 -1
  210. package/src/theme/type.ts +17 -0
  211. package/android/.gradle/7.4/checksums/checksums.lock +0 -0
  212. package/android/.gradle/7.4/fileChanges/last-build.bin +0 -0
  213. package/android/.gradle/7.4/fileHashes/fileHashes.lock +0 -0
  214. package/android/.gradle/7.4/gc.properties +0 -0
  215. package/android/.gradle/vcs-1/gc.properties +0 -0
@@ -32,12 +32,7 @@ import {
32
32
  StyleSheet,
33
33
  StyleProp,
34
34
  } from "react-native";
35
- import {
36
- PanGestureHandler,
37
- State,
38
- PanGestureHandlerGestureEvent,
39
- PanGestureHandlerStateChangeEvent,
40
- } from "react-native-gesture-handler";
35
+ import { SwipeToReplyView } from "./SwipeToReplyView";
41
36
  import { CometChatMessageEvents } from "../shared/events/CometChatMessageEvents";
42
37
  import { CometChatConversationEvents } from "../shared/events/conversations";
43
38
  import {
@@ -75,6 +70,47 @@ import { groupMemberAddedRows } from "../shared/utils/groupMemberAddedRows";
75
70
  import { selectLinkPreview } from "../shared/utils/linkPreviewSelection";
76
71
  import { unescapeTypedMentionTokens } from "../shared/utils/mentionTokens";
77
72
  import { CommonUtils } from "../shared/utils/CommonUtils";
73
+ import { sameMessageById, sameMessageByMuid } from "../shared/utils/messageIdentity";
74
+ import { nextCatchUpCursor } from "../shared/utils/catchUpCursor";
75
+ import { isRetryableFailedRow, resendFailedMessage, resendKindOf } from "../shared/utils/failedMessageRetry";
76
+ import { cloneRequestBuilder } from "../shared/utils/cloneRequestBuilder";
77
+ import { isOfflineOn, offlineSdk, sdkConnected } from "../shared/offline/gate";
78
+ import {
79
+ findRowIndex,
80
+ HeldReceipts,
81
+ isNotConnectedError,
82
+ cachedKeysOf,
83
+ dropUnjoinedCachedPageDesc,
84
+ newestServerId,
85
+ onlyShownRows,
86
+ reconcileServerPageDesc,
87
+ removeRowDesc,
88
+ upsertSortedDesc,
89
+ } from "../shared/offline/reconcile";
90
+ import {
91
+ isOfflineUnsent,
92
+ isSyncDelivered,
93
+ offlineRenderKey,
94
+ serverIdOf,
95
+ } from "../shared/offline/identity";
96
+ import {
97
+ CacheResetEvent,
98
+ MessageSyncEvent,
99
+ MessagesUpdatedEvent,
100
+ OfflineHub,
101
+ SendStateEvent,
102
+ ConversationSyncEvent,
103
+ SyncFailedEvent,
104
+ } from "../shared/offline/OfflineHub";
105
+ import { fetchTwoPhase, readAroundTwoPhase, resolveTwoPhase } from "../shared/offline/twoPhase";
106
+ import { mediaActionSource, notifyMediaUnavailable } from "../shared/offline/media";
107
+ import { retryFailedMessage, sendKindOf } from "../shared/offline/send";
108
+ import { canRetryUnsent, deleteUnsentMessage, OFFLINE_OPTION_IDS, unsentActionsOf, unsentRowInfo } from "../shared/offline/unsentActions";
109
+ import { OFFLINE_STRING_KEYS, offlineMutationErrorText } from "../shared/offline/notices";
110
+ import { contractRowState, messageRowContractProps } from "../shared/offline/stateContract";
111
+ import { probeFrame } from "../shared/offline/frameProbe";
112
+ import { ConnectStateView, ConnectToLoadMore, OfflineNoticeView, useOfflineNotice } from "../shared/offline/OfflineViews";
113
+ import { CONTRACT_IDS } from "../shared/offline/stateContract";
78
114
  import { CometChatBatchMediaContext, BatchMediaResult } from "../shared/utils/batchMediaContext";
79
115
  import { CometChatUIKit } from "../shared/CometChatUiKit/CometChatUIKit";
80
116
  import { CometChatNewMessageIndicator, CometChatReceipt, NewMessageIndicatorStyle } from "../shared/views";
@@ -139,6 +175,9 @@ import {
139
175
  pinSaveNeedsConfirm,
140
176
  carryPinSaveAttrs,
141
177
  } from "../shared/utils/PinSaveHelper";
178
+ import { pluralCountLabel } from "../shared/helper/pluralRules";
179
+ import { LayoutDirectionContext, directionStyle, useComponentLayoutDirection } from "../shared/helper/layoutDirection";
180
+ import { stripBidiControls } from "../shared/helper/textDirection";
142
181
 
143
182
  let _defaultRequestBuilder: CometChat.MessagesRequestBuilder;
144
183
  const AVERAGE_ITEM_LENGTH = 120;
@@ -163,6 +202,28 @@ export function skipNextAgentAutoLoad(): void {
163
202
  * Helper function to safely get message ID
164
203
  * Prevents "undefined is not a function" errors in release builds
165
204
  */
205
+ /** How long after a conversation-only sweep phase the list waits for a message phase (ON only). */
206
+ const COLD_SWEEP_SETTLE_MS = 2000;
207
+
208
+ /**
209
+ * The least time between two older-page reads a scroll gesture at the "Connect to load more" footer
210
+ * starts once the connection is back (UIK-READ-03): a scroll burst fires many events.
211
+ */
212
+ const RETRY_ON_SCROLL_GAP_MS = 1000;
213
+
214
+ /** Reconnect, blocked "Connect to load more" edges (D84 rule 9): how often to look whether the reads in flight settled, and how long to wait. */
215
+ const EDGE_RELOAD_POLL_MS = 100;
216
+ const EDGE_RELOAD_MAX_WAIT_MS = 10000;
217
+
218
+ /**
219
+ * The longest a jump or start-from-unread window stays "being positioned" (paging and the live
220
+ * auto-scroll paused) if its scroll never reports back, e.g. the list unmounted or never laid out.
221
+ */
222
+ const POSITIONING_MAX_MS = 6000;
223
+
224
+ /** How many messages after the anchor a jump or start-from-unread window reads. */
225
+ const AROUND_NEXT_PAGE_LIMIT = 15;
226
+
166
227
  const safeGetId = (item: any): string | number | undefined => {
167
228
  return typeof item?.getId === 'function' ? item.getId() : item?.id;
168
229
  };
@@ -185,7 +246,16 @@ async function getConversationIfExists(
185
246
  convId: string,
186
247
  conversationType: string
187
248
  ): Promise<CometChat.Conversation | null> {
249
+ // Gate read once for this read. Offline ON: the two-phase form, so a chat opened by id offline
250
+ // still finds its cached conversation (BEH-READ-32); OFF: today's Promise form.
251
+ const offlineOn = isOfflineOn();
188
252
  try {
253
+ if (offlineOn) {
254
+ return await resolveTwoPhase<CometChat.Conversation>(
255
+ (listener) => offlineSdk().getConversation(convId, conversationType, listener),
256
+ "Conversation"
257
+ );
258
+ }
189
259
  return await CometChat.getConversation(convId, conversationType);
190
260
  } catch (e: any) {
191
261
  if (e?.code === "ERR_CONVERSATION_NOT_ACCESSIBLE") {
@@ -222,6 +292,8 @@ function batchStateUpdates(callback: () => void): void {
222
292
  * Properties for rendering the CometChat message list component.
223
293
  */
224
294
  export interface CometChatMessageListProps {
295
+ /** Lays this component out `"ltr"` or `"rtl"`, overriding the kit's global `layoutDirection`. Not set = inherit. */
296
+ layoutDirection?: "ltr" | "rtl";
225
297
  /**
226
298
  * ID of the parent message when rendering threaded messages.
227
299
  *
@@ -541,6 +613,11 @@ export interface CometChatMessageListProps {
541
613
  * Flag to hide group action messages
542
614
  */
543
615
  hideGroupActionMessages?: boolean;
616
+ /**
617
+ * Offline support: hide the one-line notices (unsent message removed, queue full, messages not
618
+ * sent, cache rebuilt). Has no effect with offline off. Default `false`.
619
+ */
620
+ hideOfflineNotices?: boolean;
544
621
  /**
545
622
  * Flag to hide the timestamp on message bubbles
546
623
  */
@@ -801,6 +878,7 @@ export const CometChatMessageList = memo(
801
878
  hideCopyMessageOption: propHideCopyMessageOption = false,
802
879
  hideMessageInfoOption: propHideMessageInfoOption = false,
803
880
  hideGroupActionMessages: propHideGroupActionMessages = false,
881
+ hideOfflineNotices = false,
804
882
  hideTimestamp = false,
805
883
  suggestedMessages = [],
806
884
  hideSuggestedMessages = false,
@@ -824,6 +902,8 @@ export const CometChatMessageList = memo(
824
902
  newMessageIndicatorText,
825
903
  loadLastAgentConversation = false,
826
904
  } = props;
905
+ // ENG-41333: own setting → enclosing component → global; drives the root and the context.
906
+ const direction = useComponentLayoutDirection(props.layoutDirection);
827
907
 
828
908
  // §5.6 — `parentMessage` supersedes `parentMessageId`, and the id is derived from it so
829
909
  // every existing scoping path below is untouched. The deprecated prop is still honoured
@@ -870,11 +950,15 @@ export const CometChatMessageList = memo(
870
950
  const deleteItem = useRef<CometChat.BaseMessage>(undefined);
871
951
  const shouldSuppressHighlightRef = useRef(false);
872
952
  const { showToast, ToastElement } = useToast();
953
+ // The types and categories this list loads (an integrator builder's own when it sets them):
954
+ // the offline sweep inserts only rows that pass the same filter. `null` = no filter.
955
+ const sweepFilterRef = useRef<{ types: string[] | null; categories: string[] | null } | null>(null);
873
956
 
874
957
  useLayoutEffect(() => {
875
958
  // For agent chats (non-thread), don't set up message request builder
876
959
  if (isAgenticUser && !parentMessageId) {
877
960
  msgRequestBuilder.current = null as any;
961
+ sweepFilterRef.current = null;
878
962
  return;
879
963
  }
880
964
 
@@ -903,6 +987,11 @@ export const CometChatMessageList = memo(
903
987
  _updatedCustomRequestBuilder = _updatedCustomRequestBuilder.setUID(user.getUid());
904
988
  if (group)
905
989
  _updatedCustomRequestBuilder = _updatedCustomRequestBuilder.setGUID(group.getGuid());
990
+ const own: any = messageRequestBuilder;
991
+ sweepFilterRef.current = {
992
+ types: Array.isArray(own.types) && own.types.length ? own.types : null,
993
+ categories: Array.isArray(own.categories) && own.categories.length ? own.categories : null,
994
+ };
906
995
  } else {
907
996
  _updatedCustomRequestBuilder.hideReplies(true);
908
997
  if (user)
@@ -937,6 +1026,7 @@ export const CometChatMessageList = memo(
937
1026
  }
938
1027
  _updatedCustomRequestBuilder = _updatedCustomRequestBuilder.setTypes(types);
939
1028
  _updatedCustomRequestBuilder = _updatedCustomRequestBuilder.setCategories(categories);
1029
+ sweepFilterRef.current = { types, categories };
940
1030
  }
941
1031
 
942
1032
  msgRequestBuilder.current = _updatedCustomRequestBuilder;
@@ -945,7 +1035,7 @@ export const CometChatMessageList = memo(
945
1035
  const theme = useTheme();
946
1036
  const themeInternal = useThemeInternal();
947
1037
  const themeMode = themeInternal.mode; // 'light' or 'dark' - used for FlatList extraData
948
- const { t } = useCometChatTranslation();
1038
+ const { t, language } = useCometChatTranslation();
949
1039
 
950
1040
  const mergedTheme: CometChatTheme = useMemo(() => {
951
1041
  const themeClone = deepClone(theme);
@@ -1174,8 +1264,87 @@ export const CometChatMessageList = memo(
1174
1264
  const reachedFirstMessage = useRef<boolean>(false);
1175
1265
  const agenticParentMessageIdRef = useRef<string | undefined>(undefined);
1176
1266
  const [hasTargetMessageId, setHasTargetMessageId] = useState(false);
1267
+ // The window shown is anchored on an older message (a jump or start-from-unread): its newest
1268
+ // row is not the chat's. Read by the offline sweep handlers, which also run from timers.
1269
+ // `aroundReachedNewestRef`: the server's page after the anchor was short, so the window does
1270
+ // end at the chat's newest message and a sweep may insert as usual.
1271
+ const aroundReachedNewestRef = useRef(false);
1272
+ // Offline ON: a jump or start-from-unread window is being filled and scrolled to its anchor.
1273
+ // Until it is positioned the list neither pages (older or newer) nor follows live messages
1274
+ // to the bottom: either would run before the anchor is on screen and leave the list at the
1275
+ // newest messages (offline paints the window in phases, so the gap is long). `positioningRef`
1276
+ // is set when the around read starts and ends when the scroll to the anchor settles, the
1277
+ // read fails or finds nothing to scroll to, or after `POSITIONING_MAX_MS`. Never set with
1278
+ // offline off, so nothing here runs, and no timer starts, there.
1279
+ const positioningRef = useRef(false);
1280
+ const positioningTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
1281
+ const scrollTargetPendingRef = useRef(false);
1282
+ // A page the list asked for while it was being positioned. The list reports an edge once per
1283
+ // content length, so it would not ask again: it is read once the list is positioned.
1284
+ const deferredPagingRef = useRef({ older: false, newer: false });
1285
+ const pagingFnsRef = useRef<{ older: () => unknown; newer: () => unknown }>({ older: () => {}, newer: () => {} });
1286
+ const endPositioning = () => {
1287
+ positioningRef.current = false;
1288
+ scrollTargetPendingRef.current = false;
1289
+ if (positioningTimerRef.current) clearTimeout(positioningTimerRef.current);
1290
+ positioningTimerRef.current = null;
1291
+ const deferred = deferredPagingRef.current;
1292
+ deferredPagingRef.current = { older: false, newer: false };
1293
+ if (deferred.older) pagingFnsRef.current.older();
1294
+ if (deferred.newer) pagingFnsRef.current.newer();
1295
+ };
1296
+ const beginPositioning = () => {
1297
+ positioningRef.current = true;
1298
+ if (positioningTimerRef.current) clearTimeout(positioningTimerRef.current);
1299
+ positioningTimerRef.current = setTimeout(endPositioning, POSITIONING_MAX_MS);
1300
+ };
1301
+ useEffect(() => () => {
1302
+ if (positioningTimerRef.current) clearTimeout(positioningTimerRef.current);
1303
+ }, []);
1304
+ const anchoredWindowRef = useRef(false);
1305
+ anchoredWindowRef.current = hasTargetMessageId && !aroundReachedNewestRef.current;
1177
1306
  const fetchingAroundIdRef = useRef<string | null>(null); // Track which message ID we're currently fetching
1178
1307
  const [itemPositions, setItemPositions] = useState<Map<string, { y: number; height: number }>>(new Map());
1308
+ // Offline (ON path) bookkeeping. Untouched while offline is off.
1309
+ const offlinePathUsedRef = useRef(false); // this list ran an ON-path operation
1310
+ const listOpGenRef = useRef(0); // bumped on reset/logout and on a jump: late offline read callbacks are dropped
1311
+ const jumpGenRef = useRef(0); // bumped on a jump: a page read for the window left behind is dropped (offline on or off)
1312
+ const heldReceiptsRef = useRef(new HeldReceipts()); // receipts that beat their ack (§3.6)
1313
+ const [offlineFooter, setOfflineFooter] = useState<"none" | "connect">("none");
1314
+ // UIK-READ-03: the footer shows and the connection is back, so scrolling to the older end
1315
+ // reads again as tapping the footer does. Refs: read from scroll events and the hub's
1316
+ // connection event, not from a render.
1317
+ const offlineFooterRef = useRef<"none" | "connect">("none");
1318
+ offlineFooterRef.current = offlineFooter;
1319
+ const offlineFooterRetryableRef = useRef(false);
1320
+ // D84 (offline ON): the device was not connected and the chat has nothing saved: "Connect to load
1321
+ // messages" shows (the app's own ErrorView instead, if it passed one) and the newest page loads
1322
+ // again once, by itself, when the connection is back. Any other error is not loaded again.
1323
+ const reloadOnConnectRef = useRef(false);
1324
+ const [offlineMiss, setOfflineMiss] = useState(false);
1325
+ // The newer edge of an anchored window (after a jump) could not load offline: "Connect to load
1326
+ // more" shows there too, and on reconnect that page loads once by itself (D84 rule 9).
1327
+ const [offlineNewerBlocked, setOfflineNewerBlocked] = useState(false);
1328
+ const offlineNewerBlockedRef = useRef(false);
1329
+ offlineNewerBlockedRef.current = offlineNewerBlocked;
1330
+ // A read the kit starts by itself (cache reset, the reload after a reconnect) is quiet over rows
1331
+ // when it fails with a real error (D84 rule 5). Consumed by the next read.
1332
+ const quietNextReadRef = useRef(false);
1333
+ // Bumped on every reconnect and on unmount: a blocked-edge reload waiting for the reads in flight
1334
+ // to settle gives up when a newer one (or the unmount) replaces it.
1335
+ const edgeReloadTokenRef = useRef(0);
1336
+ const fetchNextMessagesRef = useRef<() => void>(() => {});
1337
+ // Counts the older / newer page reads started on the offline path: a blocked-edge reload that
1338
+ // finds its edge already read again since the reconnect (a tap, a scroll) leaves it to that read.
1339
+ const olderReadSeqRef = useRef(0);
1340
+ const newerReadSeqRef = useRef(0);
1341
+ useEffect(
1342
+ () => () => {
1343
+ edgeReloadTokenRef.current++;
1344
+ },
1345
+ []
1346
+ );
1347
+ const lastRetryOnScrollRef = useRef(0);
1179
1348
  const markUnreadMessageAsRead = (message?: CometChat.BaseMessage) => {
1180
1349
  const messageToMark = message || messagesContentListRef.current[0];
1181
1350
  if (
@@ -1252,12 +1421,21 @@ export const CometChatMessageList = memo(
1252
1421
  }, [onLoad, hasTargetMessageId]);
1253
1422
 
1254
1423
  const getPreviousMessages = async () => {
1424
+ const quietRead = quietNextReadRef.current; // a read the kit starts by itself
1425
+ quietNextReadRef.current = false;
1426
+ if (positioningRef.current) {
1427
+ deferredPagingRef.current.older = true;
1428
+ return;
1429
+ }
1255
1430
  if (fetchingAroundIdRef.current) return;
1256
1431
 
1257
1432
  if (loadingPrevMessagesRef.current) {
1258
1433
  return;
1259
1434
  }
1260
1435
  loadingPrevMessagesRef.current = true;
1436
+ // A jump (getMessagesAroundId) replaces the window this read was asked for: the read's
1437
+ // answer is then dropped, and the jump owns the loading flags.
1438
+ const readGen = jumpGenRef.current;
1261
1439
  // For agent chats with no conversation loaded, don't fetch previous messages
1262
1440
  if (isAgenticUser && !parentMessageId && !agenticParentMessageIdRef.current) {
1263
1441
  return;
@@ -1292,9 +1470,16 @@ export const CometChatMessageList = memo(
1292
1470
  onError && onError(e);
1293
1471
  }
1294
1472
  }
1473
+ if (readGen !== jumpGenRef.current) return; // a jump began while the scope was fetched
1474
+ // Offline: gate read once for this read. ON → two-phase; OFF → today's fetch below.
1475
+ if (isOfflineOn() && messageRequest.current) {
1476
+ return getPreviousMessagesOffline(messageRequest.current, quietRead);
1477
+ }
1478
+ failStrandedOfflineSends();
1295
1479
  return messageRequest.current
1296
1480
  ?.fetchPrevious()
1297
1481
  .then((msgs: any[]) => {
1482
+ if (readGen !== jumpGenRef.current) return; // older page of a window a jump replaced
1298
1483
  if ((messageRequest.current?.getLimit() ?? 0) > msgs.length) {
1299
1484
  reachedFirstMessage.current = true;
1300
1485
  }
@@ -1394,7 +1579,9 @@ export const CometChatMessageList = memo(
1394
1579
  !message.hasOwnProperty("readAt") &&
1395
1580
  loggedInUser.current?.getUid() != message?.getSender()?.getUid()
1396
1581
  ) {
1397
- CometChat.markAsRead(message);
1582
+ CometChat.markAsRead(message).catch((error: any) => {
1583
+ console.log("Error marking message as read", error);
1584
+ });
1398
1585
  if (index == 0)
1399
1586
  CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, {
1400
1587
  message,
@@ -1447,6 +1634,7 @@ export const CometChatMessageList = memo(
1447
1634
  setListState("");
1448
1635
  })
1449
1636
  .catch((e: any) => {
1637
+ if (readGen !== jumpGenRef.current) return;
1450
1638
  if (messagesContentListRef.current.length == 0) setListState("error");
1451
1639
  if (e?.code === "REQUEST_IN_PROGRESS") return;
1452
1640
  else {
@@ -1455,8 +1643,639 @@ export const CometChatMessageList = memo(
1455
1643
  }
1456
1644
  onError && onError(e);
1457
1645
  }).finally(() => {
1458
- loadingPrevMessagesRef.current = false;
1646
+ if (readGen === jumpGenRef.current) loadingPrevMessagesRef.current = false;
1647
+ });
1648
+ };
1649
+
1650
+ // ── Offline (ON) path ─────────────────────────────────────────────────────────────
1651
+ // Everything below runs only when CometChat.isOfflineEnabled() said "on" for that
1652
+ // operation, or for rows the offline SDK produced (local id / offline status). With
1653
+ // offline off none of it changes a request, an event or a render (README P1).
1654
+
1655
+ /** Replace the rows (newest-first) after an ON-path reconcile; applies held receipts. */
1656
+ const commitOfflineRows = (rows: any[]) => {
1657
+ messagesContentListRef.current = rows;
1658
+ setMessagesList(rows);
1659
+ // addToMessageList commits in the next animation frame; a pending/ack upsert that lands
1660
+ // before that frame would be overwritten by its stale list. Re-assert in the same queue so
1661
+ // the latest writer wins.
1662
+ batchStateUpdates(() => setMessagesList(rows));
1663
+ onLoad && onLoad([...rows].reverse());
1664
+ const held = heldReceiptsRef.current;
1665
+ if (held.size > 0) {
1666
+ for (const row of rows) {
1667
+ const id = serverIdOf(row);
1668
+ const receipt = id > 0 ? held.take(id) : undefined;
1669
+ if (receipt) updateMessageReceipt(receipt);
1670
+ }
1671
+ }
1672
+ };
1673
+
1674
+ const applyOfflineResult = (result: { rows: any[]; changed: boolean }) => {
1675
+ if (result.changed) commitOfflineRows(result.rows);
1676
+ };
1677
+
1678
+ /** Does `message` belong to this list (same chat, same thread level)? */
1679
+ const belongsToThisList = (message: any): boolean => {
1680
+ if (!message) return false;
1681
+ const inChat =
1682
+ checkSameConversation(message) ||
1683
+ checkMessageInSameConversation(message) ||
1684
+ messageToSameConversation(message);
1685
+ if (!inChat) return false;
1686
+ const parentId = message.getParentMessageId?.();
1687
+ if (parentMessageId) return String(parentId) === String(parentMessageId);
1688
+ return !parentId || isAgenticUser;
1689
+ };
1690
+
1691
+ /** The read receipt state an ON-path row shows, or null to keep today's derivation. */
1692
+ const offlineReceiptOf = (item: any): "wait" | "error" | null => {
1693
+ const info = unsentRowInfo(item);
1694
+ if (!info) return null;
1695
+ return info.state === "failed" ? "error" : "wait";
1696
+ };
1697
+
1698
+ /** Mark the open chat read while offline: the SDK clears the badge; remember it (AC-7.4). */
1699
+ const rememberIfReadOffline = (error: any) => {
1700
+ if (!isNotConnectedError(error)) return;
1701
+ const hub = OfflineHub.getInstance();
1702
+ if (user) hub.rememberReadWhileOffline(user.getUid(), CometChat.RECEIVER_TYPE.USER);
1703
+ else if (group) hub.rememberReadWhileOffline(group.getGuid(), CometChat.RECEIVER_TYPE.GROUP);
1704
+ };
1705
+
1706
+ /**
1707
+ * Today's first-page side effects (active-chat event, read marks, unread indicator), run once
1708
+ * per ON-path read: with the server page, or with the cached rows when the read ended offline.
1709
+ */
1710
+ const runOfflinePageEffects = (pageDesc: any[], isInitialLoad: boolean) => {
1711
+ if (isInitialLoad && (pageDesc.length > 0 || !parentMessageId)) {
1712
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccActiveChatChanged, {
1713
+ message: pageDesc[0],
1714
+ user: user,
1715
+ group: group,
1716
+ theme: mergedTheme,
1717
+ parentMessageId: parentMessageId,
1459
1718
  });
1719
+ if (pageDesc.length > 0 && conversationId.current == null) {
1720
+ conversationId.current = pageDesc[0].getConversationId?.() ?? null;
1721
+ }
1722
+ }
1723
+ if (startFromUnreadMessages && pageDesc.length > 0) {
1724
+ if (!goToMessageId && isInitialLoad) {
1725
+ const oldestMessage = pageDesc[pageDesc.length - 1];
1726
+ const msgId = safeGetId(oldestMessage);
1727
+ if (msgId !== undefined) setNewMessageIndicatorId(String(msgId));
1728
+ }
1729
+ if (isInitialLoad && !navigatedFromSearch) {
1730
+ if (user) {
1731
+ CometChat.markConversationAsRead(user.getUid(), CometChat.RECEIVER_TYPE.USER).catch(rememberIfReadOffline);
1732
+ } else if (group) {
1733
+ CometChat.markConversationAsRead(group.getGuid(), CometChat.RECEIVER_TYPE.GROUP).catch(rememberIfReadOffline);
1734
+ }
1735
+ setUnreadCount(0);
1736
+ setNewMessageIndicatorId(null);
1737
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, { message: pageDesc[0] });
1738
+ }
1739
+ return;
1740
+ }
1741
+ for (let index = 0; index < pageDesc.length; index++) {
1742
+ const message = pageDesc[index];
1743
+ if (!message || isOfflineUnsent(message) || message.getReadAt?.()) break;
1744
+ if (loggedInUser.current?.getUid() === message.getSender?.()?.getUid()) break;
1745
+ CometChat.markAsRead(message).catch(rememberIfReadOffline);
1746
+ if (index === 0) CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, { message });
1747
+ }
1748
+ };
1749
+
1750
+ /**
1751
+ * Older messages, two-phase (README §3.3): the cached page paints first, the server page
1752
+ * replaces the same slice in place. Only an empty server page ends history (BEH-READ-09b);
1753
+ * an offline read past the cache keeps what is shown and offers "Connect to load more".
1754
+ */
1755
+ const getPreviousMessagesOffline = (request: CometChat.MessagesRequest, quietRead = false) => {
1756
+ offlinePathUsedRef.current = true;
1757
+ olderReadSeqRef.current++;
1758
+ const opGen = listOpGenRef.current;
1759
+ const hubGen = OfflineHub.getInstance().gen;
1760
+ const stale = () => opGen !== listOpGenRef.current || hubGen !== OfflineHub.getInstance().gen;
1761
+ const isInitialLoad = messagesContentListRef.current.length === 0;
1762
+ let cachedKeys = new Set<string>();
1763
+ let paintedKeys: string[] = [];
1764
+ let cachedDesc: any[] = [];
1765
+ let effectsRun = false;
1766
+ const finishLoad = () => {
1767
+ if (messagesContentListRef.current.length === 0) {
1768
+ onEmpty && onEmpty();
1769
+ } else {
1770
+ onLoad && onLoad([...messagesContentListRef.current].reverse());
1771
+ }
1772
+ setLoadingMessages(false);
1773
+ loadingMessagesRef.current = false;
1774
+ setListState("");
1775
+ };
1776
+ return fetchTwoPhase<any>(
1777
+ request,
1778
+ "previous",
1779
+ {
1780
+ onCached: (page) => {
1781
+ cachedDesc = [...page].reverse();
1782
+ cachedKeys = cachedKeysOf(page);
1783
+ const listed = cachedKeysOf(messagesContentListRef.current);
1784
+ paintedKeys = [...cachedKeys].filter((key) => !listed.has(key));
1785
+ applyOfflineResult(upsertSortedDesc(messagesContentListRef.current, page));
1786
+ // Cached rows are the first paint: no loader over them.
1787
+ if (messagesContentListRef.current.length > 0) setListState("");
1788
+ },
1789
+ onServer: (page) => {
1790
+ applyOfflineResult(
1791
+ dropUnjoinedCachedPageDesc(
1792
+ reconcileServerPageDesc(messagesContentListRef.current, cachedKeys, page),
1793
+ paintedKeys,
1794
+ [...cachedKeys],
1795
+ page,
1796
+ "previous"
1797
+ )
1798
+ );
1799
+ if (page.length === 0) reachedFirstMessage.current = true;
1800
+ reloadOnConnectRef.current = false;
1801
+ setOfflineMiss(false);
1802
+ setOfflineFooter("none");
1803
+ offlineFooterRetryableRef.current = false;
1804
+ if (!effectsRun) {
1805
+ effectsRun = true;
1806
+ runOfflinePageEffects([...page].reverse(), isInitialLoad);
1807
+ }
1808
+ finishLoad();
1809
+ },
1810
+ onError: (error, failedOffline) => {
1811
+ // Not connected: the SDK said so, or it reports no connection.
1812
+ const notConnected = failedOffline || sdkConnected() === false;
1813
+ if (notConnected) {
1814
+ if (messagesContentListRef.current.length === 0) {
1815
+ // D84 rule 3: nothing on screen and not connected: "Connect to load messages" (the
1816
+ // app's own ErrorView instead if it passed one), not an empty chat; onError once.
1817
+ // It loads again once on reconnect.
1818
+ reloadOnConnectRef.current = true;
1819
+ setOfflineMiss(true);
1820
+ setOfflineFooter("none");
1821
+ offlineFooterRetryableRef.current = false;
1822
+ setListState("error");
1823
+ setLoadingMessages(false);
1824
+ loadingMessagesRef.current = false;
1825
+ onError && onError(error as CometChat.CometChatException);
1826
+ return;
1827
+ }
1828
+ // Saved messages stay (BEH-READ-05) with "Connect to load more" at that edge. D84 rule 2:
1829
+ // not connected over rows is not an error, so nothing is reported. A read that gave up
1830
+ // after the connection was already back is retryable by scrolling at once.
1831
+ setOfflineFooter("connect");
1832
+ offlineFooterRetryableRef.current = sdkConnected() === true;
1833
+ if (!effectsRun && isInitialLoad && cachedDesc.length > 0) {
1834
+ effectsRun = true;
1835
+ runOfflinePageEffects(cachedDesc, isInitialLoad);
1836
+ }
1837
+ finishLoad();
1838
+ return;
1839
+ }
1840
+ reloadOnConnectRef.current = false;
1841
+ setOfflineMiss(false);
1842
+ // Never blank cached rows already shown (BEH-READ-06).
1843
+ const nothingShown = messagesContentListRef.current.length == 0;
1844
+ if (nothingShown) setListState("error");
1845
+ setLoadingMessages(false);
1846
+ loadingMessagesRef.current = false;
1847
+ // D84 rule 4 and 5: a real error is reported once; over rows only when the user or app
1848
+ // started the read (open, paging), not one the kit started by itself.
1849
+ if (nothingShown || !quietRead) onError && onError(error as CometChat.CometChatException);
1850
+ },
1851
+ },
1852
+ stale
1853
+ ).finally(() => {
1854
+ loadingPrevMessagesRef.current = false;
1855
+ });
1856
+ };
1857
+
1858
+ /** "Connect to load more" tapped (or scrolled to, once online): try the older page again. */
1859
+ const retryOfflineOlderPage = () => {
1860
+ setOfflineFooter("none");
1861
+ offlineFooterRetryableRef.current = false;
1862
+ loadingPrevMessagesRef.current = false;
1863
+ getPreviousMessages();
1864
+ };
1865
+
1866
+ /** "Connect to load more" tapped at the newer edge of an anchored window: try that page again. */
1867
+ const retryOfflineNewerPage = () => {
1868
+ setOfflineNewerBlocked(false);
1869
+ offlineNewerBlockedRef.current = false;
1870
+ fetchNextMessagesRef.current();
1871
+ };
1872
+
1873
+ /**
1874
+ * Reconnect (D84 rule 9): the page that failed offline at each blocked "Connect to load more" edge
1875
+ * loads once, by itself. It waits for the reads in flight to settle, loads the older edge, waits for
1876
+ * that to settle, then the newer edge. An edge loads only if it is still blocked when its turn comes
1877
+ * (a tap, or a read that answered meanwhile, already took care of it), and nothing loads once the
1878
+ * window changed (a jump, a logout, another chat) or the list is being positioned past its limit.
1879
+ * With nothing shown the empty list reads the newest page instead (the error state's reload).
1880
+ */
1881
+ const loadBlockedEdgesOnReconnect = () => {
1882
+ if (!isOfflineOn() || messagesContentListRef.current.length === 0) return;
1883
+ if (offlineFooterRef.current !== "connect" && !offlineNewerBlockedRef.current) return;
1884
+ const token = ++edgeReloadTokenRef.current;
1885
+ const olderSeq = olderReadSeqRef.current;
1886
+ const newerSeq = newerReadSeqRef.current;
1887
+ const opGen = listOpGenRef.current;
1888
+ const jumpGen = jumpGenRef.current;
1889
+ const sameWindow = () =>
1890
+ token === edgeReloadTokenRef.current && opGen === listOpGenRef.current && jumpGen === jumpGenRef.current;
1891
+ const idle = () =>
1892
+ !loadingPrevMessagesRef.current &&
1893
+ !loadingMessagesRef.current &&
1894
+ !fetchingAroundIdRef.current &&
1895
+ !positioningRef.current;
1896
+ /** Resolves true once no read is in flight and the window is still this one. */
1897
+ const settled = async (): Promise<boolean> => {
1898
+ for (let waited = 0; waited <= EDGE_RELOAD_MAX_WAIT_MS; waited += EDGE_RELOAD_POLL_MS) {
1899
+ if (!sameWindow()) return false;
1900
+ if (idle()) return true;
1901
+ await new Promise<void>((resolve) => setTimeout(() => resolve(), EDGE_RELOAD_POLL_MS));
1902
+ }
1903
+ return false;
1904
+ };
1905
+ void (async () => {
1906
+ if (!(await settled())) return;
1907
+ if (offlineFooterRef.current === "connect" && olderReadSeqRef.current === olderSeq) {
1908
+ retryOfflineOlderPage();
1909
+ // A read that starts but never finishes (a hung request) must not hold the newer edge forever.
1910
+ await new Promise<void>((resolve) => setTimeout(() => resolve(), 0));
1911
+ if (!(await settled())) return;
1912
+ }
1913
+ if (offlineNewerBlockedRef.current && newerReadSeqRef.current === newerSeq) retryOfflineNewerPage();
1914
+ })();
1915
+ };
1916
+
1917
+ /**
1918
+ * UIK-READ-03: once the connection is back, a scroll gesture at the older end reads the page
1919
+ * the footer stands for, as a tap on it does. The list's own end-reached event does not fire
1920
+ * again while the user stays at that end, so the scroll events themselves are the trigger.
1921
+ * Nothing is read on reconnect by itself (UIK-SYNC-01). Inert unless the footer shows and the
1922
+ * connection is back, so with offline off it never runs.
1923
+ */
1924
+ const retryOlderOnScroll = () => {
1925
+ if (!offlineFooterRetryableRef.current || offlineFooterRef.current !== "connect") return;
1926
+ if (loadingPrevMessagesRef.current || loadingMessagesRef.current || fetchingAroundIdRef.current) return;
1927
+ const { layoutHeight, contentHeight } = currentScrollPosition.current;
1928
+ const y = currentScrollPosition.current.y ?? 0;
1929
+ // Inverted list: the older end is where the offset plus the viewport reaches the content's end.
1930
+ if (!layoutHeight || contentHeight - (y + layoutHeight) > layoutHeight * 0.5) return;
1931
+ const now = Date.now();
1932
+ if (now - lastRetryOnScrollRef.current < RETRY_ON_SCROLL_GAP_MS) return;
1933
+ lastRetryOnScrollRef.current = now;
1934
+ retryOfflineOlderPage();
1935
+ };
1936
+
1937
+ /**
1938
+ * After a PARTIAL or failed sweep: one fresh two-phase read of the newest window (README
1939
+ * §3.7). If the server page does not overlap what is shown, more was missed than one page,
1940
+ * so the list resets to that window (own unsent rows stay); older pages reload on scroll.
1941
+ */
1942
+ const refreshNewestWindow = () => {
1943
+ if (!msgRequestBuilder.current) return;
1944
+ offlinePathUsedRef.current = true;
1945
+ const builder: any = cloneRequestBuilder(msgRequestBuilder.current as any);
1946
+ builder?.setMessageId?.(0);
1947
+ const request = builder?.build?.();
1948
+ if (!request) return;
1949
+ const shownIds = new Set(messagesContentListRef.current.map(serverIdOf).filter((id) => id > 0));
1950
+ const opGen = listOpGenRef.current;
1951
+ const hubGen = OfflineHub.getInstance().gen;
1952
+ const stale = () => opGen !== listOpGenRef.current || hubGen !== OfflineHub.getInstance().gen;
1953
+ let cachedKeys = new Set<string>();
1954
+ void fetchTwoPhase<any>(
1955
+ request,
1956
+ "previous",
1957
+ {
1958
+ onCached: (page) => {
1959
+ cachedKeys = cachedKeysOf(page);
1960
+ },
1961
+ onServer: (page) => {
1962
+ const overlaps = page.length === 0 || shownIds.size === 0 || page.some((m) => shownIds.has(serverIdOf(m)));
1963
+ if (overlaps) {
1964
+ applyOfflineResult(reconcileServerPageDesc(messagesContentListRef.current, cachedKeys, page));
1965
+ return;
1966
+ }
1967
+ const unsent = messagesContentListRef.current.filter((m) => serverIdOf(m) === 0 && !m?.isStreamMessage);
1968
+ const reset = upsertSortedDesc([...page].reverse(), unsent).rows;
1969
+ messageRequest.current = request;
1970
+ reachedFirstMessage.current = false;
1971
+ temporaryMessageListRef.current = [];
1972
+ commitOfflineRows(reset);
1973
+ },
1974
+ onError: () => {
1975
+ /* the next sweep heals; never blank the list */
1976
+ },
1977
+ },
1978
+ stale
1979
+ );
1980
+ };
1981
+
1982
+ /**
1983
+ * Kill switch (UIK-LIFE-03): offline turned off while un-acked rows are shown. They turn
1984
+ * failed (direct), with Retry as a fresh send, and one notice. Only lists that used the
1985
+ * offline path can hold such rows.
1986
+ */
1987
+ const failStrandedOfflineSends = () => {
1988
+ if (!offlinePathUsedRef.current) return;
1989
+ const hub = OfflineHub.getInstance();
1990
+ const stranded = [...messagesContentListRef.current, ...temporaryMessageListRef.current].filter(
1991
+ (m) => {
1992
+ const info = unsentRowInfo(m, hub);
1993
+ return !!info && !info.direct && info.state !== "failed";
1994
+ }
1995
+ );
1996
+ if (stranded.length === 0) return;
1997
+ for (const message of stranded) hub.reportFailure(message, "", { direct: true });
1998
+ hub.notify({ kind: "messages_not_sent", count: stranded.length, conversationId: conversationId.current ?? undefined });
1999
+ };
2000
+
2001
+ /**
2002
+ * Whether a swept row would show: its type and category pass the filter the list loads with.
2003
+ * Keeps the server's `action`/`message` record of an edit or delete (BEH-SYNC-25/31) out of the
2004
+ * list; the edited or deleted original (a normal message) still updates in place.
2005
+ */
2006
+ const sweptRowAccepted = (m: any): boolean => {
2007
+ const filter = sweepFilterRef.current;
2008
+ if (!filter) return true;
2009
+ if (filter.types && !filter.types.includes(m?.getType?.())) return false;
2010
+ if (filter.categories && !filter.categories.includes(m?.getCategory?.())) return false;
2011
+ return true;
2012
+ };
2013
+
2014
+ /** A message the SDK's sweep delivered (`source === "SYNC"`): sorted insert, no sound/+1/receipt. */
2015
+ const insertSyncedMessage = (message: any) => {
2016
+ if (!belongsToThisList(message) || !sweptRowAccepted(message)) return;
2017
+ offlinePathUsedRef.current = true;
2018
+ // Anchored on an older message: take the copy of a row shown, never insert past the end.
2019
+ const rows = messagesContentListRef.current;
2020
+ const incoming = anchoredWindowRef.current ? onlyShownRows(rows, [message]) : [message];
2021
+ if (incoming.length > 0) applyOfflineResult(upsertSortedDesc(rows, incoming));
2022
+ };
2023
+
2024
+ /**
2025
+ * A sweep that ran its conversation phase only (a cold start: no message phase until the SDK
2026
+ * has a sync watermark, BEH-SYNC-11/32) brings this chat's newer last message on the
2027
+ * conversation, not on any message callback. When no message phase follows for this chat
2028
+ * and that message is not shown, refresh the newest window once (the same single read a
2029
+ * PARTIAL sweep gets) so the open chat does not miss it.
2030
+ */
2031
+ const coldSweepCheckRef = useRef<ReturnType<typeof setTimeout> | null>(null);
2032
+ const onConversationSynced = (event: ConversationSyncEvent) => {
2033
+ const hub = OfflineHub.getInstance();
2034
+ if (event.gen !== hub.gen || !offlinePathUsedRef.current) return;
2035
+ // Anchored on an older message: the newest window is not what is shown; "load newer" reads it.
2036
+ if (anchoredWindowRef.current) return;
2037
+ const mine = event.conversations.find((c: any) => {
2038
+ const last = c?.getLastMessage?.();
2039
+ return !!last && belongsToThisList(last) && !last.getParentMessageId?.();
2040
+ });
2041
+ const last = mine?.getLastMessage?.();
2042
+ const lastId = serverIdOf(last);
2043
+ if (!lastId || lastId <= newestServerId(messagesContentListRef.current)) return;
2044
+ if (coldSweepCheckRef.current) clearTimeout(coldSweepCheckRef.current);
2045
+ const gen = hub.gen;
2046
+ coldSweepCheckRef.current = setTimeout(() => {
2047
+ coldSweepCheckRef.current = null;
2048
+ if (gen !== OfflineHub.getInstance().gen || anchoredWindowRef.current) return;
2049
+ if (messagesContentListRef.current.some((m) => serverIdOf(m) === lastId)) return;
2050
+ refreshNewestWindow();
2051
+ }, COLD_SWEEP_SETTLE_MS);
2052
+ };
2053
+
2054
+ /** Read the newest page again, two-phase, from a fresh request (cache reset; reconnect over an error view). */
2055
+ const reloadNewestPage = () => {
2056
+ reachedFirstMessage.current = false;
2057
+ loadingPrevMessagesRef.current = false;
2058
+ loadingMessagesRef.current = false;
2059
+ if (msgRequestBuilder.current) {
2060
+ const builder: any = cloneRequestBuilder(msgRequestBuilder.current as any);
2061
+ builder?.setMessageId?.(0);
2062
+ messageRequest.current = builder?.build?.() ?? messageRequest.current;
2063
+ }
2064
+ setListState("loading");
2065
+ quietNextReadRef.current = true; // the kit starts this read: a real error over rows stays quiet
2066
+ getPreviousMessages();
2067
+ };
2068
+
2069
+ const offlineHandlers = {
2070
+ onConversationSync: onConversationSynced,
2071
+ onSendState: (event: SendStateEvent) => {
2072
+ const hub = OfflineHub.getInstance();
2073
+ if (event.gen !== hub.gen || !belongsToThisList(event.message)) return;
2074
+ offlinePathUsedRef.current = true;
2075
+ if (event.state === "discarded") {
2076
+ temporaryMessageListRef.current = temporaryMessageListRef.current.filter(
2077
+ (m) => findRowIndex([m], event.message) === -1
2078
+ );
2079
+ applyOfflineResult(removeRowDesc(messagesContentListRef.current, event.message));
2080
+ return;
2081
+ }
2082
+ // A fresh reference, so the memoized bubble re-renders with the new state.
2083
+ applyOfflineResult(upsertSortedDesc(messagesContentListRef.current, [CommonUtils.clone(event.message)]));
2084
+ },
2085
+ onMessageSync: (event: MessageSyncEvent) => {
2086
+ const hub = OfflineHub.getInstance();
2087
+ if (event.gen !== hub.gen) return;
2088
+ // A message phase ran: it delivers the chat's new messages itself (no cold refresh).
2089
+ if (coldSweepCheckRef.current) {
2090
+ clearTimeout(coldSweepCheckRef.current);
2091
+ coldSweepCheckRef.current = null;
2092
+ }
2093
+ const anchored = anchoredWindowRef.current;
2094
+ const forThisChat = event.messages.filter(
2095
+ (m: any) =>
2096
+ belongsToThisList(m) &&
2097
+ !(hideGroupActionMessages && m?.getCategory?.() === MessageCategoryConstants.action) &&
2098
+ sweptRowAccepted(m)
2099
+ );
2100
+ // Anchored on an older message (a jump, start-from-unread): the sweep updates the rows
2101
+ // shown and inserts nothing. A newer message put past the window's end leaves a hole, and
2102
+ // "load newer" anchors on the newest row shown, so it would skip everything in it. The
2103
+ // messages are in the SDK's store: scrolling to the end, or "latest", reads them.
2104
+ const forThisList = anchored ? onlyShownRows(messagesContentListRef.current, forThisChat) : forThisChat;
2105
+ heldReceiptsRef.current.clear();
2106
+ if (forThisList.length > 0) {
2107
+ offlinePathUsedRef.current = true;
2108
+ applyOfflineResult(upsertSortedDesc(messagesContentListRef.current, forThisList));
2109
+ }
2110
+ // One cumulative read receipt for the newest message, if the user is at the bottom.
2111
+ const newest = messagesContentListRef.current.find((m) => serverIdOf(m) > 0 && !m?.isStreamMessage);
2112
+ if (
2113
+ !anchored &&
2114
+ forThisList.length > 0 &&
2115
+ newest &&
2116
+ (isAtBottom() || isNearBottom()) &&
2117
+ !newest.getReadAt?.() &&
2118
+ newest.getSender?.()?.getUid?.() !== loggedInUser.current?.getUid()
2119
+ ) {
2120
+ CometChat.markAsRead(newest).catch(rememberIfReadOffline);
2121
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, { message: newest });
2122
+ }
2123
+ if (event.outcome === "PARTIAL" && offlinePathUsedRef.current && !anchored) refreshNewestWindow();
2124
+ },
2125
+ onSyncFailed: (event: SyncFailedEvent) => {
2126
+ if (event.phase !== "message" || event.gen !== OfflineHub.getInstance().gen) return;
2127
+ if (offlinePathUsedRef.current && !anchoredWindowRef.current) refreshNewestWindow();
2128
+ },
2129
+ onMessagesUpdated: (event: MessagesUpdatedEvent) => {
2130
+ if (event.gen !== OfflineHub.getInstance().gen) return;
2131
+ const rows = messagesContentListRef.current;
2132
+ // Update rows shown; never insert (BEH-INV-11).
2133
+ const shown = event.messages.filter((m: any) => findRowIndex(rows, m) !== -1);
2134
+ if (shown.length > 0) applyOfflineResult(upsertSortedDesc(rows, shown));
2135
+ },
2136
+ onSessionEnded: () => {
2137
+ // Logout, user switch or cache reset: nothing of the old session stays on screen.
2138
+ if (!offlinePathUsedRef.current) return;
2139
+ listOpGenRef.current++;
2140
+ heldReceiptsRef.current.clear();
2141
+ temporaryMessageListRef.current = [];
2142
+ messagesContentListRef.current = [];
2143
+ setMessagesList([]);
2144
+ setOfflineFooter("none");
2145
+ setOfflineNewerBlocked(false);
2146
+ setOfflineMiss(false);
2147
+ offlineFooterRetryableRef.current = false;
2148
+ reloadOnConnectRef.current = false;
2149
+ },
2150
+ onConnected: () => {
2151
+ // The connection is back (offline ON): a shown footer now loads on scroll as well as on
2152
+ // tap (UIK-READ-03). Nothing is fetched on reconnect except the one load again of the offline
2153
+ // state (D84 rule 8) and the page behind each blocked "Connect to load more" edge (rule 9).
2154
+ if (isOfflineOn() && offlineFooterRef.current === "connect") offlineFooterRetryableRef.current = true;
2155
+ if (reloadOnConnectRef.current && isOfflineOn()) {
2156
+ reloadOnConnectRef.current = false;
2157
+ reloadNewestPage();
2158
+ return;
2159
+ }
2160
+ loadBlockedEdgesOnReconnect();
2161
+ },
2162
+ onCacheReset: (event: CacheResetEvent) => {
2163
+ if (event.gen !== OfflineHub.getInstance().gen) return;
2164
+ if (!offlinePathUsedRef.current && !isOfflineOn()) return;
2165
+ // Reload two-phase from the rebuilt cache.
2166
+ reloadNewestPage();
2167
+ },
2168
+ };
2169
+ const offlineHandlersRef = useRef(offlineHandlers);
2170
+ offlineHandlersRef.current = offlineHandlers;
2171
+
2172
+ useEffect(() => {
2173
+ // Private hub channel (never the public bus). Inert while offline is off: nothing emits.
2174
+ const hub = OfflineHub.getInstance();
2175
+ const subscriptions = [
2176
+ hub.sendState$.subscribe((e) => offlineHandlersRef.current.onSendState(e)),
2177
+ hub.messageSync$.subscribe((e) => offlineHandlersRef.current.onMessageSync(e)),
2178
+ hub.conversationSync$.subscribe((e) => offlineHandlersRef.current.onConversationSync(e)),
2179
+ hub.syncFailed$.subscribe((e) => offlineHandlersRef.current.onSyncFailed(e)),
2180
+ hub.messagesUpdated$.subscribe((e) => offlineHandlersRef.current.onMessagesUpdated(e)),
2181
+ hub.session$.subscribe(() => offlineHandlersRef.current.onSessionEnded()),
2182
+ hub.cacheReset$.subscribe((e) => offlineHandlersRef.current.onCacheReset(e)),
2183
+ hub.connected$.subscribe(() => offlineHandlersRef.current.onConnected()),
2184
+ ];
2185
+ return () => {
2186
+ subscriptions.forEach((s) => s.unsubscribe());
2187
+ if (coldSweepCheckRef.current) clearTimeout(coldSweepCheckRef.current);
2188
+ };
2189
+ }, []);
2190
+
2191
+ const { notice: offlineNotice, dismiss: dismissOfflineNotice } = useOfflineNotice(
2192
+ !hideOfflineNotices,
2193
+ (n) => !n.previewsOnly && (!n.conversationId || !conversationId.current || n.conversationId === conversationId.current)
2194
+ );
2195
+
2196
+ /** Retry on a failed row: the SDK's retry for an outbox row, a fresh send otherwise. */
2197
+ const onRetryPress = (item: any) => {
2198
+ const hub = OfflineHub.getInstance();
2199
+ const offlineRow = isOfflineUnsent(item) || hub.directFailureOf(item) !== undefined;
2200
+ if (offlineRow && isOfflineOn()) {
2201
+ retryFailedMessage(item, sendKindOf(item));
2202
+ return;
2203
+ }
2204
+ if (offlineRow) hub.clearDirectFailed(item);
2205
+ resendMediaMessage(item);
2206
+ };
2207
+
2208
+ /**
2209
+ * Delete on an unsent row (BEH-SEND-36, R162): `discardLocalMessage` for an outbox row, the
2210
+ * screen only for a direct failure. A refusal never leaves a ghost row or a half change.
2211
+ */
2212
+ const onDeleteUnsentPress = (item: any) => {
2213
+ void deleteUnsentMessage(item).then((outcome) => {
2214
+ switch (outcome.kind) {
2215
+ case "removed":
2216
+ return; // the hub's discarded event removed the row
2217
+ case "sent": {
2218
+ // It went out meanwhile: delete it on the server, today's path and events.
2219
+ const sent = messagesContentListRef.current.find((m) => serverIdOf(m) === outcome.serverId);
2220
+ if (sent) deleteMessage(sent);
2221
+ else
2222
+ CometChat.deleteMessage(String(outcome.serverId))
2223
+ .then((res: any) => CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageDeleted, { message: res }))
2224
+ .catch((e: any) => onError && onError(e));
2225
+ return;
2226
+ }
2227
+ case "disabled":
2228
+ // Kill switch: every stranded row turns failed (direct); this one is then removed
2229
+ // from the screen, which is what Delete does for a direct failure.
2230
+ failStrandedOfflineSends();
2231
+ OfflineHub.getInstance().reportDiscardedByUser(item);
2232
+ return;
2233
+ case "in_flight":
2234
+ // Its send is under way: the row stays and the "Sending… try again in a moment"
2235
+ // notice is up (raised by the SDK's answer, R162). Not an error.
2236
+ return;
2237
+ default:
2238
+ // Not connected, store blip: the row stays; today's error.
2239
+ onError && onError((outcome as any).error);
2240
+ showToast(t("SOMETHING_WRONG"));
2241
+ }
2242
+ });
2243
+ };
2244
+
2245
+ /**
2246
+ * The options of an own unsent row (R162 / S73): Retry and Delete on every PENDING, SENDING
2247
+ * and FAILED row, and nothing that needs a server id. The SDK decides whether it can act: a
2248
+ * row whose send is under way answers IN_FLIGHT and the "Sending…" notice shows.
2249
+ */
2250
+ const openUnsentMessageOptions = (item: any) => {
2251
+ const actions = unsentActionsOf(unsentRowInfo(item));
2252
+ if (actions.length === 0) return;
2253
+ const dataSource: any = ChatConfigurator.dataSource;
2254
+ const options: any[] = [];
2255
+ if (actions.includes("retry")) {
2256
+ options.push({
2257
+ id: OFFLINE_OPTION_IDS.retry,
2258
+ title: t("RETRY"),
2259
+ icon: <Icon name="retry" color={mergedTheme.color.iconSecondary} />,
2260
+ onPress: () => {
2261
+ onRetryPress(item);
2262
+ requestAnimationFrame(() => setShowMessageOptions([]));
2263
+ },
2264
+ });
2265
+ }
2266
+ if (actions.includes("delete")) {
2267
+ const del = dataSource?.getDeleteOption?.(mergedTheme) ?? { id: MessageOptionConstants.deleteMessage, title: t("DELETE") };
2268
+ options.push({
2269
+ ...del,
2270
+ id: OFFLINE_OPTION_IDS.delete,
2271
+ onPress: () => {
2272
+ requestAnimationFrame(() => setShowMessageOptions([]));
2273
+ onDeleteUnsentPress(item);
2274
+ },
2275
+ });
2276
+ }
2277
+ setSelectedMessage(item);
2278
+ setShowMessageOptions(options);
1460
2279
  };
1461
2280
 
1462
2281
  const highlightMessage = (messageId: string) => {
@@ -1489,6 +2308,21 @@ export const CometChatMessageList = memo(
1489
2308
  }
1490
2309
 
1491
2310
  fetchingAroundIdRef.current = messageId; // Mark this message as being fetched
2311
+ // The jump replaces the window: a page read already in flight (older or newer) belongs to
2312
+ // the window being left and must not land in the jumped-to one. Its callbacks are dropped
2313
+ // (generation), so its loading flags are released here instead.
2314
+ jumpGenRef.current++;
2315
+ listOpGenRef.current++;
2316
+ loadingPrevMessagesRef.current = false;
2317
+ loadingMessagesRef.current = false;
2318
+ setLoadingMessages(false);
2319
+ setBottomLoading(false);
2320
+ setOfflineNewerBlocked(false); // the window being left owned that edge
2321
+ aroundReachedNewestRef.current = false;
2322
+ const aroundIdOffline = isOfflineOn(); // gate read once for this jump
2323
+ // Offline ON only (UIK-GATE-02/03): its phased paint is what leaves the list unpositioned
2324
+ // while paging and live messages run. With offline off the around read is today's, untouched.
2325
+ if (aroundIdOffline) beginPositioning();
1492
2326
 
1493
2327
  // Check if message exists in current list
1494
2328
  const messageExists = messagesContentListRef.current.find(msg =>
@@ -1508,169 +2342,237 @@ export const CometChatMessageList = memo(
1508
2342
  msgRequestBuilder.current?.setMessageId(targetMessageId);
1509
2343
  messageRequest.current = msgRequestBuilder.current?.build() || null;
1510
2344
 
1511
- // Get the target message first to ensure it exists
1512
- const targetMessage = await CometChat.getMessageDetails(targetMessageId);
1513
- if (!targetMessage) {
1514
- setListState("");
1515
- return;
1516
- }
1517
-
1518
2345
  // Create request builder for next messages (messages after the target).
1519
2346
  // Same types/categories filter as the main list: without it the server also returns
1520
2347
  // the hidden edit/delete records (category "action", type "message"), which no
1521
2348
  // template renders, so each one became an empty padded row after the jump.
1522
- let nextMessagesRequest = new CometChat.MessagesRequestBuilder()
1523
- .setLimit(15)
1524
- .setMessageId(targetMessageId)
1525
- .setTypes(ChatConfigurator.dataSource.getAllMessageTypes())
1526
- .setCategories(ChatConfigurator.dataSource.getAllMessageCategories());
1527
-
1528
- if (user) {
1529
- nextMessagesRequest = nextMessagesRequest.setUID(user.getUid());
1530
- }
2349
+ const buildNextMessagesRequest = () => {
2350
+ let nextMessagesRequest = new CometChat.MessagesRequestBuilder()
2351
+ .setLimit(AROUND_NEXT_PAGE_LIMIT)
2352
+ .setMessageId(targetMessageId)
2353
+ .setTypes(ChatConfigurator.dataSource.getAllMessageTypes())
2354
+ .setCategories(ChatConfigurator.dataSource.getAllMessageCategories());
1531
2355
 
1532
- if (group) {
1533
- nextMessagesRequest = nextMessagesRequest.setGUID(group.getGuid());
1534
- }
1535
-
1536
- // Main chat: Server excludes thread replies
1537
- if (!parentMessageId) {
1538
- nextMessagesRequest = nextMessagesRequest.hideReplies(true);
1539
- }
1540
- // Thread: Server includes only relevant messages
1541
- else {
1542
- nextMessagesRequest = nextMessagesRequest
1543
- .setParentMessageId(Number(parentMessageId))
1544
- .hideReplies(false);
1545
- if (isAgenticUser) {
1546
- nextMessagesRequest = nextMessagesRequest.withParent(true);
2356
+ if (user) {
2357
+ nextMessagesRequest = nextMessagesRequest.setUID(user.getUid());
1547
2358
  }
1548
- }
1549
2359
 
1550
- // Fetch messages before and after the target message
1551
- const nextMessages = await nextMessagesRequest.build().fetchNext();
2360
+ if (group) {
2361
+ nextMessagesRequest = nextMessagesRequest.setGUID(group.getGuid());
2362
+ }
1552
2363
 
1553
- // Combine messages: previous (reversed) + target + next
1554
- const allMessages = [
1555
- // ...previousMessages,
1556
- targetMessage,
1557
- ...nextMessages
1558
- ].reverse();
1559
-
1560
- // Remove duplicates and sort by timestamp (newest at top for FlatList)
1561
- const uniqueMessages = allMessages
1562
- // .filter((message, index, array) =>
1563
- // array.findIndex(m => m.getId() === message.getId()) === index
1564
- // )
1565
- // .sort((a, b) => b.getSentAt() - a.getSentAt());
1566
-
1567
- if (uniqueMessages.length > 0) {
1568
- // Check if this is the initial load using ref to ensure fresh state
1569
- const isInitialLoad = messagesContentListRef.current.length === 0;
1570
- messagesContentListRef.current = uniqueMessages;
1571
- setMessagesList(uniqueMessages);
1572
- onLoad && onLoad([...uniqueMessages].reverse());
1573
-
1574
- //This check is used to determine if this is the Initial Load of the chat screen.
1575
- // Check if this is the initial load (messagesList is empty).
1576
- // We check messagesList.length === 0 because setMessagesList above is async,
1577
- // so messagesList still reflects the state before this update.
1578
- // We only want to mark as read on the first load, not during subsequent updates.
1579
- // The !navigatedFromSearch condition ensures we don't mark as read when navigating from search results,
1580
- // as the user might want to keep messages unread for reference.
1581
- if (startFromUnreadMessages && isInitialLoad && !navigatedFromSearch && !goToMessageId) {
1582
- shouldSuppressHighlightRef.current = true;
1583
- // Mark entire conversation as read — clears unread count on server
1584
- if (user) {
1585
- CometChat.markConversationAsRead(user.getUid(), CometChat.RECEIVER_TYPE.USER).catch((e) => {
1586
- console.log("Error marking user conversation as read", e);
1587
- });
1588
- } else if (group) {
1589
- CometChat.markConversationAsRead(group.getGuid(), CometChat.RECEIVER_TYPE.GROUP).catch((e) => {
1590
- console.log("Error marking group conversation as read", e);
1591
- });
1592
- }
1593
- setUnreadCount(0);
1594
- // If we have next messages (unread messages), set the indicator on the first one.
1595
- // Otherwise, fallback to the target message (last read message).
1596
- if (nextMessages.length > 0) {
1597
- setNewMessageIndicatorId(String(nextMessages[0].getId()));
1598
- } else {
1599
- setNewMessageIndicatorId(messageId);
2364
+ // Main chat: Server excludes thread replies
2365
+ if (!parentMessageId) {
2366
+ nextMessagesRequest = nextMessagesRequest.hideReplies(true);
2367
+ }
2368
+ // Thread: Server includes only relevant messages
2369
+ else {
2370
+ nextMessagesRequest = nextMessagesRequest
2371
+ .setParentMessageId(Number(parentMessageId))
2372
+ .hideReplies(false);
2373
+ if (isAgenticUser) {
2374
+ nextMessagesRequest = nextMessagesRequest.withParent(true);
1600
2375
  }
1601
- //emitting event to update read receipts in other components
1602
- CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, {
1603
- message: uniqueMessages[0],
1604
- });
1605
- } else if (navigatedFromSearch) {
1606
- // If we navigated from search, we want to show the "New Messages" indicator
1607
- // but NOT mark the conversation as read immediately.
1608
- // We fetch the first unread message to place the indicator correctly.
1609
- const fetchFirstUnread = async () => {
1610
- try {
1611
- const convId = user?.getUid() ?? group?.getGuid();
1612
- const conversationType = user
1613
- ? CometChat.RECEIVER_TYPE.USER
1614
- : CometChat.RECEIVER_TYPE.GROUP;
1615
-
1616
- if (!convId) return;
1617
-
1618
- const conversation = await getConversationIfExists(convId, conversationType);
1619
- if (!conversation) return;
1620
- const unreadCount = conversation.getUnreadMessageCount();
1621
- setUnreadCount(unreadCount);
1622
-
1623
- if (unreadCount > 0) {
1624
- const lastReadMsgId = conversation.getLastReadMessageId();
1625
-
1626
- if (lastReadMsgId) {
1627
- // Filtered like the main list, so the "New messages" marker lands on the
1628
- // first unread message that is actually shown, not on a hidden edit/delete record.
1629
- let request = new CometChat.MessagesRequestBuilder()
1630
- .setLimit(1)
1631
- .setMessageId(Number(lastReadMsgId))
1632
- .setTypes(ChatConfigurator.dataSource.getAllMessageTypes())
1633
- .setCategories(ChatConfigurator.dataSource.getAllMessageCategories());
2376
+ }
2377
+ return nextMessagesRequest;
2378
+ };
1634
2379
 
1635
- if (user) request = request.setUID(user.getUid());
1636
- if (group) request = request.setGUID(group.getGuid());
2380
+ // Show the anchored window (target + the page after it). `firstPaint` is false only for
2381
+ // the offline path's server repaint over its cached paint: the one-time work (search
2382
+ // unread lookup, scroll target) is not repeated.
2383
+ const presentAroundPage = (targetMessage: any, nextMessages: any[], firstPaint: boolean) => {
2384
+ // Combine messages: previous (reversed) + target + next
2385
+ const allMessages = [
2386
+ // ...previousMessages,
2387
+ targetMessage,
2388
+ ...nextMessages
2389
+ ].reverse();
2390
+
2391
+ // Remove duplicates and sort by timestamp (newest at top for FlatList)
2392
+ const uniqueMessages = allMessages
2393
+ // .filter((message, index, array) =>
2394
+ // array.findIndex(m => m.getId() === message.getId()) === index
2395
+ // )
2396
+ // .sort((a, b) => b.getSentAt() - a.getSentAt());
2397
+
2398
+ if (uniqueMessages.length > 0) {
2399
+ // Check if this is the initial load using ref to ensure fresh state
2400
+ const isInitialLoad = messagesContentListRef.current.length === 0;
2401
+ messagesContentListRef.current = uniqueMessages;
2402
+ setMessagesList(uniqueMessages);
2403
+ onLoad && onLoad([...uniqueMessages].reverse());
2404
+
2405
+ //This check is used to determine if this is the Initial Load of the chat screen.
2406
+ // Check if this is the initial load (messagesList is empty).
2407
+ // We check messagesList.length === 0 because setMessagesList above is async,
2408
+ // so messagesList still reflects the state before this update.
2409
+ // We only want to mark as read on the first load, not during subsequent updates.
2410
+ // The !navigatedFromSearch condition ensures we don't mark as read when navigating from search results,
2411
+ // as the user might want to keep messages unread for reference.
2412
+ if (startFromUnreadMessages && isInitialLoad && !navigatedFromSearch && !goToMessageId) {
2413
+ shouldSuppressHighlightRef.current = true;
2414
+ // Mark entire conversation as read — clears unread count on server
2415
+ if (user) {
2416
+ CometChat.markConversationAsRead(user.getUid(), CometChat.RECEIVER_TYPE.USER).catch((e) => {
2417
+ console.log("Error marking user conversation as read", e);
2418
+ });
2419
+ } else if (group) {
2420
+ CometChat.markConversationAsRead(group.getGuid(), CometChat.RECEIVER_TYPE.GROUP).catch((e) => {
2421
+ console.log("Error marking group conversation as read", e);
2422
+ });
2423
+ }
2424
+ setUnreadCount(0);
2425
+ // If we have next messages (unread messages), set the indicator on the first one.
2426
+ // Otherwise, fallback to the target message (last read message).
2427
+ if (nextMessages.length > 0) {
2428
+ setNewMessageIndicatorId(String(nextMessages[0].getId()));
2429
+ } else {
2430
+ setNewMessageIndicatorId(messageId);
2431
+ }
2432
+ //emitting event to update read receipts in other components
2433
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, {
2434
+ message: uniqueMessages[0],
2435
+ });
2436
+ } else if (navigatedFromSearch && firstPaint) {
2437
+ // If we navigated from search, we want to show the "New Messages" indicator
2438
+ // but NOT mark the conversation as read immediately.
2439
+ // We fetch the first unread message to place the indicator correctly.
2440
+ const fetchFirstUnread = async () => {
2441
+ try {
2442
+ const convId = user?.getUid() ?? group?.getGuid();
2443
+ const conversationType = user
2444
+ ? CometChat.RECEIVER_TYPE.USER
2445
+ : CometChat.RECEIVER_TYPE.GROUP;
2446
+
2447
+ if (!convId) return;
2448
+
2449
+ const conversation = await getConversationIfExists(convId, conversationType);
2450
+ if (!conversation) return;
2451
+ const unreadCount = conversation.getUnreadMessageCount();
2452
+ setUnreadCount(unreadCount);
2453
+
2454
+ if (unreadCount > 0) {
2455
+ const lastReadMsgId = conversation.getLastReadMessageId();
2456
+
2457
+ if (lastReadMsgId) {
2458
+ // Filtered like the main list, so the "New messages" marker lands on the
2459
+ // first unread message that is actually shown, not on a hidden edit/delete record.
2460
+ let request = new CometChat.MessagesRequestBuilder()
2461
+ .setLimit(1)
2462
+ .setMessageId(Number(lastReadMsgId))
2463
+ .setTypes(ChatConfigurator.dataSource.getAllMessageTypes())
2464
+ .setCategories(ChatConfigurator.dataSource.getAllMessageCategories());
2465
+
2466
+ if (user) request = request.setUID(user.getUid());
2467
+ if (group) request = request.setGUID(group.getGuid());
1637
2468
 
1638
- if (!parentMessageId) {
1639
- request = request.hideReplies(true);
1640
- } else {
1641
- request = request.setParentMessageId(Number(parentMessageId)).hideReplies(false);
1642
- if (isAgenticUser) {
1643
- request = request.withParent(true);
2469
+ if (!parentMessageId) {
2470
+ request = request.hideReplies(true);
2471
+ } else {
2472
+ request = request.setParentMessageId(Number(parentMessageId)).hideReplies(false);
2473
+ if (isAgenticUser) {
2474
+ request = request.withParent(true);
2475
+ }
1644
2476
  }
1645
- }
1646
2477
 
1647
- const unreadMessages = await request.build().fetchNext();
1648
- if (unreadMessages.length > 0) {
1649
- setNewMessageIndicatorId(String(unreadMessages[0].getId()));
2478
+ const unreadMessages = await request.build().fetchNext();
2479
+ if (unreadMessages.length > 0) {
2480
+ setNewMessageIndicatorId(String(unreadMessages[0].getId()));
2481
+ }
1650
2482
  }
1651
2483
  }
2484
+ } catch (e) {
2485
+ console.log("Error fetching first unread message", e);
1652
2486
  }
1653
- } catch (e) {
1654
- console.log("Error fetching first unread message", e);
1655
- }
1656
- };
1657
- fetchFirstUnread();
2487
+ };
2488
+ fetchFirstUnread();
2489
+ }
2490
+
2491
+ // Reset layout state and set up for scrolling to target message
2492
+ // console.log(`Setting scroll target to message: ${messageId}`);
2493
+ if (firstPaint) {
2494
+ scrollTargetPendingRef.current = true;
2495
+ setScrollTargetId(messageId);
2496
+ }
1658
2497
  }
2498
+ };
1659
2499
 
1660
- // Reset layout state and set up for scrolling to target message
1661
- // console.log(`Setting scroll target to message: ${messageId}`);
1662
- setScrollTargetId(messageId);
2500
+ if (aroundIdOffline) {
2501
+ // Offline ON (BEH-READ-29): the target and the page after it, both two-phase. The
2502
+ // cached pair paints first; the server pair replaces it; offline a cached pair stays.
2503
+ const opGen = listOpGenRef.current;
2504
+ const hubGen = OfflineHub.getInstance().gen;
2505
+ let painted = false;
2506
+ let failure: { error: unknown; notConnected: boolean } | null = null;
2507
+ offlinePathUsedRef.current = true;
2508
+ await readAroundTwoPhase<any>(
2509
+ (listener) => offlineSdk().getMessageDetails(targetMessageId, listener),
2510
+ buildNextMessagesRequest().build(),
2511
+ {
2512
+ onPaint: (targetMessage, nextMessages, phase) => {
2513
+ // A short page from the server is the chat's newest end; a cached one proves nothing.
2514
+ aroundReachedNewestRef.current = phase === "server" && nextMessages.length < AROUND_NEXT_PAGE_LIMIT;
2515
+ presentAroundPage(targetMessage, nextMessages, !painted);
2516
+ painted = true;
2517
+ },
2518
+ onError: (error, notConnected) => {
2519
+ failure = { error, notConnected };
2520
+ },
2521
+ // The saved window stays on screen. D84 rule 2 and 5: a jump that could not reach the server
2522
+ // reports nothing; a real error reports once (the user started the jump).
2523
+ onKeptRowsError: (error) => {
2524
+ if (isNotConnectedError(error) || sdkConnected() === false) return;
2525
+ onError && onError(error as CometChat.CometChatException);
2526
+ },
2527
+ },
2528
+ () => opGen !== listOpGenRef.current || hubGen !== OfflineHub.getInstance().gen
2529
+ );
2530
+ if (failure) throw (failure as { error: unknown }).error ?? new Error("message not found");
2531
+ setListState("");
2532
+ return;
2533
+ }
2534
+
2535
+ // Get the target message first to ensure it exists
2536
+ const targetMessage = await CometChat.getMessageDetails(targetMessageId);
2537
+ if (!targetMessage) {
2538
+ setListState("");
2539
+ return;
1663
2540
  }
1664
2541
 
2542
+ let nextMessagesRequest = buildNextMessagesRequest();
2543
+
2544
+ // Fetch messages before and after the target message
2545
+ const nextMessages = await nextMessagesRequest.build().fetchNext();
2546
+
2547
+ presentAroundPage(targetMessage, nextMessages, true);
2548
+
1665
2549
  setListState("");
1666
2550
  } catch (error) {
1667
2551
  console.log("Error fetching messages around ID:", error);
1668
- setListState("error");
2552
+ if (aroundIdOffline && isNotConnectedError(error)) {
2553
+ // Offline: the anchored read needs the server; open on the saved newest window instead.
2554
+ endPositioning();
2555
+ setNavigationLoading(false);
2556
+ setHasTargetMessageId(false);
2557
+ fetchingAroundIdRef.current = null;
2558
+ msgRequestBuilder.current?.setMessageId(0);
2559
+ messageRequest.current = msgRequestBuilder.current?.build() || null;
2560
+ // D84 rule 2: rows on screen stay and a jump that could not reach the server reports nothing.
2561
+ // With nothing on screen the newest-page read below shows "Connect to load messages" and reports.
2562
+ getPreviousMessages();
2563
+ return;
2564
+ }
2565
+ endPositioning();
2566
+ // D83 (offline ON): rows on screen stay, no error view over them.
2567
+ if (aroundIdOffline && messagesContentListRef.current.length > 0) setListState("");
2568
+ else setListState("error");
1669
2569
  setNavigationLoading(false);
1670
2570
  onError && onError(error as CometChat.CometChatException);
1671
2571
  } finally {
1672
2572
  // setNavigationLoading(false);
1673
2573
  fetchingAroundIdRef.current = null;
2574
+ // Nothing was painted to scroll to (an empty answer): there is nothing to wait for.
2575
+ if (!scrollTargetPendingRef.current) endPositioning();
1674
2576
  }
1675
2577
  };
1676
2578
 
@@ -1713,6 +2615,7 @@ export const CometChatMessageList = memo(
1713
2615
  }
1714
2616
  shouldSuppressHighlightRef.current = false;
1715
2617
  setNavigationLoading(false); // Clear loading when scroll completes
2618
+ endPositioning(); // positioned: paging and live auto-scroll may run again
1716
2619
  }, 150);
1717
2620
  } else {
1718
2621
  // Position not measured yet - retry with faster progressive delays (up to 5 times)
@@ -1738,6 +2641,7 @@ export const CometChatMessageList = memo(
1738
2641
  }
1739
2642
  shouldSuppressHighlightRef.current = false;
1740
2643
  setNavigationLoading(false); // Clear loading when scroll completes
2644
+ endPositioning();
1741
2645
  }, 250);
1742
2646
  } catch (scrollError) {
1743
2647
  console.error('scrollToIndex failed immediately:', scrollError);
@@ -1746,6 +2650,7 @@ export const CometChatMessageList = memo(
1746
2650
  }
1747
2651
  shouldSuppressHighlightRef.current = false;
1748
2652
  setNavigationLoading(false); // Clear loading on final failure
2653
+ endPositioning();
1749
2654
  }
1750
2655
  }
1751
2656
  }
@@ -1789,14 +2694,17 @@ export const CometChatMessageList = memo(
1789
2694
  .catch((e: any) => console.log("error while fetching updated msgs", e));
1790
2695
  };
1791
2696
 
1792
- const getNewMessages = (updatedList: any[]) => {
2697
+ const getNewMessages = (updatedList: any[], cursor: number = lastID.current) => {
1793
2698
  let newRequestBuilder = msgRequestBuilder.current;
1794
- newRequestBuilder?.setMessageId(lastID.current);
2699
+ newRequestBuilder?.setMessageId(cursor);
2700
+ const newRequest = newRequestBuilder?.build();
2701
+ // D3: page against the request's own limit, from a cursor that moves.
2702
+ const requestLimit = Number((newRequest as any)?.getLimit?.()) || 30;
1795
2703
 
1796
- newRequestBuilder
1797
- ?.build()
1798
- .fetchNext()
2704
+ newRequest
2705
+ ?.fetchNext()
1799
2706
  .then((newMessages: any[]) => {
2707
+ const nextCursor = nextCatchUpCursor(newMessages, cursor, requestLimit);
1800
2708
  let cleanUpdatedList = [...updatedList];
1801
2709
  let finalOutput = CommonUtils.mergeArrays(newMessages.reverse(), cleanUpdatedList, [
1802
2710
  "id",
@@ -1837,8 +2745,9 @@ export const CometChatMessageList = memo(
1837
2745
  temporaryMessageListRef.current = [...currentUnreadMessages];
1838
2746
  setUnreadCount(temporaryMessageListRef.current.length);
1839
2747
  }
1840
- if (newMessages.length === 30) {
1841
- getNewMessages(tmpList);
2748
+ if (nextCursor !== null) {
2749
+ lastID.current = nextCursor;
2750
+ getNewMessages(tmpList, nextCursor);
1842
2751
  }
1843
2752
  newRequestBuilder?.setMessageId(undefined);
1844
2753
  })
@@ -2074,6 +2983,8 @@ export const CometChatMessageList = memo(
2074
2983
  },
2075
2984
  (error: any) => {
2076
2985
  console.log("Error marking as unread", error);
2986
+ // Offline this fails every time: nothing is left half-done on screen (UIK-MUT-01).
2987
+ if (isOfflineOn()) setShowMessageOptions([]);
2077
2988
  }
2078
2989
  );
2079
2990
  };
@@ -2183,6 +3094,14 @@ export const CometChatMessageList = memo(
2183
3094
  const newMessage = (newMessage: any, isReceived = true) => {
2184
3095
  let baseMessage = newMessage as CometChat.BaseMessage;
2185
3096
 
3097
+ // Offline: a message the SDK's catch-up sweep delivered goes into its sorted place with no
3098
+ // sound, no unread +1 and no per-message receipt (UIK-SYNC-02). Only the offline SDK
3099
+ // stamps SYNC, so this never runs with offline off.
3100
+ if (isReceived && isSyncDelivered(newMessage)) {
3101
+ insertSyncedMessage(newMessage);
3102
+ return;
3103
+ }
3104
+
2186
3105
  // Cases 2b/4b — a message I sent from ANOTHER of my devices. Sending subscribes me
2187
3106
  // wherever I sent it from, but this copy came over the socket and carries no flag, so
2188
3107
  // without this my own message reads "Subscribe" here until a refetch. Checked BEFORE
@@ -2231,7 +3150,9 @@ export const CometChatMessageList = memo(
2231
3150
  (String(baseMessage.getParentMessageId()) === String(agenticParentId) ||
2232
3151
  String(baseMessage.getId()) === String(agenticParentId))))
2233
3152
  ) {
2234
- CometChat.markAsDelivered(newMessage);
3153
+ CometChat.markAsDelivered(newMessage).catch((error: any) => {
3154
+ console.log("Error marking message as delivered", error);
3155
+ });
2235
3156
  bottomHandler(newMessage, isReceived);
2236
3157
  } else {
2237
3158
  return;
@@ -2243,9 +3164,13 @@ export const CometChatMessageList = memo(
2243
3164
  messageToSameConversation(baseMessage);
2244
3165
  if (inSameConversation) {
2245
3166
  if (user) {
2246
- CometChat.markConversationAsDelivered(user.getUid(), CometChat.RECEIVER_TYPE.USER);
3167
+ CometChat.markConversationAsDelivered(user.getUid(), CometChat.RECEIVER_TYPE.USER).catch((error: any) => {
3168
+ console.log("Error marking conversation as delivered", error);
3169
+ });
2247
3170
  } else if (group) {
2248
- CometChat.markConversationAsDelivered(group.getGuid(), CometChat.RECEIVER_TYPE.GROUP);
3171
+ CometChat.markConversationAsDelivered(group.getGuid(), CometChat.RECEIVER_TYPE.GROUP).catch((error: any) => {
3172
+ console.log("Error marking conversation as delivered", error);
3173
+ });
2249
3174
  }
2250
3175
  if (!parentMessageId && newMessage.getParentMessageId()) {
2251
3176
  const parentId = String(
@@ -2336,6 +3261,14 @@ export const CometChatMessageList = memo(
2336
3261
  if (!isReceived) {
2337
3262
  return;
2338
3263
  }
3264
+ if (positioningRef.current) {
3265
+ // A jump or start-from-unread window is still being scrolled to its anchor: following
3266
+ // this message to the bottom would end the list at the newest messages. It waits with
3267
+ // the others that arrived while reading older ones.
3268
+ if (!skipAddToList) temporaryMessageListRef.current = [newMessage, ...temporaryMessageListRef.current];
3269
+ setUnreadCount((prev) => prev + 1);
3270
+ return;
3271
+ }
2339
3272
  if (isAtBottom() || isNearBottom() || scrollToBottomOnNewMessages) {
2340
3273
  if (!skipAddToList) {
2341
3274
  addToMessageList(newMessage);
@@ -2593,9 +3526,10 @@ export const CometChatMessageList = memo(
2593
3526
  pinSaveAuthoritative: boolean = false
2594
3527
  ) => {
2595
3528
  let condition: (value: any, index: number, obj: any[]) => unknown;
3529
+ // D2: null-safe — two rows that both lack the identity are never the same message.
2596
3530
  if (withMuid) {
2597
- condition = (msg) => msg["muid"] == editedMessage["muid"];
2598
- } else condition = (msg) => msg.getId() == editedMessage.getId();
3531
+ condition = (msg) => sameMessageByMuid(msg, editedMessage);
3532
+ } else condition = (msg) => sameMessageById(msg, editedMessage);
2599
3533
  let msgIndex = messagesContentListRef.current.findIndex(condition);
2600
3534
  if (msgIndex > -1) {
2601
3535
 
@@ -2685,6 +3619,8 @@ export const CometChatMessageList = memo(
2685
3619
  };
2686
3620
 
2687
3621
  const deleteMessage = (message: CometChat.BaseMessage) => {
3622
+ // Offline ON (gate read once): a failed delete also shows today's error notice (ENG-41199).
3623
+ const offlineOn = isOfflineOn();
2688
3624
  CometChat.deleteMessage(message.getId().toString())
2689
3625
  .then((res: any) => {
2690
3626
  CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageDeleted, {
@@ -2698,6 +3634,8 @@ export const CometChatMessageList = memo(
2698
3634
  deleteItem.current = undefined;
2699
3635
  setShowDeleteModal(false);
2700
3636
  onError && onError(rej);
3637
+ const errorText = offlineMutationErrorText(offlineOn, t);
3638
+ if (errorText) showToast(errorText);
2701
3639
  });
2702
3640
  };
2703
3641
 
@@ -2849,7 +3787,13 @@ export const CometChatMessageList = memo(
2849
3787
  }
2850
3788
  );
2851
3789
 
2852
- if (index === -1) return;
3790
+ if (index === -1) {
3791
+ // Offline: the receipt beat the ack of an own unsent row; apply it when the id lands.
3792
+ if (offlinePathUsedRef.current && messagesContentListRef.current.some((m) => isOfflineUnsent(m))) {
3793
+ heldReceiptsRef.current.hold(Number(receiptMessageId), receipt);
3794
+ }
3795
+ return;
3796
+ }
2853
3797
 
2854
3798
  // Clone-first approach: shallow copy the array, then clone only messages
2855
3799
  // whose receipt status actually changes. Unchanged items keep original references
@@ -3057,7 +4001,13 @@ export const CometChatMessageList = memo(
3057
4001
  // for getMessagesAroundId causes it to leak into the main message list.
3058
4002
  if (!parentMessageId) {
3059
4003
  try {
3060
- const lastReadMsg = await CometChat.getMessageDetails(Number(lastReadMessageId));
4004
+ // Offline ON: two-phase, so a cached anchor validates offline.
4005
+ const lastReadMsg: any = isOfflineOn()
4006
+ ? await resolveTwoPhase<any>(
4007
+ (listener) => offlineSdk().getMessageDetails(Number(lastReadMessageId), listener),
4008
+ "Message"
4009
+ )
4010
+ : await CometChat.getMessageDetails(Number(lastReadMessageId));
3061
4011
  const lastReadParentId = lastReadMsg?.getParentMessageId
3062
4012
  ? lastReadMsg.getParentMessageId()
3063
4013
  : (lastReadMsg as any)?.parentMessageId;
@@ -3191,8 +4141,24 @@ export const CometChatMessageList = memo(
3191
4141
  }
3192
4142
  }, [user?.getUid(), group?.getGuid(), isAgenticUser]);
3193
4143
 
4144
+ // D4: the SDK/UI listeners below are registered once per chat. They used to re-subscribe on
4145
+ // every unreadCount change (it was an effect dependency only so the handlers would see the
4146
+ // current count), and each re-subscribe was a window in which a connection or message event
4147
+ // could be missed. The handlers now reach the current render's functions through this ref,
4148
+ // so they read current state without the listeners churning.
4149
+ // (Assigned on every render further down, once every handler it names is declared.)
4150
+ const listenerHandlersRef = useRef<any>(null);
4151
+
3194
4152
  useEffect(() => {
3195
4153
  //add listeners
4154
+ const newMessage = (...args: any[]) => listenerHandlersRef.current.newMessage(...args);
4155
+ const messageEdited = (...args: any[]) => listenerHandlersRef.current.messageEdited(...args);
4156
+ const updateMessageReceipt = (...args: any[]) =>
4157
+ listenerHandlersRef.current.updateMessageReceipt(...args);
4158
+ const updateMessageReaction = (...args: any[]) =>
4159
+ listenerHandlersRef.current.updateMessageReaction(...args);
4160
+ const getUpdatedPreviousMessages = () => listenerHandlersRef.current.getUpdatedPreviousMessages();
4161
+ const addToMessageList = (...args: any[]) => listenerHandlersRef.current.addToMessageList(...args);
3196
4162
 
3197
4163
  // AI Assistant listener for agent chats
3198
4164
  if (isAgenticUser && user && (!parentMessageId || (parentMessageId && isAgenticUser))) {
@@ -3711,6 +4677,11 @@ export const CometChatMessageList = memo(
3711
4677
  new CometChat.ConnectionListener({
3712
4678
  onConnected: () => {
3713
4679
  streamOnConnected();
4680
+ // Offline ON: no kit message fetch on reconnect; the SDK's sweep delivers what was
4681
+ // missed (UIK-SYNC-01). OFF: today's catch-up, unchanged.
4682
+ if (isOfflineOn()) return;
4683
+ // Kill switch: offline turned off with un-acked rows shown → failed (direct) + notice.
4684
+ listenerHandlersRef.current.failStrandedOfflineSends();
3714
4685
  if (lastID.current && !isAgenticUser) {
3715
4686
  getUpdatedPreviousMessages();
3716
4687
  }
@@ -3749,7 +4720,7 @@ export const CometChatMessageList = memo(
3749
4720
  }
3750
4721
  }
3751
4722
  };
3752
- }, [unreadCount, user, group, isAgenticUser]);
4723
+ }, [user, group, isAgenticUser]);
3753
4724
 
3754
4725
  useEffect(() => {
3755
4726
  if (aiAssistantTools) {
@@ -3867,6 +4838,17 @@ export const CometChatMessageList = memo(
3867
4838
  messageEdited(modifiedMessage, false);
3868
4839
  };
3869
4840
 
4841
+ // D4: the current render's handlers, for the once-per-chat listeners registered above.
4842
+ listenerHandlersRef.current = {
4843
+ newMessage,
4844
+ messageEdited,
4845
+ updateMessageReceipt,
4846
+ updateMessageReaction,
4847
+ getUpdatedPreviousMessages,
4848
+ addToMessageList,
4849
+ failStrandedOfflineSends,
4850
+ };
4851
+
3870
4852
  const getCurrentBubbleStyle = useCallback(
3871
4853
  (item: CometChat.BaseMessage): BubbleStyles => {
3872
4854
  const type = (() => {
@@ -3977,7 +4959,7 @@ export const CometChatMessageList = memo(
3977
4959
  item.getCategory()
3978
4960
  )
3979
4961
  ) {
3980
- const senderName = (item.getSender()?.getName() || "").trim();
4962
+ const senderName = stripBidiControls(item.getSender()?.getName()).trim();
3981
4963
  return (
3982
4964
  <View style={staticStyles.flexRow}>
3983
4965
  {Boolean(senderName) && (
@@ -4065,7 +5047,13 @@ export const CometChatMessageList = memo(
4065
5047
  const hasErrorMetadata = item?.getData?.()?.metaData?.error;
4066
5048
  const hasErrorInMetadata = item?.getMetadata?.()?.error;
4067
5049
  const hasErrorProp = (item as any)?.error;
4068
- if (hasErrorMetadata || hasErrorInMetadata || hasErrorProp) {
5050
+ // Offline rows show their state from the SDK (clock / failed), never a receipt.
5051
+ const offlineReceipt = offlineReceiptOf(item);
5052
+ if (offlineReceipt === "error") {
5053
+ messageState = MessageReceipt.ERROR;
5054
+ } else if (offlineReceipt === "wait") {
5055
+ messageState = MessageReceipt.WAIT;
5056
+ } else if (hasErrorMetadata || hasErrorInMetadata || hasErrorProp) {
4069
5057
  messageState = MessageReceipt.ERROR;
4070
5058
  } else if (item.getReadAt() || nextItemIsRead) messageState = MessageReceipt.READ;
4071
5059
  else if (item.getDeliveredAt() || nextItemIsDelivered)
@@ -4220,33 +5208,74 @@ export const CometChatMessageList = memo(
4220
5208
  sentIconStyle: _style.receiptStyles.sentIconStyle,
4221
5209
  readIconStyle: _style.receiptStyles.readIconStyle,
4222
5210
  waitIconStyle: _style.receiptStyles.waitIconStyle,
4223
- errorIconStyle: _style.receiptStyles.errorIconStyle,
5211
+ errorIconStyle:
5212
+ offlineReceipt === "error" && mergedTheme.messageListStyles?.offlineStyles?.failedIconStyle
5213
+ ? { ..._style.receiptStyles.errorIconStyle, ...mergedTheme.messageListStyles.offlineStyles.failedIconStyle }
5214
+ : _style.receiptStyles.errorIconStyle,
4224
5215
  deliveredIconStyle: _style.receiptStyles.deliveredIconStyle,
4225
5216
  }}
4226
5217
  />
4227
5218
  );
5219
+ // Offline rows are announced, not shown by icon colour alone (UIK-A11Y-01).
5220
+ if (offlineReceipt === "wait") {
5221
+ return (
5222
+ <View
5223
+ style={staticStyles.receiptContainer}
5224
+ accessible={true}
5225
+ accessibilityLabel={t(OFFLINE_STRING_KEYS.notSentYet)}
5226
+ >
5227
+ {receiptEl}
5228
+ <Text
5229
+ testID="cc.message.status.not-sent-yet"
5230
+ style={[
5231
+ _style.dateStyles.textStyle,
5232
+ { textTransform: "none", marginStart: 4 },
5233
+ mergedTheme.messageListStyles?.offlineStyles?.notSentYetTextStyle,
5234
+ ]}
5235
+ >
5236
+ {t(OFFLINE_STRING_KEYS.notSentYet)}
5237
+ </Text>
5238
+ </View>
5239
+ );
5240
+ }
4228
5241
  // A first/middle failed/blocked batch member shows JUST the error icon (no
4229
5242
  // timestamp, no Retry label) so the group collapse never hides the failure.
4230
5243
  if (messageState === MessageReceipt.ERROR && _isCollapsibleBatchMember) {
4231
5244
  return <View testID="batch-error-icon" style={staticStyles.receiptContainer}>{receiptEl}</View>;
4232
5245
  }
4233
5246
  // §12.1 — a failed send becomes a tappable "Retry" (re-sends this message).
4234
- return messageState === MessageReceipt.ERROR ? (
5247
+ // D1: only for a row the server never accepted and moderation did not reject;
5248
+ // those keep the error icon with no Retry.
5249
+ // Offline rows: every failed row offers Retry, whatever its reason (R162). Otherwise
5250
+ // only a category the kit can re-send (text, media, custom): an interactive message
5251
+ // has no resend path here, so it keeps the error icon with no Retry that does nothing.
5252
+ return messageState === MessageReceipt.ERROR &&
5253
+ isRetryableFailedRow(item, getModerationStatus(item)) &&
5254
+ (offlineReceipt === null ? resendKindOf(item) !== null : canRetryUnsent(item)) ? (
4235
5255
  <TouchableOpacity
4236
- style={[staticStyles.receiptContainer, staticStyles.receiptRow]}
4237
- onPress={() => resendMediaMessage(item)}
5256
+ style={[
5257
+ staticStyles.receiptContainer,
5258
+ staticStyles.receiptRow,
5259
+ offlineReceipt === "error" ? mergedTheme.messageListStyles?.offlineStyles?.failedRowStyle : null,
5260
+ ]}
5261
+ onPress={() => onRetryPress(item)}
4238
5262
  accessibilityRole="button"
4239
- accessibilityLabel={t("RETRY") ?? "Retry"}
5263
+ accessibilityLabel={
5264
+ offlineReceipt === "error"
5265
+ ? t(OFFLINE_STRING_KEYS.notSentTapToRetry)
5266
+ : t("RETRY") ?? "Retry"
5267
+ }
4240
5268
  hitSlop={{ top: 6, bottom: 6, left: 6, right: 6 }}
4241
5269
  >
4242
5270
  {receiptEl}
4243
5271
  <Text
4244
5272
  style={[
4245
5273
  _style.dateStyles.textStyle,
4246
- { textTransform: "none", marginLeft: 4, color: mergedTheme.color.error },
5274
+ { textTransform: "none", marginStart: 4, color: mergedTheme.color.error },
5275
+ offlineReceipt === "error" ? mergedTheme.messageListStyles?.offlineStyles?.retryTextStyle : null,
4247
5276
  ]}
4248
5277
  >
4249
- {t("RETRY") ?? "Retry"}
5278
+ {offlineReceipt === "error" ? t(OFFLINE_STRING_KEYS.notSentTapToRetry) : t("RETRY") ?? "Retry"}
4250
5279
  </Text>
4251
5280
  </TouchableOpacity>
4252
5281
  ) : (
@@ -4306,28 +5335,20 @@ export const CometChatMessageList = memo(
4306
5335
  [getBatchImageVideoItems]
4307
5336
  );
4308
5337
 
4309
- // §12.1 — retry a FAILED outgoing media message (e.g. one member of a partial batch).
4310
- // Clears the error flag, then re-sends via the canonical CometChatUIKit path which
4311
- // re-emits ccMessageSent inprogress→success/error; this list reconciles by muid in place.
5338
+ // §12.1 / D1 — retry a FAILED outgoing message (text, custom or media, e.g. one member of a
5339
+ // partial batch) that the server never accepted. Clears the error marks, then re-sends via
5340
+ // the canonical CometChatUIKit path which re-emits ccMessageSent inprogress→success/error;
5341
+ // this list reconciles by muid in place. Moderation-disapproved rows are never re-sent.
4312
5342
  const resendMediaMessage = useCallback((message: CometChat.BaseMessage) => {
4313
- try {
4314
- if (!(message instanceof CometChat.MediaMessage)) return;
4315
- const data: any = (message as any).getData?.() || {};
4316
- if (data?.metaData?.error) {
4317
- delete data.metaData.error;
4318
- (message as any).setData?.(data);
4319
- }
4320
- const md: any = (message as any).getMetadata?.();
4321
- if (md?.error) {
4322
- delete md.error;
4323
- (message as any).setMetadata?.(md);
4324
- }
4325
- (message as any).error = undefined;
4326
- // On failure CometChatUIKit.sendMediaMessage re-applies the error flag + emits error.
4327
- CometChatUIKit.sendMediaMessage(message as CometChat.MediaMessage).catch(() => {});
4328
- } catch (e) {
4329
- // best-effort retry
4330
- }
5343
+ resendFailedMessage(
5344
+ message,
5345
+ {
5346
+ sendText: (m) => CometChatUIKit.sendTextMessage(m),
5347
+ sendMedia: (m) => CometChatUIKit.sendMediaMessage(m),
5348
+ sendCustom: (m) => CometChatUIKit.sendCustomMessage(m),
5349
+ },
5350
+ getModerationStatus(message)
5351
+ );
4331
5352
  }, []);
4332
5353
 
4333
5354
  const reactToMessage = (emoji: string, messageObj?: CometChat.BaseMessage) => {
@@ -4338,6 +5359,11 @@ export const CometChatMessageList = memo(
4338
5359
  msgObj.getId = () => originalMessage.getId();
4339
5360
  }
4340
5361
 
5362
+ // The untouched copy a failed write rolls back to (UIK-MUT-01). The optimistic update below
5363
+ // mutates msgObj's own reaction objects, so rolling back to msgObj left the change on screen.
5364
+ const rollbackMessage = CommonUtils.clone(msgObj);
5365
+ // Offline ON (gate read once): a failed write also shows today's error notice (ENG-41199).
5366
+ const offlineOn = isOfflineOn();
4341
5367
  const messageId = msgObj?.getId();
4342
5368
  const reactions = msgObj?.getReactions() || [];
4343
5369
  const emojiObject = reactions?.find((reaction: any) => {
@@ -4372,9 +5398,11 @@ export const CometChatMessageList = memo(
4372
5398
  .then((message: any) => { })
4373
5399
  .catch((error: any) => {
4374
5400
  CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageEdited, {
4375
- message: msgObj,
5401
+ message: rollbackMessage,
4376
5402
  status: messageStatus.success,
4377
5403
  });
5404
+ const errorText = offlineMutationErrorText(offlineOn, t);
5405
+ if (errorText) showToast(errorText);
4378
5406
  });
4379
5407
  } else {
4380
5408
  const updatedReactions: any[] = [];
@@ -4409,9 +5437,11 @@ export const CometChatMessageList = memo(
4409
5437
  .then((response: any) => { })
4410
5438
  .catch((error: any) => {
4411
5439
  CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageEdited, {
4412
- message: msgObj,
5440
+ message: rollbackMessage,
4413
5441
  status: messageStatus.success,
4414
5442
  });
5443
+ const errorText = offlineMutationErrorText(offlineOn, t);
5444
+ if (errorText) showToast(errorText);
4415
5445
  });
4416
5446
  }
4417
5447
 
@@ -4555,8 +5585,7 @@ export const CometChatMessageList = memo(
4555
5585
 
4556
5586
  <Text
4557
5587
  style={_style.threadedMessageStyles?.indicatorTextStyle}
4558
- >{`${item.getReplyCount()} ${item.getReplyCount() > 1 ? t("REPLIES") : t("REPLY")
4559
- }`}</Text>
5588
+ >{pluralCountLabel(t, "REPLY_COUNT", item.getReplyCount(), language)}</Text>
4560
5589
  <CometChatBadge
4561
5590
  style={{
4562
5591
  containerStyle: _style.threadedMessageStyles?.unreadCountStyle?.containerStyle,
@@ -4567,7 +5596,7 @@ export const CometChatMessageList = memo(
4567
5596
  </TouchableOpacity>
4568
5597
  );
4569
5598
  },
4570
- [mergedTheme]
5599
+ [mergedTheme, t, language]
4571
5600
  );
4572
5601
 
4573
5602
  const privateMessage = (item: CometChat.BaseMessage) => {
@@ -4591,9 +5620,26 @@ export const CometChatMessageList = memo(
4591
5620
  // Tokens become names; typed token text (stored escaped) reads as typed.
4592
5621
  let textMessage = unescapeTypedMentionTokens(getPlainString(strippedText, messageObject));
4593
5622
  let fileUrl = messageObject.getData()["url"];
5623
+ // Offline ON: share the saved file, never re-fetch the URL (BEH-MEDIA-18). The saved file has
5624
+ // no extension, so it is named after the attachment.
5625
+ let localMediaName = "";
5626
+ if (messageObject["type"] !== "text" && fileUrl) {
5627
+ const attachment = messageObject?.getAttachment?.();
5628
+ const source = attachment ? mediaActionSource(attachment) : null;
5629
+ if (source?.kind === "unavailable") {
5630
+ setShowMessageOptions([]);
5631
+ notifyMediaUnavailable();
5632
+ return;
5633
+ }
5634
+ if (source?.kind === "local") {
5635
+ fileUrl = source.uri;
5636
+ localMediaName = attachment?.getName?.() ?? "";
5637
+ }
5638
+ }
4594
5639
 
4595
5640
  const getFileName = () => {
4596
5641
  if (!fileUrl) return "";
5642
+ if (localMediaName) return localMediaName;
4597
5643
  return fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length).replace(" ", "_");
4598
5644
  };
4599
5645
 
@@ -4897,87 +5943,48 @@ export const CometChatMessageList = memo(
4897
5943
  return hasTemplate?.ReplyView?.(message, bubbleAlignment) || null;
4898
5944
  }, [hasTemplate, message, bubbleAlignment, mergedTheme, templates]);
4899
5945
 
4900
- if (hasTemplate) {
4901
- if (hasTemplate?.BubbleView) return hasTemplate?.BubbleView(message);
4902
-
4903
- const onLongPress = useCallback(() => {
4904
- // Ensure the keyboard is dismissed before showing options so the action sheet / menu isn't obscured
4905
- Keyboard.dismiss();
4906
-
4907
- if (message.getDeletedBy() != null) return;
4908
-
4909
- if (!message.getId()) {
4910
- return;
4911
- }
4912
- // console.log({hasTemplate});
4913
-
4914
- setSelectedMessage(message);
4915
- hasTemplate && openOptionsForMessage(message, hasTemplate);
4916
- }, [hasTemplate, message, openOptionsForMessage]);
4917
-
4918
- const onPress = useCallback(() => {
4919
- Keyboard.dismiss();
4920
- }, []);
4921
-
4922
- // Swipe-to-reply functionality
4923
- const onReply = useCallback(() => {
4924
- if (message.getDeletedBy() != null) return;
4925
- if (!message.getId()) return;
4926
-
4927
- CometChatMessageEvents.emit(CometChatMessageEvents.ccReplyToMessage, {
4928
- message: message,
4929
- status: messageStatus.inprogress,
4930
- });
4931
- }, [message]);
4932
-
4933
- const swipeAnimatedValue = useRef(new Animated.Value(0)).current;
4934
- const replyIconOpacity = useRef(new Animated.Value(0)).current;
4935
-
4936
- const handlePanGesture = useCallback((event: PanGestureHandlerGestureEvent) => {
4937
- const { translationX, velocityX } = event.nativeEvent;
4938
-
4939
- // Only allow swiping from left to right for replies
4940
- if (translationX <= 0) return;
5946
+ // Hooks run before the template check so every render calls the same hooks.
5947
+ const onLongPress = useCallback(() => {
5948
+ // Ensure the keyboard is dismissed before showing options so the action sheet / menu isn't obscured
5949
+ Keyboard.dismiss();
4941
5950
 
4942
- const swipeThreshold = 80; // Threshold to trigger reply
4943
- const maxSwipeDistance = 120; // Maximum swipe distance
5951
+ if (message.getDeletedBy() != null) return;
4944
5952
 
4945
- // Calculate progress (0 to 1)
4946
- const progress = Math.min(translationX / maxSwipeDistance, 1);
5953
+ if (!message.getId()) {
5954
+ // Offline: an unsent row offers Retry and Delete (R162).
5955
+ if (offlineReceiptOf(message) !== null) openUnsentMessageOptions(message);
5956
+ return;
5957
+ }
5958
+ // console.log({hasTemplate});
4947
5959
 
4948
- // Update animated values
4949
- swipeAnimatedValue.setValue(Math.min(translationX, maxSwipeDistance));
4950
- replyIconOpacity.setValue(progress);
4951
- }, []);
5960
+ setSelectedMessage(message);
5961
+ hasTemplate && openOptionsForMessage(message, hasTemplate);
5962
+ }, [hasTemplate, message, openOptionsForMessage]);
4952
5963
 
4953
- const handlePanStateChange = useCallback((event: PanGestureHandlerStateChangeEvent) => {
4954
- const { state, translationX, velocityX } = event.nativeEvent;
5964
+ const onPress = useCallback(() => {
5965
+ Keyboard.dismiss();
5966
+ }, []);
4955
5967
 
4956
- if (state === State.END) {
4957
- const swipeThreshold = 80;
5968
+ // Swipe-to-reply functionality
5969
+ const onReply = useCallback(() => {
5970
+ if (message.getDeletedBy() != null) return;
5971
+ if (!message.getId()) return;
4958
5972
 
4959
- // Reset animations
4960
- Animated.parallel([
4961
- Animated.spring(swipeAnimatedValue, {
4962
- toValue: 0,
4963
- useNativeDriver: true,
4964
- }),
4965
- Animated.spring(replyIconOpacity, {
4966
- toValue: 0,
4967
- useNativeDriver: true,
4968
- }),
4969
- ]).start();
5973
+ CometChatMessageEvents.emit(CometChatMessageEvents.ccReplyToMessage, {
5974
+ message: message,
5975
+ status: messageStatus.inprogress,
5976
+ });
5977
+ }, [message]);
4970
5978
 
4971
- const moderationStatus = getModerationStatus(message);
4972
- const isOutgoing = message.getSender()?.getUid() === loggedInUser.current?.getUid();
4973
- if (isOutgoing && moderationStatus && moderationStatus !== "approved" && moderationStatus !== "unmoderated") return;
5979
+ // Moderation gate for swipe-to-reply, read on release.
5980
+ const canReply = useCallback(() => {
5981
+ const moderationStatus = getModerationStatus(message);
5982
+ const isOutgoing = message.getSender()?.getUid() === loggedInUser.current?.getUid();
5983
+ return !(isOutgoing && moderationStatus && moderationStatus !== "approved" && moderationStatus !== "unmoderated");
5984
+ }, [message]);
4974
5985
 
4975
- // Trigger reply if threshold is met
4976
- if (translationX > swipeThreshold || velocityX > 500) {
4977
- onReply();
4978
- }
4979
- }
4980
- }, [onReply, message]);
5986
+ if (hasTemplate) {
5987
+ if (hasTemplate?.BubbleView) return hasTemplate?.BubbleView(message);
4981
5988
 
4982
5989
  // Disable swipe-to-reply for agent ("@agentic") messages. Covers both the
4983
5990
  // 1:1 AI chat (isAgenticUser, whole conversation) and agent messages inside a
@@ -4987,6 +5994,10 @@ export const CometChatMessageList = memo(
4987
5994
  isAgenticUser ||
4988
5995
  message.getSender?.()?.getRole?.() === "@agentic" ||
4989
5996
  message.getCategory?.() === MessageCategoryConstants.agentic;
5997
+ // The agent's own replies are markdown, which has no natural width: let them fill.
5998
+ const fillWidth =
5999
+ message.getCategory?.() === MessageCategoryConstants.agentic ||
6000
+ message.getCategory?.() === MessageCategoryConstants.stream;
4990
6001
 
4991
6002
  return (
4992
6003
  message.getCategory() === MessageCategoryConstants.action || isAgenticMessage ? (
@@ -5008,40 +6019,34 @@ export const CometChatMessageList = memo(
5008
6019
  BottomView={BottomView}
5009
6020
  StatusInfoView={StatusInfoView}
5010
6021
  style={getCurrentBubbleStyle(message)}
6022
+ fillWidth={fillWidth}
5011
6023
  />
5012
6024
  </TouchableOpacity>
5013
6025
  </View>
5014
6026
  ) : (
5015
- <PanGestureHandler
5016
- onGestureEvent={handlePanGesture}
5017
- onHandlerStateChange={handlePanStateChange}
5018
- activeOffsetX={[-10, 10]}
5019
- failOffsetY={[-50, 50]}
5020
- >
5021
- <Animated.View style={{ transform: [{ translateX: swipeAnimatedValue }] }}>
5022
- <View style={staticStyles.positionRelative}>
5023
- <TouchableOpacity
5024
- activeOpacity={1}
5025
- onPress={Platform.OS === "ios" ? onPress : undefined}
5026
- onLongPress={() => (showOptions ? onLongPress() : undefined)}
5027
- >
5028
- <CometChatMessageBubble
5029
- id={`${message.getId()}`}
5030
- LeadingView={LeadingView}
5031
- HeaderView={HeaderView}
5032
- FooterView={FooterView}
5033
- ReplyView={ReplyView}
5034
- alignment={isThreaded ? "left" : bubbleAlignment}
5035
- ContentView={ContentView}
5036
- ThreadView={ThreadedView}
5037
- BottomView={BottomView}
5038
- StatusInfoView={StatusInfoView}
5039
- style={getCurrentBubbleStyle(message)}
5040
- />
5041
- </TouchableOpacity>
5042
- </View>
5043
- </Animated.View>
5044
- </PanGestureHandler>
6027
+ <SwipeToReplyView onReply={onReply} canReply={canReply}>
6028
+ <View style={staticStyles.positionRelative}>
6029
+ <TouchableOpacity
6030
+ activeOpacity={1}
6031
+ onPress={Platform.OS === "ios" ? onPress : undefined}
6032
+ onLongPress={() => (showOptions ? onLongPress() : undefined)}
6033
+ >
6034
+ <CometChatMessageBubble
6035
+ id={`${message.getId()}`}
6036
+ LeadingView={LeadingView}
6037
+ HeaderView={HeaderView}
6038
+ FooterView={FooterView}
6039
+ ReplyView={ReplyView}
6040
+ alignment={isThreaded ? "left" : bubbleAlignment}
6041
+ ContentView={ContentView}
6042
+ ThreadView={ThreadedView}
6043
+ BottomView={BottomView}
6044
+ StatusInfoView={StatusInfoView}
6045
+ style={getCurrentBubbleStyle(message)}
6046
+ />
6047
+ </TouchableOpacity>
6048
+ </View>
6049
+ </SwipeToReplyView>
5045
6050
  )
5046
6051
  );
5047
6052
  } else {
@@ -5157,8 +6162,9 @@ export const CometChatMessageList = memo(
5157
6162
  lastMessageDate.current = getSentAtTimestamp(item);
5158
6163
  const id = typeof item?.getId === 'function' ? item.getId() : (item as any)?.id;
5159
6164
  const muid = typeof item?.getMuid === 'function' ? item.getMuid() : (item as any)?.muid;
6165
+ // Offline: an own message keeps one key from compose to ack (no remount); else today's.
5160
6166
  return (
5161
- <React.Fragment key={`${id}_${muid}`}>
6167
+ <React.Fragment key={offlineRenderKey(item, loggedInUser.current?.getUid?.()) ?? `${id}_${muid}`}>
5162
6168
  <MessageView message={item} currentIndex={index} />
5163
6169
  </React.Fragment>
5164
6170
  );
@@ -5172,6 +6178,10 @@ export const CometChatMessageList = memo(
5172
6178
  const muid = typeof item?.getMuid === 'function' ? item.getMuid() : item?.muid;
5173
6179
 
5174
6180
 
6181
+ // Offline: an own message the SDK handled keeps one key from compose to ack.
6182
+ const offlineKey = offlineRenderKey(item, loggedInUser.current?.getUid?.());
6183
+ if (offlineKey) return offlineKey;
6184
+
5175
6185
  // For stream messages in agentic mode, use a unique combination
5176
6186
  // to prevent duplicate keys when navigating between chat and history
5177
6187
  if (item?.isStreamMessage) {
@@ -5263,7 +6273,8 @@ export const CometChatMessageList = memo(
5263
6273
  color: textPrimary,
5264
6274
  }}
5265
6275
  >
5266
- {userMetadata?.greetingMessage ?? `Hi, I'm ${user.getName()}`}
6276
+ {userMetadata?.greetingMessage ??
6277
+ t("AI_AGENT_GREETING").replace("{name}", () => user.getName())}
5267
6278
  </Text>
5268
6279
  )}
5269
6280
 
@@ -5279,8 +6290,7 @@ export const CometChatMessageList = memo(
5279
6290
  color: textTertiary,
5280
6291
  }}
5281
6292
  >
5282
- {userMetadata?.introductoryMessage ??
5283
- "I'm here to help! Ask me anything or choose from the suggestions below."}
6293
+ {userMetadata?.introductoryMessage ?? t("AI_AGENT_INTRO")}
5284
6294
  </Text>
5285
6295
  )}
5286
6296
 
@@ -5318,7 +6328,7 @@ export const CometChatMessageList = memo(
5318
6328
  fontWeight: theme.typography.body.regular.fontWeight,
5319
6329
  fontSize: theme.typography.body.regular.fontSize,
5320
6330
  color: textSecondary,
5321
- paddingRight: mergedTheme.spacing.padding.p2,
6331
+ paddingEnd: mergedTheme.spacing.padding.p2,
5322
6332
  flexShrink: 1,
5323
6333
  }}
5324
6334
  >
@@ -5341,6 +6351,7 @@ export const CometChatMessageList = memo(
5341
6351
  emptyChatImageView,
5342
6352
  onSuggestedMessageClick,
5343
6353
  mergedTheme,
6354
+ t,
5344
6355
  ]);
5345
6356
 
5346
6357
  const fetchConversationStarters = (): Promise<string[]> => {
@@ -5409,6 +6420,18 @@ export const CometChatMessageList = memo(
5409
6420
  const getErrorStateView = useCallback(() => {
5410
6421
  if (hideError) return null;
5411
6422
  if (ErrorView) return ErrorView();
6423
+ if (offlineMiss) {
6424
+ // D84 rule 3: offline with nothing saved: the offline state, no Retry.
6425
+ return (
6426
+ <ConnectStateView
6427
+ testID={CONTRACT_IDS.emptyConnectToLoad}
6428
+ title={t(OFFLINE_STRING_KEYS.connectToLoadMessages)}
6429
+ containerStyle={mergedTheme.messageListStyles.errorStateStyle?.containerStyle}
6430
+ titleStyle={mergedTheme.messageListStyles.errorStateStyle?.titleStyle}
6431
+ subtitleStyle={mergedTheme.messageListStyles.errorStateStyle?.subtitleStyle}
6432
+ />
6433
+ );
6434
+ }
5412
6435
  return (
5413
6436
  <ErrorEmptyView
5414
6437
  title={t("OOPS")}
@@ -5430,7 +6453,7 @@ export const CometChatMessageList = memo(
5430
6453
  subTitleStyle={mergedTheme.messageListStyles.errorStateStyle?.subtitleStyle}
5431
6454
  />
5432
6455
  );
5433
- }, [mergedTheme]);
6456
+ }, [mergedTheme, offlineMiss]);
5434
6457
 
5435
6458
  const getLoadingStateView = useCallback(() => {
5436
6459
  if (LoadingView) return LoadingView();
@@ -5443,14 +6466,23 @@ export const CometChatMessageList = memo(
5443
6466
  }, []);
5444
6467
 
5445
6468
  const fetchNextMessages = async () => {
6469
+ if (positioningRef.current) {
6470
+ deferredPagingRef.current.newer = true;
6471
+ return;
6472
+ }
5446
6473
  if (loadingMessagesRef.current || !hasTargetMessageId) return;
5447
6474
 
5448
6475
  if (messagesContentListRef.current.length === 0) return;
5449
6476
 
5450
6477
  const newestMessage = messagesContentListRef.current[0];
5451
- const newestMessageId = newestMessage.getId();
6478
+ const offlineRead = isOfflineOn(); // gate read once for this read
6479
+ // Offline: anchor on the newest row WITH a server id (an unsent row has none, UIK-READ-06).
6480
+ const newestMessageId = offlineRead
6481
+ ? newestServerId(messagesContentListRef.current) || newestMessage.getId()
6482
+ : newestMessage.getId();
5452
6483
  setBottomLoading(true);
5453
6484
  loadingMessagesRef.current = true;
6485
+ const readGen = jumpGenRef.current; // a jump during the read drops its answer
5454
6486
 
5455
6487
  try {
5456
6488
  // Filtered like the main list (see getMessagesAroundId): scrolling down after a jump
@@ -5480,7 +6512,53 @@ export const CometChatMessageList = memo(
5480
6512
  }
5481
6513
  }
5482
6514
 
6515
+ if (offlineRead) {
6516
+ offlinePathUsedRef.current = true;
6517
+ newerReadSeqRef.current++;
6518
+ const opGen = listOpGenRef.current;
6519
+ let cachedKeys = new Set<string>();
6520
+ let paintedKeys: string[] = [];
6521
+ await fetchTwoPhase<any>(
6522
+ nextMessagesRequest.build(),
6523
+ "next",
6524
+ {
6525
+ onCached: (page) => {
6526
+ cachedKeys = cachedKeysOf(page);
6527
+ const listed = cachedKeysOf(messagesContentListRef.current);
6528
+ paintedKeys = [...cachedKeys].filter((key) => !listed.has(key));
6529
+ applyOfflineResult(upsertSortedDesc(messagesContentListRef.current, page));
6530
+ },
6531
+ onServer: (page) => {
6532
+ applyOfflineResult(
6533
+ dropUnjoinedCachedPageDesc(
6534
+ reconcileServerPageDesc(messagesContentListRef.current, cachedKeys, page),
6535
+ paintedKeys,
6536
+ [...cachedKeys],
6537
+ page,
6538
+ "next"
6539
+ )
6540
+ );
6541
+ // Only an empty online page says the newest end is reached.
6542
+ if (page.length === 0) setHasTargetMessageId(false);
6543
+ setOfflineNewerBlocked(false);
6544
+ },
6545
+ onError: (error, failedOffline) => {
6546
+ if (failedOffline || sdkConnected() === false) {
6547
+ // D84 rule 2 and 9: not connected keeps the rows with "Connect to load more" at the
6548
+ // newer edge (no onError); the page loads by itself when the connection is back.
6549
+ setOfflineNewerBlocked(true);
6550
+ return;
6551
+ }
6552
+ // D84 rule 5: a real error is reported once (the user's scroll started the read).
6553
+ onError && onError(error as CometChat.CometChatException);
6554
+ },
6555
+ },
6556
+ () => opGen !== listOpGenRef.current
6557
+ );
6558
+ return;
6559
+ }
5483
6560
  const nextMessages = await nextMessagesRequest.build().fetchNext();
6561
+ if (readGen !== jumpGenRef.current) return;
5484
6562
  if (nextMessages.length > 0) {
5485
6563
 
5486
6564
  const existingIds = new Set(messagesContentListRef.current.map(m => m.getId()));
@@ -5502,11 +6580,18 @@ export const CometChatMessageList = memo(
5502
6580
  } catch (error) {
5503
6581
  console.error('[fetchNextMessages] Error:', error);
5504
6582
  } finally {
5505
- setBottomLoading(false);
5506
- loadingMessagesRef.current = false;
6583
+ // After a jump the flags belong to the jump (and any read it let start).
6584
+ if (readGen === jumpGenRef.current) {
6585
+ setBottomLoading(false);
6586
+ loadingMessagesRef.current = false;
6587
+ }
5507
6588
  }
5508
6589
  };
5509
6590
 
6591
+ // The latest paging functions, for a page deferred while the list was being positioned.
6592
+ pagingFnsRef.current = { older: getPreviousMessages, newer: fetchNextMessages };
6593
+ fetchNextMessagesRef.current = fetchNextMessages;
6594
+
5510
6595
  const renderFooter = () => {
5511
6596
  if (!bottomLoading) return null;
5512
6597
  return (
@@ -5539,6 +6624,7 @@ export const CometChatMessageList = memo(
5539
6624
 
5540
6625
  const nearBottom = isNearBottom();
5541
6626
  setHideScrollToBottomButton(nearBottom);
6627
+ retryOlderOnScroll();
5542
6628
 
5543
6629
  if (nearBottom && temporaryMessageListRef.current.length > 0) {
5544
6630
  // Merge temporary messages when scrolling near bottom
@@ -5710,6 +6796,18 @@ export const CometChatMessageList = memo(
5710
6796
 
5711
6797
 
5712
6798
  // Optimized FlatList renderItem using memoized component
6799
+ // Dev and sample builds only: the row list of every committed frame (TEST-PLAN §3.3).
6800
+ useEffect(() => {
6801
+ probeFrame("messages", () =>
6802
+ messagesList.map((item: any, index: number) => ({
6803
+ key: keyExtractor(item, index),
6804
+ id: serverIdOf(item),
6805
+ state: contractRowState(item),
6806
+ item,
6807
+ }))
6808
+ );
6809
+ }, [messagesList, keyExtractor]);
6810
+
5713
6811
  const memoizedRenderItem = useCallback(
5714
6812
  ({ item, index }: any) => {
5715
6813
  const nextItem = messagesContentListRef.current[index + 1];
@@ -5740,7 +6838,7 @@ export const CometChatMessageList = memo(
5740
6838
  const showNewMessageIndicator = !isAgenticUser && (startFromUnreadMessages || showMarkAsUnreadOption || navigatedFromSearch) && newMessageIndicatorId === String(item.getId());
5741
6839
 
5742
6840
  return (
5743
- <View>
6841
+ <View {...messageRowContractProps(keyExtractor(item, index), item)}>
5744
6842
  <MessageListItem
5745
6843
  item={item}
5746
6844
  index={index}
@@ -5783,7 +6881,8 @@ export const CometChatMessageList = memo(
5783
6881
  startFromUnreadMessages,
5784
6882
  showMarkAsUnreadOption,
5785
6883
  navigatedFromSearch,
5786
- isAgenticUser
6884
+ isAgenticUser,
6885
+ keyExtractor
5787
6886
  ]
5788
6887
  );
5789
6888
 
@@ -5796,15 +6895,30 @@ export const CometChatMessageList = memo(
5796
6895
  messagesContentListRef.current = orderedMessagesList;
5797
6896
 
5798
6897
  return (
6898
+ <LayoutDirectionContext.Provider value={direction}>
5799
6899
  <CometChatBatchMediaContext.Provider value={batchMediaContextValue}>
5800
- <View style={mergedTheme.messageListStyles.containerStyle}>
6900
+ <View style={[mergedTheme.messageListStyles.containerStyle, directionStyle(direction)]}>
5801
6901
  {listState == "loading" && messagesList.length == 0 ? (
5802
6902
  getLoadingStateView()
5803
6903
  ) : listState == "error" ? (
5804
6904
  getErrorStateView()
5805
6905
  ) : (
5806
6906
  messagesList.length == 0 ? (
5807
- getEmptyStateView()
6907
+ offlineFooter === "connect" ? (
6908
+ // Offline ON, a chat never cached: nothing invented, and a way to try again (P6).
6909
+ <View style={staticStyles.listContainer}>
6910
+ <View style={{ flex: 1 }}>{getEmptyStateView()}</View>
6911
+ <ConnectToLoadMore
6912
+ t={t}
6913
+ onRetry={retryOfflineOlderPage}
6914
+ textColor={mergedTheme.color.textSecondary as string}
6915
+ containerStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.containerStyle}
6916
+ textStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.textStyle}
6917
+ />
6918
+ </View>
6919
+ ) : (
6920
+ getEmptyStateView()
6921
+ )
5808
6922
  ) : (
5809
6923
  <View style={staticStyles.listContainer}>
5810
6924
  {HeaderView && (
@@ -5833,6 +6947,7 @@ export const CometChatMessageList = memo(
5833
6947
  showsVerticalScrollIndicator={false}
5834
6948
  ref={messageListRef}
5835
6949
  onMomentumScrollEnd={handleScrollInternal}
6950
+ onScrollBeginDrag={handleScrollInternal}
5836
6951
  onScroll={handleScrollInternal}
5837
6952
  inverted={true}
5838
6953
  maintainVisibleContentPosition={{
@@ -5848,7 +6963,31 @@ export const CometChatMessageList = memo(
5848
6963
  extraData={themeMode}
5849
6964
  keyExtractor={keyExtractor}
5850
6965
  renderItem={memoizedRenderItem}
5851
- ListHeaderComponent={renderFooter}
6966
+ ListHeaderComponent={
6967
+ offlineNewerBlocked && !bottomLoading
6968
+ ? () => (
6969
+ // Inverted list: the header sits at the newer end.
6970
+ <ConnectToLoadMore
6971
+ t={t}
6972
+ onRetry={retryOfflineNewerPage}
6973
+ textColor={mergedTheme.color.textSecondary as string}
6974
+ containerStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.containerStyle}
6975
+ textStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.textStyle}
6976
+ />
6977
+ )
6978
+ : renderFooter
6979
+ }
6980
+ ListFooterComponent={
6981
+ offlineFooter === "connect" ? (
6982
+ <ConnectToLoadMore
6983
+ t={t}
6984
+ onRetry={retryOfflineOlderPage}
6985
+ textColor={mergedTheme.color.textSecondary as string}
6986
+ containerStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.containerStyle}
6987
+ textStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.textStyle}
6988
+ />
6989
+ ) : undefined
6990
+ }
5852
6991
  onScrollToIndexFailed={handleScrollToIndexFailed}
5853
6992
  viewabilityConfig={viewabilityConfig}
5854
6993
  onViewableItemsChanged={handleViewableItemsChanged}
@@ -5901,6 +7040,17 @@ export const CometChatMessageList = memo(
5901
7040
  )
5902
7041
  )}
5903
7042
 
7043
+ {offlineNotice && !hideOfflineNotices ? (
7044
+ <OfflineNoticeView
7045
+ notice={offlineNotice}
7046
+ t={t}
7047
+ onDismiss={dismissOfflineNotice}
7048
+ containerStyle={mergedTheme.messageListStyles?.offlineStyles?.noticeStyle?.containerStyle}
7049
+ textStyle={mergedTheme.messageListStyles?.offlineStyles?.noticeStyle?.textStyle}
7050
+ actionTextStyle={mergedTheme.messageListStyles?.offlineStyles?.noticeStyle?.actionTextStyle}
7051
+ />
7052
+ ) : null}
7053
+
5904
7054
  {!hideScrollToBottomButton && (
5905
7055
  <Pressable
5906
7056
  onPress={newMsgIndicatorPressed}
@@ -5965,7 +7115,8 @@ export const CometChatMessageList = memo(
5965
7115
  messageInfo={messageInfo}
5966
7116
  infoObject={infoObject}
5967
7117
  selectedMessage={selectedMessage}
5968
- hideReactionOption={hideReactionOption}
7118
+ // Offline: an unsent row cannot be reacted to (it has no server id; R162 offers Retry and Delete only).
7119
+ hideReactionOption={hideReactionOption || (selectedMessage != null && offlineReceiptOf(selectedMessage) !== null)}
5969
7120
  quickReactionList={quickReactionList as [string, string?, string?, string?, string?]}
5970
7121
  templatesMap={templatesMap}
5971
7122
  mergedTheme={mergedTheme}
@@ -6008,6 +7159,7 @@ export const CometChatMessageList = memo(
6008
7159
  {ToastElement}
6009
7160
  </View>
6010
7161
  </CometChatBatchMediaContext.Provider>
7162
+ </LayoutDirectionContext.Provider>
6011
7163
  );
6012
7164
 
6013
7165
  }
@@ -6109,7 +7261,7 @@ const staticStyles = StyleSheet.create({
6109
7261
  textAlignVertical: "center",
6110
7262
  },
6111
7263
  receiptContainer: {
6112
- marginLeft: 2,
7264
+ marginStart: 2,
6113
7265
  alignItems: "center",
6114
7266
  justifyContent: "center",
6115
7267
  },