@cometchat/chat-uikit-react-native 5.4.0 → 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.
@@ -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.
@@ -0,0 +1,76 @@
1
+ # CometChatUIKit.ts — Auth-check refactor
2
+
3
+ ## What changed
4
+
5
+ The `checkAuthSettings()` helper and its call sites were refactored. The single
6
+ function that did three jobs (predicate + error construction + error
7
+ dispatch via a callback) was split into three small, single-purpose pieces:
8
+
9
+ | Member | Kind | Responsibility |
10
+ | --- | --- | --- |
11
+ | `checkAuthSettings()` | public, pure predicate | Returns `true` when the UIKit is configured well enough to make authenticated calls (`uiKitSettings != null && uiKitSettings.appId` set). No side effects. |
12
+ | `authError()` | private factory | Single source of truth for the "not initialized" exception. Returns the correct `CometChatException` (`code: "ERR"` when settings are null, `code: "appIdErr"` when only `appId` is missing). |
13
+ | `assertInitialized()` | private guard | Throws `authError()` when unconfigured. Safe in both `async` methods (the throw becomes a rejected promise) and sync methods that are caught. |
14
+
15
+ Call sites updated:
16
+
17
+ - `getLoggedInUser()` / `login()` → `CometChatUIKit.assertInitialized();`
18
+ - `logout()` / `createUser()` / `updateUser()` → `if (!this.checkAuthSettings()) return Promise.reject(this.authError());`
19
+
20
+ ## Why it was necessary
21
+
22
+ The old `checkAuthSettings(onError)` took an error callback and returned a
23
+ boolean, and **every call site was using it incorrectly** — the guard either
24
+ did nothing or did the opposite of what was intended:
25
+
26
+ 1. **No-op guards (`getLoggedInUser`, `login`)**
27
+
28
+ ```ts
29
+ if (CometChatUIKit.checkAuthSettings(Promise.reject)) null;
30
+ ```
31
+
32
+ `Promise.reject` was passed as the `onError` callback, but its return value
33
+ was discarded and the `if` body was just `null`. When settings were missing
34
+ the method continued anyway instead of stopping — so the guard provided **no
35
+ protection at all**.
36
+
37
+ 2. **Inverted logic (`logout`)**
38
+
39
+ ```ts
40
+ if (this.checkAuthSettings(Promise.reject)) {
41
+ return Promise.reject(/* not initialized */);
42
+ }
43
+ ```
44
+
45
+ `checkAuthSettings` returned `true` when the UIKit **was** properly
46
+ configured. So this rejected with "UIKit not initialized" exactly when it
47
+ *was* initialized, and proceeded when it was not — **backwards**.
48
+
49
+ 3. **Empty guards (`createUser`, `updateUser`)**
50
+
51
+ ```ts
52
+ if (this.checkAuthSettings(Promise.reject)) {
53
+ }
54
+ ```
55
+
56
+ Empty body. The only effect was the `Promise.reject` callback firing as a
57
+ side effect, creating an unhandled rejection while the method continued.
58
+
59
+ The root cause was a function that mixed a **predicate** with **error
60
+ dispatch**, which made every call site ambiguous and easy to get wrong. After
61
+ the split:
62
+
63
+ - `checkAuthSettings()` reads as a plain question — `if (!checkAuthSettings())`
64
+ is unambiguous.
65
+ - Async methods `assertInitialized()` (throw → rejected promise).
66
+ - The exception text/codes live in one place (`authError()`), so the
67
+ "call `init()` first" message is consistent everywhere.
68
+
69
+ ## Behavioral result
70
+
71
+ Every public entry point now **actually fails fast** with the correct
72
+ `CometChatException` when the UIKit has not been initialized, instead of
73
+ silently continuing or rejecting on the wrong condition.
74
+
75
+ The accompanying test file `__tests__/CometChatUIKit.test.ts` was updated to
76
+ cover these guards.
@@ -0,0 +1,211 @@
1
+ # `checkAuthSettings` — Code Review & Recommended Approach
2
+
3
+ > File: `packages/ChatUiKit/src/shared/CometChatUiKit/CometChatUIKit.ts`
4
+ > Trigger: "is using `!` the best approach in `if (!this.checkAuthSettings(Promise.reject))`?"
5
+ > Verified against source on review date — **5** call sites, line numbers below.
6
+
7
+ ---
8
+
9
+ ## 1. TL;DR
10
+
11
+ - The `!` you asked about is the **logical NOT operator**, not a TypeScript non-null assertion. It is
12
+ correct and idiomatic — **keep it**. It was never the problem.
13
+ - The real problems sit *around* it:
14
+ 1. `checkAuthSettings` is a **side-effecting predicate** — it returns a `boolean` *and* fires an
15
+ `onError` callback. (line 323)
16
+ 2. Every caller passes `Promise.reject` as that callback, which creates a **floating, unhandled
17
+ rejected promise**.
18
+ 3. `logout()` is the only caller that branches correctly — but it **double-fires** the error.
19
+ 4. The other **four** callers (`getLoggedInUser`, `login`, `createUser`, `updateUser`) use the guard
20
+ as a **no-op** — validation is silently skipped.
21
+ 5. Separately: `uiKitSettings` is typed non-optional but is `undefined` until `init()` runs — the
22
+ type lies, which is what lets the unsafe `.authKey` access compile.
23
+
24
+ ---
25
+
26
+ ## 2. Call-site inventory (verified)
27
+
28
+ | Method | Line | Form | Effect |
29
+ | --- | --- | --- | --- |
30
+ | `getLoggedInUser` | 220 | `if (checkAuthSettings(Promise.reject)) null;` | **no-op** |
31
+ | `login` | 267 | `if (checkAuthSettings(Promise.reject)) null;` | **no-op** |
32
+ | `logout` | 293 | `if (!checkAuthSettings(Promise.reject)) { return Promise.reject(...) }` | branches, but double-fires |
33
+ | `createUser` | 309 | `if (checkAuthSettings(Promise.reject)) { }` | **no-op** |
34
+ | `updateUser` | 316 | `if (checkAuthSettings(Promise.reject)) { }` | **no-op** |
35
+
36
+ ---
37
+
38
+ ## 3. The guard itself (line 323)
39
+
40
+ ```ts
41
+ // returns boolean AND calls onError as a side effect
42
+ static checkAuthSettings(onError: (e: CometChat.CometChatException) => void): boolean {
43
+ if (this.uiKitSettings == null) {
44
+ if (onError != null) {
45
+ onError(new CometChat.CometChatException({
46
+ code: "ERR", name: "Authentication null",
47
+ message: "Populate authSettings before initializing",
48
+ }));
49
+ }
50
+ return false;
51
+ }
52
+ if (!this.uiKitSettings?.appId) {
53
+ if (onError != null) {
54
+ onError(new CometChat.CometChatException({
55
+ code: "appIdErr", name: "APP ID null",
56
+ message: "Populate appId in authSettings before initializing",
57
+ }));
58
+ }
59
+ return false;
60
+ }
61
+ return true;
62
+ }
63
+ ```
64
+
65
+ ---
66
+
67
+ ## 4. Why this is a problem
68
+
69
+ ### 4.1 `Promise.reject` as a callback → unhandled rejection
70
+ `Promise.reject(error)` does **not** reject the calling function. It synchronously constructs a new,
71
+ already-rejected promise that nobody awaits or `.catch()`es. On Hermes/Node this surfaces as an
72
+ `UnhandledPromiseRejection` — noise at best, a crash signal at worst.
73
+
74
+ ### 4.2 Dual contract (command + query)
75
+ `checkAuthSettings` both **answers a question** (is config valid?) and **performs an action** (fire the
76
+ error). Callers can't tell from the signature that calling it has side effects — which is precisely how
77
+ the no-op call sites slipped in. A predicate should be pure.
78
+
79
+ ### 4.3 `logout()` double-fires (line 293)
80
+ ```ts
81
+ if (!this.checkAuthSettings(Promise.reject)) { // (a) fires Promise.reject(error) internally
82
+ return Promise.reject(new CometChat.CometChatException({ code: "ERR", ... })); // (b) fires again
83
+ }
84
+ ```
85
+ `(a)` is an unhandled rejection that also carries the *more specific* code (`appIdErr` when appId is
86
+ missing); `(b)` is the real return but always uses the generic `ERR`. One failure, two error objects,
87
+ worse error code.
88
+
89
+ ### 4.4 Four call sites validate nothing
90
+ `if (cond) null;` and `if (cond) {}` are no-ops — the result is computed and thrown away. `getLoggedInUser`,
91
+ `login`, `createUser`, and `updateUser` proceed even when `uiKitSettings` is `null`, deferring to a
92
+ later, more cryptic crash (e.g. `this.uiKitSettings.authKey` reading a property of `undefined`).
93
+
94
+ ### 4.5 The type lies (line 21)
95
+ ```ts
96
+ static uiKitSettings: UIKitSettings; // declared always-present, but undefined until init()
97
+ ```
98
+ Because the declared type is non-optional, TypeScript believes `this.uiKitSettings.authKey` is always
99
+ safe — so the unsafe access in `createUser`/`updateUser` compiles cleanly. The type should be
100
+ `UIKitSettings | undefined` so the compiler forces a guard.
101
+
102
+ ---
103
+
104
+ ## 5. Recommended approach
105
+
106
+ Make `checkAuthSettings` a **pure predicate**, centralize the exception in a factory, and let each
107
+ caller decide how to report failure. Throwing assertions (no eager `Promise.reject`) avoid
108
+ re-introducing the unhandled-rejection footgun.
109
+
110
+ > ⚠️ **Breaking change:** dropping `onError` changes the signature of the `static` (public)
111
+ > `checkAuthSettings`. Grep the repo + consuming apps and migrate all callers, or keep `onError`
112
+ > optional and ignore it. Treat as a semver-minor/major change, not a drop-in edit.
113
+
114
+ ### 5.1 Pure predicate + error factory + throwing assert
115
+ ```ts
116
+ /** Pure predicate: is the UIKit configured well enough to make authenticated calls? */
117
+ static checkAuthSettings(): boolean {
118
+ return this.uiKitSettings != null && !!this.uiKitSettings.appId;
119
+ }
120
+
121
+ /** Single source of truth for the "not initialized" exception (preserves the specific code). */
122
+ private static authError(): CometChat.CometChatException {
123
+ if (this.uiKitSettings == null) {
124
+ return new CometChat.CometChatException({
125
+ code: "ERR", name: "Authentication null",
126
+ message: "Populate authSettings before initializing. Call CometChatUIKit.init() first.",
127
+ });
128
+ }
129
+ return new CometChat.CometChatException({
130
+ code: "appIdErr", name: "APP ID null",
131
+ message: "Populate appId in authSettings before initializing.",
132
+ });
133
+ }
134
+
135
+ /** Throws the right exception when unconfigured. Works in sync (caught below) and async methods. */
136
+ private static assertInitialized(): void {
137
+ if (!this.checkAuthSettings()) throw this.authError();
138
+ }
139
+ ```
140
+
141
+ ### 5.2 Call sites — async methods just `throw`
142
+ ```ts
143
+ static async getLoggedInUser(): Promise<CometChat.User> {
144
+ this.assertInitialized(); // rejection is automatic in an async fn
145
+ // ...existing logic
146
+ }
147
+
148
+ static async login({ uid, authToken }: { uid?: string; authToken?: string }): Promise<CometChat.User> {
149
+ this.assertInitialized(); // keep the destructured params — body uses uid/authToken
150
+ // ...existing logic
151
+ }
152
+ ```
153
+
154
+ ### 5.3 Call sites — sync methods return a rejected promise once
155
+ ```ts
156
+ static logout(): Promise<Object> {
157
+ if (!this.checkAuthSettings()) return Promise.reject(this.authError()); // single fire, correct code
158
+ return CometChat.logout().then(() => {
159
+ CometChatUIKit.loggedInUser = null;
160
+ return {};
161
+ });
162
+ }
163
+
164
+ static createUser(user: CometChat.User): Promise<CometChat.User> {
165
+ if (!this.checkAuthSettings()) return Promise.reject(this.authError());
166
+ // authKey is safe here because checkAuthSettings() guaranteed uiKitSettings is set
167
+ return CometChat.createUser(user, this.uiKitSettings.authKey as string);
168
+ }
169
+
170
+ static updateUser(user: CometChat.User): Promise<CometChat.User> {
171
+ if (!this.checkAuthSettings()) return Promise.reject(this.authError());
172
+ return CometChat.updateUser(user, this.uiKitSettings.authKey as string);
173
+ }
174
+ ```
175
+
176
+ > Why not a `requireAuth()` helper that returns a `Promise.reject`? Because building the rejected
177
+ > promise inside the helper makes it float unhandled for a microtask if the caller `await`s anything
178
+ > before returning it — re-creating bug 4.1. A **throwing** assert has no such window.
179
+
180
+ ---
181
+
182
+ ## 6. Before / After
183
+
184
+ | Concern | Before | After |
185
+ | --- | --- | --- |
186
+ | `checkAuthSettings` contract | boolean **+** side effect | pure boolean predicate |
187
+ | `checkAuthSettings` signature | `(onError)` | `()` — **breaking; migrate callers** |
188
+ | Unhandled rejections | yes (`Promise.reject` as callback) | none (throw / single return) |
189
+ | `logout` error firing | twice; generic code wins | once; specific code preserved |
190
+ | `getLoggedInUser` / `login` validation | no-op (`if (...) null;`) | real guard |
191
+ | `createUser` / `updateUser` validation | no-op (empty block) | real guard |
192
+ | Error message source | duplicated inline ×5 | single `authError()` factory |
193
+ | `uiKitSettings` type | non-optional (lies) | `UIKitSettings \| undefined` (optional improvement) |
194
+
195
+ ---
196
+
197
+ ## 7. Answer to the original question
198
+
199
+ `if (!this.checkAuthSettings())` is the clearest way to express "bail out when config is invalid" — the
200
+ `!` is correct and should stay. What actually deserved scrutiny was the side-effecting validator and the
201
+ `Promise.reject`-as-callback pattern wrapped around it. Fix those (pure predicate + factory + throwing
202
+ assert) and the `!` reads exactly as intended at every call site.
203
+
204
+ ---
205
+
206
+ ## 8. Follow-ups (out of scope here)
207
+
208
+ - Change `uiKitSettings` to `UIKitSettings | undefined` so the compiler enforces the guard.
209
+ - Add unit tests asserting each public method rejects with the right `code` when `uiKitSettings` is
210
+ `null` and when `appId` is missing (covers all 5 call sites).
211
+ - Consider a lint rule against expression-statement no-ops (`if (x) null;`) to prevent regressions.
@@ -2,6 +2,7 @@ import { CometChat } from "@cometchat/chat-sdk-react-native";
2
2
  import React, { JSX } from "react";
