@cometchat/chat-uikit-react-native 5.3.10 → 5.4.1

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 (132) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/CometChatClipboardModule.kt +52 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/CometchatUiKitPackage.java +1 -0
  3. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +95 -8
  4. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +300 -7
  5. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorViewManager.kt +2 -1
  6. package/android/src/main/java/com/reactnativecometchatuikit/SoundPlayer.java +85 -47
  7. package/ios/CometChatClipboardModule.m +11 -0
  8. package/ios/CometChatClipboardModule.swift +41 -0
  9. package/ios/FileManager.m +201 -39
  10. package/ios/RichTextEditorView.swift +367 -8
  11. package/ios/RichTextEditorViewManager.m +1 -0
  12. package/ios/SoundPlayer.m +18 -6
  13. package/package.json +10 -7
  14. package/react-native-cometchat-ui-kit.podspec +1 -0
  15. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +692 -107
  16. package/src/CometChatConversations/CometChatConversations.tsx +19 -6
  17. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +649 -49
  18. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +23 -4
  19. package/src/CometChatMessageList/CometChatMessageList.tsx +463 -54
  20. package/src/CometChatMessageList/SEARCH_NAV_SLOWNESS_FINDINGS_AND_FIX.md +313 -0
  21. package/src/CometChatMessageList/components/MessageListItem.tsx +30 -17
  22. package/src/CometChatMessageList/style.ts +33 -5
  23. package/src/CometChatRichTextEditor/RichTextEditorViewNativeComponent.ts +13 -0
  24. package/src/CometChatRichTextEditor/index.tsx +25 -0
  25. package/src/CometChatSearch/CometChatSearch.tsx +296 -154
  26. package/src/calls/CallingExtension.tsx +19 -13
  27. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +20 -1
  28. package/src/extensions/ThumbnailGeneration/ThumbnailGenerationDecorator.tsx +20 -9
  29. package/src/index.ts +39 -0
  30. package/src/shared/CometChatUiKit/CometChatUIKit.ts +40 -34
  31. package/src/shared/base/Types.ts +3 -0
  32. package/src/shared/constants/UIKitConstants.ts +15 -1
  33. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +3 -2
  34. package/src/shared/framework/DataSource.ts +14 -4
  35. package/src/shared/framework/DataSourceDecorator.tsx +17 -8
  36. package/src/shared/framework/MessageDataSource.tsx +307 -60
  37. package/src/shared/helper/useToast.tsx +29 -0
  38. package/src/shared/icons/components/audio-file-type.tsx +11 -22
  39. package/src/shared/icons/components/document-file-type.tsx +11 -24
  40. package/src/shared/icons/components/image-file-type.tsx +12 -21
  41. package/src/shared/icons/components/link-file-type.tsx +25 -0
  42. package/src/shared/icons/components/pdf-file-type.tsx +11 -22
  43. package/src/shared/icons/components/presentation-file-type.tsx +11 -24
  44. package/src/shared/icons/components/spreadsheet-file-type.tsx +11 -24
  45. package/src/shared/icons/components/text-file-type.tsx +11 -21
  46. package/src/shared/icons/components/unknown-file-type.tsx +21 -25
  47. package/src/shared/icons/components/video-file-type.tsx +11 -24
  48. package/src/shared/icons/components/zip-file-type.tsx +11 -24
  49. package/src/shared/icons/icon-mapping.tsx +2 -0
  50. package/src/shared/index.ts +28 -0
  51. package/src/shared/modals/AttachmentPickerConfiguration.ts +13 -0
  52. package/src/shared/modals/SelectedAttachment.ts +65 -0
  53. package/src/shared/modals/UploadState.ts +10 -0
  54. package/src/shared/modals/index.ts +4 -0
  55. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +42 -1
  56. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +42 -1
  57. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +43 -2
  58. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +43 -2
  59. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +43 -2
  60. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +43 -2
  61. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +43 -2
  62. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +43 -2
  63. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +43 -2
  64. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +43 -2
  65. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +43 -2
  66. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +43 -2
  67. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +43 -2
  68. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +43 -2
  69. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +43 -2
  70. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +43 -2
  71. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +43 -2
  72. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +43 -2
  73. package/src/shared/services/UploadQueueService.ts +145 -0
  74. package/src/shared/services/index.ts +2 -0
  75. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +44 -19
  76. package/src/shared/utils/MessageUtils.tsx +13 -4
  77. package/src/shared/utils/attachmentLimits.ts +156 -0
  78. package/src/shared/utils/audioPlaybackCoordinator.ts +28 -0
  79. package/src/shared/utils/batchMediaContext.tsx +30 -0
  80. package/src/shared/utils/conversationUtils.ts +26 -4
  81. package/src/shared/utils/elementType.tsx +38 -0
  82. package/src/shared/utils/groupAttachments.ts +93 -0
  83. package/src/shared/utils/index.ts +8 -0
  84. package/src/shared/utils/openMultiFileChooser.ts +123 -0
  85. package/src/shared/utils/partitionAttachmentsByKind.ts +44 -0
  86. package/src/shared/views/ClipboardPasteHandler/ClipboardPasteHandler.ts +28 -0
  87. package/src/shared/views/ClipboardPasteHandler/NativeCometChatClipboardModule.ts +16 -0
  88. package/src/shared/views/ClipboardPasteHandler/index.ts +2 -0
  89. package/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +1 -0
  90. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreview.style.ts +32 -0
  91. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreview.tsx +90 -0
  92. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreviewItem.tsx +276 -0
  93. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTile.tsx +827 -0
  94. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTray.tsx +110 -0
  95. package/src/shared/views/CometChatAttachmentPreview/StagedVideoDurationProbe.tsx +53 -0
  96. package/src/shared/views/CometChatAttachmentPreview/index.ts +8 -0
  97. package/src/shared/views/CometChatAttachmentViewer/CometChatAttachmentViewer.tsx +305 -0
  98. package/src/shared/views/CometChatAttachmentViewer/index.ts +2 -0
  99. package/src/shared/views/CometChatAudioBubble/CometChatAudioBubble.tsx +71 -74
  100. package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +587 -0
  101. package/src/shared/views/CometChatAudiosBubble/index.ts +2 -0
  102. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +31 -20
  103. package/src/shared/views/CometChatCaptionText/CometChatCaptionText.tsx +182 -0
  104. package/src/shared/views/CometChatCaptionText/index.ts +2 -0
  105. package/src/shared/views/CometChatComposerErrorBanner.tsx +83 -0
  106. package/src/shared/views/CometChatConversationStarter/CometChatConversationStarter.tsx +141 -0
  107. package/src/shared/views/CometChatConversationStarter/index.ts +2 -0
  108. package/src/shared/views/CometChatConversationSummary/CometChatConversationSummary.tsx +155 -0
  109. package/src/shared/views/CometChatConversationSummary/index.ts +2 -0
  110. package/src/shared/views/CometChatFileBubble/style.ts +6 -4
  111. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +316 -0
  112. package/src/shared/views/CometChatFilesBubble/index.ts +2 -0
  113. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +323 -0
  114. package/src/shared/views/CometChatImagesBubble/index.ts +2 -0
  115. package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +425 -0
  116. package/src/shared/views/CometChatMediaViewer/index.ts +2 -0
  117. package/src/shared/views/CometChatMediaViewer/mediaViewerUtils.ts +30 -0
  118. package/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx +14 -4
  119. package/src/shared/views/CometChatSendButtonView/CometChatSendButtonView.tsx +1 -0
  120. package/src/shared/views/CometChatSmartReplies/CometChatSmartReplies.tsx +172 -0
  121. package/src/shared/views/CometChatSmartReplies/index.ts +2 -0
  122. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +4 -3
  123. package/src/shared/views/CometChatVideoBubble/style.ts +3 -3
  124. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +441 -0
  125. package/src/shared/views/CometChatVideosBubble/index.ts +2 -0
  126. package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +78 -0
  127. package/src/shared/views/CometChatVoiceNoteBubble/index.ts +2 -0
  128. package/src/shared/views/index.ts +37 -1
  129. package/src/theme/CometChatThemeHelper.ts +8 -0
  130. package/src/theme/default/color/dark.ts +9 -0
  131. package/src/theme/default/color/light.ts +10 -0
  132. package/src/theme/type.ts +73 -0
