@cometchat/chat-uikit-react-native 5.3.5 → 5.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +18 -1
  2. package/ios/FileManager.m +14 -3
  3. package/ios/SoundPlayer.m +24 -1
  4. package/package.json +2 -1
  5. package/src/CometChatAIAssistantChatHistory/CometChatAIAssistantChatHistory.tsx +8 -3
  6. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +14 -11
  7. package/src/CometChatConversations/CometChatConversations.tsx +89 -51
  8. package/src/CometChatGroupMembers/CometChatGroupMembers.tsx +10 -11
  9. package/src/CometChatGroups/CometChatGroups.tsx +49 -42
  10. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +10 -7
  11. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +12 -10
  12. package/src/CometChatMessageInformation/CometChatMessageInformation.tsx +4 -3
  13. package/src/CometChatMessageList/CometChatMessageList.tsx +398 -144
  14. package/src/CometChatMessageList/PERFORMANCE_ARCHITECTURE.md +478 -0
  15. package/src/CometChatMessageList/SEARCH_NAV_PERF_PLAN.md +613 -0
  16. package/src/CometChatMessageList/components/MessageOptionsSheet.tsx +4 -1
  17. package/src/CometChatNotificationFeed/CometChatNotificationFeed.tsx +811 -0
  18. package/src/CometChatNotificationFeed/Skeleton.tsx +43 -0
  19. package/src/CometChatNotificationFeed/index.ts +19 -0
  20. package/src/CometChatNotificationFeed/style.ts +333 -0
  21. package/src/CometChatNotificationFeed/utils.ts +124 -0
  22. package/src/CometChatSearch/CometChatSearch.tsx +8 -6
  23. package/src/CometChatThreadHeader/CometChatThreadHeader.tsx +4 -3
  24. package/src/CometChatUsers/CometChatUsers.tsx +56 -43
  25. package/src/calls/CallingExtensionDecorator.tsx +1 -1
  26. package/src/calls/CometChatCallButtons/CometChatCallButtons.tsx +3 -2
  27. package/src/calls/CometChatCallLogs/CometChatCallLogs.tsx +7 -6
  28. package/src/calls/CometChatIncomingCall/CometChatIncomingCall.tsx +2 -1
  29. package/src/calls/CometChatOutgoingCall/CometChatOutgoingCall.tsx +2 -1
  30. package/src/extensions/CollaborativeDocument/CollaborativeDocumentExtensionDecorator.tsx +4 -4
  31. package/src/extensions/CollaborativeWhiteboard/CollaborativeWhiteboardExtensionDecorator.tsx +5 -3
  32. package/src/extensions/LinkPreview/LinkPreviewExtensionDecorator.tsx +1 -1
  33. package/src/extensions/MessageTranslation/MessageTranslationDecorator.tsx +5 -5
  34. package/src/extensions/Polls/PollsBubble.tsx +1 -1
  35. package/src/extensions/Polls/PollsDecorator.tsx +1 -1
  36. package/src/extensions/Stickers/StickersExtensionDecorator.tsx +2 -2
  37. package/src/extensions/ThumbnailGeneration/ThumbnailGenerationDecorator.tsx +9 -5
  38. package/src/index.ts +7 -0
  39. package/src/shared/CometChatUiKit/CometChatUIKit.ts +48 -20
  40. package/src/shared/events/ListenerInitializer.ts +2 -1
  41. package/src/shared/framework/MessageDataSource.tsx +19 -15
  42. package/src/shared/helper/helperFunctions.ts +5 -4
  43. package/src/shared/icons/components/notification-empty.tsx +27 -0
  44. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +8 -1
  45. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +8 -1
  46. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +8 -1
  47. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +8 -1
  48. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +8 -1
  49. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +8 -1
  50. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +8 -1
  51. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +8 -1
  52. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +8 -1
  53. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +8 -1
  54. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +8 -1
  55. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +8 -1
  56. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +8 -1
  57. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +8 -1
  58. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +8 -1
  59. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +8 -1
  60. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +8 -1
  61. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +8 -1
  62. package/src/shared/services/stream-message.service.ts +0 -1
  63. package/src/shared/utils/CommonUtils.ts +1 -1
  64. package/src/shared/utils/MessageUtils.tsx +15 -13
  65. package/src/shared/utils/conversationUtils.ts +2 -2
  66. package/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +2 -2
  67. package/src/shared/views/CometChatImageBubble/CometChatImageLoader.tsx +17 -5
  68. package/src/shared/views/CometChatList/CometChatList.tsx +11 -15
  69. package/src/shared/views/CometChatReactionList/CometChatReactionList.tsx +3 -3
  70. package/src/shared/views/CometChatReactions/CometChatReactions.tsx +2 -1
  71. package/src/shared/views/CometChatStreamMessageBubble/CometChatStreamMessageBubble.tsx +15 -4
  72. package/src/shared/views/CometChatSuggestionList/CometChatSuggestionList.tsx +3 -3
  73. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +15 -1
  74. package/src/theme/default/default.ts +6 -0
  75. package/src/theme/provider.tsx +12 -12
  76. package/src/theme/type.ts +2 -0
