@cometchat/chat-uikit-react-native 5.5.4 → 5.6.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.
- package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +78 -3
- package/android/src/main/java/com/reactnativecometchatuikit/SafeFileName.java +78 -0
- package/ios/CCLocalFileGuard.h +19 -0
- package/ios/CCLocalFileGuard.m +34 -0
- package/ios/FileManager.m +70 -6
- package/ios/VideoManager.m +1 -1
- package/package.json +18 -3
- package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +124 -55
- package/src/CometChatConversations/CometChatConversations.tsx +240 -117
- package/src/CometChatGroupMembers/CometChatGroupMembers.tsx +4 -0
- package/src/CometChatGroups/CometChatGroups.tsx +61 -52
- package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +146 -66
- package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +7 -3
- package/src/CometChatMessageHeader/listners.ts +76 -56
- package/src/CometChatMessageList/CometChatMessageList.tsx +1371 -188
- package/src/CometChatNotificationFeed/CometChatNotificationFeed.tsx +71 -7
- package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +74 -2
- package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +69 -4
- package/src/CometChatSearch/CometChatSearch.tsx +353 -101
- package/src/CometChatThreadHeader/CometChatThreadHeader.tsx +23 -1
- package/src/CometChatUsers/CometChatUsers.tsx +2 -0
- package/src/calls/CometChatCallButtons/CometChatCallButtons.tsx +19 -0
- package/src/extensions/Stickers/StickersExtensionDecorator.tsx +2 -0
- package/src/index.ts +6 -0
- package/src/shared/CometChatUiKit/CometChatUIKit.ts +85 -2
- package/src/shared/CometChatUiKit/UIKitSettings.ts +20 -0
- package/src/shared/events/CometChatUIEventHandler/Listener.ts +10 -0
- package/src/shared/events/index.ts +4 -0
- package/src/shared/events/offline.ts +28 -0
- package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +5 -3
- package/src/shared/framework/MessageDataSource.tsx +34 -14
- package/src/shared/index.ts +2 -0
- package/src/shared/offline/OfflineHub.ts +651 -0
- package/src/shared/offline/OfflineMediaBubble.tsx +49 -0
- package/src/shared/offline/OfflineViews.tsx +218 -0
- package/src/shared/offline/conversationPins.ts +137 -0
- package/src/shared/offline/conversations.ts +325 -0
- package/src/shared/offline/frameProbe.ts +24 -0
- package/src/shared/offline/gate.ts +94 -0
- package/src/shared/offline/groupActions.ts +81 -0
- package/src/shared/offline/identity.ts +162 -0
- package/src/shared/offline/index.ts +76 -0
- package/src/shared/offline/media.ts +247 -0
- package/src/shared/offline/notices.ts +90 -0
- package/src/shared/offline/reconcile.ts +296 -0
- package/src/shared/offline/searchOutcome.ts +62 -0
- package/src/shared/offline/send.ts +430 -0
- package/src/shared/offline/stateContract.ts +85 -0
- package/src/shared/offline/threadReplies.ts +125 -0
- package/src/shared/offline/twoPhase.ts +372 -0
- package/src/shared/offline/unsentActions.ts +168 -0
- package/src/shared/offline/useOfflineMediaUri.ts +87 -0
- package/src/shared/offline/useOfflineReconnect.ts +25 -0
- package/src/shared/offline/useOfflineSessionEnded.ts +22 -0
- package/src/shared/offline/useOfflineUploadTray.ts +76 -0
- package/src/shared/offline/usePresenceHidden.ts +33 -0
- package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +24 -1
- package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +24 -1
- package/src/shared/services/UploadQueueService.ts +106 -1
- package/src/shared/utils/MessageReceiptUtils.ts +8 -0
- package/src/shared/utils/SavedMessagesHelper.ts +18 -1
- package/src/shared/utils/catchUpCursor.ts +36 -0
- package/src/shared/utils/failedMessageRetry.ts +73 -0
- package/src/shared/utils/messageIdentity.ts +38 -0
- package/src/shared/views/CometChatAttachmentViewer/CometChatAttachmentViewer.tsx +34 -5
- package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +10 -2
- package/src/shared/views/CometChatFileBubble/CometChatFileBubble.tsx +13 -27
- package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +60 -11
- package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +27 -2
- package/src/shared/views/CometChatList/CometChatList.tsx +468 -7
- package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +27 -5
- package/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx +1 -0
- package/src/shared/views/CometChatReactionList/CometChatReactionList.tsx +56 -10
- package/src/shared/views/CometChatStatusIndicator/CometChatStatusIndicator.tsx +4 -0
- package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +36 -2
- package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +24 -12
- package/src/theme/type.ts +17 -0
- package/android/.gradle/7.4/checksums/checksums.lock +0 -0
- package/android/.gradle/7.4/fileChanges/last-build.bin +0 -0
- package/android/.gradle/7.4/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/7.4/gc.properties +0 -0
- package/android/.gradle/vcs-1/gc.properties +0 -0
|
@@ -75,6 +75,47 @@ import { groupMemberAddedRows } from "../shared/utils/groupMemberAddedRows";
|
|
|
75
75
|
import { selectLinkPreview } from "../shared/utils/linkPreviewSelection";
|
|
76
76
|
import { unescapeTypedMentionTokens } from "../shared/utils/mentionTokens";
|
|
77
77
|
import { CommonUtils } from "../shared/utils/CommonUtils";
|
|
78
|
+
import { sameMessageById, sameMessageByMuid } from "../shared/utils/messageIdentity";
|
|
79
|
+
import { nextCatchUpCursor } from "../shared/utils/catchUpCursor";
|
|
80
|
+
import { isRetryableFailedRow, resendFailedMessage, resendKindOf } from "../shared/utils/failedMessageRetry";
|
|
81
|
+
import { cloneRequestBuilder } from "../shared/utils/cloneRequestBuilder";
|
|
82
|
+
import { isOfflineOn, offlineSdk, sdkConnected } from "../shared/offline/gate";
|
|
83
|
+
import {
|
|
84
|
+
findRowIndex,
|
|
85
|
+
HeldReceipts,
|
|
86
|
+
isNotConnectedError,
|
|
87
|
+
cachedKeysOf,
|
|
88
|
+
dropUnjoinedCachedPageDesc,
|
|
89
|
+
newestServerId,
|
|
90
|
+
onlyShownRows,
|
|
91
|
+
reconcileServerPageDesc,
|
|
92
|
+
removeRowDesc,
|
|
93
|
+
upsertSortedDesc,
|
|
94
|
+
} from "../shared/offline/reconcile";
|
|
95
|
+
import {
|
|
96
|
+
isOfflineUnsent,
|
|
97
|
+
isSyncDelivered,
|
|
98
|
+
offlineRenderKey,
|
|
99
|
+
serverIdOf,
|
|
100
|
+
} from "../shared/offline/identity";
|
|
101
|
+
import {
|
|
102
|
+
CacheResetEvent,
|
|
103
|
+
MessageSyncEvent,
|
|
104
|
+
MessagesUpdatedEvent,
|
|
105
|
+
OfflineHub,
|
|
106
|
+
SendStateEvent,
|
|
107
|
+
ConversationSyncEvent,
|
|
108
|
+
SyncFailedEvent,
|
|
109
|
+
} from "../shared/offline/OfflineHub";
|
|
110
|
+
import { fetchTwoPhase, readAroundTwoPhase, resolveTwoPhase } from "../shared/offline/twoPhase";
|
|
111
|
+
import { mediaActionSource, notifyMediaUnavailable } from "../shared/offline/media";
|
|
112
|
+
import { retryFailedMessage, sendKindOf } from "../shared/offline/send";
|
|
113
|
+
import { canRetryUnsent, deleteUnsentMessage, OFFLINE_OPTION_IDS, unsentActionsOf, unsentRowInfo } from "../shared/offline/unsentActions";
|
|
114
|
+
import { OFFLINE_STRING_KEYS, offlineMutationErrorText } from "../shared/offline/notices";
|
|
115
|
+
import { contractRowState, messageRowContractProps } from "../shared/offline/stateContract";
|
|
116
|
+
import { probeFrame } from "../shared/offline/frameProbe";
|
|
117
|
+
import { ConnectStateView, ConnectToLoadMore, OfflineNoticeView, useOfflineNotice } from "../shared/offline/OfflineViews";
|
|
118
|
+
import { CONTRACT_IDS } from "../shared/offline/stateContract";
|
|
78
119
|
import { CometChatBatchMediaContext, BatchMediaResult } from "../shared/utils/batchMediaContext";
|
|
79
120
|
import { CometChatUIKit } from "../shared/CometChatUiKit/CometChatUIKit";
|
|
80
121
|
import { CometChatNewMessageIndicator, CometChatReceipt, NewMessageIndicatorStyle } from "../shared/views";
|
|
@@ -163,6 +204,28 @@ export function skipNextAgentAutoLoad(): void {
|
|
|
163
204
|
* Helper function to safely get message ID
|
|
164
205
|
* Prevents "undefined is not a function" errors in release builds
|
|
165
206
|
*/
|
|
207
|
+
/** How long after a conversation-only sweep phase the list waits for a message phase (ON only). */
|
|
208
|
+
const COLD_SWEEP_SETTLE_MS = 2000;
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* The least time between two older-page reads a scroll gesture at the "Connect to load more" footer
|
|
212
|
+
* starts once the connection is back (UIK-READ-03): a scroll burst fires many events.
|
|
213
|
+
*/
|
|
214
|
+
const RETRY_ON_SCROLL_GAP_MS = 1000;
|
|
215
|
+
|
|
216
|
+
/** 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. */
|
|
217
|
+
const EDGE_RELOAD_POLL_MS = 100;
|
|
218
|
+
const EDGE_RELOAD_MAX_WAIT_MS = 10000;
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* The longest a jump or start-from-unread window stays "being positioned" (paging and the live
|
|
222
|
+
* auto-scroll paused) if its scroll never reports back, e.g. the list unmounted or never laid out.
|
|
223
|
+
*/
|
|
224
|
+
const POSITIONING_MAX_MS = 6000;
|
|
225
|
+
|
|
226
|
+
/** How many messages after the anchor a jump or start-from-unread window reads. */
|
|
227
|
+
const AROUND_NEXT_PAGE_LIMIT = 15;
|
|
228
|
+
|
|
166
229
|
const safeGetId = (item: any): string | number | undefined => {
|
|
167
230
|
return typeof item?.getId === 'function' ? item.getId() : item?.id;
|
|
168
231
|
};
|
|
@@ -185,7 +248,16 @@ async function getConversationIfExists(
|
|
|
185
248
|
convId: string,
|
|
186
249
|
conversationType: string
|
|
187
250
|
): Promise<CometChat.Conversation | null> {
|
|
251
|
+
// Gate read once for this read. Offline ON: the two-phase form, so a chat opened by id offline
|
|
252
|
+
// still finds its cached conversation (BEH-READ-32); OFF: today's Promise form.
|
|
253
|
+
const offlineOn = isOfflineOn();
|
|
188
254
|
try {
|
|
255
|
+
if (offlineOn) {
|
|
256
|
+
return await resolveTwoPhase<CometChat.Conversation>(
|
|
257
|
+
(listener) => offlineSdk().getConversation(convId, conversationType, listener),
|
|
258
|
+
"Conversation"
|
|
259
|
+
);
|
|
260
|
+
}
|
|
189
261
|
return await CometChat.getConversation(convId, conversationType);
|
|
190
262
|
} catch (e: any) {
|
|
191
263
|
if (e?.code === "ERR_CONVERSATION_NOT_ACCESSIBLE") {
|
|
@@ -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,
|
|
@@ -870,11 +948,15 @@ export const CometChatMessageList = memo(
|
|
|
870
948
|
const deleteItem = useRef<CometChat.BaseMessage>(undefined);
|
|
871
949
|
const shouldSuppressHighlightRef = useRef(false);
|
|
872
950
|
const { showToast, ToastElement } = useToast();
|
|
951
|
+
// The types and categories this list loads (an integrator builder's own when it sets them):
|
|
952
|
+
// the offline sweep inserts only rows that pass the same filter. `null` = no filter.
|
|
953
|
+
const sweepFilterRef = useRef<{ types: string[] | null; categories: string[] | null } | null>(null);
|
|
873
954
|
|
|
874
955
|
useLayoutEffect(() => {
|
|
875
956
|
// For agent chats (non-thread), don't set up message request builder
|
|
876
957
|
if (isAgenticUser && !parentMessageId) {
|
|
877
958
|
msgRequestBuilder.current = null as any;
|
|
959
|
+
sweepFilterRef.current = null;
|
|
878
960
|
return;
|
|
879
961
|
}
|
|
880
962
|
|
|
@@ -903,6 +985,11 @@ export const CometChatMessageList = memo(
|
|
|
903
985
|
_updatedCustomRequestBuilder = _updatedCustomRequestBuilder.setUID(user.getUid());
|
|
904
986
|
if (group)
|
|
905
987
|
_updatedCustomRequestBuilder = _updatedCustomRequestBuilder.setGUID(group.getGuid());
|
|
988
|
+
const own: any = messageRequestBuilder;
|
|
989
|
+
sweepFilterRef.current = {
|
|
990
|
+
types: Array.isArray(own.types) && own.types.length ? own.types : null,
|
|
991
|
+
categories: Array.isArray(own.categories) && own.categories.length ? own.categories : null,
|
|
992
|
+
};
|
|
906
993
|
} else {
|
|
907
994
|
_updatedCustomRequestBuilder.hideReplies(true);
|
|
908
995
|
if (user)
|
|
@@ -937,6 +1024,7 @@ export const CometChatMessageList = memo(
|
|
|
937
1024
|
}
|
|
938
1025
|
_updatedCustomRequestBuilder = _updatedCustomRequestBuilder.setTypes(types);
|
|
939
1026
|
_updatedCustomRequestBuilder = _updatedCustomRequestBuilder.setCategories(categories);
|
|
1027
|
+
sweepFilterRef.current = { types, categories };
|
|
940
1028
|
}
|
|
941
1029
|
|
|
942
1030
|
msgRequestBuilder.current = _updatedCustomRequestBuilder;
|
|
@@ -1174,8 +1262,87 @@ export const CometChatMessageList = memo(
|
|
|
1174
1262
|
const reachedFirstMessage = useRef<boolean>(false);
|
|
1175
1263
|
const agenticParentMessageIdRef = useRef<string | undefined>(undefined);
|
|
1176
1264
|
const [hasTargetMessageId, setHasTargetMessageId] = useState(false);
|
|
1265
|
+
// The window shown is anchored on an older message (a jump or start-from-unread): its newest
|
|
1266
|
+
// row is not the chat's. Read by the offline sweep handlers, which also run from timers.
|
|
1267
|
+
// `aroundReachedNewestRef`: the server's page after the anchor was short, so the window does
|
|
1268
|
+
// end at the chat's newest message and a sweep may insert as usual.
|
|
1269
|
+
const aroundReachedNewestRef = useRef(false);
|
|
1270
|
+
// Offline ON: a jump or start-from-unread window is being filled and scrolled to its anchor.
|
|
1271
|
+
// Until it is positioned the list neither pages (older or newer) nor follows live messages
|
|
1272
|
+
// to the bottom: either would run before the anchor is on screen and leave the list at the
|
|
1273
|
+
// newest messages (offline paints the window in phases, so the gap is long). `positioningRef`
|
|
1274
|
+
// is set when the around read starts and ends when the scroll to the anchor settles, the
|
|
1275
|
+
// read fails or finds nothing to scroll to, or after `POSITIONING_MAX_MS`. Never set with
|
|
1276
|
+
// offline off, so nothing here runs, and no timer starts, there.
|
|
1277
|
+
const positioningRef = useRef(false);
|
|
1278
|
+
const positioningTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
1279
|
+
const scrollTargetPendingRef = useRef(false);
|
|
1280
|
+
// A page the list asked for while it was being positioned. The list reports an edge once per
|
|
1281
|
+
// content length, so it would not ask again: it is read once the list is positioned.
|
|
1282
|
+
const deferredPagingRef = useRef({ older: false, newer: false });
|
|
1283
|
+
const pagingFnsRef = useRef<{ older: () => unknown; newer: () => unknown }>({ older: () => {}, newer: () => {} });
|
|
1284
|
+
const endPositioning = () => {
|
|
1285
|
+
positioningRef.current = false;
|
|
1286
|
+
scrollTargetPendingRef.current = false;
|
|
1287
|
+
if (positioningTimerRef.current) clearTimeout(positioningTimerRef.current);
|
|
1288
|
+
positioningTimerRef.current = null;
|
|
1289
|
+
const deferred = deferredPagingRef.current;
|
|
1290
|
+
deferredPagingRef.current = { older: false, newer: false };
|
|
1291
|
+
if (deferred.older) pagingFnsRef.current.older();
|
|
1292
|
+
if (deferred.newer) pagingFnsRef.current.newer();
|
|
1293
|
+
};
|
|
1294
|
+
const beginPositioning = () => {
|
|
1295
|
+
positioningRef.current = true;
|
|
1296
|
+
if (positioningTimerRef.current) clearTimeout(positioningTimerRef.current);
|
|
1297
|
+
positioningTimerRef.current = setTimeout(endPositioning, POSITIONING_MAX_MS);
|
|
1298
|
+
};
|
|
1299
|
+
useEffect(() => () => {
|
|
1300
|
+
if (positioningTimerRef.current) clearTimeout(positioningTimerRef.current);
|
|
1301
|
+
}, []);
|
|
1302
|
+
const anchoredWindowRef = useRef(false);
|
|
1303
|
+
anchoredWindowRef.current = hasTargetMessageId && !aroundReachedNewestRef.current;
|
|
1177
1304
|
const fetchingAroundIdRef = useRef<string | null>(null); // Track which message ID we're currently fetching
|
|
1178
1305
|
const [itemPositions, setItemPositions] = useState<Map<string, { y: number; height: number }>>(new Map());
|
|
1306
|
+
// Offline (ON path) bookkeeping. Untouched while offline is off.
|
|
1307
|
+
const offlinePathUsedRef = useRef(false); // this list ran an ON-path operation
|
|
1308
|
+
const listOpGenRef = useRef(0); // bumped on reset/logout and on a jump: late offline read callbacks are dropped
|
|
1309
|
+
const jumpGenRef = useRef(0); // bumped on a jump: a page read for the window left behind is dropped (offline on or off)
|
|
1310
|
+
const heldReceiptsRef = useRef(new HeldReceipts()); // receipts that beat their ack (§3.6)
|
|
1311
|
+
const [offlineFooter, setOfflineFooter] = useState<"none" | "connect">("none");
|
|
1312
|
+
// UIK-READ-03: the footer shows and the connection is back, so scrolling to the older end
|
|
1313
|
+
// reads again as tapping the footer does. Refs: read from scroll events and the hub's
|
|
1314
|
+
// connection event, not from a render.
|
|
1315
|
+
const offlineFooterRef = useRef<"none" | "connect">("none");
|
|
1316
|
+
offlineFooterRef.current = offlineFooter;
|
|
1317
|
+
const offlineFooterRetryableRef = useRef(false);
|
|
1318
|
+
// D84 (offline ON): the device was not connected and the chat has nothing saved: "Connect to load
|
|
1319
|
+
// messages" shows (the app's own ErrorView instead, if it passed one) and the newest page loads
|
|
1320
|
+
// again once, by itself, when the connection is back. Any other error is not loaded again.
|
|
1321
|
+
const reloadOnConnectRef = useRef(false);
|
|
1322
|
+
const [offlineMiss, setOfflineMiss] = useState(false);
|
|
1323
|
+
// The newer edge of an anchored window (after a jump) could not load offline: "Connect to load
|
|
1324
|
+
// more" shows there too, and on reconnect that page loads once by itself (D84 rule 9).
|
|
1325
|
+
const [offlineNewerBlocked, setOfflineNewerBlocked] = useState(false);
|
|
1326
|
+
const offlineNewerBlockedRef = useRef(false);
|
|
1327
|
+
offlineNewerBlockedRef.current = offlineNewerBlocked;
|
|
1328
|
+
// A read the kit starts by itself (cache reset, the reload after a reconnect) is quiet over rows
|
|
1329
|
+
// when it fails with a real error (D84 rule 5). Consumed by the next read.
|
|
1330
|
+
const quietNextReadRef = useRef(false);
|
|
1331
|
+
// Bumped on every reconnect and on unmount: a blocked-edge reload waiting for the reads in flight
|
|
1332
|
+
// to settle gives up when a newer one (or the unmount) replaces it.
|
|
1333
|
+
const edgeReloadTokenRef = useRef(0);
|
|
1334
|
+
const fetchNextMessagesRef = useRef<() => void>(() => {});
|
|
1335
|
+
// Counts the older / newer page reads started on the offline path: a blocked-edge reload that
|
|
1336
|
+
// finds its edge already read again since the reconnect (a tap, a scroll) leaves it to that read.
|
|
1337
|
+
const olderReadSeqRef = useRef(0);
|
|
1338
|
+
const newerReadSeqRef = useRef(0);
|
|
1339
|
+
useEffect(
|
|
1340
|
+
() => () => {
|
|
1341
|
+
edgeReloadTokenRef.current++;
|
|
1342
|
+
},
|
|
1343
|
+
[]
|
|
1344
|
+
);
|
|
1345
|
+
const lastRetryOnScrollRef = useRef(0);
|
|
1179
1346
|
const markUnreadMessageAsRead = (message?: CometChat.BaseMessage) => {
|
|
1180
1347
|
const messageToMark = message || messagesContentListRef.current[0];
|
|
1181
1348
|
if (
|
|
@@ -1252,12 +1419,21 @@ export const CometChatMessageList = memo(
|
|
|
1252
1419
|
}, [onLoad, hasTargetMessageId]);
|
|
1253
1420
|
|
|
1254
1421
|
const getPreviousMessages = async () => {
|
|
1422
|
+
const quietRead = quietNextReadRef.current; // a read the kit starts by itself
|
|
1423
|
+
quietNextReadRef.current = false;
|
|
1424
|
+
if (positioningRef.current) {
|
|
1425
|
+
deferredPagingRef.current.older = true;
|
|
1426
|
+
return;
|
|
1427
|
+
}
|
|
1255
1428
|
if (fetchingAroundIdRef.current) return;
|
|
1256
1429
|
|
|
1257
1430
|
if (loadingPrevMessagesRef.current) {
|
|
1258
1431
|
return;
|
|
1259
1432
|
}
|
|
1260
1433
|
loadingPrevMessagesRef.current = true;
|
|
1434
|
+
// A jump (getMessagesAroundId) replaces the window this read was asked for: the read's
|
|
1435
|
+
// answer is then dropped, and the jump owns the loading flags.
|
|
1436
|
+
const readGen = jumpGenRef.current;
|
|
1261
1437
|
// For agent chats with no conversation loaded, don't fetch previous messages
|
|
1262
1438
|
if (isAgenticUser && !parentMessageId && !agenticParentMessageIdRef.current) {
|
|
1263
1439
|
return;
|
|
@@ -1292,9 +1468,16 @@ export const CometChatMessageList = memo(
|
|
|
1292
1468
|
onError && onError(e);
|
|
1293
1469
|
}
|
|
1294
1470
|
}
|
|
1471
|
+
if (readGen !== jumpGenRef.current) return; // a jump began while the scope was fetched
|
|
1472
|
+
// Offline: gate read once for this read. ON → two-phase; OFF → today's fetch below.
|
|
1473
|
+
if (isOfflineOn() && messageRequest.current) {
|
|
1474
|
+
return getPreviousMessagesOffline(messageRequest.current, quietRead);
|
|
1475
|
+
}
|
|
1476
|
+
failStrandedOfflineSends();
|
|
1295
1477
|
return messageRequest.current
|
|
1296
1478
|
?.fetchPrevious()
|
|
1297
1479
|
.then((msgs: any[]) => {
|
|
1480
|
+
if (readGen !== jumpGenRef.current) return; // older page of a window a jump replaced
|
|
1298
1481
|
if ((messageRequest.current?.getLimit() ?? 0) > msgs.length) {
|
|
1299
1482
|
reachedFirstMessage.current = true;
|
|
1300
1483
|
}
|
|
@@ -1447,6 +1630,7 @@ export const CometChatMessageList = memo(
|
|
|
1447
1630
|
setListState("");
|
|
1448
1631
|
})
|
|
1449
1632
|
.catch((e: any) => {
|
|
1633
|
+
if (readGen !== jumpGenRef.current) return;
|
|
1450
1634
|
if (messagesContentListRef.current.length == 0) setListState("error");
|
|
1451
1635
|
if (e?.code === "REQUEST_IN_PROGRESS") return;
|
|
1452
1636
|
else {
|
|
@@ -1455,8 +1639,639 @@ export const CometChatMessageList = memo(
|
|
|
1455
1639
|
}
|
|
1456
1640
|
onError && onError(e);
|
|
1457
1641
|
}).finally(() => {
|
|
1458
|
-
loadingPrevMessagesRef.current = false;
|
|
1642
|
+
if (readGen === jumpGenRef.current) loadingPrevMessagesRef.current = false;
|
|
1643
|
+
});
|
|
1644
|
+
};
|
|
1645
|
+
|
|
1646
|
+
// ── Offline (ON) path ─────────────────────────────────────────────────────────────
|
|
1647
|
+
// Everything below runs only when CometChat.isOfflineEnabled() said "on" for that
|
|
1648
|
+
// operation, or for rows the offline SDK produced (local id / offline status). With
|
|
1649
|
+
// offline off none of it changes a request, an event or a render (README P1).
|
|
1650
|
+
|
|
1651
|
+
/** Replace the rows (newest-first) after an ON-path reconcile; applies held receipts. */
|
|
1652
|
+
const commitOfflineRows = (rows: any[]) => {
|
|
1653
|
+
messagesContentListRef.current = rows;
|
|
1654
|
+
setMessagesList(rows);
|
|
1655
|
+
// addToMessageList commits in the next animation frame; a pending/ack upsert that lands
|
|
1656
|
+
// before that frame would be overwritten by its stale list. Re-assert in the same queue so
|
|
1657
|
+
// the latest writer wins.
|
|
1658
|
+
batchStateUpdates(() => setMessagesList(rows));
|
|
1659
|
+
onLoad && onLoad([...rows].reverse());
|
|
1660
|
+
const held = heldReceiptsRef.current;
|
|
1661
|
+
if (held.size > 0) {
|
|
1662
|
+
for (const row of rows) {
|
|
1663
|
+
const id = serverIdOf(row);
|
|
1664
|
+
const receipt = id > 0 ? held.take(id) : undefined;
|
|
1665
|
+
if (receipt) updateMessageReceipt(receipt);
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
};
|
|
1669
|
+
|
|
1670
|
+
const applyOfflineResult = (result: { rows: any[]; changed: boolean }) => {
|
|
1671
|
+
if (result.changed) commitOfflineRows(result.rows);
|
|
1672
|
+
};
|
|
1673
|
+
|
|
1674
|
+
/** Does `message` belong to this list (same chat, same thread level)? */
|
|
1675
|
+
const belongsToThisList = (message: any): boolean => {
|
|
1676
|
+
if (!message) return false;
|
|
1677
|
+
const inChat =
|
|
1678
|
+
checkSameConversation(message) ||
|
|
1679
|
+
checkMessageInSameConversation(message) ||
|
|
1680
|
+
messageToSameConversation(message);
|
|
1681
|
+
if (!inChat) return false;
|
|
1682
|
+
const parentId = message.getParentMessageId?.();
|
|
1683
|
+
if (parentMessageId) return String(parentId) === String(parentMessageId);
|
|
1684
|
+
return !parentId || isAgenticUser;
|
|
1685
|
+
};
|
|
1686
|
+
|
|
1687
|
+
/** The read receipt state an ON-path row shows, or null to keep today's derivation. */
|
|
1688
|
+
const offlineReceiptOf = (item: any): "wait" | "error" | null => {
|
|
1689
|
+
const info = unsentRowInfo(item);
|
|
1690
|
+
if (!info) return null;
|
|
1691
|
+
return info.state === "failed" ? "error" : "wait";
|
|
1692
|
+
};
|
|
1693
|
+
|
|
1694
|
+
/** Mark the open chat read while offline: the SDK clears the badge; remember it (AC-7.4). */
|
|
1695
|
+
const rememberIfReadOffline = (error: any) => {
|
|
1696
|
+
if (!isNotConnectedError(error)) return;
|
|
1697
|
+
const hub = OfflineHub.getInstance();
|
|
1698
|
+
if (user) hub.rememberReadWhileOffline(user.getUid(), CometChat.RECEIVER_TYPE.USER);
|
|
1699
|
+
else if (group) hub.rememberReadWhileOffline(group.getGuid(), CometChat.RECEIVER_TYPE.GROUP);
|
|
1700
|
+
};
|
|
1701
|
+
|
|
1702
|
+
/**
|
|
1703
|
+
* Today's first-page side effects (active-chat event, read marks, unread indicator), run once
|
|
1704
|
+
* per ON-path read: with the server page, or with the cached rows when the read ended offline.
|
|
1705
|
+
*/
|
|
1706
|
+
const runOfflinePageEffects = (pageDesc: any[], isInitialLoad: boolean) => {
|
|
1707
|
+
if (isInitialLoad && (pageDesc.length > 0 || !parentMessageId)) {
|
|
1708
|
+
CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccActiveChatChanged, {
|
|
1709
|
+
message: pageDesc[0],
|
|
1710
|
+
user: user,
|
|
1711
|
+
group: group,
|
|
1712
|
+
theme: mergedTheme,
|
|
1713
|
+
parentMessageId: parentMessageId,
|
|
1459
1714
|
});
|
|
1715
|
+
if (pageDesc.length > 0 && conversationId.current == null) {
|
|
1716
|
+
conversationId.current = pageDesc[0].getConversationId?.() ?? null;
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
if (startFromUnreadMessages && pageDesc.length > 0) {
|
|
1720
|
+
if (!goToMessageId && isInitialLoad) {
|
|
1721
|
+
const oldestMessage = pageDesc[pageDesc.length - 1];
|
|
1722
|
+
const msgId = safeGetId(oldestMessage);
|
|
1723
|
+
if (msgId !== undefined) setNewMessageIndicatorId(String(msgId));
|
|
1724
|
+
}
|
|
1725
|
+
if (isInitialLoad && !navigatedFromSearch) {
|
|
1726
|
+
if (user) {
|
|
1727
|
+
CometChat.markConversationAsRead(user.getUid(), CometChat.RECEIVER_TYPE.USER).catch(rememberIfReadOffline);
|
|
1728
|
+
} else if (group) {
|
|
1729
|
+
CometChat.markConversationAsRead(group.getGuid(), CometChat.RECEIVER_TYPE.GROUP).catch(rememberIfReadOffline);
|
|
1730
|
+
}
|
|
1731
|
+
setUnreadCount(0);
|
|
1732
|
+
setNewMessageIndicatorId(null);
|
|
1733
|
+
CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, { message: pageDesc[0] });
|
|
1734
|
+
}
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
for (let index = 0; index < pageDesc.length; index++) {
|
|
1738
|
+
const message = pageDesc[index];
|
|
1739
|
+
if (!message || isOfflineUnsent(message) || message.getReadAt?.()) break;
|
|
1740
|
+
if (loggedInUser.current?.getUid() === message.getSender?.()?.getUid()) break;
|
|
1741
|
+
CometChat.markAsRead(message).catch(rememberIfReadOffline);
|
|
1742
|
+
if (index === 0) CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, { message });
|
|
1743
|
+
}
|
|
1744
|
+
};
|
|
1745
|
+
|
|
1746
|
+
/**
|
|
1747
|
+
* Older messages, two-phase (README §3.3): the cached page paints first, the server page
|
|
1748
|
+
* replaces the same slice in place. Only an empty server page ends history (BEH-READ-09b);
|
|
1749
|
+
* an offline read past the cache keeps what is shown and offers "Connect to load more".
|
|
1750
|
+
*/
|
|
1751
|
+
const getPreviousMessagesOffline = (request: CometChat.MessagesRequest, quietRead = false) => {
|
|
1752
|
+
offlinePathUsedRef.current = true;
|
|
1753
|
+
olderReadSeqRef.current++;
|
|
1754
|
+
const opGen = listOpGenRef.current;
|
|
1755
|
+
const hubGen = OfflineHub.getInstance().gen;
|
|
1756
|
+
const stale = () => opGen !== listOpGenRef.current || hubGen !== OfflineHub.getInstance().gen;
|
|
1757
|
+
const isInitialLoad = messagesContentListRef.current.length === 0;
|
|
1758
|
+
let cachedKeys = new Set<string>();
|
|
1759
|
+
let paintedKeys: string[] = [];
|
|
1760
|
+
let cachedDesc: any[] = [];
|
|
1761
|
+
let effectsRun = false;
|
|
1762
|
+
const finishLoad = () => {
|
|
1763
|
+
if (messagesContentListRef.current.length === 0) {
|
|
1764
|
+
onEmpty && onEmpty();
|
|
1765
|
+
} else {
|
|
1766
|
+
onLoad && onLoad([...messagesContentListRef.current].reverse());
|
|
1767
|
+
}
|
|
1768
|
+
setLoadingMessages(false);
|
|
1769
|
+
loadingMessagesRef.current = false;
|
|
1770
|
+
setListState("");
|
|
1771
|
+
};
|
|
1772
|
+
return fetchTwoPhase<any>(
|
|
1773
|
+
request,
|
|
1774
|
+
"previous",
|
|
1775
|
+
{
|
|
1776
|
+
onCached: (page) => {
|
|
1777
|
+
cachedDesc = [...page].reverse();
|
|
1778
|
+
cachedKeys = cachedKeysOf(page);
|
|
1779
|
+
const listed = cachedKeysOf(messagesContentListRef.current);
|
|
1780
|
+
paintedKeys = [...cachedKeys].filter((key) => !listed.has(key));
|
|
1781
|
+
applyOfflineResult(upsertSortedDesc(messagesContentListRef.current, page));
|
|
1782
|
+
// Cached rows are the first paint: no loader over them.
|
|
1783
|
+
if (messagesContentListRef.current.length > 0) setListState("");
|
|
1784
|
+
},
|
|
1785
|
+
onServer: (page) => {
|
|
1786
|
+
applyOfflineResult(
|
|
1787
|
+
dropUnjoinedCachedPageDesc(
|
|
1788
|
+
reconcileServerPageDesc(messagesContentListRef.current, cachedKeys, page),
|
|
1789
|
+
paintedKeys,
|
|
1790
|
+
[...cachedKeys],
|
|
1791
|
+
page,
|
|
1792
|
+
"previous"
|
|
1793
|
+
)
|
|
1794
|
+
);
|
|
1795
|
+
if (page.length === 0) reachedFirstMessage.current = true;
|
|
1796
|
+
reloadOnConnectRef.current = false;
|
|
1797
|
+
setOfflineMiss(false);
|
|
1798
|
+
setOfflineFooter("none");
|
|
1799
|
+
offlineFooterRetryableRef.current = false;
|
|
1800
|
+
if (!effectsRun) {
|
|
1801
|
+
effectsRun = true;
|
|
1802
|
+
runOfflinePageEffects([...page].reverse(), isInitialLoad);
|
|
1803
|
+
}
|
|
1804
|
+
finishLoad();
|
|
1805
|
+
},
|
|
1806
|
+
onError: (error, failedOffline) => {
|
|
1807
|
+
// Not connected: the SDK said so, or it reports no connection.
|
|
1808
|
+
const notConnected = failedOffline || sdkConnected() === false;
|
|
1809
|
+
if (notConnected) {
|
|
1810
|
+
if (messagesContentListRef.current.length === 0) {
|
|
1811
|
+
// D84 rule 3: nothing on screen and not connected: "Connect to load messages" (the
|
|
1812
|
+
// app's own ErrorView instead if it passed one), not an empty chat; onError once.
|
|
1813
|
+
// It loads again once on reconnect.
|
|
1814
|
+
reloadOnConnectRef.current = true;
|
|
1815
|
+
setOfflineMiss(true);
|
|
1816
|
+
setOfflineFooter("none");
|
|
1817
|
+
offlineFooterRetryableRef.current = false;
|
|
1818
|
+
setListState("error");
|
|
1819
|
+
setLoadingMessages(false);
|
|
1820
|
+
loadingMessagesRef.current = false;
|
|
1821
|
+
onError && onError(error as CometChat.CometChatException);
|
|
1822
|
+
return;
|
|
1823
|
+
}
|
|
1824
|
+
// Saved messages stay (BEH-READ-05) with "Connect to load more" at that edge. D84 rule 2:
|
|
1825
|
+
// not connected over rows is not an error, so nothing is reported. A read that gave up
|
|
1826
|
+
// after the connection was already back is retryable by scrolling at once.
|
|
1827
|
+
setOfflineFooter("connect");
|
|
1828
|
+
offlineFooterRetryableRef.current = sdkConnected() === true;
|
|
1829
|
+
if (!effectsRun && isInitialLoad && cachedDesc.length > 0) {
|
|
1830
|
+
effectsRun = true;
|
|
1831
|
+
runOfflinePageEffects(cachedDesc, isInitialLoad);
|
|
1832
|
+
}
|
|
1833
|
+
finishLoad();
|
|
1834
|
+
return;
|
|
1835
|
+
}
|
|
1836
|
+
reloadOnConnectRef.current = false;
|
|
1837
|
+
setOfflineMiss(false);
|
|
1838
|
+
// Never blank cached rows already shown (BEH-READ-06).
|
|
1839
|
+
const nothingShown = messagesContentListRef.current.length == 0;
|
|
1840
|
+
if (nothingShown) setListState("error");
|
|
1841
|
+
setLoadingMessages(false);
|
|
1842
|
+
loadingMessagesRef.current = false;
|
|
1843
|
+
// D84 rule 4 and 5: a real error is reported once; over rows only when the user or app
|
|
1844
|
+
// started the read (open, paging), not one the kit started by itself.
|
|
1845
|
+
if (nothingShown || !quietRead) onError && onError(error as CometChat.CometChatException);
|
|
1846
|
+
},
|
|
1847
|
+
},
|
|
1848
|
+
stale
|
|
1849
|
+
).finally(() => {
|
|
1850
|
+
loadingPrevMessagesRef.current = false;
|
|
1851
|
+
});
|
|
1852
|
+
};
|
|
1853
|
+
|
|
1854
|
+
/** "Connect to load more" tapped (or scrolled to, once online): try the older page again. */
|
|
1855
|
+
const retryOfflineOlderPage = () => {
|
|
1856
|
+
setOfflineFooter("none");
|
|
1857
|
+
offlineFooterRetryableRef.current = false;
|
|
1858
|
+
loadingPrevMessagesRef.current = false;
|
|
1859
|
+
getPreviousMessages();
|
|
1860
|
+
};
|
|
1861
|
+
|
|
1862
|
+
/** "Connect to load more" tapped at the newer edge of an anchored window: try that page again. */
|
|
1863
|
+
const retryOfflineNewerPage = () => {
|
|
1864
|
+
setOfflineNewerBlocked(false);
|
|
1865
|
+
offlineNewerBlockedRef.current = false;
|
|
1866
|
+
fetchNextMessagesRef.current();
|
|
1867
|
+
};
|
|
1868
|
+
|
|
1869
|
+
/**
|
|
1870
|
+
* Reconnect (D84 rule 9): the page that failed offline at each blocked "Connect to load more" edge
|
|
1871
|
+
* loads once, by itself. It waits for the reads in flight to settle, loads the older edge, waits for
|
|
1872
|
+
* that to settle, then the newer edge. An edge loads only if it is still blocked when its turn comes
|
|
1873
|
+
* (a tap, or a read that answered meanwhile, already took care of it), and nothing loads once the
|
|
1874
|
+
* window changed (a jump, a logout, another chat) or the list is being positioned past its limit.
|
|
1875
|
+
* With nothing shown the empty list reads the newest page instead (the error state's reload).
|
|
1876
|
+
*/
|
|
1877
|
+
const loadBlockedEdgesOnReconnect = () => {
|
|
1878
|
+
if (!isOfflineOn() || messagesContentListRef.current.length === 0) return;
|
|
1879
|
+
if (offlineFooterRef.current !== "connect" && !offlineNewerBlockedRef.current) return;
|
|
1880
|
+
const token = ++edgeReloadTokenRef.current;
|
|
1881
|
+
const olderSeq = olderReadSeqRef.current;
|
|
1882
|
+
const newerSeq = newerReadSeqRef.current;
|
|
1883
|
+
const opGen = listOpGenRef.current;
|
|
1884
|
+
const jumpGen = jumpGenRef.current;
|
|
1885
|
+
const sameWindow = () =>
|
|
1886
|
+
token === edgeReloadTokenRef.current && opGen === listOpGenRef.current && jumpGen === jumpGenRef.current;
|
|
1887
|
+
const idle = () =>
|
|
1888
|
+
!loadingPrevMessagesRef.current &&
|
|
1889
|
+
!loadingMessagesRef.current &&
|
|
1890
|
+
!fetchingAroundIdRef.current &&
|
|
1891
|
+
!positioningRef.current;
|
|
1892
|
+
/** Resolves true once no read is in flight and the window is still this one. */
|
|
1893
|
+
const settled = async (): Promise<boolean> => {
|
|
1894
|
+
for (let waited = 0; waited <= EDGE_RELOAD_MAX_WAIT_MS; waited += EDGE_RELOAD_POLL_MS) {
|
|
1895
|
+
if (!sameWindow()) return false;
|
|
1896
|
+
if (idle()) return true;
|
|
1897
|
+
await new Promise<void>((resolve) => setTimeout(() => resolve(), EDGE_RELOAD_POLL_MS));
|
|
1898
|
+
}
|
|
1899
|
+
return false;
|
|
1900
|
+
};
|
|
1901
|
+
void (async () => {
|
|
1902
|
+
if (!(await settled())) return;
|
|
1903
|
+
if (offlineFooterRef.current === "connect" && olderReadSeqRef.current === olderSeq) {
|
|
1904
|
+
retryOfflineOlderPage();
|
|
1905
|
+
// A read that starts but never finishes (a hung request) must not hold the newer edge forever.
|
|
1906
|
+
await new Promise<void>((resolve) => setTimeout(() => resolve(), 0));
|
|
1907
|
+
if (!(await settled())) return;
|
|
1908
|
+
}
|
|
1909
|
+
if (offlineNewerBlockedRef.current && newerReadSeqRef.current === newerSeq) retryOfflineNewerPage();
|
|
1910
|
+
})();
|
|
1911
|
+
};
|
|
1912
|
+
|
|
1913
|
+
/**
|
|
1914
|
+
* UIK-READ-03: once the connection is back, a scroll gesture at the older end reads the page
|
|
1915
|
+
* the footer stands for, as a tap on it does. The list's own end-reached event does not fire
|
|
1916
|
+
* again while the user stays at that end, so the scroll events themselves are the trigger.
|
|
1917
|
+
* Nothing is read on reconnect by itself (UIK-SYNC-01). Inert unless the footer shows and the
|
|
1918
|
+
* connection is back, so with offline off it never runs.
|
|
1919
|
+
*/
|
|
1920
|
+
const retryOlderOnScroll = () => {
|
|
1921
|
+
if (!offlineFooterRetryableRef.current || offlineFooterRef.current !== "connect") return;
|
|
1922
|
+
if (loadingPrevMessagesRef.current || loadingMessagesRef.current || fetchingAroundIdRef.current) return;
|
|
1923
|
+
const { layoutHeight, contentHeight } = currentScrollPosition.current;
|
|
1924
|
+
const y = currentScrollPosition.current.y ?? 0;
|
|
1925
|
+
// Inverted list: the older end is where the offset plus the viewport reaches the content's end.
|
|
1926
|
+
if (!layoutHeight || contentHeight - (y + layoutHeight) > layoutHeight * 0.5) return;
|
|
1927
|
+
const now = Date.now();
|
|
1928
|
+
if (now - lastRetryOnScrollRef.current < RETRY_ON_SCROLL_GAP_MS) return;
|
|
1929
|
+
lastRetryOnScrollRef.current = now;
|
|
1930
|
+
retryOfflineOlderPage();
|
|
1931
|
+
};
|
|
1932
|
+
|
|
1933
|
+
/**
|
|
1934
|
+
* After a PARTIAL or failed sweep: one fresh two-phase read of the newest window (README
|
|
1935
|
+
* §3.7). If the server page does not overlap what is shown, more was missed than one page,
|
|
1936
|
+
* so the list resets to that window (own unsent rows stay); older pages reload on scroll.
|
|
1937
|
+
*/
|
|
1938
|
+
const refreshNewestWindow = () => {
|
|
1939
|
+
if (!msgRequestBuilder.current) return;
|
|
1940
|
+
offlinePathUsedRef.current = true;
|
|
1941
|
+
const builder: any = cloneRequestBuilder(msgRequestBuilder.current as any);
|
|
1942
|
+
builder?.setMessageId?.(0);
|
|
1943
|
+
const request = builder?.build?.();
|
|
1944
|
+
if (!request) return;
|
|
1945
|
+
const shownIds = new Set(messagesContentListRef.current.map(serverIdOf).filter((id) => id > 0));
|
|
1946
|
+
const opGen = listOpGenRef.current;
|
|
1947
|
+
const hubGen = OfflineHub.getInstance().gen;
|
|
1948
|
+
const stale = () => opGen !== listOpGenRef.current || hubGen !== OfflineHub.getInstance().gen;
|
|
1949
|
+
let cachedKeys = new Set<string>();
|
|
1950
|
+
void fetchTwoPhase<any>(
|
|
1951
|
+
request,
|
|
1952
|
+
"previous",
|
|
1953
|
+
{
|
|
1954
|
+
onCached: (page) => {
|
|
1955
|
+
cachedKeys = cachedKeysOf(page);
|
|
1956
|
+
},
|
|
1957
|
+
onServer: (page) => {
|
|
1958
|
+
const overlaps = page.length === 0 || shownIds.size === 0 || page.some((m) => shownIds.has(serverIdOf(m)));
|
|
1959
|
+
if (overlaps) {
|
|
1960
|
+
applyOfflineResult(reconcileServerPageDesc(messagesContentListRef.current, cachedKeys, page));
|
|
1961
|
+
return;
|
|
1962
|
+
}
|
|
1963
|
+
const unsent = messagesContentListRef.current.filter((m) => serverIdOf(m) === 0 && !m?.isStreamMessage);
|
|
1964
|
+
const reset = upsertSortedDesc([...page].reverse(), unsent).rows;
|
|
1965
|
+
messageRequest.current = request;
|
|
1966
|
+
reachedFirstMessage.current = false;
|
|
1967
|
+
temporaryMessageListRef.current = [];
|
|
1968
|
+
commitOfflineRows(reset);
|
|
1969
|
+
},
|
|
1970
|
+
onError: () => {
|
|
1971
|
+
/* the next sweep heals; never blank the list */
|
|
1972
|
+
},
|
|
1973
|
+
},
|
|
1974
|
+
stale
|
|
1975
|
+
);
|
|
1976
|
+
};
|
|
1977
|
+
|
|
1978
|
+
/**
|
|
1979
|
+
* Kill switch (UIK-LIFE-03): offline turned off while un-acked rows are shown. They turn
|
|
1980
|
+
* failed (direct), with Retry as a fresh send, and one notice. Only lists that used the
|
|
1981
|
+
* offline path can hold such rows.
|
|
1982
|
+
*/
|
|
1983
|
+
const failStrandedOfflineSends = () => {
|
|
1984
|
+
if (!offlinePathUsedRef.current) return;
|
|
1985
|
+
const hub = OfflineHub.getInstance();
|
|
1986
|
+
const stranded = [...messagesContentListRef.current, ...temporaryMessageListRef.current].filter(
|
|
1987
|
+
(m) => {
|
|
1988
|
+
const info = unsentRowInfo(m, hub);
|
|
1989
|
+
return !!info && !info.direct && info.state !== "failed";
|
|
1990
|
+
}
|
|
1991
|
+
);
|
|
1992
|
+
if (stranded.length === 0) return;
|
|
1993
|
+
for (const message of stranded) hub.reportFailure(message, "", { direct: true });
|
|
1994
|
+
hub.notify({ kind: "messages_not_sent", count: stranded.length, conversationId: conversationId.current ?? undefined });
|
|
1995
|
+
};
|
|
1996
|
+
|
|
1997
|
+
/**
|
|
1998
|
+
* Whether a swept row would show: its type and category pass the filter the list loads with.
|
|
1999
|
+
* Keeps the server's `action`/`message` record of an edit or delete (BEH-SYNC-25/31) out of the
|
|
2000
|
+
* list; the edited or deleted original (a normal message) still updates in place.
|
|
2001
|
+
*/
|
|
2002
|
+
const sweptRowAccepted = (m: any): boolean => {
|
|
2003
|
+
const filter = sweepFilterRef.current;
|
|
2004
|
+
if (!filter) return true;
|
|
2005
|
+
if (filter.types && !filter.types.includes(m?.getType?.())) return false;
|
|
2006
|
+
if (filter.categories && !filter.categories.includes(m?.getCategory?.())) return false;
|
|
2007
|
+
return true;
|
|
2008
|
+
};
|
|
2009
|
+
|
|
2010
|
+
/** A message the SDK's sweep delivered (`source === "SYNC"`): sorted insert, no sound/+1/receipt. */
|
|
2011
|
+
const insertSyncedMessage = (message: any) => {
|
|
2012
|
+
if (!belongsToThisList(message) || !sweptRowAccepted(message)) return;
|
|
2013
|
+
offlinePathUsedRef.current = true;
|
|
2014
|
+
// Anchored on an older message: take the copy of a row shown, never insert past the end.
|
|
2015
|
+
const rows = messagesContentListRef.current;
|
|
2016
|
+
const incoming = anchoredWindowRef.current ? onlyShownRows(rows, [message]) : [message];
|
|
2017
|
+
if (incoming.length > 0) applyOfflineResult(upsertSortedDesc(rows, incoming));
|
|
2018
|
+
};
|
|
2019
|
+
|
|
2020
|
+
/**
|
|
2021
|
+
* A sweep that ran its conversation phase only (a cold start: no message phase until the SDK
|
|
2022
|
+
* has a sync watermark, BEH-SYNC-11/32) brings this chat's newer last message on the
|
|
2023
|
+
* conversation, not on any message callback. When no message phase follows for this chat
|
|
2024
|
+
* and that message is not shown, refresh the newest window once (the same single read a
|
|
2025
|
+
* PARTIAL sweep gets) so the open chat does not miss it.
|
|
2026
|
+
*/
|
|
2027
|
+
const coldSweepCheckRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
2028
|
+
const onConversationSynced = (event: ConversationSyncEvent) => {
|
|
2029
|
+
const hub = OfflineHub.getInstance();
|
|
2030
|
+
if (event.gen !== hub.gen || !offlinePathUsedRef.current) return;
|
|
2031
|
+
// Anchored on an older message: the newest window is not what is shown; "load newer" reads it.
|
|
2032
|
+
if (anchoredWindowRef.current) return;
|
|
2033
|
+
const mine = event.conversations.find((c: any) => {
|
|
2034
|
+
const last = c?.getLastMessage?.();
|
|
2035
|
+
return !!last && belongsToThisList(last) && !last.getParentMessageId?.();
|
|
2036
|
+
});
|
|
2037
|
+
const last = mine?.getLastMessage?.();
|
|
2038
|
+
const lastId = serverIdOf(last);
|
|
2039
|
+
if (!lastId || lastId <= newestServerId(messagesContentListRef.current)) return;
|
|
2040
|
+
if (coldSweepCheckRef.current) clearTimeout(coldSweepCheckRef.current);
|
|
2041
|
+
const gen = hub.gen;
|
|
2042
|
+
coldSweepCheckRef.current = setTimeout(() => {
|
|
2043
|
+
coldSweepCheckRef.current = null;
|
|
2044
|
+
if (gen !== OfflineHub.getInstance().gen || anchoredWindowRef.current) return;
|
|
2045
|
+
if (messagesContentListRef.current.some((m) => serverIdOf(m) === lastId)) return;
|
|
2046
|
+
refreshNewestWindow();
|
|
2047
|
+
}, COLD_SWEEP_SETTLE_MS);
|
|
2048
|
+
};
|
|
2049
|
+
|
|
2050
|
+
/** Read the newest page again, two-phase, from a fresh request (cache reset; reconnect over an error view). */
|
|
2051
|
+
const reloadNewestPage = () => {
|
|
2052
|
+
reachedFirstMessage.current = false;
|
|
2053
|
+
loadingPrevMessagesRef.current = false;
|
|
2054
|
+
loadingMessagesRef.current = false;
|
|
2055
|
+
if (msgRequestBuilder.current) {
|
|
2056
|
+
const builder: any = cloneRequestBuilder(msgRequestBuilder.current as any);
|
|
2057
|
+
builder?.setMessageId?.(0);
|
|
2058
|
+
messageRequest.current = builder?.build?.() ?? messageRequest.current;
|
|
2059
|
+
}
|
|
2060
|
+
setListState("loading");
|
|
2061
|
+
quietNextReadRef.current = true; // the kit starts this read: a real error over rows stays quiet
|
|
2062
|
+
getPreviousMessages();
|
|
2063
|
+
};
|
|
2064
|
+
|
|
2065
|
+
const offlineHandlers = {
|
|
2066
|
+
onConversationSync: onConversationSynced,
|
|
2067
|
+
onSendState: (event: SendStateEvent) => {
|
|
2068
|
+
const hub = OfflineHub.getInstance();
|
|
2069
|
+
if (event.gen !== hub.gen || !belongsToThisList(event.message)) return;
|
|
2070
|
+
offlinePathUsedRef.current = true;
|
|
2071
|
+
if (event.state === "discarded") {
|
|
2072
|
+
temporaryMessageListRef.current = temporaryMessageListRef.current.filter(
|
|
2073
|
+
(m) => findRowIndex([m], event.message) === -1
|
|
2074
|
+
);
|
|
2075
|
+
applyOfflineResult(removeRowDesc(messagesContentListRef.current, event.message));
|
|
2076
|
+
return;
|
|
2077
|
+
}
|
|
2078
|
+
// A fresh reference, so the memoized bubble re-renders with the new state.
|
|
2079
|
+
applyOfflineResult(upsertSortedDesc(messagesContentListRef.current, [CommonUtils.clone(event.message)]));
|
|
2080
|
+
},
|
|
2081
|
+
onMessageSync: (event: MessageSyncEvent) => {
|
|
2082
|
+
const hub = OfflineHub.getInstance();
|
|
2083
|
+
if (event.gen !== hub.gen) return;
|
|
2084
|
+
// A message phase ran: it delivers the chat's new messages itself (no cold refresh).
|
|
2085
|
+
if (coldSweepCheckRef.current) {
|
|
2086
|
+
clearTimeout(coldSweepCheckRef.current);
|
|
2087
|
+
coldSweepCheckRef.current = null;
|
|
2088
|
+
}
|
|
2089
|
+
const anchored = anchoredWindowRef.current;
|
|
2090
|
+
const forThisChat = event.messages.filter(
|
|
2091
|
+
(m: any) =>
|
|
2092
|
+
belongsToThisList(m) &&
|
|
2093
|
+
!(hideGroupActionMessages && m?.getCategory?.() === MessageCategoryConstants.action) &&
|
|
2094
|
+
sweptRowAccepted(m)
|
|
2095
|
+
);
|
|
2096
|
+
// Anchored on an older message (a jump, start-from-unread): the sweep updates the rows
|
|
2097
|
+
// shown and inserts nothing. A newer message put past the window's end leaves a hole, and
|
|
2098
|
+
// "load newer" anchors on the newest row shown, so it would skip everything in it. The
|
|
2099
|
+
// messages are in the SDK's store: scrolling to the end, or "latest", reads them.
|
|
2100
|
+
const forThisList = anchored ? onlyShownRows(messagesContentListRef.current, forThisChat) : forThisChat;
|
|
2101
|
+
heldReceiptsRef.current.clear();
|
|
2102
|
+
if (forThisList.length > 0) {
|
|
2103
|
+
offlinePathUsedRef.current = true;
|
|
2104
|
+
applyOfflineResult(upsertSortedDesc(messagesContentListRef.current, forThisList));
|
|
2105
|
+
}
|
|
2106
|
+
// One cumulative read receipt for the newest message, if the user is at the bottom.
|
|
2107
|
+
const newest = messagesContentListRef.current.find((m) => serverIdOf(m) > 0 && !m?.isStreamMessage);
|
|
2108
|
+
if (
|
|
2109
|
+
!anchored &&
|
|
2110
|
+
forThisList.length > 0 &&
|
|
2111
|
+
newest &&
|
|
2112
|
+
(isAtBottom() || isNearBottom()) &&
|
|
2113
|
+
!newest.getReadAt?.() &&
|
|
2114
|
+
newest.getSender?.()?.getUid?.() !== loggedInUser.current?.getUid()
|
|
2115
|
+
) {
|
|
2116
|
+
CometChat.markAsRead(newest).catch(rememberIfReadOffline);
|
|
2117
|
+
CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, { message: newest });
|
|
2118
|
+
}
|
|
2119
|
+
if (event.outcome === "PARTIAL" && offlinePathUsedRef.current && !anchored) refreshNewestWindow();
|
|
2120
|
+
},
|
|
2121
|
+
onSyncFailed: (event: SyncFailedEvent) => {
|
|
2122
|
+
if (event.phase !== "message" || event.gen !== OfflineHub.getInstance().gen) return;
|
|
2123
|
+
if (offlinePathUsedRef.current && !anchoredWindowRef.current) refreshNewestWindow();
|
|
2124
|
+
},
|
|
2125
|
+
onMessagesUpdated: (event: MessagesUpdatedEvent) => {
|
|
2126
|
+
if (event.gen !== OfflineHub.getInstance().gen) return;
|
|
2127
|
+
const rows = messagesContentListRef.current;
|
|
2128
|
+
// Update rows shown; never insert (BEH-INV-11).
|
|
2129
|
+
const shown = event.messages.filter((m: any) => findRowIndex(rows, m) !== -1);
|
|
2130
|
+
if (shown.length > 0) applyOfflineResult(upsertSortedDesc(rows, shown));
|
|
2131
|
+
},
|
|
2132
|
+
onSessionEnded: () => {
|
|
2133
|
+
// Logout, user switch or cache reset: nothing of the old session stays on screen.
|
|
2134
|
+
if (!offlinePathUsedRef.current) return;
|
|
2135
|
+
listOpGenRef.current++;
|
|
2136
|
+
heldReceiptsRef.current.clear();
|
|
2137
|
+
temporaryMessageListRef.current = [];
|
|
2138
|
+
messagesContentListRef.current = [];
|
|
2139
|
+
setMessagesList([]);
|
|
2140
|
+
setOfflineFooter("none");
|
|
2141
|
+
setOfflineNewerBlocked(false);
|
|
2142
|
+
setOfflineMiss(false);
|
|
2143
|
+
offlineFooterRetryableRef.current = false;
|
|
2144
|
+
reloadOnConnectRef.current = false;
|
|
2145
|
+
},
|
|
2146
|
+
onConnected: () => {
|
|
2147
|
+
// The connection is back (offline ON): a shown footer now loads on scroll as well as on
|
|
2148
|
+
// tap (UIK-READ-03). Nothing is fetched on reconnect except the one load again of the offline
|
|
2149
|
+
// state (D84 rule 8) and the page behind each blocked "Connect to load more" edge (rule 9).
|
|
2150
|
+
if (isOfflineOn() && offlineFooterRef.current === "connect") offlineFooterRetryableRef.current = true;
|
|
2151
|
+
if (reloadOnConnectRef.current && isOfflineOn()) {
|
|
2152
|
+
reloadOnConnectRef.current = false;
|
|
2153
|
+
reloadNewestPage();
|
|
2154
|
+
return;
|
|
2155
|
+
}
|
|
2156
|
+
loadBlockedEdgesOnReconnect();
|
|
2157
|
+
},
|
|
2158
|
+
onCacheReset: (event: CacheResetEvent) => {
|
|
2159
|
+
if (event.gen !== OfflineHub.getInstance().gen) return;
|
|
2160
|
+
if (!offlinePathUsedRef.current && !isOfflineOn()) return;
|
|
2161
|
+
// Reload two-phase from the rebuilt cache.
|
|
2162
|
+
reloadNewestPage();
|
|
2163
|
+
},
|
|
2164
|
+
};
|
|
2165
|
+
const offlineHandlersRef = useRef(offlineHandlers);
|
|
2166
|
+
offlineHandlersRef.current = offlineHandlers;
|
|
2167
|
+
|
|
2168
|
+
useEffect(() => {
|
|
2169
|
+
// Private hub channel (never the public bus). Inert while offline is off: nothing emits.
|
|
2170
|
+
const hub = OfflineHub.getInstance();
|
|
2171
|
+
const subscriptions = [
|
|
2172
|
+
hub.sendState$.subscribe((e) => offlineHandlersRef.current.onSendState(e)),
|
|
2173
|
+
hub.messageSync$.subscribe((e) => offlineHandlersRef.current.onMessageSync(e)),
|
|
2174
|
+
hub.conversationSync$.subscribe((e) => offlineHandlersRef.current.onConversationSync(e)),
|
|
2175
|
+
hub.syncFailed$.subscribe((e) => offlineHandlersRef.current.onSyncFailed(e)),
|
|
2176
|
+
hub.messagesUpdated$.subscribe((e) => offlineHandlersRef.current.onMessagesUpdated(e)),
|
|
2177
|
+
hub.session$.subscribe(() => offlineHandlersRef.current.onSessionEnded()),
|
|
2178
|
+
hub.cacheReset$.subscribe((e) => offlineHandlersRef.current.onCacheReset(e)),
|
|
2179
|
+
hub.connected$.subscribe(() => offlineHandlersRef.current.onConnected()),
|
|
2180
|
+
];
|
|
2181
|
+
return () => {
|
|
2182
|
+
subscriptions.forEach((s) => s.unsubscribe());
|
|
2183
|
+
if (coldSweepCheckRef.current) clearTimeout(coldSweepCheckRef.current);
|
|
2184
|
+
};
|
|
2185
|
+
}, []);
|
|
2186
|
+
|
|
2187
|
+
const { notice: offlineNotice, dismiss: dismissOfflineNotice } = useOfflineNotice(
|
|
2188
|
+
!hideOfflineNotices,
|
|
2189
|
+
(n) => !n.previewsOnly && (!n.conversationId || !conversationId.current || n.conversationId === conversationId.current)
|
|
2190
|
+
);
|
|
2191
|
+
|
|
2192
|
+
/** Retry on a failed row: the SDK's retry for an outbox row, a fresh send otherwise. */
|
|
2193
|
+
const onRetryPress = (item: any) => {
|
|
2194
|
+
const hub = OfflineHub.getInstance();
|
|
2195
|
+
const offlineRow = isOfflineUnsent(item) || hub.directFailureOf(item) !== undefined;
|
|
2196
|
+
if (offlineRow && isOfflineOn()) {
|
|
2197
|
+
retryFailedMessage(item, sendKindOf(item));
|
|
2198
|
+
return;
|
|
2199
|
+
}
|
|
2200
|
+
if (offlineRow) hub.clearDirectFailed(item);
|
|
2201
|
+
resendMediaMessage(item);
|
|
2202
|
+
};
|
|
2203
|
+
|
|
2204
|
+
/**
|
|
2205
|
+
* Delete on an unsent row (BEH-SEND-36, R162): `discardLocalMessage` for an outbox row, the
|
|
2206
|
+
* screen only for a direct failure. A refusal never leaves a ghost row or a half change.
|
|
2207
|
+
*/
|
|
2208
|
+
const onDeleteUnsentPress = (item: any) => {
|
|
2209
|
+
void deleteUnsentMessage(item).then((outcome) => {
|
|
2210
|
+
switch (outcome.kind) {
|
|
2211
|
+
case "removed":
|
|
2212
|
+
return; // the hub's discarded event removed the row
|
|
2213
|
+
case "sent": {
|
|
2214
|
+
// It went out meanwhile: delete it on the server, today's path and events.
|
|
2215
|
+
const sent = messagesContentListRef.current.find((m) => serverIdOf(m) === outcome.serverId);
|
|
2216
|
+
if (sent) deleteMessage(sent);
|
|
2217
|
+
else
|
|
2218
|
+
CometChat.deleteMessage(String(outcome.serverId))
|
|
2219
|
+
.then((res: any) => CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageDeleted, { message: res }))
|
|
2220
|
+
.catch((e: any) => onError && onError(e));
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
case "disabled":
|
|
2224
|
+
// Kill switch: every stranded row turns failed (direct); this one is then removed
|
|
2225
|
+
// from the screen, which is what Delete does for a direct failure.
|
|
2226
|
+
failStrandedOfflineSends();
|
|
2227
|
+
OfflineHub.getInstance().reportDiscardedByUser(item);
|
|
2228
|
+
return;
|
|
2229
|
+
case "in_flight":
|
|
2230
|
+
// Its send is under way: the row stays and the "Sending… try again in a moment"
|
|
2231
|
+
// notice is up (raised by the SDK's answer, R162). Not an error.
|
|
2232
|
+
return;
|
|
2233
|
+
default:
|
|
2234
|
+
// Not connected, store blip: the row stays; today's error.
|
|
2235
|
+
onError && onError((outcome as any).error);
|
|
2236
|
+
showToast(t("SOMETHING_WRONG"));
|
|
2237
|
+
}
|
|
2238
|
+
});
|
|
2239
|
+
};
|
|
2240
|
+
|
|
2241
|
+
/**
|
|
2242
|
+
* The options of an own unsent row (R162 / S73): Retry and Delete on every PENDING, SENDING
|
|
2243
|
+
* and FAILED row, and nothing that needs a server id. The SDK decides whether it can act: a
|
|
2244
|
+
* row whose send is under way answers IN_FLIGHT and the "Sending…" notice shows.
|
|
2245
|
+
*/
|
|
2246
|
+
const openUnsentMessageOptions = (item: any) => {
|
|
2247
|
+
const actions = unsentActionsOf(unsentRowInfo(item));
|
|
2248
|
+
if (actions.length === 0) return;
|
|
2249
|
+
const dataSource: any = ChatConfigurator.dataSource;
|
|
2250
|
+
const options: any[] = [];
|
|
2251
|
+
if (actions.includes("retry")) {
|
|
2252
|
+
options.push({
|
|
2253
|
+
id: OFFLINE_OPTION_IDS.retry,
|
|
2254
|
+
title: t("RETRY"),
|
|
2255
|
+
icon: <Icon name="retry" color={mergedTheme.color.iconSecondary} />,
|
|
2256
|
+
onPress: () => {
|
|
2257
|
+
onRetryPress(item);
|
|
2258
|
+
requestAnimationFrame(() => setShowMessageOptions([]));
|
|
2259
|
+
},
|
|
2260
|
+
});
|
|
2261
|
+
}
|
|
2262
|
+
if (actions.includes("delete")) {
|
|
2263
|
+
const del = dataSource?.getDeleteOption?.(mergedTheme) ?? { id: MessageOptionConstants.deleteMessage, title: t("DELETE") };
|
|
2264
|
+
options.push({
|
|
2265
|
+
...del,
|
|
2266
|
+
id: OFFLINE_OPTION_IDS.delete,
|
|
2267
|
+
onPress: () => {
|
|
2268
|
+
requestAnimationFrame(() => setShowMessageOptions([]));
|
|
2269
|
+
onDeleteUnsentPress(item);
|
|
2270
|
+
},
|
|
2271
|
+
});
|
|
2272
|
+
}
|
|
2273
|
+
setSelectedMessage(item);
|
|
2274
|
+
setShowMessageOptions(options);
|
|
1460
2275
|
};
|
|
1461
2276
|
|
|
1462
2277
|
const highlightMessage = (messageId: string) => {
|
|
@@ -1489,6 +2304,21 @@ export const CometChatMessageList = memo(
|
|
|
1489
2304
|
}
|
|
1490
2305
|
|
|
1491
2306
|
fetchingAroundIdRef.current = messageId; // Mark this message as being fetched
|
|
2307
|
+
// The jump replaces the window: a page read already in flight (older or newer) belongs to
|
|
2308
|
+
// the window being left and must not land in the jumped-to one. Its callbacks are dropped
|
|
2309
|
+
// (generation), so its loading flags are released here instead.
|
|
2310
|
+
jumpGenRef.current++;
|
|
2311
|
+
listOpGenRef.current++;
|
|
2312
|
+
loadingPrevMessagesRef.current = false;
|
|
2313
|
+
loadingMessagesRef.current = false;
|
|
2314
|
+
setLoadingMessages(false);
|
|
2315
|
+
setBottomLoading(false);
|
|
2316
|
+
setOfflineNewerBlocked(false); // the window being left owned that edge
|
|
2317
|
+
aroundReachedNewestRef.current = false;
|
|
2318
|
+
const aroundIdOffline = isOfflineOn(); // gate read once for this jump
|
|
2319
|
+
// Offline ON only (UIK-GATE-02/03): its phased paint is what leaves the list unpositioned
|
|
2320
|
+
// while paging and live messages run. With offline off the around read is today's, untouched.
|
|
2321
|
+
if (aroundIdOffline) beginPositioning();
|
|
1492
2322
|
|
|
1493
2323
|
// Check if message exists in current list
|
|
1494
2324
|
const messageExists = messagesContentListRef.current.find(msg =>
|
|
@@ -1508,169 +2338,237 @@ export const CometChatMessageList = memo(
|
|
|
1508
2338
|
msgRequestBuilder.current?.setMessageId(targetMessageId);
|
|
1509
2339
|
messageRequest.current = msgRequestBuilder.current?.build() || null;
|
|
1510
2340
|
|
|
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
2341
|
// Create request builder for next messages (messages after the target).
|
|
1519
2342
|
// Same types/categories filter as the main list: without it the server also returns
|
|
1520
2343
|
// the hidden edit/delete records (category "action", type "message"), which no
|
|
1521
2344
|
// template renders, so each one became an empty padded row after the jump.
|
|
1522
|
-
|
|
1523
|
-
.
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
if (user) {
|
|
1529
|
-
nextMessagesRequest = nextMessagesRequest.setUID(user.getUid());
|
|
1530
|
-
}
|
|
2345
|
+
const buildNextMessagesRequest = () => {
|
|
2346
|
+
let nextMessagesRequest = new CometChat.MessagesRequestBuilder()
|
|
2347
|
+
.setLimit(AROUND_NEXT_PAGE_LIMIT)
|
|
2348
|
+
.setMessageId(targetMessageId)
|
|
2349
|
+
.setTypes(ChatConfigurator.dataSource.getAllMessageTypes())
|
|
2350
|
+
.setCategories(ChatConfigurator.dataSource.getAllMessageCategories());
|
|
1531
2351
|
|
|
1532
|
-
|
|
1533
|
-
|
|
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);
|
|
2352
|
+
if (user) {
|
|
2353
|
+
nextMessagesRequest = nextMessagesRequest.setUID(user.getUid());
|
|
1547
2354
|
}
|
|
1548
|
-
}
|
|
1549
2355
|
|
|
1550
|
-
|
|
1551
|
-
|
|
2356
|
+
if (group) {
|
|
2357
|
+
nextMessagesRequest = nextMessagesRequest.setGUID(group.getGuid());
|
|
2358
|
+
}
|
|
1552
2359
|
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
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);
|
|
2360
|
+
// Main chat: Server excludes thread replies
|
|
2361
|
+
if (!parentMessageId) {
|
|
2362
|
+
nextMessagesRequest = nextMessagesRequest.hideReplies(true);
|
|
2363
|
+
}
|
|
2364
|
+
// Thread: Server includes only relevant messages
|
|
2365
|
+
else {
|
|
2366
|
+
nextMessagesRequest = nextMessagesRequest
|
|
2367
|
+
.setParentMessageId(Number(parentMessageId))
|
|
2368
|
+
.hideReplies(false);
|
|
2369
|
+
if (isAgenticUser) {
|
|
2370
|
+
nextMessagesRequest = nextMessagesRequest.withParent(true);
|
|
1600
2371
|
}
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
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());
|
|
2372
|
+
}
|
|
2373
|
+
return nextMessagesRequest;
|
|
2374
|
+
};
|
|
1634
2375
|
|
|
1635
|
-
|
|
1636
|
-
|
|
2376
|
+
// Show the anchored window (target + the page after it). `firstPaint` is false only for
|
|
2377
|
+
// the offline path's server repaint over its cached paint: the one-time work (search
|
|
2378
|
+
// unread lookup, scroll target) is not repeated.
|
|
2379
|
+
const presentAroundPage = (targetMessage: any, nextMessages: any[], firstPaint: boolean) => {
|
|
2380
|
+
// Combine messages: previous (reversed) + target + next
|
|
2381
|
+
const allMessages = [
|
|
2382
|
+
// ...previousMessages,
|
|
2383
|
+
targetMessage,
|
|
2384
|
+
...nextMessages
|
|
2385
|
+
].reverse();
|
|
2386
|
+
|
|
2387
|
+
// Remove duplicates and sort by timestamp (newest at top for FlatList)
|
|
2388
|
+
const uniqueMessages = allMessages
|
|
2389
|
+
// .filter((message, index, array) =>
|
|
2390
|
+
// array.findIndex(m => m.getId() === message.getId()) === index
|
|
2391
|
+
// )
|
|
2392
|
+
// .sort((a, b) => b.getSentAt() - a.getSentAt());
|
|
2393
|
+
|
|
2394
|
+
if (uniqueMessages.length > 0) {
|
|
2395
|
+
// Check if this is the initial load using ref to ensure fresh state
|
|
2396
|
+
const isInitialLoad = messagesContentListRef.current.length === 0;
|
|
2397
|
+
messagesContentListRef.current = uniqueMessages;
|
|
2398
|
+
setMessagesList(uniqueMessages);
|
|
2399
|
+
onLoad && onLoad([...uniqueMessages].reverse());
|
|
2400
|
+
|
|
2401
|
+
//This check is used to determine if this is the Initial Load of the chat screen.
|
|
2402
|
+
// Check if this is the initial load (messagesList is empty).
|
|
2403
|
+
// We check messagesList.length === 0 because setMessagesList above is async,
|
|
2404
|
+
// so messagesList still reflects the state before this update.
|
|
2405
|
+
// We only want to mark as read on the first load, not during subsequent updates.
|
|
2406
|
+
// The !navigatedFromSearch condition ensures we don't mark as read when navigating from search results,
|
|
2407
|
+
// as the user might want to keep messages unread for reference.
|
|
2408
|
+
if (startFromUnreadMessages && isInitialLoad && !navigatedFromSearch && !goToMessageId) {
|
|
2409
|
+
shouldSuppressHighlightRef.current = true;
|
|
2410
|
+
// Mark entire conversation as read — clears unread count on server
|
|
2411
|
+
if (user) {
|
|
2412
|
+
CometChat.markConversationAsRead(user.getUid(), CometChat.RECEIVER_TYPE.USER).catch((e) => {
|
|
2413
|
+
console.log("Error marking user conversation as read", e);
|
|
2414
|
+
});
|
|
2415
|
+
} else if (group) {
|
|
2416
|
+
CometChat.markConversationAsRead(group.getGuid(), CometChat.RECEIVER_TYPE.GROUP).catch((e) => {
|
|
2417
|
+
console.log("Error marking group conversation as read", e);
|
|
2418
|
+
});
|
|
2419
|
+
}
|
|
2420
|
+
setUnreadCount(0);
|
|
2421
|
+
// If we have next messages (unread messages), set the indicator on the first one.
|
|
2422
|
+
// Otherwise, fallback to the target message (last read message).
|
|
2423
|
+
if (nextMessages.length > 0) {
|
|
2424
|
+
setNewMessageIndicatorId(String(nextMessages[0].getId()));
|
|
2425
|
+
} else {
|
|
2426
|
+
setNewMessageIndicatorId(messageId);
|
|
2427
|
+
}
|
|
2428
|
+
//emitting event to update read receipts in other components
|
|
2429
|
+
CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageRead, {
|
|
2430
|
+
message: uniqueMessages[0],
|
|
2431
|
+
});
|
|
2432
|
+
} else if (navigatedFromSearch && firstPaint) {
|
|
2433
|
+
// If we navigated from search, we want to show the "New Messages" indicator
|
|
2434
|
+
// but NOT mark the conversation as read immediately.
|
|
2435
|
+
// We fetch the first unread message to place the indicator correctly.
|
|
2436
|
+
const fetchFirstUnread = async () => {
|
|
2437
|
+
try {
|
|
2438
|
+
const convId = user?.getUid() ?? group?.getGuid();
|
|
2439
|
+
const conversationType = user
|
|
2440
|
+
? CometChat.RECEIVER_TYPE.USER
|
|
2441
|
+
: CometChat.RECEIVER_TYPE.GROUP;
|
|
2442
|
+
|
|
2443
|
+
if (!convId) return;
|
|
2444
|
+
|
|
2445
|
+
const conversation = await getConversationIfExists(convId, conversationType);
|
|
2446
|
+
if (!conversation) return;
|
|
2447
|
+
const unreadCount = conversation.getUnreadMessageCount();
|
|
2448
|
+
setUnreadCount(unreadCount);
|
|
2449
|
+
|
|
2450
|
+
if (unreadCount > 0) {
|
|
2451
|
+
const lastReadMsgId = conversation.getLastReadMessageId();
|
|
2452
|
+
|
|
2453
|
+
if (lastReadMsgId) {
|
|
2454
|
+
// Filtered like the main list, so the "New messages" marker lands on the
|
|
2455
|
+
// first unread message that is actually shown, not on a hidden edit/delete record.
|
|
2456
|
+
let request = new CometChat.MessagesRequestBuilder()
|
|
2457
|
+
.setLimit(1)
|
|
2458
|
+
.setMessageId(Number(lastReadMsgId))
|
|
2459
|
+
.setTypes(ChatConfigurator.dataSource.getAllMessageTypes())
|
|
2460
|
+
.setCategories(ChatConfigurator.dataSource.getAllMessageCategories());
|
|
2461
|
+
|
|
2462
|
+
if (user) request = request.setUID(user.getUid());
|
|
2463
|
+
if (group) request = request.setGUID(group.getGuid());
|
|
1637
2464
|
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
2465
|
+
if (!parentMessageId) {
|
|
2466
|
+
request = request.hideReplies(true);
|
|
2467
|
+
} else {
|
|
2468
|
+
request = request.setParentMessageId(Number(parentMessageId)).hideReplies(false);
|
|
2469
|
+
if (isAgenticUser) {
|
|
2470
|
+
request = request.withParent(true);
|
|
2471
|
+
}
|
|
1644
2472
|
}
|
|
1645
|
-
}
|
|
1646
2473
|
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
2474
|
+
const unreadMessages = await request.build().fetchNext();
|
|
2475
|
+
if (unreadMessages.length > 0) {
|
|
2476
|
+
setNewMessageIndicatorId(String(unreadMessages[0].getId()));
|
|
2477
|
+
}
|
|
1650
2478
|
}
|
|
1651
2479
|
}
|
|
2480
|
+
} catch (e) {
|
|
2481
|
+
console.log("Error fetching first unread message", e);
|
|
1652
2482
|
}
|
|
1653
|
-
}
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
2483
|
+
};
|
|
2484
|
+
fetchFirstUnread();
|
|
2485
|
+
}
|
|
2486
|
+
|
|
2487
|
+
// Reset layout state and set up for scrolling to target message
|
|
2488
|
+
// console.log(`Setting scroll target to message: ${messageId}`);
|
|
2489
|
+
if (firstPaint) {
|
|
2490
|
+
scrollTargetPendingRef.current = true;
|
|
2491
|
+
setScrollTargetId(messageId);
|
|
2492
|
+
}
|
|
1658
2493
|
}
|
|
2494
|
+
};
|
|
2495
|
+
|
|
2496
|
+
if (aroundIdOffline) {
|
|
2497
|
+
// Offline ON (BEH-READ-29): the target and the page after it, both two-phase. The
|
|
2498
|
+
// cached pair paints first; the server pair replaces it; offline a cached pair stays.
|
|
2499
|
+
const opGen = listOpGenRef.current;
|
|
2500
|
+
const hubGen = OfflineHub.getInstance().gen;
|
|
2501
|
+
let painted = false;
|
|
2502
|
+
let failure: { error: unknown; notConnected: boolean } | null = null;
|
|
2503
|
+
offlinePathUsedRef.current = true;
|
|
2504
|
+
await readAroundTwoPhase<any>(
|
|
2505
|
+
(listener) => offlineSdk().getMessageDetails(targetMessageId, listener),
|
|
2506
|
+
buildNextMessagesRequest().build(),
|
|
2507
|
+
{
|
|
2508
|
+
onPaint: (targetMessage, nextMessages, phase) => {
|
|
2509
|
+
// A short page from the server is the chat's newest end; a cached one proves nothing.
|
|
2510
|
+
aroundReachedNewestRef.current = phase === "server" && nextMessages.length < AROUND_NEXT_PAGE_LIMIT;
|
|
2511
|
+
presentAroundPage(targetMessage, nextMessages, !painted);
|
|
2512
|
+
painted = true;
|
|
2513
|
+
},
|
|
2514
|
+
onError: (error, notConnected) => {
|
|
2515
|
+
failure = { error, notConnected };
|
|
2516
|
+
},
|
|
2517
|
+
// The saved window stays on screen. D84 rule 2 and 5: a jump that could not reach the server
|
|
2518
|
+
// reports nothing; a real error reports once (the user started the jump).
|
|
2519
|
+
onKeptRowsError: (error) => {
|
|
2520
|
+
if (isNotConnectedError(error) || sdkConnected() === false) return;
|
|
2521
|
+
onError && onError(error as CometChat.CometChatException);
|
|
2522
|
+
},
|
|
2523
|
+
},
|
|
2524
|
+
() => opGen !== listOpGenRef.current || hubGen !== OfflineHub.getInstance().gen
|
|
2525
|
+
);
|
|
2526
|
+
if (failure) throw (failure as { error: unknown }).error ?? new Error("message not found");
|
|
2527
|
+
setListState("");
|
|
2528
|
+
return;
|
|
2529
|
+
}
|
|
1659
2530
|
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
2531
|
+
// Get the target message first to ensure it exists
|
|
2532
|
+
const targetMessage = await CometChat.getMessageDetails(targetMessageId);
|
|
2533
|
+
if (!targetMessage) {
|
|
2534
|
+
setListState("");
|
|
2535
|
+
return;
|
|
1663
2536
|
}
|
|
1664
2537
|
|
|
2538
|
+
let nextMessagesRequest = buildNextMessagesRequest();
|
|
2539
|
+
|
|
2540
|
+
// Fetch messages before and after the target message
|
|
2541
|
+
const nextMessages = await nextMessagesRequest.build().fetchNext();
|
|
2542
|
+
|
|
2543
|
+
presentAroundPage(targetMessage, nextMessages, true);
|
|
2544
|
+
|
|
1665
2545
|
setListState("");
|
|
1666
2546
|
} catch (error) {
|
|
1667
2547
|
console.log("Error fetching messages around ID:", error);
|
|
1668
|
-
|
|
2548
|
+
if (aroundIdOffline && isNotConnectedError(error)) {
|
|
2549
|
+
// Offline: the anchored read needs the server; open on the saved newest window instead.
|
|
2550
|
+
endPositioning();
|
|
2551
|
+
setNavigationLoading(false);
|
|
2552
|
+
setHasTargetMessageId(false);
|
|
2553
|
+
fetchingAroundIdRef.current = null;
|
|
2554
|
+
msgRequestBuilder.current?.setMessageId(0);
|
|
2555
|
+
messageRequest.current = msgRequestBuilder.current?.build() || null;
|
|
2556
|
+
// D84 rule 2: rows on screen stay and a jump that could not reach the server reports nothing.
|
|
2557
|
+
// With nothing on screen the newest-page read below shows "Connect to load messages" and reports.
|
|
2558
|
+
getPreviousMessages();
|
|
2559
|
+
return;
|
|
2560
|
+
}
|
|
2561
|
+
endPositioning();
|
|
2562
|
+
// D83 (offline ON): rows on screen stay, no error view over them.
|
|
2563
|
+
if (aroundIdOffline && messagesContentListRef.current.length > 0) setListState("");
|
|
2564
|
+
else setListState("error");
|
|
1669
2565
|
setNavigationLoading(false);
|
|
1670
2566
|
onError && onError(error as CometChat.CometChatException);
|
|
1671
2567
|
} finally {
|
|
1672
2568
|
// setNavigationLoading(false);
|
|
1673
2569
|
fetchingAroundIdRef.current = null;
|
|
2570
|
+
// Nothing was painted to scroll to (an empty answer): there is nothing to wait for.
|
|
2571
|
+
if (!scrollTargetPendingRef.current) endPositioning();
|
|
1674
2572
|
}
|
|
1675
2573
|
};
|
|
1676
2574
|
|
|
@@ -1713,6 +2611,7 @@ export const CometChatMessageList = memo(
|
|
|
1713
2611
|
}
|
|
1714
2612
|
shouldSuppressHighlightRef.current = false;
|
|
1715
2613
|
setNavigationLoading(false); // Clear loading when scroll completes
|
|
2614
|
+
endPositioning(); // positioned: paging and live auto-scroll may run again
|
|
1716
2615
|
}, 150);
|
|
1717
2616
|
} else {
|
|
1718
2617
|
// Position not measured yet - retry with faster progressive delays (up to 5 times)
|
|
@@ -1738,6 +2637,7 @@ export const CometChatMessageList = memo(
|
|
|
1738
2637
|
}
|
|
1739
2638
|
shouldSuppressHighlightRef.current = false;
|
|
1740
2639
|
setNavigationLoading(false); // Clear loading when scroll completes
|
|
2640
|
+
endPositioning();
|
|
1741
2641
|
}, 250);
|
|
1742
2642
|
} catch (scrollError) {
|
|
1743
2643
|
console.error('scrollToIndex failed immediately:', scrollError);
|
|
@@ -1746,6 +2646,7 @@ export const CometChatMessageList = memo(
|
|
|
1746
2646
|
}
|
|
1747
2647
|
shouldSuppressHighlightRef.current = false;
|
|
1748
2648
|
setNavigationLoading(false); // Clear loading on final failure
|
|
2649
|
+
endPositioning();
|
|
1749
2650
|
}
|
|
1750
2651
|
}
|
|
1751
2652
|
}
|
|
@@ -1789,14 +2690,17 @@ export const CometChatMessageList = memo(
|
|
|
1789
2690
|
.catch((e: any) => console.log("error while fetching updated msgs", e));
|
|
1790
2691
|
};
|
|
1791
2692
|
|
|
1792
|
-
const getNewMessages = (updatedList: any[]) => {
|
|
2693
|
+
const getNewMessages = (updatedList: any[], cursor: number = lastID.current) => {
|
|
1793
2694
|
let newRequestBuilder = msgRequestBuilder.current;
|
|
1794
|
-
newRequestBuilder?.setMessageId(
|
|
2695
|
+
newRequestBuilder?.setMessageId(cursor);
|
|
2696
|
+
const newRequest = newRequestBuilder?.build();
|
|
2697
|
+
// D3: page against the request's own limit, from a cursor that moves.
|
|
2698
|
+
const requestLimit = Number((newRequest as any)?.getLimit?.()) || 30;
|
|
1795
2699
|
|
|
1796
|
-
|
|
1797
|
-
?.
|
|
1798
|
-
.fetchNext()
|
|
2700
|
+
newRequest
|
|
2701
|
+
?.fetchNext()
|
|
1799
2702
|
.then((newMessages: any[]) => {
|
|
2703
|
+
const nextCursor = nextCatchUpCursor(newMessages, cursor, requestLimit);
|
|
1800
2704
|
let cleanUpdatedList = [...updatedList];
|
|
1801
2705
|
let finalOutput = CommonUtils.mergeArrays(newMessages.reverse(), cleanUpdatedList, [
|
|
1802
2706
|
"id",
|
|
@@ -1837,8 +2741,9 @@ export const CometChatMessageList = memo(
|
|
|
1837
2741
|
temporaryMessageListRef.current = [...currentUnreadMessages];
|
|
1838
2742
|
setUnreadCount(temporaryMessageListRef.current.length);
|
|
1839
2743
|
}
|
|
1840
|
-
if (
|
|
1841
|
-
|
|
2744
|
+
if (nextCursor !== null) {
|
|
2745
|
+
lastID.current = nextCursor;
|
|
2746
|
+
getNewMessages(tmpList, nextCursor);
|
|
1842
2747
|
}
|
|
1843
2748
|
newRequestBuilder?.setMessageId(undefined);
|
|
1844
2749
|
})
|
|
@@ -2074,6 +2979,8 @@ export const CometChatMessageList = memo(
|
|
|
2074
2979
|
},
|
|
2075
2980
|
(error: any) => {
|
|
2076
2981
|
console.log("Error marking as unread", error);
|
|
2982
|
+
// Offline this fails every time: nothing is left half-done on screen (UIK-MUT-01).
|
|
2983
|
+
if (isOfflineOn()) setShowMessageOptions([]);
|
|
2077
2984
|
}
|
|
2078
2985
|
);
|
|
2079
2986
|
};
|
|
@@ -2183,6 +3090,14 @@ export const CometChatMessageList = memo(
|
|
|
2183
3090
|
const newMessage = (newMessage: any, isReceived = true) => {
|
|
2184
3091
|
let baseMessage = newMessage as CometChat.BaseMessage;
|
|
2185
3092
|
|
|
3093
|
+
// Offline: a message the SDK's catch-up sweep delivered goes into its sorted place with no
|
|
3094
|
+
// sound, no unread +1 and no per-message receipt (UIK-SYNC-02). Only the offline SDK
|
|
3095
|
+
// stamps SYNC, so this never runs with offline off.
|
|
3096
|
+
if (isReceived && isSyncDelivered(newMessage)) {
|
|
3097
|
+
insertSyncedMessage(newMessage);
|
|
3098
|
+
return;
|
|
3099
|
+
}
|
|
3100
|
+
|
|
2186
3101
|
// Cases 2b/4b — a message I sent from ANOTHER of my devices. Sending subscribes me
|
|
2187
3102
|
// wherever I sent it from, but this copy came over the socket and carries no flag, so
|
|
2188
3103
|
// without this my own message reads "Subscribe" here until a refetch. Checked BEFORE
|
|
@@ -2336,6 +3251,14 @@ export const CometChatMessageList = memo(
|
|
|
2336
3251
|
if (!isReceived) {
|
|
2337
3252
|
return;
|
|
2338
3253
|
}
|
|
3254
|
+
if (positioningRef.current) {
|
|
3255
|
+
// A jump or start-from-unread window is still being scrolled to its anchor: following
|
|
3256
|
+
// this message to the bottom would end the list at the newest messages. It waits with
|
|
3257
|
+
// the others that arrived while reading older ones.
|
|
3258
|
+
if (!skipAddToList) temporaryMessageListRef.current = [newMessage, ...temporaryMessageListRef.current];
|
|
3259
|
+
setUnreadCount((prev) => prev + 1);
|
|
3260
|
+
return;
|
|
3261
|
+
}
|
|
2339
3262
|
if (isAtBottom() || isNearBottom() || scrollToBottomOnNewMessages) {
|
|
2340
3263
|
if (!skipAddToList) {
|
|
2341
3264
|
addToMessageList(newMessage);
|
|
@@ -2593,9 +3516,10 @@ export const CometChatMessageList = memo(
|
|
|
2593
3516
|
pinSaveAuthoritative: boolean = false
|
|
2594
3517
|
) => {
|
|
2595
3518
|
let condition: (value: any, index: number, obj: any[]) => unknown;
|
|
3519
|
+
// D2: null-safe — two rows that both lack the identity are never the same message.
|
|
2596
3520
|
if (withMuid) {
|
|
2597
|
-
condition = (msg) => msg
|
|
2598
|
-
} else condition = (msg) => msg
|
|
3521
|
+
condition = (msg) => sameMessageByMuid(msg, editedMessage);
|
|
3522
|
+
} else condition = (msg) => sameMessageById(msg, editedMessage);
|
|
2599
3523
|
let msgIndex = messagesContentListRef.current.findIndex(condition);
|
|
2600
3524
|
if (msgIndex > -1) {
|
|
2601
3525
|
|
|
@@ -2685,6 +3609,8 @@ export const CometChatMessageList = memo(
|
|
|
2685
3609
|
};
|
|
2686
3610
|
|
|
2687
3611
|
const deleteMessage = (message: CometChat.BaseMessage) => {
|
|
3612
|
+
// Offline ON (gate read once): a failed delete also shows today's error notice (ENG-41199).
|
|
3613
|
+
const offlineOn = isOfflineOn();
|
|
2688
3614
|
CometChat.deleteMessage(message.getId().toString())
|
|
2689
3615
|
.then((res: any) => {
|
|
2690
3616
|
CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageDeleted, {
|
|
@@ -2698,6 +3624,8 @@ export const CometChatMessageList = memo(
|
|
|
2698
3624
|
deleteItem.current = undefined;
|
|
2699
3625
|
setShowDeleteModal(false);
|
|
2700
3626
|
onError && onError(rej);
|
|
3627
|
+
const errorText = offlineMutationErrorText(offlineOn, t);
|
|
3628
|
+
if (errorText) showToast(errorText);
|
|
2701
3629
|
});
|
|
2702
3630
|
};
|
|
2703
3631
|
|
|
@@ -2849,7 +3777,13 @@ export const CometChatMessageList = memo(
|
|
|
2849
3777
|
}
|
|
2850
3778
|
);
|
|
2851
3779
|
|
|
2852
|
-
if (index === -1)
|
|
3780
|
+
if (index === -1) {
|
|
3781
|
+
// Offline: the receipt beat the ack of an own unsent row; apply it when the id lands.
|
|
3782
|
+
if (offlinePathUsedRef.current && messagesContentListRef.current.some((m) => isOfflineUnsent(m))) {
|
|
3783
|
+
heldReceiptsRef.current.hold(Number(receiptMessageId), receipt);
|
|
3784
|
+
}
|
|
3785
|
+
return;
|
|
3786
|
+
}
|
|
2853
3787
|
|
|
2854
3788
|
// Clone-first approach: shallow copy the array, then clone only messages
|
|
2855
3789
|
// whose receipt status actually changes. Unchanged items keep original references
|
|
@@ -3057,7 +3991,13 @@ export const CometChatMessageList = memo(
|
|
|
3057
3991
|
// for getMessagesAroundId causes it to leak into the main message list.
|
|
3058
3992
|
if (!parentMessageId) {
|
|
3059
3993
|
try {
|
|
3060
|
-
|
|
3994
|
+
// Offline ON: two-phase, so a cached anchor validates offline.
|
|
3995
|
+
const lastReadMsg: any = isOfflineOn()
|
|
3996
|
+
? await resolveTwoPhase<any>(
|
|
3997
|
+
(listener) => offlineSdk().getMessageDetails(Number(lastReadMessageId), listener),
|
|
3998
|
+
"Message"
|
|
3999
|
+
)
|
|
4000
|
+
: await CometChat.getMessageDetails(Number(lastReadMessageId));
|
|
3061
4001
|
const lastReadParentId = lastReadMsg?.getParentMessageId
|
|
3062
4002
|
? lastReadMsg.getParentMessageId()
|
|
3063
4003
|
: (lastReadMsg as any)?.parentMessageId;
|
|
@@ -3191,8 +4131,24 @@ export const CometChatMessageList = memo(
|
|
|
3191
4131
|
}
|
|
3192
4132
|
}, [user?.getUid(), group?.getGuid(), isAgenticUser]);
|
|
3193
4133
|
|
|
4134
|
+
// D4: the SDK/UI listeners below are registered once per chat. They used to re-subscribe on
|
|
4135
|
+
// every unreadCount change (it was an effect dependency only so the handlers would see the
|
|
4136
|
+
// current count), and each re-subscribe was a window in which a connection or message event
|
|
4137
|
+
// could be missed. The handlers now reach the current render's functions through this ref,
|
|
4138
|
+
// so they read current state without the listeners churning.
|
|
4139
|
+
// (Assigned on every render further down, once every handler it names is declared.)
|
|
4140
|
+
const listenerHandlersRef = useRef<any>(null);
|
|
4141
|
+
|
|
3194
4142
|
useEffect(() => {
|
|
3195
4143
|
//add listeners
|
|
4144
|
+
const newMessage = (...args: any[]) => listenerHandlersRef.current.newMessage(...args);
|
|
4145
|
+
const messageEdited = (...args: any[]) => listenerHandlersRef.current.messageEdited(...args);
|
|
4146
|
+
const updateMessageReceipt = (...args: any[]) =>
|
|
4147
|
+
listenerHandlersRef.current.updateMessageReceipt(...args);
|
|
4148
|
+
const updateMessageReaction = (...args: any[]) =>
|
|
4149
|
+
listenerHandlersRef.current.updateMessageReaction(...args);
|
|
4150
|
+
const getUpdatedPreviousMessages = () => listenerHandlersRef.current.getUpdatedPreviousMessages();
|
|
4151
|
+
const addToMessageList = (...args: any[]) => listenerHandlersRef.current.addToMessageList(...args);
|
|
3196
4152
|
|
|
3197
4153
|
// AI Assistant listener for agent chats
|
|
3198
4154
|
if (isAgenticUser && user && (!parentMessageId || (parentMessageId && isAgenticUser))) {
|
|
@@ -3711,6 +4667,11 @@ export const CometChatMessageList = memo(
|
|
|
3711
4667
|
new CometChat.ConnectionListener({
|
|
3712
4668
|
onConnected: () => {
|
|
3713
4669
|
streamOnConnected();
|
|
4670
|
+
// Offline ON: no kit message fetch on reconnect; the SDK's sweep delivers what was
|
|
4671
|
+
// missed (UIK-SYNC-01). OFF: today's catch-up, unchanged.
|
|
4672
|
+
if (isOfflineOn()) return;
|
|
4673
|
+
// Kill switch: offline turned off with un-acked rows shown → failed (direct) + notice.
|
|
4674
|
+
listenerHandlersRef.current.failStrandedOfflineSends();
|
|
3714
4675
|
if (lastID.current && !isAgenticUser) {
|
|
3715
4676
|
getUpdatedPreviousMessages();
|
|
3716
4677
|
}
|
|
@@ -3749,7 +4710,7 @@ export const CometChatMessageList = memo(
|
|
|
3749
4710
|
}
|
|
3750
4711
|
}
|
|
3751
4712
|
};
|
|
3752
|
-
}, [
|
|
4713
|
+
}, [user, group, isAgenticUser]);
|
|
3753
4714
|
|
|
3754
4715
|
useEffect(() => {
|
|
3755
4716
|
if (aiAssistantTools) {
|
|
@@ -3867,6 +4828,17 @@ export const CometChatMessageList = memo(
|
|
|
3867
4828
|
messageEdited(modifiedMessage, false);
|
|
3868
4829
|
};
|
|
3869
4830
|
|
|
4831
|
+
// D4: the current render's handlers, for the once-per-chat listeners registered above.
|
|
4832
|
+
listenerHandlersRef.current = {
|
|
4833
|
+
newMessage,
|
|
4834
|
+
messageEdited,
|
|
4835
|
+
updateMessageReceipt,
|
|
4836
|
+
updateMessageReaction,
|
|
4837
|
+
getUpdatedPreviousMessages,
|
|
4838
|
+
addToMessageList,
|
|
4839
|
+
failStrandedOfflineSends,
|
|
4840
|
+
};
|
|
4841
|
+
|
|
3870
4842
|
const getCurrentBubbleStyle = useCallback(
|
|
3871
4843
|
(item: CometChat.BaseMessage): BubbleStyles => {
|
|
3872
4844
|
const type = (() => {
|
|
@@ -4065,7 +5037,13 @@ export const CometChatMessageList = memo(
|
|
|
4065
5037
|
const hasErrorMetadata = item?.getData?.()?.metaData?.error;
|
|
4066
5038
|
const hasErrorInMetadata = item?.getMetadata?.()?.error;
|
|
4067
5039
|
const hasErrorProp = (item as any)?.error;
|
|
4068
|
-
|
|
5040
|
+
// Offline rows show their state from the SDK (clock / failed), never a receipt.
|
|
5041
|
+
const offlineReceipt = offlineReceiptOf(item);
|
|
5042
|
+
if (offlineReceipt === "error") {
|
|
5043
|
+
messageState = MessageReceipt.ERROR;
|
|
5044
|
+
} else if (offlineReceipt === "wait") {
|
|
5045
|
+
messageState = MessageReceipt.WAIT;
|
|
5046
|
+
} else if (hasErrorMetadata || hasErrorInMetadata || hasErrorProp) {
|
|
4069
5047
|
messageState = MessageReceipt.ERROR;
|
|
4070
5048
|
} else if (item.getReadAt() || nextItemIsRead) messageState = MessageReceipt.READ;
|
|
4071
5049
|
else if (item.getDeliveredAt() || nextItemIsDelivered)
|
|
@@ -4220,23 +5198,63 @@ export const CometChatMessageList = memo(
|
|
|
4220
5198
|
sentIconStyle: _style.receiptStyles.sentIconStyle,
|
|
4221
5199
|
readIconStyle: _style.receiptStyles.readIconStyle,
|
|
4222
5200
|
waitIconStyle: _style.receiptStyles.waitIconStyle,
|
|
4223
|
-
errorIconStyle:
|
|
5201
|
+
errorIconStyle:
|
|
5202
|
+
offlineReceipt === "error" && mergedTheme.messageListStyles?.offlineStyles?.failedIconStyle
|
|
5203
|
+
? { ..._style.receiptStyles.errorIconStyle, ...mergedTheme.messageListStyles.offlineStyles.failedIconStyle }
|
|
5204
|
+
: _style.receiptStyles.errorIconStyle,
|
|
4224
5205
|
deliveredIconStyle: _style.receiptStyles.deliveredIconStyle,
|
|
4225
5206
|
}}
|
|
4226
5207
|
/>
|
|
4227
5208
|
);
|
|
5209
|
+
// Offline rows are announced, not shown by icon colour alone (UIK-A11Y-01).
|
|
5210
|
+
if (offlineReceipt === "wait") {
|
|
5211
|
+
return (
|
|
5212
|
+
<View
|
|
5213
|
+
style={staticStyles.receiptContainer}
|
|
5214
|
+
accessible={true}
|
|
5215
|
+
accessibilityLabel={t(OFFLINE_STRING_KEYS.notSentYet)}
|
|
5216
|
+
>
|
|
5217
|
+
{receiptEl}
|
|
5218
|
+
<Text
|
|
5219
|
+
testID="cc.message.status.not-sent-yet"
|
|
5220
|
+
style={[
|
|
5221
|
+
_style.dateStyles.textStyle,
|
|
5222
|
+
{ textTransform: "none", marginLeft: 4 },
|
|
5223
|
+
mergedTheme.messageListStyles?.offlineStyles?.notSentYetTextStyle,
|
|
5224
|
+
]}
|
|
5225
|
+
>
|
|
5226
|
+
{t(OFFLINE_STRING_KEYS.notSentYet)}
|
|
5227
|
+
</Text>
|
|
5228
|
+
</View>
|
|
5229
|
+
);
|
|
5230
|
+
}
|
|
4228
5231
|
// A first/middle failed/blocked batch member shows JUST the error icon (no
|
|
4229
5232
|
// timestamp, no Retry label) so the group collapse never hides the failure.
|
|
4230
5233
|
if (messageState === MessageReceipt.ERROR && _isCollapsibleBatchMember) {
|
|
4231
5234
|
return <View testID="batch-error-icon" style={staticStyles.receiptContainer}>{receiptEl}</View>;
|
|
4232
5235
|
}
|
|
4233
5236
|
// §12.1 — a failed send becomes a tappable "Retry" (re-sends this message).
|
|
4234
|
-
|
|
5237
|
+
// D1: only for a row the server never accepted and moderation did not reject;
|
|
5238
|
+
// those keep the error icon with no Retry.
|
|
5239
|
+
// Offline rows: every failed row offers Retry, whatever its reason (R162). Otherwise
|
|
5240
|
+
// only a category the kit can re-send (text, media, custom): an interactive message
|
|
5241
|
+
// has no resend path here, so it keeps the error icon with no Retry that does nothing.
|
|
5242
|
+
return messageState === MessageReceipt.ERROR &&
|
|
5243
|
+
isRetryableFailedRow(item, getModerationStatus(item)) &&
|
|
5244
|
+
(offlineReceipt === null ? resendKindOf(item) !== null : canRetryUnsent(item)) ? (
|
|
4235
5245
|
<TouchableOpacity
|
|
4236
|
-
style={[
|
|
4237
|
-
|
|
5246
|
+
style={[
|
|
5247
|
+
staticStyles.receiptContainer,
|
|
5248
|
+
staticStyles.receiptRow,
|
|
5249
|
+
offlineReceipt === "error" ? mergedTheme.messageListStyles?.offlineStyles?.failedRowStyle : null,
|
|
5250
|
+
]}
|
|
5251
|
+
onPress={() => onRetryPress(item)}
|
|
4238
5252
|
accessibilityRole="button"
|
|
4239
|
-
accessibilityLabel={
|
|
5253
|
+
accessibilityLabel={
|
|
5254
|
+
offlineReceipt === "error"
|
|
5255
|
+
? t(OFFLINE_STRING_KEYS.notSentTapToRetry)
|
|
5256
|
+
: t("RETRY") ?? "Retry"
|
|
5257
|
+
}
|
|
4240
5258
|
hitSlop={{ top: 6, bottom: 6, left: 6, right: 6 }}
|
|
4241
5259
|
>
|
|
4242
5260
|
{receiptEl}
|
|
@@ -4244,9 +5262,10 @@ export const CometChatMessageList = memo(
|
|
|
4244
5262
|
style={[
|
|
4245
5263
|
_style.dateStyles.textStyle,
|
|
4246
5264
|
{ textTransform: "none", marginLeft: 4, color: mergedTheme.color.error },
|
|
5265
|
+
offlineReceipt === "error" ? mergedTheme.messageListStyles?.offlineStyles?.retryTextStyle : null,
|
|
4247
5266
|
]}
|
|
4248
5267
|
>
|
|
4249
|
-
{t("RETRY") ?? "Retry"}
|
|
5268
|
+
{offlineReceipt === "error" ? t(OFFLINE_STRING_KEYS.notSentTapToRetry) : t("RETRY") ?? "Retry"}
|
|
4250
5269
|
</Text>
|
|
4251
5270
|
</TouchableOpacity>
|
|
4252
5271
|
) : (
|
|
@@ -4306,28 +5325,20 @@ export const CometChatMessageList = memo(
|
|
|
4306
5325
|
[getBatchImageVideoItems]
|
|
4307
5326
|
);
|
|
4308
5327
|
|
|
4309
|
-
// §12.1 — retry a FAILED outgoing
|
|
4310
|
-
// Clears the error
|
|
4311
|
-
// re-emits ccMessageSent inprogress→success/error;
|
|
5328
|
+
// §12.1 / D1 — retry a FAILED outgoing message (text, custom or media, e.g. one member of a
|
|
5329
|
+
// partial batch) that the server never accepted. Clears the error marks, then re-sends via
|
|
5330
|
+
// the canonical CometChatUIKit path which re-emits ccMessageSent inprogress→success/error;
|
|
5331
|
+
// this list reconciles by muid in place. Moderation-disapproved rows are never re-sent.
|
|
4312
5332
|
const resendMediaMessage = useCallback((message: CometChat.BaseMessage) => {
|
|
4313
|
-
|
|
4314
|
-
|
|
4315
|
-
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
(
|
|
4319
|
-
}
|
|
4320
|
-
|
|
4321
|
-
|
|
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
|
-
}
|
|
5333
|
+
resendFailedMessage(
|
|
5334
|
+
message,
|
|
5335
|
+
{
|
|
5336
|
+
sendText: (m) => CometChatUIKit.sendTextMessage(m),
|
|
5337
|
+
sendMedia: (m) => CometChatUIKit.sendMediaMessage(m),
|
|
5338
|
+
sendCustom: (m) => CometChatUIKit.sendCustomMessage(m),
|
|
5339
|
+
},
|
|
5340
|
+
getModerationStatus(message)
|
|
5341
|
+
);
|
|
4331
5342
|
}, []);
|
|
4332
5343
|
|
|
4333
5344
|
const reactToMessage = (emoji: string, messageObj?: CometChat.BaseMessage) => {
|
|
@@ -4338,6 +5349,11 @@ export const CometChatMessageList = memo(
|
|
|
4338
5349
|
msgObj.getId = () => originalMessage.getId();
|
|
4339
5350
|
}
|
|
4340
5351
|
|
|
5352
|
+
// The untouched copy a failed write rolls back to (UIK-MUT-01). The optimistic update below
|
|
5353
|
+
// mutates msgObj's own reaction objects, so rolling back to msgObj left the change on screen.
|
|
5354
|
+
const rollbackMessage = CommonUtils.clone(msgObj);
|
|
5355
|
+
// Offline ON (gate read once): a failed write also shows today's error notice (ENG-41199).
|
|
5356
|
+
const offlineOn = isOfflineOn();
|
|
4341
5357
|
const messageId = msgObj?.getId();
|
|
4342
5358
|
const reactions = msgObj?.getReactions() || [];
|
|
4343
5359
|
const emojiObject = reactions?.find((reaction: any) => {
|
|
@@ -4372,9 +5388,11 @@ export const CometChatMessageList = memo(
|
|
|
4372
5388
|
.then((message: any) => { })
|
|
4373
5389
|
.catch((error: any) => {
|
|
4374
5390
|
CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageEdited, {
|
|
4375
|
-
message:
|
|
5391
|
+
message: rollbackMessage,
|
|
4376
5392
|
status: messageStatus.success,
|
|
4377
5393
|
});
|
|
5394
|
+
const errorText = offlineMutationErrorText(offlineOn, t);
|
|
5395
|
+
if (errorText) showToast(errorText);
|
|
4378
5396
|
});
|
|
4379
5397
|
} else {
|
|
4380
5398
|
const updatedReactions: any[] = [];
|
|
@@ -4409,9 +5427,11 @@ export const CometChatMessageList = memo(
|
|
|
4409
5427
|
.then((response: any) => { })
|
|
4410
5428
|
.catch((error: any) => {
|
|
4411
5429
|
CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageEdited, {
|
|
4412
|
-
message:
|
|
5430
|
+
message: rollbackMessage,
|
|
4413
5431
|
status: messageStatus.success,
|
|
4414
5432
|
});
|
|
5433
|
+
const errorText = offlineMutationErrorText(offlineOn, t);
|
|
5434
|
+
if (errorText) showToast(errorText);
|
|
4415
5435
|
});
|
|
4416
5436
|
}
|
|
4417
5437
|
|
|
@@ -4591,9 +5611,26 @@ export const CometChatMessageList = memo(
|
|
|
4591
5611
|
// Tokens become names; typed token text (stored escaped) reads as typed.
|
|
4592
5612
|
let textMessage = unescapeTypedMentionTokens(getPlainString(strippedText, messageObject));
|
|
4593
5613
|
let fileUrl = messageObject.getData()["url"];
|
|
5614
|
+
// Offline ON: share the saved file, never re-fetch the URL (BEH-MEDIA-18). The saved file has
|
|
5615
|
+
// no extension, so it is named after the attachment.
|
|
5616
|
+
let localMediaName = "";
|
|
5617
|
+
if (messageObject["type"] !== "text" && fileUrl) {
|
|
5618
|
+
const attachment = messageObject?.getAttachment?.();
|
|
5619
|
+
const source = attachment ? mediaActionSource(attachment) : null;
|
|
5620
|
+
if (source?.kind === "unavailable") {
|
|
5621
|
+
setShowMessageOptions([]);
|
|
5622
|
+
notifyMediaUnavailable();
|
|
5623
|
+
return;
|
|
5624
|
+
}
|
|
5625
|
+
if (source?.kind === "local") {
|
|
5626
|
+
fileUrl = source.uri;
|
|
5627
|
+
localMediaName = attachment?.getName?.() ?? "";
|
|
5628
|
+
}
|
|
5629
|
+
}
|
|
4594
5630
|
|
|
4595
5631
|
const getFileName = () => {
|
|
4596
5632
|
if (!fileUrl) return "";
|
|
5633
|
+
if (localMediaName) return localMediaName;
|
|
4597
5634
|
return fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length).replace(" ", "_");
|
|
4598
5635
|
};
|
|
4599
5636
|
|
|
@@ -4907,6 +5944,8 @@ export const CometChatMessageList = memo(
|
|
|
4907
5944
|
if (message.getDeletedBy() != null) return;
|
|
4908
5945
|
|
|
4909
5946
|
if (!message.getId()) {
|
|
5947
|
+
// Offline: an unsent row offers Retry and Delete (R162).
|
|
5948
|
+
if (offlineReceiptOf(message) !== null) openUnsentMessageOptions(message);
|
|
4910
5949
|
return;
|
|
4911
5950
|
}
|
|
4912
5951
|
// console.log({hasTemplate});
|
|
@@ -5157,8 +6196,9 @@ export const CometChatMessageList = memo(
|
|
|
5157
6196
|
lastMessageDate.current = getSentAtTimestamp(item);
|
|
5158
6197
|
const id = typeof item?.getId === 'function' ? item.getId() : (item as any)?.id;
|
|
5159
6198
|
const muid = typeof item?.getMuid === 'function' ? item.getMuid() : (item as any)?.muid;
|
|
6199
|
+
// Offline: an own message keeps one key from compose to ack (no remount); else today's.
|
|
5160
6200
|
return (
|
|
5161
|
-
<React.Fragment key={`${id}_${muid}`}>
|
|
6201
|
+
<React.Fragment key={offlineRenderKey(item, loggedInUser.current?.getUid?.()) ?? `${id}_${muid}`}>
|
|
5162
6202
|
<MessageView message={item} currentIndex={index} />
|
|
5163
6203
|
</React.Fragment>
|
|
5164
6204
|
);
|
|
@@ -5172,6 +6212,10 @@ export const CometChatMessageList = memo(
|
|
|
5172
6212
|
const muid = typeof item?.getMuid === 'function' ? item.getMuid() : item?.muid;
|
|
5173
6213
|
|
|
5174
6214
|
|
|
6215
|
+
// Offline: an own message the SDK handled keeps one key from compose to ack.
|
|
6216
|
+
const offlineKey = offlineRenderKey(item, loggedInUser.current?.getUid?.());
|
|
6217
|
+
if (offlineKey) return offlineKey;
|
|
6218
|
+
|
|
5175
6219
|
// For stream messages in agentic mode, use a unique combination
|
|
5176
6220
|
// to prevent duplicate keys when navigating between chat and history
|
|
5177
6221
|
if (item?.isStreamMessage) {
|
|
@@ -5409,6 +6453,18 @@ export const CometChatMessageList = memo(
|
|
|
5409
6453
|
const getErrorStateView = useCallback(() => {
|
|
5410
6454
|
if (hideError) return null;
|
|
5411
6455
|
if (ErrorView) return ErrorView();
|
|
6456
|
+
if (offlineMiss) {
|
|
6457
|
+
// D84 rule 3: offline with nothing saved: the offline state, no Retry.
|
|
6458
|
+
return (
|
|
6459
|
+
<ConnectStateView
|
|
6460
|
+
testID={CONTRACT_IDS.emptyConnectToLoad}
|
|
6461
|
+
title={t(OFFLINE_STRING_KEYS.connectToLoadMessages)}
|
|
6462
|
+
containerStyle={mergedTheme.messageListStyles.errorStateStyle?.containerStyle}
|
|
6463
|
+
titleStyle={mergedTheme.messageListStyles.errorStateStyle?.titleStyle}
|
|
6464
|
+
subtitleStyle={mergedTheme.messageListStyles.errorStateStyle?.subtitleStyle}
|
|
6465
|
+
/>
|
|
6466
|
+
);
|
|
6467
|
+
}
|
|
5412
6468
|
return (
|
|
5413
6469
|
<ErrorEmptyView
|
|
5414
6470
|
title={t("OOPS")}
|
|
@@ -5430,7 +6486,7 @@ export const CometChatMessageList = memo(
|
|
|
5430
6486
|
subTitleStyle={mergedTheme.messageListStyles.errorStateStyle?.subtitleStyle}
|
|
5431
6487
|
/>
|
|
5432
6488
|
);
|
|
5433
|
-
}, [mergedTheme]);
|
|
6489
|
+
}, [mergedTheme, offlineMiss]);
|
|
5434
6490
|
|
|
5435
6491
|
const getLoadingStateView = useCallback(() => {
|
|
5436
6492
|
if (LoadingView) return LoadingView();
|
|
@@ -5443,14 +6499,23 @@ export const CometChatMessageList = memo(
|
|
|
5443
6499
|
}, []);
|
|
5444
6500
|
|
|
5445
6501
|
const fetchNextMessages = async () => {
|
|
6502
|
+
if (positioningRef.current) {
|
|
6503
|
+
deferredPagingRef.current.newer = true;
|
|
6504
|
+
return;
|
|
6505
|
+
}
|
|
5446
6506
|
if (loadingMessagesRef.current || !hasTargetMessageId) return;
|
|
5447
6507
|
|
|
5448
6508
|
if (messagesContentListRef.current.length === 0) return;
|
|
5449
6509
|
|
|
5450
6510
|
const newestMessage = messagesContentListRef.current[0];
|
|
5451
|
-
const
|
|
6511
|
+
const offlineRead = isOfflineOn(); // gate read once for this read
|
|
6512
|
+
// Offline: anchor on the newest row WITH a server id (an unsent row has none, UIK-READ-06).
|
|
6513
|
+
const newestMessageId = offlineRead
|
|
6514
|
+
? newestServerId(messagesContentListRef.current) || newestMessage.getId()
|
|
6515
|
+
: newestMessage.getId();
|
|
5452
6516
|
setBottomLoading(true);
|
|
5453
6517
|
loadingMessagesRef.current = true;
|
|
6518
|
+
const readGen = jumpGenRef.current; // a jump during the read drops its answer
|
|
5454
6519
|
|
|
5455
6520
|
try {
|
|
5456
6521
|
// Filtered like the main list (see getMessagesAroundId): scrolling down after a jump
|
|
@@ -5480,7 +6545,53 @@ export const CometChatMessageList = memo(
|
|
|
5480
6545
|
}
|
|
5481
6546
|
}
|
|
5482
6547
|
|
|
6548
|
+
if (offlineRead) {
|
|
6549
|
+
offlinePathUsedRef.current = true;
|
|
6550
|
+
newerReadSeqRef.current++;
|
|
6551
|
+
const opGen = listOpGenRef.current;
|
|
6552
|
+
let cachedKeys = new Set<string>();
|
|
6553
|
+
let paintedKeys: string[] = [];
|
|
6554
|
+
await fetchTwoPhase<any>(
|
|
6555
|
+
nextMessagesRequest.build(),
|
|
6556
|
+
"next",
|
|
6557
|
+
{
|
|
6558
|
+
onCached: (page) => {
|
|
6559
|
+
cachedKeys = cachedKeysOf(page);
|
|
6560
|
+
const listed = cachedKeysOf(messagesContentListRef.current);
|
|
6561
|
+
paintedKeys = [...cachedKeys].filter((key) => !listed.has(key));
|
|
6562
|
+
applyOfflineResult(upsertSortedDesc(messagesContentListRef.current, page));
|
|
6563
|
+
},
|
|
6564
|
+
onServer: (page) => {
|
|
6565
|
+
applyOfflineResult(
|
|
6566
|
+
dropUnjoinedCachedPageDesc(
|
|
6567
|
+
reconcileServerPageDesc(messagesContentListRef.current, cachedKeys, page),
|
|
6568
|
+
paintedKeys,
|
|
6569
|
+
[...cachedKeys],
|
|
6570
|
+
page,
|
|
6571
|
+
"next"
|
|
6572
|
+
)
|
|
6573
|
+
);
|
|
6574
|
+
// Only an empty online page says the newest end is reached.
|
|
6575
|
+
if (page.length === 0) setHasTargetMessageId(false);
|
|
6576
|
+
setOfflineNewerBlocked(false);
|
|
6577
|
+
},
|
|
6578
|
+
onError: (error, failedOffline) => {
|
|
6579
|
+
if (failedOffline || sdkConnected() === false) {
|
|
6580
|
+
// D84 rule 2 and 9: not connected keeps the rows with "Connect to load more" at the
|
|
6581
|
+
// newer edge (no onError); the page loads by itself when the connection is back.
|
|
6582
|
+
setOfflineNewerBlocked(true);
|
|
6583
|
+
return;
|
|
6584
|
+
}
|
|
6585
|
+
// D84 rule 5: a real error is reported once (the user's scroll started the read).
|
|
6586
|
+
onError && onError(error as CometChat.CometChatException);
|
|
6587
|
+
},
|
|
6588
|
+
},
|
|
6589
|
+
() => opGen !== listOpGenRef.current
|
|
6590
|
+
);
|
|
6591
|
+
return;
|
|
6592
|
+
}
|
|
5483
6593
|
const nextMessages = await nextMessagesRequest.build().fetchNext();
|
|
6594
|
+
if (readGen !== jumpGenRef.current) return;
|
|
5484
6595
|
if (nextMessages.length > 0) {
|
|
5485
6596
|
|
|
5486
6597
|
const existingIds = new Set(messagesContentListRef.current.map(m => m.getId()));
|
|
@@ -5502,11 +6613,18 @@ export const CometChatMessageList = memo(
|
|
|
5502
6613
|
} catch (error) {
|
|
5503
6614
|
console.error('[fetchNextMessages] Error:', error);
|
|
5504
6615
|
} finally {
|
|
5505
|
-
|
|
5506
|
-
|
|
6616
|
+
// After a jump the flags belong to the jump (and any read it let start).
|
|
6617
|
+
if (readGen === jumpGenRef.current) {
|
|
6618
|
+
setBottomLoading(false);
|
|
6619
|
+
loadingMessagesRef.current = false;
|
|
6620
|
+
}
|
|
5507
6621
|
}
|
|
5508
6622
|
};
|
|
5509
6623
|
|
|
6624
|
+
// The latest paging functions, for a page deferred while the list was being positioned.
|
|
6625
|
+
pagingFnsRef.current = { older: getPreviousMessages, newer: fetchNextMessages };
|
|
6626
|
+
fetchNextMessagesRef.current = fetchNextMessages;
|
|
6627
|
+
|
|
5510
6628
|
const renderFooter = () => {
|
|
5511
6629
|
if (!bottomLoading) return null;
|
|
5512
6630
|
return (
|
|
@@ -5539,6 +6657,7 @@ export const CometChatMessageList = memo(
|
|
|
5539
6657
|
|
|
5540
6658
|
const nearBottom = isNearBottom();
|
|
5541
6659
|
setHideScrollToBottomButton(nearBottom);
|
|
6660
|
+
retryOlderOnScroll();
|
|
5542
6661
|
|
|
5543
6662
|
if (nearBottom && temporaryMessageListRef.current.length > 0) {
|
|
5544
6663
|
// Merge temporary messages when scrolling near bottom
|
|
@@ -5710,6 +6829,18 @@ export const CometChatMessageList = memo(
|
|
|
5710
6829
|
|
|
5711
6830
|
|
|
5712
6831
|
// Optimized FlatList renderItem using memoized component
|
|
6832
|
+
// Dev and sample builds only: the row list of every committed frame (TEST-PLAN §3.3).
|
|
6833
|
+
useEffect(() => {
|
|
6834
|
+
probeFrame("messages", () =>
|
|
6835
|
+
messagesList.map((item: any, index: number) => ({
|
|
6836
|
+
key: keyExtractor(item, index),
|
|
6837
|
+
id: serverIdOf(item),
|
|
6838
|
+
state: contractRowState(item),
|
|
6839
|
+
item,
|
|
6840
|
+
}))
|
|
6841
|
+
);
|
|
6842
|
+
}, [messagesList, keyExtractor]);
|
|
6843
|
+
|
|
5713
6844
|
const memoizedRenderItem = useCallback(
|
|
5714
6845
|
({ item, index }: any) => {
|
|
5715
6846
|
const nextItem = messagesContentListRef.current[index + 1];
|
|
@@ -5740,7 +6871,7 @@ export const CometChatMessageList = memo(
|
|
|
5740
6871
|
const showNewMessageIndicator = !isAgenticUser && (startFromUnreadMessages || showMarkAsUnreadOption || navigatedFromSearch) && newMessageIndicatorId === String(item.getId());
|
|
5741
6872
|
|
|
5742
6873
|
return (
|
|
5743
|
-
<View>
|
|
6874
|
+
<View {...messageRowContractProps(keyExtractor(item, index), item)}>
|
|
5744
6875
|
<MessageListItem
|
|
5745
6876
|
item={item}
|
|
5746
6877
|
index={index}
|
|
@@ -5783,7 +6914,8 @@ export const CometChatMessageList = memo(
|
|
|
5783
6914
|
startFromUnreadMessages,
|
|
5784
6915
|
showMarkAsUnreadOption,
|
|
5785
6916
|
navigatedFromSearch,
|
|
5786
|
-
isAgenticUser
|
|
6917
|
+
isAgenticUser,
|
|
6918
|
+
keyExtractor
|
|
5787
6919
|
]
|
|
5788
6920
|
);
|
|
5789
6921
|
|
|
@@ -5804,7 +6936,21 @@ export const CometChatMessageList = memo(
|
|
|
5804
6936
|
getErrorStateView()
|
|
5805
6937
|
) : (
|
|
5806
6938
|
messagesList.length == 0 ? (
|
|
5807
|
-
|
|
6939
|
+
offlineFooter === "connect" ? (
|
|
6940
|
+
// Offline ON, a chat never cached: nothing invented, and a way to try again (P6).
|
|
6941
|
+
<View style={staticStyles.listContainer}>
|
|
6942
|
+
<View style={{ flex: 1 }}>{getEmptyStateView()}</View>
|
|
6943
|
+
<ConnectToLoadMore
|
|
6944
|
+
t={t}
|
|
6945
|
+
onRetry={retryOfflineOlderPage}
|
|
6946
|
+
textColor={mergedTheme.color.textSecondary as string}
|
|
6947
|
+
containerStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.containerStyle}
|
|
6948
|
+
textStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.textStyle}
|
|
6949
|
+
/>
|
|
6950
|
+
</View>
|
|
6951
|
+
) : (
|
|
6952
|
+
getEmptyStateView()
|
|
6953
|
+
)
|
|
5808
6954
|
) : (
|
|
5809
6955
|
<View style={staticStyles.listContainer}>
|
|
5810
6956
|
{HeaderView && (
|
|
@@ -5833,6 +6979,7 @@ export const CometChatMessageList = memo(
|
|
|
5833
6979
|
showsVerticalScrollIndicator={false}
|
|
5834
6980
|
ref={messageListRef}
|
|
5835
6981
|
onMomentumScrollEnd={handleScrollInternal}
|
|
6982
|
+
onScrollBeginDrag={handleScrollInternal}
|
|
5836
6983
|
onScroll={handleScrollInternal}
|
|
5837
6984
|
inverted={true}
|
|
5838
6985
|
maintainVisibleContentPosition={{
|
|
@@ -5848,7 +6995,31 @@ export const CometChatMessageList = memo(
|
|
|
5848
6995
|
extraData={themeMode}
|
|
5849
6996
|
keyExtractor={keyExtractor}
|
|
5850
6997
|
renderItem={memoizedRenderItem}
|
|
5851
|
-
ListHeaderComponent={
|
|
6998
|
+
ListHeaderComponent={
|
|
6999
|
+
offlineNewerBlocked && !bottomLoading
|
|
7000
|
+
? () => (
|
|
7001
|
+
// Inverted list: the header sits at the newer end.
|
|
7002
|
+
<ConnectToLoadMore
|
|
7003
|
+
t={t}
|
|
7004
|
+
onRetry={retryOfflineNewerPage}
|
|
7005
|
+
textColor={mergedTheme.color.textSecondary as string}
|
|
7006
|
+
containerStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.containerStyle}
|
|
7007
|
+
textStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.textStyle}
|
|
7008
|
+
/>
|
|
7009
|
+
)
|
|
7010
|
+
: renderFooter
|
|
7011
|
+
}
|
|
7012
|
+
ListFooterComponent={
|
|
7013
|
+
offlineFooter === "connect" ? (
|
|
7014
|
+
<ConnectToLoadMore
|
|
7015
|
+
t={t}
|
|
7016
|
+
onRetry={retryOfflineOlderPage}
|
|
7017
|
+
textColor={mergedTheme.color.textSecondary as string}
|
|
7018
|
+
containerStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.containerStyle}
|
|
7019
|
+
textStyle={mergedTheme.messageListStyles?.offlineStyles?.footerStyle?.textStyle}
|
|
7020
|
+
/>
|
|
7021
|
+
) : undefined
|
|
7022
|
+
}
|
|
5852
7023
|
onScrollToIndexFailed={handleScrollToIndexFailed}
|
|
5853
7024
|
viewabilityConfig={viewabilityConfig}
|
|
5854
7025
|
onViewableItemsChanged={handleViewableItemsChanged}
|
|
@@ -5901,6 +7072,17 @@ export const CometChatMessageList = memo(
|
|
|
5901
7072
|
)
|
|
5902
7073
|
)}
|
|
5903
7074
|
|
|
7075
|
+
{offlineNotice && !hideOfflineNotices ? (
|
|
7076
|
+
<OfflineNoticeView
|
|
7077
|
+
notice={offlineNotice}
|
|
7078
|
+
t={t}
|
|
7079
|
+
onDismiss={dismissOfflineNotice}
|
|
7080
|
+
containerStyle={mergedTheme.messageListStyles?.offlineStyles?.noticeStyle?.containerStyle}
|
|
7081
|
+
textStyle={mergedTheme.messageListStyles?.offlineStyles?.noticeStyle?.textStyle}
|
|
7082
|
+
actionTextStyle={mergedTheme.messageListStyles?.offlineStyles?.noticeStyle?.actionTextStyle}
|
|
7083
|
+
/>
|
|
7084
|
+
) : null}
|
|
7085
|
+
|
|
5904
7086
|
{!hideScrollToBottomButton && (
|
|
5905
7087
|
<Pressable
|
|
5906
7088
|
onPress={newMsgIndicatorPressed}
|
|
@@ -5965,7 +7147,8 @@ export const CometChatMessageList = memo(
|
|
|
5965
7147
|
messageInfo={messageInfo}
|
|
5966
7148
|
infoObject={infoObject}
|
|
5967
7149
|
selectedMessage={selectedMessage}
|
|
5968
|
-
|
|
7150
|
+
// Offline: an unsent row cannot be reacted to (it has no server id; R162 offers Retry and Delete only).
|
|
7151
|
+
hideReactionOption={hideReactionOption || (selectedMessage != null && offlineReceiptOf(selectedMessage) !== null)}
|
|
5969
7152
|
quickReactionList={quickReactionList as [string, string?, string?, string?, string?]}
|
|
5970
7153
|
templatesMap={templatesMap}
|
|
5971
7154
|
mergedTheme={mergedTheme}
|