@@ -0,0 +1,313 @@
1
+ # Search → "Go to Message" is Slow — Findings & Fix (v2, review-hardened)
2
+
3
+ **Status:** Investigated (code-verified) + senior-reviewed. Not yet implemented.
4
+ **Component:** `packages/ChatUiKit/src/CometChatMessageList/CometChatMessageList.tsx`
5
+ **Scope of fix:** this one file only — **no prop changes, no public API changes**.
6
+
7
+ **What changed in v2:** the fix section was reworked after an adversarial review found
8
+ that the first draft (and the older `SEARCH_NAV_PERF_PLAN.md`) contained a **breaking
9
+ change** (dropping `getMessageDetails`), a **global scroll regression** (constant
10
+ `getItemLayout` on a variable-height list), and a **deadlock trap** (a leaked
11
+ pagination gate). Those are corrected below. Root-cause analysis (§1–4) is unchanged
12
+ and still accurate; the safe, de-risked plan is in §5; the review findings that drove
13
+ the changes are preserved in §9.
14
+
15
+ ---
16
+
17
+ ## 1. Symptom
18
+
19
+ Searching messages and tapping a result — especially a **historical** (far-back)
20
+ message — takes **~1.5–3s** to navigate (worse on 3G / older Android). The list
21
+ stalls, sometimes auto-scrolls visibly, then lands on and highlights the target.
22
+ Normal conversation open is fine; the slowness is specific to the search → *jump to a
23
+ specific message* path.
24
+
25
+ ---
26
+
27
+ ## 2. What happens today (traced flow)
28
+
29
+ ```
30
+ User taps a search result
31
+ → getMessagesAroundId(messageId) [L1573]
32
+ getMessageDetails(targetId) [L1621] ← network call #1 (sequential)
33
+ fetchNext(limit: 15) [L1660] ← network call #2 (sequential)
34
+ allMessages = [target, ...15 next] [L1663] ← NO previous page (commented out)
35
+ setMessagesList(~16) [L1680]
36
+ setScrollTargetId(messageId) [L1767]
37
+ → rAF effect [L2408] → scrollToMessage(target)
38
+ → scrollToMessage(messageId, retryCount) [L1789]
39
+ pos = itemPositions.get(target) [L1801] ← state Map
40
+ pos undefined (row not rendered yet)
41
+ → setTimeout retry 100/200/300/400/500ms [L1829-1835] ← up to 1.5s polling
42
+ → scrollToIndex fallback → onScrollToIndexFailed [L5439] → scrollToOffset + 300ms [L5459]
43
+ Meanwhile:
44
+ ~16 messages underfill the screen
45
+ → onEndReached → getPreviousMessages(30) [L5629] → setMessagesList → re-render
46
+ → onEndReached AGAIN → repeats 2–3× (no gate to stop it)
47
+ every onLayout → setItemPositions(...) [L5492] ← 1 re-render per row
48
+ significant length change → setItemPositions(new Map()) [L5483] ← wipes measurements
49
+ ```
50
+
51
+ ---
52
+
53
+ ## 3. Root causes (verified against current code)
54
+
55
+ ### RC-1 — No `getItemLayout` → a polling loop stands in for it
56
+ The FlatList ([L5619-5648]) has no `getItemLayout`. `AVERAGE_ITEM_LENGTH = 120` ([L115])
57
+ exists but is only used in the scroll-failure handler ([L5443]). Without layout info,
58
+ `scrollToIndex` can't resolve an offset for an unrendered row, so `scrollToMessage`
59
+ ([L1789]) reads a measured position and, when it's missing, **polls via `setTimeout` at
60
+ 100/200/300/400/500 ms — up to 1.5 s** ([L1829-1835]). For a far-back target the row is
61
+ outside the window, so the position is missing on nearly every attempt. **Dominant latency.**
62
+
63
+ ### RC-2 — `getMessagesAroundId` fetches too little, sequentially, redundantly
64
+ In [L1611-1667]: two sequential round-trips — `getMessageDetails` ([L1621]) then
65
+ `fetchNext(15)` ([L1660]) — and **zero previous messages** (the prev page is commented
66
+ out, [L1663-1667]). Result: ~16 messages, target pinned to the oldest edge of the window.
67
+
68
+ ### RC-3 — Underfilled viewport → unguarded `onEndReached` cascade
69
+ 16 messages don't fill the screen → `onEndReached → getPreviousMessages` ([L5629]) fires
70
+ 2–3× (re-render each). No navigation gate suppresses pagination during the jump.
71
+
72
+ ### RC-4 — `itemPositions` is React state, not a ref
73
+ `useState` ([L996]); `setItemPositions` on every `onLayout` ([L5490-5497]) → one
74
+ re-render per row; a memo depends on `[itemPositions]` ([L5472]); the map is wiped on
75
+ large length changes ([L5483]) — discarding the measurements RC-1's loop needs.
76
+
77
+ ---
78
+
79
+ ## 4. Latency breakdown
80
+
81
+ | Contributor | Cost |
82
+ |---|---|
83
+ | `getMessageDetails` + `fetchNext` sequential | 2 × network RTT |
84
+ | `onEndReached` cascade (2–3 cycles) | 2–3 × (RTT + big re-render) |
85
+ | `scrollToMessage` polling for layout | up to 1500 ms |
86
+ | `onScrollToIndexFailed` fallback | + ~300 ms |
87
+ | Re-render storm from `setItemPositions` | dozens of renders |
88
+
89
+ All scale with how far back the target is — hence historical messages are the worst case.
90
+
91
+ ---
92
+
93
+ ## 5. The fix (de-risked)
94
+
95
+ Four internal changes. **Note the deliberate rejection of a global `getItemLayout`** —
96
+ see §9-R2 for why. Ship in the order given; each is independently valuable.
97
+
98
+ ### Step 1 — B: `itemPositions` state → ref *(removes RC-4; lowest risk)*
99
+ - Replace `useState` ([L996]) with `const itemPositionsRef = useRef<Map<string,{y:number;height:number}>>(new Map())`.
100
+ - `handleItemLayout` ([L5490]) becomes a pure `itemPositionsRef.current.set(id, {y,height})` — no `setState`.
101
+ - Clear effect ([L5478]): skip while navigating; else `itemPositionsRef.current = new Map()`.
102
+ - Update reads at [L1801] and [L5442]; drop `itemPositions` from `handleScrollToIndexFailed` deps ([L5472]).
103
+ - **Verified safe:** `itemPositions` has no render-path read (only imperative uses).
104
+
105
+ ### Step 2 — D: navigation gate, **deadlock-proofed** *(removes RC-3)*
106
+ - Add `const navigationInProgressRef = useRef(false)` and a **watchdog ref**.
107
+ - Provide one helper pair:
108
+ ```ts
109
+ const openNavGate = () => {
110
+ navigationInProgressRef.current = false;
111
+ if (navGateWatchdog.current) { clearTimeout(navGateWatchdog.current); navGateWatchdog.current = null; }
112
+ };
113
+ const closeNavGate = () => {
114
+ navigationInProgressRef.current = true;
115
+ if (navGateWatchdog.current) clearTimeout(navGateWatchdog.current);
116
+ navGateWatchdog.current = setTimeout(openNavGate, 5000); // FAILSAFE: never deadlock
117
+ };
118
+ ```
119
+ - `closeNavGate()` at the top of `getMessagesAroundId` (after the existing guards, ~[L1596]).
120
+ - `openNavGate()` in **every terminal branch of `scrollToMessage`** (scroll done, target
121
+ not found give-up, empty-list early return) — the gate must stay closed across
122
+ fetch **and** scroll, so it opens only when the scroll settles, not when the fetch ends.
123
+ - The offline error path ([L1771-1784]) calls `getPreviousMessages()`; call `openNavGate()`
124
+ **before** it (see §6-G1), or the gate swallows the cached-page render.
125
+ - Guards: `if (navigationInProgressRef.current) { loadingPrevMessagesRef.current = false; return; }`
126
+ at top of `getPreviousMessages` ([L1080]); `if (navigationInProgressRef.current) return;`
127
+ at top of `fetchNextMessages` ([L5258]).
128
+ - **Why the watchdog:** a single missed clear would disable *all* pagination permanently.
129
+ The 5 s failsafe converts a potential hard bug into at worst a one-time delayed reopen.
130
+
131
+ ### Step 3 — C: rewrite `scrollToMessage` — accurate, event-driven, no global `getItemLayout` *(removes RC-1)*
132
+ Keep the **measured-offset** scroll (today's accurate path, [L1806-1816]); delete the
133
+ 1.5 s polling; make the far-target case event-driven off the target's own `onLayout`.
134
+ ```ts
135
+ const scrollToMessage = (messageId: string) => {
136
+ if (!messageListRef.current || messagesContentListRef.current.length === 0) { openNavGate(); setNavigationLoading(false); return; }
137
+ const idx = messagesContentListRef.current.findIndex(m => String(m.getId()) === messageId);
138
+ if (idx === -1) { // not in window
139
+ if (triedFetchForRef.current === messageId) { triedFetchForRef.current = null; openNavGate(); setNavigationLoading(false); return; }
140
+ triedFetchForRef.current = messageId; getMessagesAroundId(messageId); return; // one bounded retry
141
+ }
142
+ triedFetchForRef.current = null;
143
+ const pos = itemPositionsRef.current.get(messageId);
144
+ if (pos) { // measured → jump exactly, now
145
+ const h = currentScrollPosition.current.scrollViewHeight || Dimensions.get('window').height;
146
+ messageListRef.current.scrollToOffset({ offset: Math.max(0, pos.y - h/2 + pos.height/2), animated: false });
147
+ requestAnimationFrame(() => { if (!shouldSuppressHighlightRef.current) highlightMessage(messageId); shouldSuppressHighlightRef.current = false; setNavigationLoading(false); openNavGate(); });
148
+ } else { // not measured yet → coarse jump, correct on its onLayout
149
+ pendingScrollTargetRef.current = messageId;
150
+ messageListRef.current.scrollToIndex({ index: idx, animated: false, viewPosition: 0.5 }); // onScrollToIndexFailed handles far targets
151
+ // handleItemLayout finishes the job when the target row mounts (below)
152
+ }
153
+ };
154
+ ```
155
+ In `handleItemLayout`, after storing the measurement, finish a pending navigation:
156
+ ```ts
157
+ if (messageId === pendingScrollTargetRef.current) {
158
+ pendingScrollTargetRef.current = null;
159
+ const p = itemPositionsRef.current.get(messageId);
160
+ const h = currentScrollPosition.current.scrollViewHeight || Dimensions.get('window').height;
161
+ if (p) messageListRef.current?.scrollToOffset({ offset: Math.max(0, p.y - h/2 + p.height/2), animated: false });
162
+ requestAnimationFrame(() => { if (!shouldSuppressHighlightRef.current) highlightMessage(messageId); shouldSuppressHighlightRef.current = false; setNavigationLoading(false); openNavGate(); });
163
+ }
164
+ ```
165
+ Make `handleScrollToIndexFailed` ([L5439]) **bounded** (2–3 retries using the measured
166
+ average from `itemPositionsRef`) instead of a single blind retry. Add refs
167
+ `triedFetchForRef` and `pendingScrollTargetRef`.
168
+ **Result:** no 1.5 s polling, final position is always the *measured* offset (accurate),
169
+ and — critically — **no global `getItemLayout`, so normal reading/scroll math is untouched.**
170
+ `animated:false` is an intentional UX change (instant jump; matches WhatsApp/Telegram) —
171
+ flag for design/QA sign-off.
172
+
173
+ ### Step 4 — E: parallel window fetch — **keep `getMessageDetails`** *(removes RC-2)*
174
+ The target is **not** returned by `fetchNext`/`fetchPrevious` (both are exclusive of the
175
+ anchor — see §9-R1). So we keep `getMessageDetails`, but run all three in parallel and
176
+ add the previous page:
177
+ ```ts
178
+ const targetMessageId = Number(messageId);
179
+ const build = (limit: number) => { /* setLimit(limit).setMessageId(targetMessageId) + uid/guid/parent/hideReplies/withParent EXACTLY as L1637-1657, for BOTH directions */ };
180
+ const guard = (p) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error('AROUND_TIMEOUT')), 3500))]);
181
+
182
+ const [detailsR, prevR, nextR] = await Promise.allSettled([
183
+ guard(CometChat.getMessageDetails(targetMessageId)),
184
+ guard(build(50).fetchPrevious()), // older than target
185
+ guard(build(50).fetchNext()), // newer than target
186
+ ]);
187
+ const target = detailsR.status === 'fulfilled' ? detailsR.value : null;
188
+ const prev = prevR.status === 'fulfilled' ? prevR.value : [];
189
+ const next = nextR.status === 'fulfilled' ? nextR.value : [];
190
+
191
+ if (!target && prev.length === 0 && next.length === 0) { // total failure → offline cached-page fallback (§6-G1)
192
+ openNavGate(); fetchingAroundIdRef.current = null; setHasTargetMessageId(false);
193
+ getPreviousMessages(); onError && onError(prevR.reason ?? nextR.reason);
194
+ return;
195
+ }
196
+ // Newest-first for the inverted list; dedup by String(getId()); target between the two pages.
197
+ const seen = new Set<string>(); const allMessages: any[] = [];
198
+ const push = (m: any) => { const id = String(m.getId()); if (id && !seen.has(id)) { seen.add(id); allMessages.push(m); } };
199
+ [...next].reverse().forEach(push); // newest → just-after-target
200
+ if (target) push(target); // the anchor
201
+ [...prev].reverse().forEach(push); // just-before-target → oldest
202
+ // then setMessagesList(allMessages) + setScrollTargetId(messageId), preserving the
203
+ // startFromUnreadMessages / navigatedFromSearch indicator logic at L1690-1763 verbatim.
204
+ ```
205
+ **Cursor continuity (must specify):** after the window loads, set the pagination cursor
206
+ so scroll-up (`getPreviousMessages`) continues from the **oldest** loaded id and
207
+ scroll-down (`fetchNextMessages`) from the **newest**. Do not leave the cursor at the
208
+ target id, or scroll-up will re-fetch the window (see §9-R5).
209
+
210
+ *(No Step for a global `getItemLayout` — intentionally removed vs. the first draft.)*
211
+
212
+ ---
213
+
214
+ ## 6. Offline / composition gotchas (must preserve)
215
+
216
+ - **G1 — total-failure path falls back to the cached page, not a hard error.** Mirror the
217
+ current catch ([L1771-1784]): open the gate, clear `fetchingAroundIdRef`,
218
+ `setHasTargetMessageId(false)`, `getPreviousMessages()`, `onError`. A plain
219
+ `setListState("error")` would regress offline search.
220
+ - **G2 — release the gate before the offline fallback.** Because that path calls
221
+ `getPreviousMessages()`, `openNavGate()` must run first or the gate blocks it.
222
+ - **G3 — composes with the blank-flash fix.** `getMessagesAroundId`'s fallback and the
223
+ two-phase load we just changed live in the same open path; test them together.
224
+
225
+ ---
226
+
227
+ ## 7. Implementation order
228
+
229
+ 1. **B** — state → ref (self-contained; kills the re-render storm).
230
+ 2. **D** — gate + watchdog (declaration + guards; safe on its own).
231
+ 3. **C** — rewrite `scrollToMessage` (needs B + D).
232
+ 4. **E** — parallel 3-way fetch + previous page + cursor handling (heaviest; last).
233
+
234
+ Landing **B + D + C** already removes the ~1.5 s polling and the cascade — the most
235
+ visible lag — without touching the fetch shape.
236
+
237
+ ---
238
+
239
+ ## 8. Verification
240
+
241
+ **Static:** `cd packages/ChatUiKit && npx tsc --noEmit` — no *new* errors. (Two
242
+ pre-existing `ErrorEmptyView` JSX-type errors at L5227/L5241 are unrelated.)
243
+
244
+ **Device** (Metro Fast Refresh, then force-stop + relaunch), **both iOS and Android**:
245
+
246
+ | Test | Expected |
247
+ |---|---|
248
+ | Search → tap recent message | centered, instant, no white flash |
249
+ | Search → tap **very old** message | < ~500 ms, target **visible and centered**, no cascade |
250
+ | Search → tap thread reply | thread opens, target highlighted |
251
+ | Search → tap deleted / missing message | one bounded retry, then settles (no infinite loop) |
252
+ | **Offline** → search → tap | cached page renders (no error screen, no hang) |
253
+ | **Normal open with `startFromUnreadMessages`** (uses `getMessagesAroundId` too — §9-R4) | unread anchor works; no regression |
254
+ | Scroll up / down after landing | pagination resumes (gate reopened) |
255
+ | Force a leaked gate (dev) | watchdog reopens within 5 s |
256
+
257
+ **Measure:** temporarily wrap tap→highlight in `console.time('nav')` / `console.timeEnd('nav')`,
258
+ read via `adb logcat`. Target ≈ one network RTT (~300–400 ms).
259
+
260
+ ---
261
+
262
+ ## 9. Risks & Open Questions (from senior review)
263
+
264
+ **R1 — [was BREAKING] `fetchNext`/`fetchPrevious` exclude the anchor.** Proven by the
265
+ current code adding `targetMessage` separately ([L1663-1667]) and by the SDK having no
266
+ "around"/inclusive option (`MessagesRequestBuilder` exposes only `setMessageId`). → §5-E
267
+ keeps `getMessageDetails`. **Do not** assume the pages contain the target.
268
+
269
+ **R2 — [was GLOBAL REGRESSION] a constant `getItemLayout` is wrong for this list.** Rows
270
+ vary from ~40px to 300px+; a fixed `120` makes `scrollToIndex` land far off, mis-centers
271
+ the target (no polling fallback remains), and — being global — degrades *all* scrolling,
272
+ with blank-cell risk under `removeClippedSubviews` (Android, [L5644]). → §5-C rejects it
273
+ and keeps the *measured-offset* scroll + event-driven correction instead.
274
+
275
+ **R3 — [was DEADLOCK] a leaked pagination gate disables scroll forever.** `getMessagesAroundId`
276
+ has multiple early returns (e.g. [L1629]) and a `finally` that clears only
277
+ `fetchingAroundIdRef`. → §5-D centralizes open/close and adds a 5 s watchdog failsafe.
278
+
279
+ **R4 — blast radius is bigger than "search."** `getMessagesAroundId` is also called on
280
+ normal open for the last-read/unread anchor ([L3216/L3218/L3225]) and deep-link goToMessageId
281
+ ([L3172]) — not only search ([L1864/L3172]). Changes D & E affect those paths; test them (§8).
282
+
283
+ **R5 — pagination cursor after a 101-msg window** must be set to oldest/newest loaded ids,
284
+ or scroll-up/down re-fetches or skips. Called out in §5-E; verify on device.
285
+
286
+ **R6 — RN combination risk.** `maintainVisibleContentPosition` ([L5625]) + programmatic
287
+ `scrollToIndex`/`scrollToOffset` on an inverted list behaves differently across
288
+ iOS/Android/Hermes. Requires real-device testing on both platforms.
289
+
290
+ **R7 — `animated:false`** is a deliberate UX change from today's animated scroll ([L1815]);
291
+ get design/QA sign-off.
292
+
293
+ **Open question:** should the window be smaller than 50+50 on low-end Android to cut
294
+ first-paint jank from image-heavy rows? Default to 50/50; revisit if the very-old-message
295
+ test janks.
296
+
297
+ ---
298
+
299
+ ## 10. Expected result
300
+
301
+ | Metric | Before | After |
302
+ |---|---|---|
303
+ | Network round-trips per navigation | 3+ sequential | 1 (3 parallel) |
304
+ | Messages fetched | ~16 | up to ~101 |
305
+ | `onEndReached` cascade cycles | 2–3 | 0 (gated) |
306
+ | Re-renders from `onLayout` | 1 per message | 0 |
307
+ | Scroll polling | up to 1500 ms | 0 (event-driven) |
308
+ | Target centering | measured (accurate) | measured (accurate) — **preserved** |
309
+ | Global scroll math | unchanged | unchanged — **no `getItemLayout`** |
310
+ | Time to target visible (4G) | 1500–3000 ms | ~360–500 ms |
311
+
312
+ Net: roughly a **4–6× speedup**, network-bound instead of CPU/retry-bound, with offline
313
+ search preserved and **no global scroll regression** — the two traps of the first draft.
@@ -5,8 +5,6 @@ import { CometChatDateSeparator } from '../../shared/views/CometChatDateSeperato
5
5
  import { CometChatTheme } from '../../theme/type';
6
6
  import { CometChatNewMessageIndicator, NewMessageIndicatorStyle } from '../../shared/views';
7
7
 
8
- const SEPARATOR_HEIGHT = 40;
9
-
10
8
  interface MessageListItemProps {
11
9
  item: CometChat.BaseMessage;
12
10
  index: number;
@@ -18,7 +16,11 @@ interface MessageListItemProps {
18
16
  timestamp: number;
19
17
  dayHeaderString: string | undefined;
20
18
  RenderMessageItem: React.ComponentType<any>;
21
- itemSeparator: () => React.ReactNode;
19
+ itemSeparator: (tight?: boolean) => React.ReactNode;
20
+ /** Collapse the TOP padding — the older (above) neighbour is in the same fan-out batch. */
21
+ tightTop?: boolean;
22
+ /** Collapse the BOTTOM padding — the newer (below) neighbour is in the same fan-out batch. */
23
+ tightBottom?: boolean;
22
24
  staticStyles: any;
23
25
  onLayout?: (event: any, messageId: string) => void;
24
26
  showNewMessageIndicator?: boolean;
@@ -39,6 +41,8 @@ const MessageListItemComponent: React.FC<MessageListItemProps> = ({
39
41
  dayHeaderString,
40
42
  RenderMessageItem,
41
43
  itemSeparator,
44
+ tightTop,
45
+ tightBottom,
42
46
  staticStyles,
43
47
  onLayout,
44
48
  showNewMessageIndicator,
@@ -55,21 +59,26 @@ const MessageListItemComponent: React.FC<MessageListItemProps> = ({
55
59
  };
56
60
 
57
61
  return (
58
- <View style={staticStyles.container} onLayout={handleLayout}>
62
+ <View
63
+ style={[
64
+ staticStyles.container,
65
+ tightTop ? staticStyles.messageTightTop : null,
66
+ tightBottom ? staticStyles.messageTightBottom : null,
67
+ ]}
68
+ onLayout={handleLayout}
69
+ >
59
70
  {isHighlighted && (
60
71
  <Animated.View
61
- style={{
62
- backgroundColor: highlightAnimatedValue.interpolate({
63
- inputRange: [0, 1],
64
- outputRange: ['transparent', String(theme.color.extendedPrimary200)],
65
- }),
66
- position: 'absolute',
67
- left: 0,
68
- right: 0,
69
- top: showSeparator ? SEPARATOR_HEIGHT : 0,
70
- bottom: 0,
71
- zIndex: 1,
72
- }}
72
+ style={[
73
+ staticStyles.highlightOverlay,
74
+ showSeparator ? staticStyles.highlightOverlayBelowSeparator : null,
75
+ {
76
+ backgroundColor: highlightAnimatedValue.interpolate({
77
+ inputRange: [0, 1],
78
+ outputRange: ['transparent', String(theme.color.extendedPrimary200)],
79
+ }),
80
+ },
81
+ ]}
73
82
  />
74
83
  )}
75
84
  <View style={staticStyles.contentWrapper}>
@@ -91,7 +100,9 @@ const MessageListItemComponent: React.FC<MessageListItemProps> = ({
91
100
  />
92
101
  )}
93
102
  <RenderMessageItem item={item} theme={theme} idx={index} />
94
- {itemSeparator()}
103
+ {/* The separator sits BELOW the bubble → it faces the newer (below) neighbour, so it must
104
+ collapse with tightBottom (not tightTop) for same-batch rows to read as one group. */}
105
+ {itemSeparator(tightBottom)}
95
106
  </View>
96
107
  </View>
97
108
  );
@@ -110,6 +121,8 @@ export const MessageListItem = memo(MessageListItemComponent, (prevProps, nextPr
110
121
  const visualsUnchanged =
111
122
  prevProps.isHighlighted === nextProps.isHighlighted &&
112
123
  prevProps.showSeparator === nextProps.showSeparator &&
124
+ prevProps.tightTop === nextProps.tightTop &&
125
+ prevProps.tightBottom === nextProps.tightBottom &&
113
126
  prevProps.timestamp === nextProps.timestamp &&
114
127
  prevProps.dayHeaderString === nextProps.dayHeaderString &&
115
128
  prevProps.showNewMessageIndicator === nextProps.showNewMessageIndicator &&
@@ -254,8 +254,12 @@ export const getMessageListStylesLight = (
254
254
  },
255
255
  imageBubbleStyles: {
256
256
  containerStyle: {
257
- padding: spacing.padding.p1,
257
+ // Figma: padding 4px top/right/left, 0 bottom — leaves a thin bubble-color
258
+ // frame around the media; the timestamp row sits flush under the grid.
259
+ paddingTop: spacing.padding.p1,
260
+ paddingRight: spacing.padding.p1,
258
261
  paddingBottom: spacing.padding.p0,
262
+ paddingLeft: spacing.padding.p1,
259
263
  borderRadius: spacing.radius.r3,
260
264
  alignSelf: "flex-start",
261
265
  },
@@ -266,7 +270,10 @@ export const getMessageListStylesLight = (
266
270
  width: 232,
267
271
  },
268
272
  dateReceiptContainerStyle: {
273
+ // Figma: 2px gap between the media grid and the timestamp row.
274
+ paddingTop: spacing.padding.p0_5,
269
275
  paddingRight: spacing.padding.p1,
276
+ paddingBottom: spacing.padding.p1,
270
277
  },
271
278
  },
272
279
  assistantBubbleStyles: {
@@ -486,8 +493,12 @@ export const getMessageListStylesLight = (
486
493
  },
487
494
  imageBubbleStyles: {
488
495
  containerStyle: {
489
- padding: spacing.padding.p1,
496
+ // Figma: padding 4px top/right/left, 0 bottom — leaves a thin bubble-color
497
+ // frame around the media; the timestamp row sits flush under the grid.
498
+ paddingTop: spacing.padding.p1,
499
+ paddingRight: spacing.padding.p1,
490
500
  paddingBottom: spacing.padding.p0,
501
+ paddingLeft: spacing.padding.p1,
491
502
  borderRadius: spacing.radius.r3,
492
503
  overflow: "hidden",
493
504
  },
@@ -499,7 +510,10 @@ export const getMessageListStylesLight = (
499
510
  minWidth: 232,
500
511
  },
501
512
  dateReceiptContainerStyle: {
513
+ // Figma: 2px gap between the media grid and the timestamp row.
514
+ paddingTop: spacing.padding.p0_5,
502
515
  paddingRight: spacing.padding.p1,
516
+ paddingBottom: spacing.padding.p1,
503
517
  },
504
518
  },
505
519
  audioBubbleStyles: getAudioBubbleStyleLight(color, spacing, typography)
@@ -758,8 +772,12 @@ export const getMessageListStylesDark = (
758
772
  },
759
773
  imageBubbleStyles: {
760
774
  containerStyle: {
761
- padding: spacing.padding.p1,
775
+ // Figma: padding 4px top/right/left, 0 bottom — leaves a thin bubble-color
776
+ // frame around the media; the timestamp row sits flush under the grid.
777
+ paddingTop: spacing.padding.p1,
778
+ paddingRight: spacing.padding.p1,
762
779
  paddingBottom: spacing.padding.p0,
780
+ paddingLeft: spacing.padding.p1,
763
781
  borderRadius: spacing.radius.r3,
764
782
  alignSelf: "flex-start",
765
783
  },
@@ -770,12 +788,15 @@ export const getMessageListStylesDark = (
770
788
  width: 232,
771
789
  },
772
790
  dateReceiptContainerStyle: {
791
+ // Figma: 2px gap between the media grid and the timestamp row.
792
+ paddingTop: spacing.padding.p0_5,
773
793
  paddingRight: spacing.padding.p1,
794
+ paddingBottom: spacing.padding.p1,
774
795
  },
775
796
  },
776
797
  assistantBubbleStyles: {
777
798
  containerStyle: {
778
- backgroundColor: "transparent",
799
+ backgroundColor: "transparent",
779
800
  borderRadius: spacing.radius.r3,
780
801
  minWidth: 90,
781
802
  alignSelf: "flex-start",
@@ -991,8 +1012,12 @@ export const getMessageListStylesDark = (
991
1012
  },
992
1013
  imageBubbleStyles: {
993
1014
  containerStyle: {
994
- padding: spacing.padding.p1,
1015
+ // Figma: padding 4px top/right/left, 0 bottom — leaves a thin bubble-color
1016
+ // frame around the media; the timestamp row sits flush under the grid.
1017
+ paddingTop: spacing.padding.p1,
1018
+ paddingRight: spacing.padding.p1,
995
1019
  paddingBottom: spacing.padding.p0,
1020
+ paddingLeft: spacing.padding.p1,
996
1021
  borderRadius: spacing.radius.r3,
997
1022
  overflow: "hidden",
998
1023
  },
@@ -1004,7 +1029,10 @@ export const getMessageListStylesDark = (
1004
1029
  minWidth: 232,
1005
1030
  },
1006
1031
  dateReceiptContainerStyle: {
1032
+ // Figma: 2px gap between the media grid and the timestamp row.
1033
+ paddingTop: spacing.padding.p0_5,
1007
1034
  paddingRight: spacing.padding.p1,
1035
+ paddingBottom: spacing.padding.p1,
1008
1036
  },
1009
1037
  },
1010
1038
  audioBubbleStyles: getAudioBubbleStyleDark(color, spacing, typography)
@@ -67,6 +67,17 @@ type LinkTapEventData = Readonly<{
67
67
  length: Int32;
68
68
  }>;
69
69
 
70
+ // One pasted media item (image or file) extracted to a temp file by the native editor.
71
+ type PasteMediaItem = Readonly<{
72
+ uri: string; // file:// path to the temp copy
73
+ mimeType: string; // real mime type (image/*, application/pdf, …)
74
+ name: string; // display filename with extension
75
+ size: Double; // bytes
76
+ }>;
77
+ type PasteMediaEventData = Readonly<{
78
+ items: ReadonlyArray<PasteMediaItem>;
79
+ }>;
80
+
70
81
  export interface NativeProps extends ViewProps {
71
82
  placeholder?: string;
72
83
  editable?: boolean;
@@ -98,6 +109,8 @@ export interface NativeProps extends ViewProps {
98
109
  onActiveStylesChange?: DirectEventHandler<ActiveStylesEventData>;
99
110
  onLinkTap?: DirectEventHandler<LinkTapEventData>;
100
111
  onSendRequest?: DirectEventHandler<Readonly<{}>>;
112
+ // Fired when the user pastes image(s)/file(s) into the editor (long-press Paste / ⌘V).
113
+ onPasteMedia?: DirectEventHandler<PasteMediaEventData>;
101
114
  }
102
115
 
103
116
  export default requireNativeComponent<NativeProps>(
@@ -101,6 +101,17 @@ interface LinkTapEvent {
101
101
  nativeEvent: LinkTapEventData;
102
102
  }
103
103
 
104
+ /** A single image/file pasted into the editor (extracted to a temp file by native). */
105
+ export interface PasteMediaItem {
106
+ uri: string;
107
+ mimeType: string;
108
+ name: string;
109
+ size: number;
110
+ }
111
+ interface PasteMediaEvent {
112
+ nativeEvent: { items: PasteMediaItem[] };
113
+ }
114
+
104
115
  export interface RichTextEditorPropsExtended extends RichTextEditorProps {
105
116
  /** Test ID for testing frameworks (e.g. Detox, React Native Testing Library) */
106
117
  testID?: string;
@@ -111,6 +122,8 @@ export interface RichTextEditorPropsExtended extends RichTextEditorProps {
111
122
  onLinkTap?: (data: LinkTapEventData) => void;
112
123
  /** Callback when Enter is pressed in "sendMessage" mode (Android only) */
113
124
  onSendRequest?: () => void;
125
+ /** Fired when the user pastes image(s)/file(s) into the editor (long-press Paste / ⌘V). */
126
+ onPasteMedia?: (items: PasteMediaItem[]) => void;
114
127
  /** Enter key behavior: "newLine" (default) or "sendMessage" (Android only) */
115
128
  enterKeyBehavior?: string;
116
129
  /** Show Bold/Italic/Underline/Strikethrough in text selection context menu */
@@ -323,6 +336,17 @@ const RichTextEditor = forwardRef<RichTextEditorRef, RichTextEditorPropsExtended
323
336
  props.onSendRequest?.();
324
337
  }, [props.onSendRequest]);
325
338
 
339
+ const handlePasteMedia = useCallback(
340
+ // permissive event type — bridges the native direct event; shape is checked at runtime
341
+ (event: any) => {
342
+ const items = event?.nativeEvent?.items;
343
+ if (Array.isArray(items) && items.length > 0) {
344
+ props.onPasteMedia?.(items as PasteMediaItem[]);
345
+ }
346
+ },
347
+ [props.onPasteMedia],
348
+ );
349
+
326
350
  const combinedStyle = StyleSheet.flatten([props.style, height != null ? { height } : undefined]);
327
351
 
328
352
  return (
@@ -356,6 +380,7 @@ const RichTextEditor = forwardRef<RichTextEditorRef, RichTextEditorPropsExtended
356
380
  onActiveStylesChange={handleActiveStylesChange}
357
381
  onLinkTap={handleLinkTap}
358
382
  onSendRequest={handleSendRequest}
383
+ onPasteMedia={handlePasteMedia}
359
384
  enterKeyBehavior={props.enterKeyBehavior}
360
385
  showTextSelectionMenuItems={props.showTextSelectionMenuItems ?? true}
361
386
  />