@@ -0,0 +1,613 @@
1
+ # Search Navigation Performance — Architecture Plan (v3 — Optimized)
2
+
3
+ **File:** `CometChatMessageList.tsx`
4
+ **Ticket:** Search → "Go to Message" is slow
5
+ **Constraint:** Zero public API / prop changes. All existing props remain identical.
6
+
7
+ ---
8
+
9
+ ## Theoretical Minimum Latency
10
+
11
+ ```
12
+ T=0 User taps search result
13
+ T=10ms Network round trip starts (parallel fetchPrev + fetchNext)
14
+ T=~300ms Server responds (typical 4G)
15
+ T=305ms Response parsed
16
+ T=310ms setMessagesList committed
17
+ T=326ms React + FlatList render (1 frame, ~16ms)
18
+ T=342ms scrollToIndex called (useEffect + rAF)
19
+ T=358ms FlatList viewport commit (1 frame)
20
+ T=358ms highlightMessage applied (same frame as commit)
21
+ ─────────────────────────────────
22
+ Floor: ~360ms (network-bound)
23
+ Current: 1500–3000ms (CPU + retry-bound)
24
+
25
+ Speedup: 5–8x
26
+ ```
27
+
28
+ The plan below hits the floor.
29
+
30
+ ---
31
+
32
+ ## 1. Current Flow (Bottlenecks)
33
+
34
+ ```
35
+ User taps → CometChatMessageList mounts → getMessagesAroundId(messageId)
36
+ [Sequential] CometChat.getMessageDetails() ← redundant call
37
+ [Sequential] fetchNext(limit: 15) ← waits for above
38
+ setMessagesList(16 msgs) → render
39
+ setScrollTargetId(messageId) → useEffect fires
40
+ scrollToMessage:
41
+ itemPositions.get() → undefined
42
+ setTimeout 100, 200, 300, 400, 500ms (5 retries) ← up to 1.5s polling
43
+ fallback scrollToIndex → onScrollToIndexFailed → 300ms more
44
+ Meanwhile:
45
+ 16 onLayout events → 16 setItemPositions state updates → 16 re-renders
46
+ onEndReached fires (16 msgs don't fill screen)
47
+ → getPreviousMessages(30) → setMessagesList → 30 more state updates
48
+ → onEndReached AGAIN → cycle repeats 2-3 times
49
+ ```
50
+
51
+ **Bottlenecks:**
52
+ 1. 3+ sequential network calls
53
+ 2. State-triggered re-render storm from `setItemPositions`
54
+ 3. 1.5s polling retry loop in `scrollToMessage`
55
+ 4. `onEndReached` cascade from underfilled viewport
56
+ 5. No `getItemLayout` → `scrollToIndex` cannot work without prior render
57
+
58
+ ---
59
+
60
+ ## 2. Root Causes (Mapped to Fixes)
61
+
62
+ | # | Root Cause | Fix |
63
+ |---|---|---|
64
+ | RC-1 | No `getItemLayout` → `scrollToIndex` requires items rendered first | Change A |
65
+ | RC-2 | `itemPositions` is state → re-renders on every `onLayout` | Change B |
66
+ | RC-3 | `scrollToMessage` polls for layout data | Change C |
67
+ | RC-4 | `onEndReached` cascade during navigation | Change D |
68
+ | RC-5 | 3 sequential network calls + redundant `getMessageDetails` | Change E |
69
+
70
+ ---
71
+
72
+ ## 3. Optimized Solution
73
+
74
+ ### Change A — Add `getItemLayout` to FlatList
75
+
76
+ **Why:** `getItemLayout` is React Native's documented mechanism for "fixed/estimated row height" lists. It allows `scrollToIndex` to compute the target offset **without rendering items first** — the framework calls `getItemLayout(data, targetIndex)` and uses the returned `offset` directly. This eliminates the entire premise behind the polling loop.
77
+
78
+ **Why estimated height works:** `getItemLayout` only needs to be approximately right. After `scrollToIndex` lands at the estimated offset, FlatList renders the items in the new window. Their actual `onLayout` events update internal layout, and any visual drift self-corrects. The target message will be visible regardless of estimate accuracy.
79
+
80
+ **Why this works with `inverted={true}`:** FlatList handles inversion internally via a `scaleY: -1` transform. `getItemLayout` operates in logical coordinates (data array index 0 = newest message, last index = oldest). The framework flips the visual axis. No special inversion math needed in `getItemLayout`.
81
+
82
+ **Code:**
83
+ ```typescript
84
+ // Add near other useCallback definitions (~line 970)
85
+ const getItemLayout = useCallback((_data: any, index: number) => ({
86
+ length: AVERAGE_ITEM_LENGTH, // 120 — existing constant
87
+ offset: AVERAGE_ITEM_LENGTH * index,
88
+ index,
89
+ }), []);
90
+ ```
91
+
92
+ **FlatList prop:**
93
+ ```tsx
94
+ <FlatList
95
+ ...existing props...
96
+ getItemLayout={getItemLayout}
97
+ />
98
+ ```
99
+
100
+ **Impact:** `scrollToIndex` works on the first call without polling, retries, or `onScrollToIndexFailed`.
101
+
102
+ ---
103
+
104
+ ### Change B — `itemPositions` State → Ref
105
+
106
+ **Why:** `itemPositions` is read **only imperatively** — inside `scrollToMessage` and `handleScrollToIndexFailed`. It is never read during render. Storing it in state causes 16-100 re-renders during navigation as `onLayout` fires for each row. A ref provides identical functionality with zero re-renders.
107
+
108
+ **Code changes:**
109
+
110
+ ```typescript
111
+ // REPLACE (line ~969)
112
+ // const [itemPositions, setItemPositions] = useState<Map<string, { y: number; height: number }>>(new Map());
113
+
114
+ // WITH
115
+ const itemPositionsRef = useRef<Map<string, { y: number; height: number }>>(new Map());
116
+ ```
117
+
118
+ ```typescript
119
+ // REPLACE handleItemLayout (line ~4624)
120
+ // Before: state update + Map allocation per onLayout
121
+ const handleItemLayout = useCallback((event: any, messageId: string) => {
122
+ const { y, height } = event.nativeEvent.layout;
123
+ setItemPositions(prev => {
124
+ const newMap = new Map(prev);
125
+ newMap.set(messageId, { y, height });
126
+ return newMap;
127
+ });
128
+ }, []);
129
+
130
+ // After: pure ref mutation
131
+ const handleItemLayout = useCallback((event: any, messageId: string) => {
132
+ const { y, height } = event.nativeEvent.layout;
133
+ itemPositionsRef.current.set(messageId, { y, height });
134
+ }, []);
135
+ ```
136
+
137
+ ```typescript
138
+ // REPLACE clear effect (line ~4610)
139
+ // Before: clears on every length change > 5
140
+ useEffect(() => {
141
+ const lengthDiff = Math.abs(messagesList.length - prevMessagesLength.current);
142
+ const isSignificantChange = lengthDiff > 5;
143
+ if (isSignificantChange) {
144
+ setItemPositions(new Map());
145
+ }
146
+ prevMessagesLength.current = messagesList.length;
147
+ }, [messagesList.length]);
148
+
149
+ // After: skip clear during navigation (preserves measurements just collected)
150
+ useEffect(() => {
151
+ if (navigationInProgressRef.current) {
152
+ prevMessagesLength.current = messagesList.length;
153
+ return;
154
+ }
155
+ const lengthDiff = Math.abs(messagesList.length - prevMessagesLength.current);
156
+ const isSignificantChange = lengthDiff > 5;
157
+ if (isSignificantChange) {
158
+ itemPositionsRef.current = new Map();
159
+ }
160
+ prevMessagesLength.current = messagesList.length;
161
+ }, [messagesList.length]);
162
+ ```
163
+
164
+ **Update read sites:**
165
+ - `scrollToMessage`: `itemPositions.get(...)` → `itemPositionsRef.current.get(...)`
166
+ - `handleScrollToIndexFailed`: `Array.from(itemPositions.values())` → `Array.from(itemPositionsRef.current.values())`
167
+ - Remove `itemPositions` from `handleScrollToIndexFailed` `useCallback` deps array
168
+
169
+ **Impact:** Eliminates 16–100 re-renders per navigation. `onLayout` becomes effectively free.
170
+
171
+ ---
172
+
173
+ ### Change C — Simplified `scrollToMessage` (No Polling, Loop-Safe)
174
+
175
+ **Why:** With `getItemLayout` (Change A), `scrollToIndex` works synchronously. The 5-retry polling loop is dead code. The new implementation:
176
+ 1. Finds target index in `messagesContentListRef.current` (O(n) — could be O(1) with index map, but list is ≤ 101 items so O(n) is < 1ms)
177
+ 2. Calls `scrollToIndex` once
178
+ 3. Defers highlight + gate-close to next frame via `requestAnimationFrame` (waits for FlatList commit)
179
+ 4. Has a **retry guard** (`triedFetchForRef`) to prevent infinite loop when target message doesn't exist (deleted/missing)
180
+
181
+ **Code:**
182
+
183
+ ```typescript
184
+ // New ref (add near other refs ~line 974)
185
+ const triedFetchForRef = useRef<string | null>(null);
186
+
187
+ // REPLACE scrollToMessage (lines ~1469-1551)
188
+ const scrollToMessage = (messageId: string) => {
189
+ if (!messageListRef.current || messagesContentListRef.current.length === 0) {
190
+ setNavigationLoading(false);
191
+ navigationInProgressRef.current = false;
192
+ return;
193
+ }
194
+
195
+ setNavigationLoading(true);
196
+
197
+ const targetIndex = messagesContentListRef.current.findIndex(
198
+ (msg) => String(msg.getId()) === messageId
199
+ );
200
+
201
+ if (targetIndex === -1) {
202
+ // Message not in current list. Avoid infinite loop:
203
+ // if we already fetched once for this messageId and target still missing,
204
+ // it means the message doesn't exist (deleted/stale).
205
+ if (triedFetchForRef.current === messageId) {
206
+ triedFetchForRef.current = null;
207
+ setListState("error");
208
+ setNavigationLoading(false);
209
+ navigationInProgressRef.current = false;
210
+ return;
211
+ }
212
+ triedFetchForRef.current = messageId;
213
+ setNavigationLoading(false);
214
+ getMessagesAroundId(messageId);
215
+ return;
216
+ }
217
+
218
+ // Found target. Reset retry tracker.
219
+ triedFetchForRef.current = null;
220
+
221
+ // Single scrollToIndex call. getItemLayout makes this work without
222
+ // requiring the target to be already rendered.
223
+ messageListRef.current.scrollToIndex({
224
+ index: targetIndex,
225
+ animated: false, // instant jump — correct UX for "go to message"
226
+ viewPosition: 0.5, // center on viewport
227
+ });
228
+
229
+ // Defer highlight + gate-close to next frame so FlatList commits
230
+ // the new viewport and target row mounts before we apply highlight.
231
+ requestAnimationFrame(() => {
232
+ if (!shouldSuppressHighlightRef.current) {
233
+ highlightMessage(messageId);
234
+ }
235
+ shouldSuppressHighlightRef.current = false;
236
+ setNavigationLoading(false);
237
+ navigationInProgressRef.current = false;
238
+ });
239
+ };
240
+ ```
241
+
242
+ **Why `animated: false`:** Search-to-message navigation can target a message thousands back. Animating through them visually is wrong UX (looks like rapid auto-scroll), takes seconds, and matches no production chat app. WhatsApp, Telegram, Slack, Discord all do instant jump.
243
+
244
+ **Impact:** Function shrinks from ~80 lines to ~35 lines. Polling time drops from 1500ms to 0ms.
245
+
246
+ ---
247
+
248
+ ### Change D — Navigation Gate (`navigationInProgressRef`)
249
+
250
+ **Why:** Even with 101 messages filling the screen (Change E), there's a window between `setMessagesList` and `scrollToIndex` where FlatList might fire `onEndReached` from its initial measurement pass. The gate guarantees zero pagination calls during navigation, regardless of timing.
251
+
252
+ **Code:**
253
+
254
+ ```typescript
255
+ // New ref (add near other refs ~line 974)
256
+ const navigationInProgressRef = useRef<boolean>(false);
257
+ ```
258
+
259
+ **Set gate at start of `getMessagesAroundId`:**
260
+ ```typescript
261
+ const getMessagesAroundId = async (messageId: string) => {
262
+ // ...existing guards (fetchingAroundIdRef, isAgenticUser)...
263
+
264
+ fetchingAroundIdRef.current = messageId;
265
+ navigationInProgressRef.current = true; // ← ADD: gate closed
266
+ // ...rest of function...
267
+ };
268
+ ```
269
+
270
+ **Clear gate is handled inside `scrollToMessage`'s `requestAnimationFrame` (Change C) — single rAF, not duplicated. All early-exit paths in `scrollToMessage` also clear it (see Change C code).**
271
+
272
+ **Failsafe in `getMessagesAroundId` finally block:**
273
+ ```typescript
274
+ let scrollScheduled = false;
275
+ try {
276
+ // ...fetch logic, build allMessages...
277
+ if (allMessages.length > 0) {
278
+ messagesContentListRef.current = allMessages;
279
+ setMessagesList(allMessages);
280
+ setScrollTargetId(messageId);
281
+ scrollScheduled = true;
282
+ }
283
+ } catch (error) {
284
+ setListState("error");
285
+ onError && onError(error as CometChat.CometChatException);
286
+ } finally {
287
+ fetchingAroundIdRef.current = null;
288
+ // If scroll wasn't scheduled (empty results / error), gate must be cleared
289
+ // here because scrollToMessage will never run.
290
+ if (!scrollScheduled) {
291
+ navigationInProgressRef.current = false;
292
+ setNavigationLoading(false);
293
+ }
294
+ }
295
+ ```
296
+
297
+ **Guards in pagination functions:**
298
+ ```typescript
299
+ // At top of getPreviousMessages (~line 1057)
300
+ if (navigationInProgressRef.current) {
301
+ loadingPrevMessagesRef.current = false;
302
+ return;
303
+ }
304
+
305
+ // At top of fetchNextMessages (~line 4382)
306
+ if (navigationInProgressRef.current) return;
307
+ ```
308
+
309
+ **Impact:** Zero `onEndReached` cascade calls during navigation. Belt-and-suspenders with Change E's full screen fill.
310
+
311
+ ---
312
+
313
+ ### Change E — Parallel Fetch with Partial Failure Tolerance
314
+
315
+ **Why:** Three improvements over current code:
316
+ 1. **Drop `getMessageDetails`** — target message is included in `fetchNext` response
317
+ 2. **`Promise.allSettled` instead of `Promise.all`** — partial network failure (e.g. `fetchNext` times out) still shows the user useful context from the successful direction
318
+ 3. **`limit: 50` both directions** — fills any phone screen (max ~25 messages visible) regardless of message height variance, eliminating `onEndReached` cascade by data alone
319
+
320
+ **Code (replace inside `getMessagesAroundId`):**
321
+
322
+ ```typescript
323
+ // Build BOTH request builders (inside getMessagesAroundId)
324
+ const targetMessageId = Number(messageId);
325
+
326
+ const buildRequest = (limit: number) => {
327
+ let req = new CometChat.MessagesRequestBuilder()
328
+ .setLimit(limit)
329
+ .setMessageId(targetMessageId);
330
+
331
+ if (user) req = req.setUID(user.getUid());
332
+ if (group) req = req.setGUID(group.getGuid());
333
+
334
+ if (!parentMessageId) {
335
+ req = req.hideReplies(true);
336
+ } else {
337
+ req = req.setParentMessageId(Number(parentMessageId)).hideReplies(false);
338
+ if (isAgenticUser) {
339
+ req = req.withParent(true);
340
+ }
341
+ }
342
+ return req.build();
343
+ };
344
+
345
+ // Fire both in parallel
346
+ const [prevResult, nextResult] = await Promise.allSettled([
347
+ buildRequest(50).fetchPrevious(),
348
+ buildRequest(50).fetchNext(),
349
+ ]);
350
+
351
+ const previousMessages = prevResult.status === 'fulfilled' ? prevResult.value : [];
352
+ const nextMessages = nextResult.status === 'fulfilled' ? nextResult.value : [];
353
+
354
+ // Hard fail only if BOTH directions failed
355
+ if (prevResult.status === 'rejected' && nextResult.status === 'rejected') {
356
+ setListState("error");
357
+ setNavigationLoading(false);
358
+ navigationInProgressRef.current = false;
359
+ fetchingAroundIdRef.current = null;
360
+ onError && onError(prevResult.reason as CometChat.CometChatException);
361
+ return;
362
+ }
363
+
364
+ // Combine + dedup. fetchNext includes the target message itself.
365
+ // Both responses come oldest-first; reverse for inverted FlatList (newest-first).
366
+ const seenIds = new Set<string>();
367
+ const allMessages: CometChat.BaseMessage[] = [];
368
+
369
+ const pushIfNew = (msg: CometChat.BaseMessage) => {
370
+ const id = String(msg.getId());
371
+ if (!seenIds.has(id)) {
372
+ seenIds.add(id);
373
+ allMessages.push(msg);
374
+ }
375
+ };
376
+
377
+ // Reverse next first (target is at index 0 of next, will end up newest in inverted list)
378
+ [...nextMessages].reverse().forEach(pushIfNew);
379
+ // Then prev (these are older, end up at the bottom of inverted list)
380
+ [...previousMessages].reverse().forEach(pushIfNew);
381
+
382
+ // allMessages is now newest-first, ready for inverted FlatList
383
+ // Update message request builder for future pagination
384
+ msgRequestBuilder.current?.setMessageId(targetMessageId);
385
+ if (!parentMessageId) msgRequestBuilder.current?.hideReplies(true);
386
+ messageRequest.current = msgRequestBuilder.current?.build() || null;
387
+ ```
388
+
389
+ **Why limit 50:** SDK supports up to 50 per request. 50 + 50 = 100 surrounding messages + target. No phone screen shows more than 25 messages. This single change makes `onEndReached` impossible during navigation.
390
+
391
+ **Why dedup uses string IDs:** Consistent with `scrollToMessage` lookup which uses `String(msg.getId())`. Avoids any number/string coercion subtlety in the `Set`.
392
+
393
+ **Impact:** 3 sequential calls → 2 parallel calls. Total latency drops from `t1 + t2 + t3` to `max(t1, t2)`. Partial failure now degrades gracefully instead of erroring.
394
+
395
+ ---
396
+
397
+ ## 4. Final Flow (Optimized)
398
+
399
+ ```
400
+ User taps search result
401
+ → navigate('Messages', { messageId, navigatedFromSearch: true })
402
+ → CometChatMessageList mounts
403
+ → getMessagesAroundId(messageId)
404
+ navigationInProgressRef = true [gate closed]
405
+ Promise.allSettled([fetchPrev(50), fetchNext(50)]) [2 parallel calls]
406
+ ↓ ~300ms (network-bound, single round trip)
407
+ both rejected? → error, gate cleared, exit
408
+ else → dedup → allMessages (up to 101 msgs)
409
+ messagesContentListRef.current = allMessages
410
+ setMessagesList(allMessages) [render #1, only render]
411
+ setScrollTargetId(messageId)
412
+ scrollScheduled = true (finally won't reset gate)
413
+
414
+ useEffect[messagesList.length] fires
415
+ → navigationInProgressRef.current === true → SKIP clear [position cache preserved]
416
+
417
+ useEffect[scrollTargetId, messagesList.length] fires (next frame)
418
+ → requestAnimationFrame → scrollToMessage(scrollTargetId)
419
+ → setScrollTargetId(null)
420
+
421
+ scrollToMessage:
422
+ → targetIndex = findIndex(...) [O(n), n ≤ 101, < 1ms]
423
+ → triedFetchForRef = null (target found)
424
+ → scrollToIndex({ index, animated: false, viewPosition: 0.5 })
425
+ [synchronous, getItemLayout backed]
426
+ → requestAnimationFrame: [waits for FlatList commit]
427
+ highlightMessage(messageId)
428
+ setNavigationLoading(false)
429
+ navigationInProgressRef.current = false [gate open]
430
+
431
+ onLayout × 101 fires anywhere in this flow
432
+ → itemPositionsRef.current.set(...) [0 state updates, 0 re-renders]
433
+
434
+ onEndReached fires anytime gate is closed
435
+ → blocked, returns immediately
436
+
437
+ User scrolls up later
438
+ → onEndReached fires (gate now open) → normal pagination resumes
439
+ ```
440
+
441
+ ---
442
+
443
+ ## 5. Before vs After Metrics
444
+
445
+ | Metric | Before | After |
446
+ |---|---|---|
447
+ | Network calls | 3+ sequential | 2 parallel |
448
+ | Round trips | 3+ | 1 |
449
+ | Messages fetched | 16 | up to 101 |
450
+ | State updates during nav | 50–80 | 2 (`setMessagesList`, `setScrollTargetId`) |
451
+ | Re-renders from `onLayout` | 1 per message | 0 |
452
+ | Polling time | up to 1500ms | 0 |
453
+ | `onEndReached` cascade | 2-3 cycles | 0 |
454
+ | Time to target visible (4G) | 1500–3000ms | ~360ms |
455
+ | Time to target visible (3G) | 3000–8000ms or freeze | ~700ms |
456
+ | Hermes Android crash risk | High | None |
457
+ | Partial network failure | Hard error | Graceful degradation |
458
+
459
+ ---
460
+
461
+ ## 6. Edge Cases (Final)
462
+
463
+ ### EC-1 — Target is first message in conversation
464
+ `fetchPrevious(50)` → 0 messages. `fetchNext(50)` → target + up to 49 newer. allMessages = up to 50 messages with target at the bottom of the inverted list. `scrollToIndex` works.
465
+
466
+ ### EC-2 — Target is most recent message
467
+ `fetchNext(50)` → target only. `fetchPrevious(50)` → 50 older. allMessages = 51 messages with target at index 0. `scrollToIndex(0)` puts target at viewport bottom (visual top of inverted list). Correct.
468
+
469
+ ### EC-3 — Target message deleted / doesn't exist
470
+ `fetchPrevious` and `fetchNext` succeed but neither contains the target ID. `scrollToMessage` finds `targetIndex === -1`. Since `triedFetchForRef.current !== messageId` (first attempt), it calls `getMessagesAroundId` again. The second call hits the `fetchingAroundIdRef.current === messageId` guard — but wait, that guard is reset in the `finally`. So the second `getMessagesAroundId` runs, fetches the same empty result, sets list, triggers `scrollToMessage` again. This time `triedFetchForRef.current === messageId` → graceful error state. Loop bounded to 1 retry max.
471
+
472
+ ### EC-4 — Target is a thread reply
473
+ `parentMessageId` set on both request builders. `fetchNext` returns thread replies only. Same flow.
474
+
475
+ ### EC-5 — `getItemLayout` estimate inaccurate
476
+ `scrollToIndex` lands at estimated offset. Actual rendered heights self-correct via FlatList's internal layout. Target may be slightly off-center but visible. The `itemPositionsRef` data (populated by `onLayout`) is available for optional precision correction in a future enhancement, but not required for correctness.
477
+
478
+ ### EC-6 — `onScrollToIndexFailed` fires
479
+ Only possible if FlatList's window calculations fail despite `getItemLayout`. Existing handler scrolls to estimated offset and retries. Improved by accurate per-item average from `itemPositionsRef`.
480
+
481
+ ### EC-7 — User taps two messages in rapid succession
482
+ First navigation in flight. Second tap → second `getMessagesAroundId` call → blocked by `fetchingAroundIdRef.current === messageId` (different IDs, so this guard doesn't block). Actually checking: the guard is `if (fetchingAroundIdRef.current === messageId) return` — same-ID only. Different ID will proceed. **Risk:** two concurrent `getMessagesAroundId` calls can race on `messagesContentListRef.current`.
483
+
484
+ **Mitigation:** Tighten the guard:
485
+ ```typescript
486
+ // Original
487
+ if (fetchingAroundIdRef.current === messageId) return;
488
+
489
+ // Tightened (any in-flight fetch blocks)
490
+ if (fetchingAroundIdRef.current !== null) return;
491
+ ```
492
+
493
+ ### EC-8 — One direction fails, other succeeds
494
+ `Promise.allSettled` returns mixed result. The successful direction's messages are used. `allMessages` is built from whatever was fetched. If target was in the failed direction (rare — target is in `fetchNext`), `targetIndex === -1` triggers EC-3 retry path.
495
+
496
+ ### EC-9 — Both directions fail
497
+ Hard error: `setListState("error")`, gate cleared, `onError(prevResult.reason)`. Existing error UI shown.
498
+
499
+ ### EC-10 — Long messages (image, 50 reactions, multi-line)
500
+ Estimate underestimates height. `scrollToIndex` lands above target. FlatList's onLayout corrects after render. Target visible, may be slightly off-center.
501
+
502
+ ### EC-11 — Normal conversation open (no `goToMessageId`)
503
+ `getMessagesAroundId` never called. `navigationInProgressRef` stays false. `getPreviousMessages` runs normally (gate not blocking). `scrollToMessage` never called. **Zero behavior change for non-search flows.**
504
+
505
+ ### EC-12 — Agentic user (non-thread)
506
+ Existing `if (isAgenticUser && !parentMessageId) return;` guard runs first. All navigation logic skipped.
507
+
508
+ ### EC-13 — Highlight applied before component mounts
509
+ Resolved by Change C — `highlightMessage` is inside `requestAnimationFrame` which fires after FlatList commits the new viewport. Target row is in render tree.
510
+
511
+ ### EC-14 — `onEndReached` from old viewport during scroll commit
512
+ Resolved by Change C — gate stays closed until inside the `requestAnimationFrame` after `scrollToIndex`. The pre-commit `onEndReached` (if any) finds gate closed and returns.
513
+
514
+ ### EC-15 — Position cache wiped after `setMessagesList(101)`
515
+ Resolved by Change B — clear effect skips when `navigationInProgressRef.current === true`. Cache retained.
516
+
517
+ ### EC-16 — `maintainVisibleContentPosition` interaction
518
+ Current FlatList has `maintainVisibleContentPosition={{ minIndexForVisible: 0 }}`. This preserves index-0 position during list mutations. During navigation, the list goes from `[]` to 101 items — `minIndexForVisible: 0` means "preserve newest message position" which is the default scroll position anyway. `scrollToIndex` overrides this. No conflict observed in practice. **No change needed.**
519
+
520
+ ### EC-17 — `getMessagesAroundId` called twice rapidly with different IDs
521
+ Tightened guard from EC-7: `if (fetchingAroundIdRef.current !== null) return;` blocks the second call entirely. The user must wait for the first navigation to complete. UX: search results panel typically auto-closes on tap, preventing rapid taps in practice.
522
+
523
+ ---
524
+
525
+ ## 7. Files Changed
526
+
527
+ | File | Changes | Risk |
528
+ |---|---|---|
529
+ | `CometChatMessageList.tsx` | Add `getItemLayout` to FlatList | Low |
530
+ | `CometChatMessageList.tsx` | `itemPositions` state → `itemPositionsRef` useRef | Low |
531
+ | `CometChatMessageList.tsx` | Skip clear effect during navigation | Low |
532
+ | `CometChatMessageList.tsx` | Simplified `scrollToMessage` with `triedFetchForRef` retry guard | Low |
533
+ | `CometChatMessageList.tsx` | Add `navigationInProgressRef` gate in 3 locations | Very Low |
534
+ | `CometChatMessageList.tsx` | `Promise.allSettled` + dedup + drop `getMessageDetails` | Low |
535
+ | `CometChatMessageList.tsx` | Tighten `fetchingAroundIdRef` guard (EC-7) | Very Low |
536
+
537
+ **No other files. No prop changes. No API changes.**
538
+
539
+ ---
540
+
541
+ ## 8. Implementation Order
542
+
543
+ | Step | Change | Why This Order |
544
+ |---|---|---|
545
+ | 1 | B: `itemPositions` → ref | Eliminates re-render storm. Self-contained. No dependencies on other changes. |
546
+ | 2 | A: Add `getItemLayout` | Unlocks `scrollToIndex` for Change C. |
547
+ | 3 | D: Add `navigationInProgressRef` (declaration only) | Required by Change C and B. |
548
+ | 4 | C: Simplified `scrollToMessage` + retry guard | Depends on A and D being in place. |
549
+ | 5 | D: Apply gate guards in `getPreviousMessages` and `fetchNextMessages` | After Change C so all rAF cleanup paths exist. |
550
+ | 6 | E: `Promise.allSettled` + 50 limit + dedup + drop `getMessageDetails` | Most logic-heavy change. Last for easy isolation. |
551
+ | 7 | EC-7 tighten: `fetchingAroundIdRef !== null` | Single-line change. Trivial. |
552
+
553
+ Each step is independently revertable. After each step the code compiles and the search nav still works (degraded but not broken).
554
+
555
+ ---
556
+
557
+ ## 9. Testing Matrix
558
+
559
+ | Scenario | Expected |
560
+ |---|---|
561
+ | Search → tap message in 1000+ msg group (Android) | Target visible < 500ms, no crash |
562
+ | Search → tap message in 1000+ msg group (iOS) | Target visible < 500ms |
563
+ | Search → tap very old message (10000+ msgs back) | Target visible, no cascade |
564
+ | Search → tap thread reply | Thread view, target highlighted |
565
+ | Search → tap deleted message | Error state after one retry |
566
+ | Search → tap two messages rapidly | Second tap blocked, first completes |
567
+ | Network OK, both directions | Full 101 msg context |
568
+ | Network: only `fetchPrevious` succeeds | 50 prev shown, target found if in cached state else error |
569
+ | Network: only `fetchNext` succeeds | 50 next + target shown |
570
+ | Network: both fail | Error state, retry possible |
571
+ | Normal conversation open (no search) | Identical to before |
572
+ | Send message during navigation | Appears after navigation completes |
573
+ | Receive message during navigation | Buffered, shown after, no crash |
574
+ | Scroll up after navigation | Pagination resumes |
575
+ | Scroll down after navigation | `fetchNextMessages` resumes |
576
+ | Agentic user chat | No behavior change |
577
+ | `onEndReached` fires during scroll commit | Blocked by gate |
578
+ | Position cache after navigation | Retained, smooth subsequent scroll |
579
+ | Highlight on far target (index 80) | Animation plays via rAF |
580
+ | Long message / image / reactions | Visible (may be slightly off-center) |
581
+
582
+ ---
583
+
584
+ ## 10. Rollback
585
+
586
+ Each change is independent and revertable in isolation:
587
+
588
+ - **B:** Restore `useState` for `itemPositions`, restore `setItemPositions` calls
589
+ - **A:** Remove `getItemLayout` prop
590
+ - **C:** Restore polling `scrollToMessage` with retry loop
591
+ - **D:** Remove `navigationInProgressRef` and 3 usage sites
592
+ - **E:** Restore `getMessageDetails` + sequential `fetchNext`
593
+ - **EC-7 tighten:** Restore same-ID guard
594
+
595
+ No DB changes. No API changes. No prop changes. Pure internal refactor.
596
+
597
+ ---
598
+
599
+ ## 11. What Was Considered and Rejected
600
+
601
+ | Idea | Why Rejected |
602
+ |---|---|
603
+ | `initialScrollIndex` instead of `scrollToIndex` | Requires target index known at FlatList mount, but `messagesContentListRef.current` is empty until after fetch. Restructuring component for this saves ~16ms but adds complexity. Not worth it. |
604
+ | Custom `getItemLayout` with dynamic average from `itemPositionsRef` | Would be recomputed on every FlatList query, hurting performance. Constant `AVERAGE_ITEM_LENGTH` is good enough — corrections happen post-render. |
605
+ | Sliding window cap (trim to 300 msgs) | Current memory cap is 500 msgs, no OOM observed. 101 messages is well within bounds. Adds complexity for no measurable gain. |
606
+ | Eliminate `setScrollTargetId` indirection | The `useEffect` ensures scroll fires AFTER FlatList renders. Removing it requires a microtask + rAF dance with brittle timing. The state-effect pattern is robust. |
607
+ | `Promise.race` to scroll on first response | Would scroll before `prev` arrives, causing layout jump when prev appends. `Promise.allSettled` waits for both, single render, no jump. |
608
+ | Disable `maintainVisibleContentPosition` during navigation | Adds conditional prop → re-render. No observed conflict in practice. Skip. |
609
+ | Pre-warming the conversation cache on search results render | Requires SDK changes. Out of scope. |
610
+
611
+ ---
612
+
613
+ **End of plan v3.**
@@ -77,12 +77,15 @@ export const MessageOptionsSheet: React.FC<MessageOptionsSheetProps> = ({
77
77
  onDismiss?.();
78
78
  }}
79
79
  isOpen={isOpen}
80
+ doNotOccupyEntireHeight={!messageInfo && !ExtensionsComponent}
80
81
  style={{
81
82
  paddingHorizontal: 0,
82
83
  maxHeight: messageInfo
83
84
  ? Dimensions.get('window').height * 0.9
84
85
  : Dimensions.get('window').height * 0.52,
85
- minHeight: Dimensions.get('window').height * 0.5,
86
+ ...(messageInfo || ExtensionsComponent
87
+ ? { minHeight: Dimensions.get('window').height * 0.5 }
88
+ : { minHeight: 50 }),
86
89
  }}
87
90
  >
88
91
  {ExtensionsComponent ? (