3
3
  import { Text, TextStyle, ViewStyle, Platform, Linking, View } from "react-native";
4
4
  import { CometChatTextFormatter } from "../CometChatTextFormatter";
5
+ import { isTextElement, isViewElement } from "../../utils/elementType";
5
6
 
6
7
  /**
7
8
  * Style configuration for rich text formatting
@@ -510,7 +511,7 @@ export class CometChatRichTextFormatter extends CometChatTextFormatter {
510
511
  // Skip groups that are only newline/whitespace Text nodes — these appear
511
512
  // between list blocks and would render as blank lines in the bubble.
512
513
  const isOnlyWhitespace = textGroup.every(el => {
513
- if (el.type !== Text) return false;
514
+ if (!isTextElement(el)) return false;
514
515
  const child = el.props?.children;
515
516
  return typeof child === 'string' && child.trim() === '';
516
517
  });
@@ -524,7 +525,7 @@ export class CometChatRichTextFormatter extends CometChatTextFormatter {
524
525
  };
525
526
 
526
527
  for (const el of elements) {
527
- if (el.type === View) {
528
+ if (isViewElement(el)) {
528
529
  flushTextGroup();
529
530
  grouped.push(el);
530
531
  } else {
@@ -9,6 +9,7 @@ import { stripMarkdown, preparePreviewText } from "../MarkdownUtils";
9
9
  import { CometChatRichTextFormatter } from "../../formatters/CometChatRichTextFormatter";
10
10
  import { applyMentionsFormatting } from "../MessageUtils";
11
11
  import { attachmentCountLabel } from "../conversationUtils";
12
+ import { isViewElement } from "../elementType";
12
13
 
13
14
  const t = getCometChatTranslation();
14
15
 
@@ -331,7 +332,7 @@ const CometChatMessagePreview = (props: CometChatMessagePreviewProps) => {
331
332
  // Detect if the formatter returned a View root (block-level content that
332
333
  // slipped through preparePreviewText). View can't nest inside Text, so we
333
334
  // render it in a height-constrained View wrapper instead.
334
- const isViewRoot = isRichSubtitle && React.isValidElement(messageText) && (messageText as React.ReactElement<any>).type === View;
335
+ const isViewRoot = isRichSubtitle && React.isValidElement(messageText) && isViewElement(messageText);
335
336
 
336
337
  return (
337
338
  <View style={containerStyle}>