@cometchat/chat-uikit-react-native 5.5.0 → 5.5.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 (72) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +20 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorViewManager.kt +9 -1
  3. package/ios/RichTextEditorView.swift +43 -0
  4. package/ios/RichTextEditorViewManager.m +1 -0
  5. package/ios/RichTextEditorViewManager.swift +8 -0
  6. package/package.json +5 -2
  7. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +38 -9
  8. package/src/CometChatConversations/CometChatConversations.tsx +8 -1
  9. package/src/CometChatGroupMembers/CometChatGroupMembers.tsx +2 -2
  10. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +15 -3
  11. package/src/CometChatMessageInformation/CometChatMessageInformation.tsx +10 -1
  12. package/src/CometChatMessageList/CometChatMessageList.tsx +5 -2
  13. package/src/CometChatMessageList/PERFORMANCE_ARCHITECTURE.md +478 -0
  14. package/src/CometChatMessageList/SEARCH_NAV_PERF_PLAN.md +613 -0
  15. package/src/CometChatMessageList/SEARCH_NAV_SLOWNESS_FINDINGS_AND_FIX.md +313 -0
  16. package/src/CometChatMessageList/components/MessageOptionsSheet.tsx +7 -8
  17. package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +43 -19
  18. package/src/CometChatRichTextEditor/index.tsx +4 -0
  19. package/src/CometChatRichTextEditor/types.ts +2 -0
  20. package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +251 -14
  21. package/src/CometChatSearch/CometChatSearch.tsx +29 -6
  22. package/src/shared/CometChatUiKit/CometChatUIKit.changes.md +76 -0
  23. package/src/shared/CometChatUiKit/CometChatUIKit.ts +2 -1
  24. package/src/shared/CometChatUiKit/checkAuthSettings-review.md +211 -0
  25. package/src/shared/constants/UIKitConstants.ts +3 -17
  26. package/src/shared/constants/textPatterns.ts +27 -0
  27. package/src/shared/events/CometChatUIEventHandler/CometChatUIEventHandler.ts +25 -259
  28. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +31 -19
  29. package/src/shared/formatters/CometChatTextFormatter.ts +22 -0
  30. package/src/shared/formatters/applyRawFormatters.ts +31 -0
  31. package/src/shared/framework/MessageDataSource.tsx +14 -8
  32. package/src/shared/resources/CometChatLocalizeNew/CometChatI18nProvider.tsx +15 -30
  33. package/src/shared/resources/CometChatLocalizeNew/CometChatLocalizationHelper.ts +138 -19
  34. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +74 -1
  35. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +0 -1
  36. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +54 -1
  37. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +54 -1
  38. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +54 -1
  39. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +54 -1
  40. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +54 -1
  41. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +54 -1
  42. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +54 -1
  43. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +54 -1
  44. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +54 -1
  45. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +54 -1
  46. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +54 -1
  47. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +54 -1
  48. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +54 -1
  49. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +54 -1
  50. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +54 -1
  51. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +54 -1
  52. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +11 -0
  53. package/src/shared/utils/MarkdownUtils.ts +34 -4
  54. package/src/shared/utils/PinnedMessagesHelper.ts +65 -0
  55. package/src/shared/utils/SavedMessagesHelper.ts +42 -6
  56. package/src/shared/utils/__testUtils__/messagesRequestBuilderMock.ts +37 -0
  57. package/src/shared/utils/cloneRequestBuilder.ts +25 -0
  58. package/src/shared/views/ClipboardPasteHandler/ClipboardPasteHandler.ts +15 -4
  59. package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +5 -0
  60. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +4 -1
  61. package/src/shared/views/CometChatCaptionText/CometChatCaptionText.tsx +8 -1
  62. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +5 -0
  63. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +5 -0
  64. package/src/shared/views/CometChatList/Header.tsx +8 -2
  65. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +5 -0
  66. package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +5 -0
  67. package/android/.gradle/7.4/checksums/checksums.lock +0 -0
  68. package/android/.gradle/7.4/fileChanges/last-build.bin +0 -0
  69. package/android/.gradle/7.4/fileHashes/fileHashes.lock +0 -0
  70. package/android/.gradle/7.4/gc.properties +0 -0
  71. package/android/.gradle/vcs-1/gc.properties +0 -0
  72. package/src/CometChatMessageList/MANUAL_TEST_CASES.md +0 -154
@@ -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.
@@ -10,12 +10,6 @@ import { CometChatTheme } from '../../theme/type';
10
10
  import { CometChatMessageTemplate } from '../../shared/modals/CometChatMessageTemplate';
11
11
  import { getModerationStatus } from '../../shared/utils/MessageUtils';
12
12
 
13
- const WINDOW_HEIGHT = Dimensions.get('window').height;
14
- const SHEET_MAX_HEIGHT_RATIO = 0.52;
15
- // Quick reactions row height (~56) + sheet paddingTop (25) + safety margin
16
- const RESERVED_HEIGHT = 100;
17
- const ACTION_SHEET_MAX_HEIGHT = WINDOW_HEIGHT * SHEET_MAX_HEIGHT_RATIO - RESERVED_HEIGHT;
18
-
19
13
  interface MessageOptionsSheetProps {
20
14
  bottomSheetRef: React.RefObject<any>;
21
15
  isOpen: boolean;
@@ -112,7 +106,9 @@ export const MessageOptionsSheet: React.FC<MessageOptionsSheetProps> = ({
112
106
  style={mergedTheme?.messageListStyles?.messageInformationStyles}
113
107
  />
114
108
  ) : (
115
- <View style={{ flex: 1 }}>
109
+ // flexShrink rather than flex: 1 — in React Native flex: 1 never shrinks below its
110
+ // content, so the column would keep its full height and the list could never scroll.
111
+ <View style={{ flexShrink: 1 }}>
116
112
  {/* Show quick reactions for disapproved messages */}
117
113
  {!hideReactionOption && getModerationStatus(selectedMessage) !== 'disapproved' && (
118
114
  <CometChatQuickReactions
@@ -141,7 +137,10 @@ export const MessageOptionsSheet: React.FC<MessageOptionsSheetProps> = ({
141
137
  theme={mergedTheme}
142
138
  />
143
139
 
144
- <View style={{ maxHeight: ACTION_SHEET_MAX_HEIGHT }}>
140
+ {/* The list takes whatever height the sheet has left after the rows above it, and
141
+ scrolls within that. A fixed cap has to guess the height of those rows, and a guess
142
+ that misses pushes the last options below the screen where they can't be reached. */}
143
+ <View style={{ flexShrink: 1 }}>
145
144
  <CometChatActionSheet
146
145
  actions={quickActions.list}
147
146
  style={mergedTheme.messageListStyles.messageOptionsStyles}
@@ -20,7 +20,8 @@
20
20
  * @module CometChatPinnedMessages
21
21
  */
22
22
  import { CometChat } from "@cometchat/chat-sdk-react-native";
23
- import Clipboard from "@react-native-clipboard/clipboard";
23
+ import { ClipboardPasteHandler } from "../shared/views/ClipboardPasteHandler/ClipboardPasteHandler";
24
+ import { stripRichText } from "../shared/utils/stripRichText";
24
25
  import React, { JSX, useCallback, useEffect, useMemo, useRef, useState } from "react";
25
26
  import { FlatList, NativeModules, Pressable, Text, View } from "react-native";
26
27
  import { ChatConfigurator } from "../shared";
@@ -56,6 +57,9 @@ import {
56
57
  } from "../shared/utils/PinSaveHelper";
57
58
  import { CometChatUIEventHandler } from "../shared/events/CometChatUIEventHandler/CometChatUIEventHandler";
58
59
  import { MessageEvents } from "../shared/events/messages";
60
+ import { CometChatTextFormatter } from "../shared/formatters/CometChatTextFormatter";
61
+ import { applyRawFormatters } from "../shared/formatters/applyRawFormatters";
62
+ import { buildPinnedMessagesRequest } from "../shared/utils/PinnedMessagesHelper";
59
63
 
60
64
  /**
61
65
  * The options this panel is willing to show, as an ALLOW-LIST.
@@ -106,6 +110,19 @@ export interface CometChatPinnedMessagesInterface {
106
110
  group?: CometChat.Group;
107
111
  /** Page size. Defaults to 30; the server caps a conversation at 100. */
108
112
  limit?: number;
113
+ /**
114
+ * Your own request builder, for anything `limit` alone cannot express — a search
115
+ * term, a category or type filter, a different page size.
116
+ *
117
+ * `setPinnedOnly(true)` and the `user`/`group` conversation scope are re-asserted
118
+ * on whatever you pass, so a builder that forgets them still returns this
119
+ * conversation's pinned messages rather than ordinary history. Set them anyway to
120
+ * keep the intent readable.
121
+ *
122
+ * The `limit` prop wins: `limit={10}` with a builder that calls `setLimit(50)` pages
123
+ * in tens. Without the prop the builder's own limit is used, and with neither, 30.
124
+ */
125
+ messagesRequestBuilder?: CometChat.MessagesRequestBuilder;
109
126
  /** Closes the panel — rendered as the ✕ in the header. */
110
127
  onBack?: () => void;
111
128
  /** Tapping a row — the host jumps its message list to this message. */
@@ -127,6 +144,12 @@ export interface CometChatPinnedMessagesInterface {
127
144
  /** Hide Unsave in the long-press sheet (§6.7). */
128
145
  hideUnsaveMessageOption?: boolean;
129
146
  ItemView?: (message: CometChat.BaseMessage) => JSX.Element;
147
+ /**
148
+ * Text formatters, same array the host passes to CometChatMessageList. The panel renders real
149
+ * bubbles, so without this a consumer's own token reaches the template unrecognised and the
150
+ * pinned copy of a message reads differently from the same message in the list.
151
+ */
152
+ textFormatters?: Array<CometChatTextFormatter>;
130
153
  title?: string;
131
154
  /** Per-instance style overrides, merged over the theme's pinnedMessagesStyles. */
132
155
  style?: DeepPartial<PinnedMessagesStyle>;
@@ -139,6 +162,7 @@ export const CometChatPinnedMessages = (props: CometChatPinnedMessagesInterface)
139
162
  user,
140
163
  group,
141
164
  limit,
165
+ messagesRequestBuilder,
142
166
  onBack,
143
167
  onItemPress,
144
168
  hideUnpinMessageOption = false,
@@ -148,6 +172,7 @@ export const CometChatPinnedMessages = (props: CometChatPinnedMessagesInterface)
148
172
  hideShareMessageOption = false,
149
173
  hideMessageInfoOption = false,
150
174
  ItemView,
175
+ textFormatters,
151
176
  title,
152
177
  style,
153
178
  } = props;
@@ -223,17 +248,10 @@ export const CometChatPinnedMessages = (props: CometChatPinnedMessagesInterface)
223
248
  * A factory rather than an inline build: a request is single-use, so retrying after
224
249
  * an error needs a fresh one.
225
250
  */
226
- const buildRequest = useCallback(() => {
227
- const builder = new CometChat.MessagesRequestBuilder().setPinnedOnly(true);
228
- // ALWAYS set. The SDK has no default: a request that never called setLimit() is
229
- // rejected with SET_LIMIT_IS_COMPULSORY before any network call. 30 matches the
230
- // SDK's own DEFAULT_VALUES.MSGS_LIMIT.
231
- builder.setLimit(limit ?? 30);
232
- // Exactly one of these; the SDK rejects neither-set.
233
- if (group) builder.setGUID(group.getGuid());
234
- else if (user) builder.setUID(user.getUid());
235
- return builder.build();
236
- }, [limit, group, user]);
251
+ const buildRequest = useCallback(
252
+ () => buildPinnedMessagesRequest({ user, group, limit, messagesRequestBuilder }),
253
+ [limit, group, user, messagesRequestBuilder]
254
+ );
237
255
 
238
256
  if (request.current === null) request.current = buildRequest();
239
257
 
@@ -483,8 +501,8 @@ export const CometChatPinnedMessages = (props: CometChatPinnedMessagesInterface)
483
501
  }, [group, user]);
484
502
 
485
503
  const templates: CometChatMessageTemplate[] = useMemo(
486
- () => ChatConfigurator.dataSource.getAllMessageTemplates(theme),
487
- [theme]
504
+ () => ChatConfigurator.dataSource.getAllMessageTemplates(theme, { textFormatters }),
505
+ [theme, textFormatters]
488
506
  );
489
507
 
490
508
  const templatesMap = useMemo(() => {
@@ -583,10 +601,15 @@ export const CometChatPinnedMessages = (props: CometChatPinnedMessagesInterface)
583
601
  };
584
602
 
585
603
  const onCopy = (message: CometChat.BaseMessage) => {
586
- // ponytail: raw text, not the mention-resolved string the message list copies via
587
- // its local getPlainString (not exported). Copying "@uid" instead of "@Name" is
588
- // the known ceiling; lift it by extracting that helper into shared/utils.
589
- Clipboard.setString(textOf(message));
604
+ // Via the shared handler, NOT Clipboard directly: it strips the rich-text wire
605
+ // format for the plain clipboard while keeping the rich version for a paste back
606
+ // into our own composer. Copying raw put `<color=#e11d48>` into Notes and mail.
607
+ //
608
+ // ponytail: still the raw text rather than the mention-resolved string the message
609
+ // list copies via its local getPlainString (not exported). Copying "@uid" instead
610
+ // of "@Name" is the known ceiling; lift it by extracting that helper into
611
+ // shared/utils.
612
+ ClipboardPasteHandler.copyMessageText(textOf(message), textFormatters);
590
613
  // Deferred like the message list does: unmounting the Modal while Clipboard is
591
614
  // still touching views crashes Fabric on iOS.
592
615
  requestAnimationFrame(closeSheet);
@@ -597,7 +620,8 @@ export const CometChatPinnedMessages = (props: CometChatPinnedMessagesInterface)
597
620
  message instanceof CometChat.MediaMessage ? message.getAttachment() : undefined;
598
621
  const fileUrl = attachment?.getUrl() ?? "";
599
622
  const shareObj = {
600
- message: textOf(message),
623
+ // Plain text: the share target is another app, which cannot read our wire format.
624
+ message: stripRichText(applyRawFormatters(textOf(message), textFormatters)),
601
625
  type: message.getType(),
602
626
  mediaName: attachment?.getName() ?? "",
603
627
  fileUrl,
@@ -30,6 +30,7 @@ const COMMANDS = {
30
30
  setChecklist: 'setChecklist',
31
31
  setParagraph: 'setParagraph',
32
32
  insertLink: 'insertLink',
33
+ replaceSelection: 'replaceSelection',
33
34
  undo: 'undo',
34
35
  redo: 'redo',
35
36
  clearFormatting: 'clearFormatting',
@@ -213,6 +214,9 @@ const RichTextEditor = forwardRef<RichTextEditorRef, RichTextEditorPropsExtended
213
214
  insertLink: (url: string, text: string) => {
214
215
  dispatchCommand(nativeRef, COMMANDS.insertLink, [url, text]);
215
216
  },
217
+ replaceSelection: (text: string) => {
218
+ dispatchCommand(nativeRef, COMMANDS.replaceSelection, [text]);
219
+ },
216
220
  undo: () => {
217
221
  dispatchCommand(nativeRef, COMMANDS.undo);
218
222
  },
@@ -152,6 +152,8 @@ export interface RichTextEditorRef {
152
152
  setChecklist: () => void;
153
153
  setParagraph: () => void;
154
154
  insertLink: (url: string, text: string) => void;
155
+ /** Replaces the selection with plain text, or inserts at the caret when nothing is selected. */
156
+ replaceSelection: (text: string) => void;
155
157
  undo: () => void;
156
158
  redo: () => void;
157
159
  clearFormatting: () => void;