@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.
- package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +63 -1
- package/ios/RichTextEditorView.swift +55 -4
- package/package.json +2 -1
- package/src/CometChatMessageList/PERFORMANCE_ARCHITECTURE.md +478 -0
- package/src/CometChatMessageList/SEARCH_NAV_PERF_PLAN.md +613 -0
- package/src/CometChatMessageList/SEARCH_NAV_SLOWNESS_FINDINGS_AND_FIX.md +313 -0
- package/src/shared/CometChatUiKit/CometChatUIKit.changes.md +76 -0
- package/src/shared/CometChatUiKit/checkAuthSettings-review.md +211 -0
- package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +3 -2
- package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +2 -1
- package/src/shared/utils/elementType.tsx +38 -0
- package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +27 -14
- package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +4 -3
- package/android/.gradle/7.4/checksums/checksums.lock +0 -0
- package/android/.gradle/7.4/fileChanges/last-build.bin +0 -0
- package/android/.gradle/7.4/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/7.4/gc.properties +0 -0
- package/android/.gradle/vcs-1/gc.properties +0 -0
- package/src/CometChatMessageList/MANUAL_TEST_CASES.md +0 -154
|
@@ -31,6 +31,7 @@ import android.view.View
|
|
|
31
31
|
import android.view.ViewGroup
|
|
32
32
|
import android.view.WindowManager
|
|
33
33
|
import android.view.inputmethod.EditorInfo
|
|
34
|
+
import android.view.inputmethod.InputMethodManager
|
|
34
35
|
import android.widget.PopupWindow
|
|
35
36
|
import android.widget.FrameLayout
|
|
36
37
|
import android.content.res.Configuration
|
|
@@ -236,6 +237,62 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
|
|
|
236
237
|
}
|
|
237
238
|
})
|
|
238
239
|
|
|
240
|
+
// ── Typing traits (autocorrect / autocapitalize / spellcheck) ────────────────
|
|
241
|
+
//
|
|
242
|
+
// Autocorrect / sentence capitalization / suggestions are never pinned to a fixed
|
|
243
|
+
// value. In prose the editor asks for exactly the flags RN's own
|
|
244
|
+
// ReactTextInputManager emits for a plain TextInput, so the IME's language and the
|
|
245
|
+
// user's keyboard settings decide; on top of that the editor drops all of them by
|
|
246
|
+
// itself while the caret sits in code (see [isCodeContext]), so autocorrect never
|
|
247
|
+
// rewrites a code sample.
|
|
248
|
+
|
|
249
|
+
/** True while the caret/selection sits inside a code block or an inline code span. */
|
|
250
|
+
private var isCodeContext = false
|
|
251
|
+
|
|
252
|
+
/** Called on every selection/style update with the resolved code state. */
|
|
253
|
+
private fun setCodeContext(inCode: Boolean) {
|
|
254
|
+
if (inCode == isCodeContext) return
|
|
255
|
+
isCodeContext = inCode
|
|
256
|
+
applyTypingTraits()
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Resolves inputType for the caret's current context and applies it, restarting the
|
|
261
|
+
* IME only when the resolved value actually changed — i.e. when the caret crosses a
|
|
262
|
+
* code boundary, never mid-word in prose.
|
|
263
|
+
*/
|
|
264
|
+
private fun applyTypingTraits() {
|
|
265
|
+
var flags = EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
|
|
266
|
+
|
|
267
|
+
flags = flags or if (isCodeContext) {
|
|
268
|
+
// Capitalizing `teh` to `Teh` inside a code block corrupts the snippet the
|
|
269
|
+
// user is typing, so code always opts out.
|
|
270
|
+
EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS
|
|
271
|
+
} else {
|
|
272
|
+
// The RN TextInput defaults: autoCapitalize="sentences" + autoCorrect=true.
|
|
273
|
+
EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES or EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (inputType == flags) return
|
|
277
|
+
|
|
278
|
+
// setInputType() rebuilds the key listener; it only rewrites text/typeface for
|
|
279
|
+
// password variations (never our case), but the caret is restored defensively.
|
|
280
|
+
val selStart = selectionStart
|
|
281
|
+
val selEnd = selectionEnd
|
|
282
|
+
inputType = flags
|
|
283
|
+
if (selStart in 0..length() && selEnd in 0..length() &&
|
|
284
|
+
(selectionStart != selStart || selectionEnd != selEnd)
|
|
285
|
+
) {
|
|
286
|
+
setSelection(selStart, selEnd)
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// The IME reads the flags when input starts, so a keyboard already up needs a restart.
|
|
290
|
+
if (hasFocus()) {
|
|
291
|
+
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)
|
|
292
|
+
?.restartInput(this)
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
239
296
|
init {
|
|
240
297
|
density = context.resources.displayMetrics.density
|
|
241
298
|
minHeightPx = 64 * density
|
|
@@ -253,7 +310,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
|
|
|
253
310
|
gravity = Gravity.TOP or Gravity.START
|
|
254
311
|
isFocusable = true
|
|
255
312
|
isFocusableInTouchMode = true
|
|
256
|
-
|
|
313
|
+
applyTypingTraits()
|
|
257
314
|
|
|
258
315
|
// Disable vertical scrolling by default
|
|
259
316
|
isVerticalScrollBarEnabled = false
|
|
@@ -1577,6 +1634,11 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
|
|
|
1577
1634
|
}
|
|
1578
1635
|
}
|
|
1579
1636
|
val codeBlockActive = hasCodeBlock || pendingStyles.contains("codeBlock")
|
|
1637
|
+
|
|
1638
|
+
// Autocorrect/autocapitalize/spellcheck follow the caret: off in code, platform
|
|
1639
|
+
// default everywhere else.
|
|
1640
|
+
setCodeContext(codeActive || codeBlockActive)
|
|
1641
|
+
|
|
1580
1642
|
map.putBoolean("code", codeActive)
|
|
1581
1643
|
map.putBoolean("codeBlock", codeBlockActive)
|
|
1582
1644
|
map.putBoolean("highlight", hasHighlight)
|
|
@@ -613,9 +613,6 @@ class RichTextView: UITextView {
|
|
|
613
613
|
}
|
|
614
614
|
|
|
615
615
|
private func disableAutofill() {
|
|
616
|
-
autocorrectionType = .no
|
|
617
|
-
autocapitalizationType = .none
|
|
618
|
-
spellCheckingType = .no
|
|
619
616
|
smartQuotesType = .no
|
|
620
617
|
smartDashesType = .no
|
|
621
618
|
smartInsertDeleteType = .no
|
|
@@ -637,6 +634,15 @@ class RichTextView: UITextView {
|
|
|
637
634
|
|
|
638
635
|
isSecureTextEntry = true
|
|
639
636
|
isSecureTextEntry = false
|
|
637
|
+
|
|
638
|
+
// The secure round-trip above rebuilds the input traits and leaves autocorrect
|
|
639
|
+
// and spell check suppressed, so the typing traits have to be re-asserted AFTER
|
|
640
|
+
// it — assigning them earlier in this method does not survive. `.default` and
|
|
641
|
+
// `.sentences` are the "let the platform decide" values, the same ones a plain
|
|
642
|
+
// UITextView / RN TextInput starts from; nothing is pinned on or off here.
|
|
643
|
+
autocorrectionType = .default
|
|
644
|
+
autocapitalizationType = .sentences
|
|
645
|
+
spellCheckingType = .default
|
|
640
646
|
}
|
|
641
647
|
|
|
642
648
|
/// Custom drawing for blockquote vertical bars (matches Android onDraw implementation).
|
|
@@ -969,6 +975,48 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
|
|
|
969
975
|
|
|
970
976
|
@objc var showToolbar: Bool = true
|
|
971
977
|
|
|
978
|
+
// MARK: - Typing traits
|
|
979
|
+
// Autocorrect / autocapitalization / spell check are never pinned to a fixed value.
|
|
980
|
+
// In prose the text view is left at the UIKit defaults — the same behaviour a plain
|
|
981
|
+
// RN `TextInput` gets for free, so the keyboard's own language and user settings
|
|
982
|
+
// decide — and the editor drops all three by itself while the caret sits in code
|
|
983
|
+
// (see `isCodeContext`), so autocorrect never rewrites a code sample.
|
|
984
|
+
private var isCodeContext = false
|
|
985
|
+
|
|
986
|
+
|
|
987
|
+
private func applyTypingTraits() {
|
|
988
|
+
let correction: UITextAutocorrectionType
|
|
989
|
+
let capitalization: UITextAutocapitalizationType
|
|
990
|
+
let spellChecking: UITextSpellCheckingType
|
|
991
|
+
|
|
992
|
+
if isCodeContext {
|
|
993
|
+
correction = .no
|
|
994
|
+
capitalization = .none
|
|
995
|
+
spellChecking = .no
|
|
996
|
+
} else {
|
|
997
|
+
correction = .default
|
|
998
|
+
capitalization = .sentences
|
|
999
|
+
spellChecking = .default
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
guard textView.autocorrectionType != correction
|
|
1003
|
+
|| textView.autocapitalizationType != capitalization
|
|
1004
|
+
|| textView.spellCheckingType != spellChecking else { return }
|
|
1005
|
+
|
|
1006
|
+
textView.autocorrectionType = correction
|
|
1007
|
+
textView.autocapitalizationType = capitalization
|
|
1008
|
+
textView.spellCheckingType = spellChecking
|
|
1009
|
+
if textView.isFirstResponder {
|
|
1010
|
+
textView.reloadInputViews()
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
private func setCodeContext(_ inCode: Bool) {
|
|
1015
|
+
guard inCode != isCodeContext else { return }
|
|
1016
|
+
isCodeContext = inCode
|
|
1017
|
+
applyTypingTraits()
|
|
1018
|
+
}
|
|
1019
|
+
|
|
972
1020
|
/// When true, Bold/Italic/Underline/Strikethrough appear in the text selection context menu.
|
|
973
1021
|
@objc var showTextSelectionMenuItems: Bool = true {
|
|
974
1022
|
didSet {
|
|
@@ -1444,6 +1492,7 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
|
|
|
1444
1492
|
let checkRange = range.length > 0 ? range : NSRange(location: max(0, range.location - 1), length: 1)
|
|
1445
1493
|
|
|
1446
1494
|
guard checkRange.location >= 0, checkRange.location < attributedText.length else {
|
|
1495
|
+
setCodeContext(pendingStyles.contains("code") || pendingStyles.contains("codeBlock"))
|
|
1447
1496
|
onActiveStylesChange?([
|
|
1448
1497
|
"bold": pendingStyles.contains("bold") && !explicitlyOffStyles.contains("bold"),
|
|
1449
1498
|
"italic": pendingStyles.contains("italic") && !explicitlyOffStyles.contains("italic"),
|
|
@@ -1574,13 +1623,15 @@ class RichTextEditorView: UIView, UITextViewDelegate, UIGestureRecognizerDelegat
|
|
|
1574
1623
|
}
|
|
1575
1624
|
}
|
|
1576
1625
|
let codeBlockActive = hasCodeBlock || pendingStyles.contains("codeBlock")
|
|
1626
|
+
let codeActive = (hasCode || pendingStyles.contains("code") || pendingStyles.contains("codeBlock")) && !explicitlyOffStyles.contains("code")
|
|
1627
|
+
setCodeContext(codeActive || codeBlockActive)
|
|
1577
1628
|
|
|
1578
1629
|
onActiveStylesChange?([
|
|
1579
1630
|
"bold": (hasBold || pendingStyles.contains("bold")) && !explicitlyOffStyles.contains("bold"),
|
|
1580
1631
|
"italic": (hasItalic || pendingStyles.contains("italic")) && !explicitlyOffStyles.contains("italic"),
|
|
1581
1632
|
"underline": (hasUnderline || pendingStyles.contains("underline")) && !explicitlyOffStyles.contains("underline"),
|
|
1582
1633
|
"strikethrough": (hasStrikethrough || pendingStyles.contains("strikethrough")) && !explicitlyOffStyles.contains("strikethrough"),
|
|
1583
|
-
"code":
|
|
1634
|
+
"code": codeActive,
|
|
1584
1635
|
"codeBlock": codeBlockActive,
|
|
1585
1636
|
"highlight": hasHighlight,
|
|
1586
1637
|
"blockType": blockType,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cometchat/chat-uikit-react-native",
|
|
3
|
-
"version": "5.4.
|
|
3
|
+
"version": "5.4.1",
|
|
4
4
|
"description": "Ready-to-use Chat UI Components for React Native",
|
|
5
5
|
"main": "src/index",
|
|
6
6
|
"module": "src/index",
|
|
@@ -82,6 +82,7 @@
|
|
|
82
82
|
"react-native": "*",
|
|
83
83
|
"react-native-gesture-handler": "*",
|
|
84
84
|
"react-native-localize": "*",
|
|
85
|
+
"react-native-safe-area-context": "*",
|
|
85
86
|
"react-native-svg": "*",
|
|
86
87
|
"react-native-video": "*"
|
|
87
88
|
},
|
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
# CometChatMessageList — Performance & Crash Fix Architecture
|
|
2
|
+
|
|
3
|
+
**Ticket:** ENG-35194
|
|
4
|
+
**Platform:** React Native (Android physical devices — Hermes engine)
|
|
5
|
+
**Component:** `CometChatMessageList.tsx` (~4800 lines)
|
|
6
|
+
**Constraint:** Zero public API/prop changes. All existing props remain identical.
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## 1. Problem Statement
|
|
11
|
+
|
|
12
|
+
When opening a group or user conversation via search results (links or messages), the app crashes or freezes on physical Android devices. The issue occurs specifically when the conversation has a large message history (1000+ messages).
|
|
13
|
+
|
|
14
|
+
### Reproduction Steps
|
|
15
|
+
1. Go to conversation list
|
|
16
|
+
2. Open Search → Click "Links" section
|
|
17
|
+
3. Tap any link result from a large group
|
|
18
|
+
4. Observe: screen stuck / app crashes
|
|
19
|
+
|
|
20
|
+
### Root Cause Summary
|
|
21
|
+
|
|
22
|
+
The crash is caused by a **cascade of expensive operations** triggered simultaneously on the single JS thread (Hermes, no JIT):
|
|
23
|
+
|
|
24
|
+
| Operation | Frequency | Cost on Hermes |
|
|
25
|
+
|-----------|-----------|----------------|
|
|
26
|
+
| `setItemPositions` (state update per message layout) | N per render batch | Re-render entire FlatList |
|
|
27
|
+
| `onEndReached` → `getPreviousMessages` | Fires immediately (16 msgs don't fill screen) | 30 more messages + all associated operations |
|
|
28
|
+
| `[...array]` spread copies | Every mutation | O(n) allocation |
|
|
29
|
+
| `onLoad([...list].reverse())` | Every mutation | O(n) copy + O(n) reverse |
|
|
30
|
+
| `rebuildMessageIndex()` | Every mutation | O(n) iteration |
|
|
31
|
+
| `CommonUtils.clone()` (deep clone) | Every message update | Expensive on Hermes (Reflect.ownKeys + descriptors) |
|
|
32
|
+
|
|
33
|
+
On iOS (JSC with JIT), these complete in ~200ms total. On Android (Hermes), they take 800-2000ms, exceeding the ANR threshold and causing OOM crashes.
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## 2. Current Architecture (Before Fix)
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
Search tap → CommonActions.reset → Messages screen mounts
|
|
41
|
+
→ CometChatMessageList mounts
|
|
42
|
+
→ useEffect[] fires
|
|
43
|
+
→ getMessagesAroundId(messageId)
|
|
44
|
+
→ Fetches 1 target + 15 next = 16 messages
|
|
45
|
+
→ setMessagesList(16 messages) → FlatList renders
|
|
46
|
+
→ Each message: onLayout → setItemPositions (STATE UPDATE × 16)
|
|
47
|
+
→ setScrollTargetId → scrollToMessage (with retries)
|
|
48
|
+
→ onEndReached fires (16 messages don't fill screen)
|
|
49
|
+
→ getPreviousMessages() → fetches 30 more
|
|
50
|
+
→ [...current, ...30new] spread
|
|
51
|
+
→ rebuildMessageIndex() — iterates 46 items
|
|
52
|
+
→ setMessagesList(46 messages) → FlatList re-renders
|
|
53
|
+
→ onLayout × 30 → setItemPositions (STATE UPDATE × 30)
|
|
54
|
+
→ onLoad([...46items].reverse()) — copy + reverse
|
|
55
|
+
→ onEndReached fires AGAIN
|
|
56
|
+
→ Cycle repeats until 500-cap or crash
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
**Total state updates in first 2 seconds:** ~50-80
|
|
60
|
+
**Total array copies:** ~10-15 (each O(n))
|
|
61
|
+
**Result on Android:** OOM crash or ANR
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## 3. Proposed Architecture (After Fix)
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
Search tap → CommonActions.reset → Messages screen mounts
|
|
69
|
+
→ CometChatMessageList mounts
|
|
70
|
+
→ useEffect[] fires
|
|
71
|
+
→ getMessagesAroundId(messageId)
|
|
72
|
+
→ navigationInProgressRef = true (GATE CLOSED)
|
|
73
|
+
→ Fetches 30 prev + 1 target + 15 next = 46 messages
|
|
74
|
+
→ messagesContentListRef.current = allMessages (ref mutation)
|
|
75
|
+
→ setMessagesList(allMessages) → FlatList renders (SINGLE render)
|
|
76
|
+
→ Each message: onLayout → itemPositionsRef.set() (NO state update)
|
|
77
|
+
→ scrollToMessage completes
|
|
78
|
+
→ navigationInProgressRef = false (GATE OPEN)
|
|
79
|
+
→ onEndReached fires? → blocked by gate → no-op
|
|
80
|
+
→ User scrolls up manually → onEndReached fires → normal pagination
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
**Total state updates in first 2 seconds:** 3 (setMessagesList, setNavigationLoading×2)
|
|
84
|
+
**Total array copies:** 1 (initial setMessagesList)
|
|
85
|
+
**Result on Android:** Smooth, no crash
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 4. Detailed Changes
|
|
90
|
+
|
|
91
|
+
### Phase 1: Stop the Crash (Critical Priority)
|
|
92
|
+
|
|
93
|
+
#### 1.1 — Navigation Pagination Gate
|
|
94
|
+
|
|
95
|
+
**File:** `CometChatMessageList.tsx`
|
|
96
|
+
**Location:** Near refs declaration (~line 974)
|
|
97
|
+
|
|
98
|
+
Add a ref that blocks pagination during initial navigation:
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
const navigationInProgressRef = useRef(false);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**In `getMessagesAroundId`** — set at the start:
|
|
105
|
+
```typescript
|
|
106
|
+
navigationInProgressRef.current = true;
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
**In `scrollToMessage`** — clear after scroll completes (in all completion paths):
|
|
110
|
+
```typescript
|
|
111
|
+
navigationInProgressRef.current = false;
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
**In `getPreviousMessages`** — add early return at top:
|
|
115
|
+
```typescript
|
|
116
|
+
if (navigationInProgressRef.current) {
|
|
117
|
+
loadingPrevMessagesRef.current = false;
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
**In `fetchNextMessages`** — add early return at top:
|
|
123
|
+
```typescript
|
|
124
|
+
if (navigationInProgressRef.current) return;
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
**Risk:** Very Low — only affects the search navigation flow
|
|
128
|
+
**Testing:** Navigate from search to message in large group. Verify messages load, scroll works, no crash.
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
#### 1.2 — Fetch More Messages in `getMessagesAroundId`
|
|
133
|
+
|
|
134
|
+
**File:** `CometChatMessageList.tsx`
|
|
135
|
+
**Location:** Inside `getMessagesAroundId` function (~line 1280)
|
|
136
|
+
|
|
137
|
+
Currently fetches: 1 target + 15 next = 16 messages (doesn't fill screen).
|
|
138
|
+
|
|
139
|
+
Change to fetch: 30 previous + 1 target + 15 next = 46 messages (fills screen).
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
// Add BEFORE the existing nextMessagesRequest:
|
|
143
|
+
let prevMessagesRequest = new CometChat.MessagesRequestBuilder()
|
|
144
|
+
.setLimit(30)
|
|
145
|
+
.setMessageId(targetMessageId);
|
|
146
|
+
|
|
147
|
+
if (user) prevMessagesRequest = prevMessagesRequest.setUID(user.getUid());
|
|
148
|
+
if (group) prevMessagesRequest = prevMessagesRequest.setGUID(group.getGuid());
|
|
149
|
+
if (!parentMessageId) {
|
|
150
|
+
prevMessagesRequest = prevMessagesRequest.hideReplies(true);
|
|
151
|
+
} else {
|
|
152
|
+
prevMessagesRequest = prevMessagesRequest
|
|
153
|
+
.setParentMessageId(Number(parentMessageId))
|
|
154
|
+
.hideReplies(false);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const previousMessages = await prevMessagesRequest.build().fetchPrevious();
|
|
158
|
+
|
|
159
|
+
// Update allMessages combination:
|
|
160
|
+
const allMessages = [
|
|
161
|
+
...previousMessages.reverse(), // oldest→newest, then reverse for inverted list
|
|
162
|
+
targetMessage,
|
|
163
|
+
...nextMessages
|
|
164
|
+
].reverse(); // newest first for inverted FlatList
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
**Risk:** Low — fetches more data upfront but prevents cascade
|
|
168
|
+
**Testing:** Verify target message is visible and centered after navigation. Verify older messages are above it.
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
#### 1.3 — ErrorBoundary per Message Row
|
|
173
|
+
|
|
174
|
+
**File:** New file `CometChatMessageList/components/MessageErrorBoundary.tsx`
|
|
175
|
+
|
|
176
|
+
```typescript
|
|
177
|
+
import React from 'react';
|
|
178
|
+
import { View } from 'react-native';
|
|
179
|
+
|
|
180
|
+
interface Props {
|
|
181
|
+
children: React.ReactNode;
|
|
182
|
+
messageId: string;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
interface State {
|
|
186
|
+
hasError: boolean;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export class MessageErrorBoundary extends React.Component<Props, State> {
|
|
190
|
+
state: State = { hasError: false };
|
|
191
|
+
|
|
192
|
+
static getDerivedStateFromError(): State {
|
|
193
|
+
return { hasError: true };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
componentDidCatch(error: Error) {
|
|
197
|
+
console.warn(
|
|
198
|
+
`[CometChatMessageList] Message ${this.props.messageId} render failed:`,
|
|
199
|
+
error.message
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
render() {
|
|
204
|
+
if (this.state.hasError) {
|
|
205
|
+
return <View style={{ height: 1 }} />;
|
|
206
|
+
}
|
|
207
|
+
return this.props.children;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
**Usage in `MessageListItem.tsx`:**
|
|
213
|
+
```typescript
|
|
214
|
+
import { MessageErrorBoundary } from './MessageErrorBoundary';
|
|
215
|
+
|
|
216
|
+
// Wrap the entire return:
|
|
217
|
+
return (
|
|
218
|
+
<MessageErrorBoundary messageId={String(item.getId())}>
|
|
219
|
+
<View style={staticStyles.container} onLayout={handleLayout}>
|
|
220
|
+
{/* ... existing content ... */}
|
|
221
|
+
</View>
|
|
222
|
+
</MessageErrorBoundary>
|
|
223
|
+
);
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
**Risk:** Very Low — only catches errors, doesn't change behavior
|
|
227
|
+
**Testing:** Intentionally corrupt a message object in dev. Verify list doesn't crash, shows placeholder.
|
|
228
|
+
|
|
229
|
+
---
|
|
230
|
+
|
|
231
|
+
### Phase 2: Eliminate State Update Storms
|
|
232
|
+
|
|
233
|
+
#### 2.1 — Move `itemPositions` from State to Ref
|
|
234
|
+
|
|
235
|
+
**File:** `CometChatMessageList.tsx`
|
|
236
|
+
|
|
237
|
+
**Current:**
|
|
238
|
+
```typescript
|
|
239
|
+
const [itemPositions, setItemPositions] = useState<Map<string, { y: number; height: number }>>(new Map());
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
**Proposed:**
|
|
243
|
+
```typescript
|
|
244
|
+
const itemPositionsRef = useRef<Map<string, { y: number; height: number }>>(new Map());
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
**Update all consumers:**
|
|
248
|
+
- `handleItemLayout`: Write to `itemPositionsRef.current.set(...)` directly (no state update)
|
|
249
|
+
- `scrollToMessage`: Read from `itemPositionsRef.current.get(...)`
|
|
250
|
+
- `onScrollToIndexFailed`: Read from `itemPositionsRef.current.values()`
|
|
251
|
+
- Remove the `pendingPositionsRef` and `layoutBatchTimerRef` (no longer needed)
|
|
252
|
+
|
|
253
|
+
**Remove from `useCallback` dependencies** where `itemPositions` was listed.
|
|
254
|
+
|
|
255
|
+
**Risk:** Low — `itemPositions` was never used for rendering, only for imperative scroll calculations
|
|
256
|
+
**Testing:** Navigate from search → verify scroll-to-target still works. Verify highlight animation still works.
|
|
257
|
+
|
|
258
|
+
---
|
|
259
|
+
|
|
260
|
+
#### 2.2 — Debounced `commitMessages` Helper
|
|
261
|
+
|
|
262
|
+
**File:** `CometChatMessageList.tsx`
|
|
263
|
+
|
|
264
|
+
```typescript
|
|
265
|
+
const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
266
|
+
|
|
267
|
+
const commitMessages = useCallback((immediate = false) => {
|
|
268
|
+
if (immediate) {
|
|
269
|
+
if (commitTimerRef.current) {
|
|
270
|
+
clearTimeout(commitTimerRef.current);
|
|
271
|
+
commitTimerRef.current = null;
|
|
272
|
+
}
|
|
273
|
+
setMessagesList([...messagesContentListRef.current]);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (commitTimerRef.current) return; // Already scheduled
|
|
278
|
+
commitTimerRef.current = setTimeout(() => {
|
|
279
|
+
setMessagesList([...messagesContentListRef.current]);
|
|
280
|
+
commitTimerRef.current = null;
|
|
281
|
+
}, 16); // One frame
|
|
282
|
+
}, []);
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
**Replace direct `setMessagesList` calls with `commitMessages()`** in:
|
|
286
|
+
- `addToMessageList` (use debounced)
|
|
287
|
+
- `messageEdited` (use debounced)
|
|
288
|
+
- `removeMessage` (use debounced)
|
|
289
|
+
|
|
290
|
+
**Keep `immediate = true`** for:
|
|
291
|
+
- `getPreviousMessages` (user expects to see messages)
|
|
292
|
+
- `getMessagesAroundId` (initial load)
|
|
293
|
+
- `scrollToBottom` merge
|
|
294
|
+
|
|
295
|
+
**Risk:** Medium — rapid message arrivals batch into single render
|
|
296
|
+
**Testing:** Send multiple messages rapidly. Verify all appear. Verify no visual delay > 16ms.
|
|
297
|
+
|
|
298
|
+
---
|
|
299
|
+
|
|
300
|
+
#### 2.3 — Debounce `onLoad` Callback
|
|
301
|
+
|
|
302
|
+
**File:** `CometChatMessageList.tsx`
|
|
303
|
+
|
|
304
|
+
```typescript
|
|
305
|
+
const onLoadTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
306
|
+
|
|
307
|
+
const notifyOnLoad = useCallback(() => {
|
|
308
|
+
if (!onLoad) return;
|
|
309
|
+
if (onLoadTimerRef.current) clearTimeout(onLoadTimerRef.current);
|
|
310
|
+
onLoadTimerRef.current = setTimeout(() => {
|
|
311
|
+
onLoad([...messagesContentListRef.current].reverse());
|
|
312
|
+
onLoadTimerRef.current = null;
|
|
313
|
+
}, 100); // 100ms debounce
|
|
314
|
+
}, [onLoad]);
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
Replace all `onLoad && onLoad([...messagesContentListRef.current].reverse())` with `notifyOnLoad()`.
|
|
318
|
+
|
|
319
|
+
**Risk:** Low — `onLoad` is informational, 100ms delay is imperceptible
|
|
320
|
+
**Testing:** Verify `onLoad` still fires with correct data. Verify no duplicate calls.
|
|
321
|
+
|
|
322
|
+
---
|
|
323
|
+
|
|
324
|
+
### Phase 3: Memory Management
|
|
325
|
+
|
|
326
|
+
#### 3.1 — Sliding Window (300 Message Cap)
|
|
327
|
+
|
|
328
|
+
**File:** `CometChatMessageList.tsx`
|
|
329
|
+
|
|
330
|
+
**In `getPreviousMessages`** — after appending messages:
|
|
331
|
+
```typescript
|
|
332
|
+
const MAX_MESSAGES_IN_MEMORY = 300;
|
|
333
|
+
|
|
334
|
+
if (messagesContentListRef.current.length > MAX_MESSAGES_IN_MEMORY) {
|
|
335
|
+
// Trim oldest messages (end of array in inverted list = oldest)
|
|
336
|
+
messagesContentListRef.current = messagesContentListRef.current.slice(0, MAX_MESSAGES_IN_MEMORY);
|
|
337
|
+
reachedFirstMessage.current = false; // Allow re-fetch if user scrolls back
|
|
338
|
+
rebuildMessageIndex();
|
|
339
|
+
}
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
**In `fetchNextMessages`** — after prepending newer messages:
|
|
343
|
+
```typescript
|
|
344
|
+
if (messagesContentListRef.current.length > MAX_MESSAGES_IN_MEMORY) {
|
|
345
|
+
// Trim oldest messages from the end
|
|
346
|
+
messagesContentListRef.current = messagesContentListRef.current.slice(0, MAX_MESSAGES_IN_MEMORY);
|
|
347
|
+
rebuildMessageIndex();
|
|
348
|
+
}
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
**Risk:** Medium — user loses access to very old messages (must scroll to re-fetch)
|
|
352
|
+
**Testing:** Load 300+ messages. Verify oldest are trimmed. Verify scrolling up re-fetches them.
|
|
353
|
+
|
|
354
|
+
---
|
|
355
|
+
|
|
356
|
+
### Phase 4: Reduce Allocations
|
|
357
|
+
|
|
358
|
+
#### 4.1 — Lazy Index Rebuild
|
|
359
|
+
|
|
360
|
+
**File:** `CometChatMessageList.tsx`
|
|
361
|
+
|
|
362
|
+
```typescript
|
|
363
|
+
const indexDirtyRef = useRef(false);
|
|
364
|
+
|
|
365
|
+
const markIndexDirty = () => { indexDirtyRef.current = true; };
|
|
366
|
+
|
|
367
|
+
const ensureIndexFresh = () => {
|
|
368
|
+
if (indexDirtyRef.current) {
|
|
369
|
+
rebuildMessageIndex();
|
|
370
|
+
indexDirtyRef.current = false;
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
**Replace `rebuildMessageIndex()` with `markIndexDirty()`** in:
|
|
376
|
+
- `addToMessageList` (after prepend)
|
|
377
|
+
- `messageEdited` (after update)
|
|
378
|
+
- `removeMessage` (after splice)
|
|
379
|
+
|
|
380
|
+
**Call `ensureIndexFresh()`** at the start of:
|
|
381
|
+
- `addToMessageList` dedup check (before Map lookup)
|
|
382
|
+
- `messageEdited` lookup (before Map lookup)
|
|
383
|
+
|
|
384
|
+
**Keep direct `rebuildMessageIndex()`** for bulk operations:
|
|
385
|
+
- `getPreviousMessages` (after appending 30 messages)
|
|
386
|
+
- `getMessagesAroundId` (after setting initial list)
|
|
387
|
+
- `fetchNextMessages` (after prepending batch)
|
|
388
|
+
- `scrollToBottom` merge
|
|
389
|
+
|
|
390
|
+
**Risk:** Low — index is always fresh before any lookup
|
|
391
|
+
**Testing:** Send message → verify dedup works. Edit message → verify update works.
|
|
392
|
+
|
|
393
|
+
---
|
|
394
|
+
|
|
395
|
+
#### 4.2 — Shallow Clone for Message Updates
|
|
396
|
+
|
|
397
|
+
**File:** `CommonUtils.ts`
|
|
398
|
+
|
|
399
|
+
Add a new method:
|
|
400
|
+
```typescript
|
|
401
|
+
static shallowCloneMessage<T>(msg: T): T {
|
|
402
|
+
if (typeof msg !== "object" || !msg) return msg;
|
|
403
|
+
const clone = Object.create(Object.getPrototypeOf(msg));
|
|
404
|
+
Object.assign(clone, msg);
|
|
405
|
+
return clone;
|
|
406
|
+
}
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
**Replace `CommonUtils.clone(editedMessage)` with `CommonUtils.shallowCloneMessage(editedMessage)`** in:
|
|
410
|
+
- `messageEdited` function
|
|
411
|
+
- `addToMessageList` dedup update path
|
|
412
|
+
|
|
413
|
+
**Keep `CommonUtils.clone()`** (deep clone) for:
|
|
414
|
+
- Conversation objects (have nested user/group objects that need independence)
|
|
415
|
+
- Cases where nested mutation would cause bugs
|
|
416
|
+
|
|
417
|
+
**Risk:** Medium — shallow clone means nested objects share references
|
|
418
|
+
**Testing:** Edit a message → verify UI updates. Delete a message → verify it disappears. Verify no stale data in reactions/threads.
|
|
419
|
+
|
|
420
|
+
---
|
|
421
|
+
|
|
422
|
+
## 5. Implementation Order
|
|
423
|
+
|
|
424
|
+
| Priority | Change | Files Modified | Est. Time |
|
|
425
|
+
|----------|--------|----------------|-----------|
|
|
426
|
+
| P0 | 1.1 Navigation gate | CometChatMessageList.tsx | 15 min |
|
|
427
|
+
| P0 | 2.1 itemPositions → ref | CometChatMessageList.tsx | 30 min |
|
|
428
|
+
| P0 | 1.3 ErrorBoundary | New file + MessageListItem.tsx | 20 min |
|
|
429
|
+
| P1 | 1.2 Fetch more in getMessagesAroundId | CometChatMessageList.tsx | 30 min |
|
|
430
|
+
| P1 | 2.3 Debounce onLoad | CometChatMessageList.tsx | 15 min |
|
|
431
|
+
| P1 | 4.1 Lazy index rebuild | CometChatMessageList.tsx | 20 min |
|
|
432
|
+
| P2 | 4.2 Shallow clone | CommonUtils.ts + CometChatMessageList.tsx | 30 min |
|
|
433
|
+
| P2 | 2.2 Debounced commitMessages | CometChatMessageList.tsx | 45 min |
|
|
434
|
+
| P2 | 3.1 Sliding window trim | CometChatMessageList.tsx | 30 min |
|
|
435
|
+
|
|
436
|
+
**Total estimated time:** ~4 hours
|
|
437
|
+
|
|
438
|
+
---
|
|
439
|
+
|
|
440
|
+
## 6. Testing Matrix
|
|
441
|
+
|
|
442
|
+
| Scenario | Expected Result |
|
|
443
|
+
|----------|-----------------|
|
|
444
|
+
| Search → tap link in large group (Android) | No crash, messages load in < 1s |
|
|
445
|
+
| Search → tap link in large group (iOS) | Same behavior as before (no regression) |
|
|
446
|
+
| Normal conversation open (no search) | No change in behavior |
|
|
447
|
+
| Send message in large group (Android) | Clock icon disappears within 500ms |
|
|
448
|
+
| Receive messages while scrolled up | Unread count increments, no crash |
|
|
449
|
+
| Scroll to very old messages | Pagination works, newer messages trimmed |
|
|
450
|
+
| Scroll back to bottom after deep scroll | Messages re-fetch correctly |
|
|
451
|
+
| Message with malformed metadata | ErrorBoundary catches, list continues |
|
|
452
|
+
| Thread navigation from search | Thread messages load correctly |
|
|
453
|
+
| Agentic user chat | No regression in streaming behavior |
|
|
454
|
+
|
|
455
|
+
---
|
|
456
|
+
|
|
457
|
+
## 7. Metrics to Track
|
|
458
|
+
|
|
459
|
+
| Metric | Before | Target |
|
|
460
|
+
|--------|--------|--------|
|
|
461
|
+
| Time to first message visible (search nav, Android) | 2-5s or crash | < 800ms |
|
|
462
|
+
| State updates during search navigation | 50-80 | 3-5 |
|
|
463
|
+
| Peak memory (300-msg conversation) | Unbounded | ~300 objects max |
|
|
464
|
+
| `messageEdited` lookup time | O(n) | O(1) |
|
|
465
|
+
| `addToMessageList` dedup time | O(n) | O(1) |
|
|
466
|
+
| Array copies per message send | 3-4 | 1 |
|
|
467
|
+
|
|
468
|
+
---
|
|
469
|
+
|
|
470
|
+
## 8. Rollback Plan
|
|
471
|
+
|
|
472
|
+
Each phase is independent. If any phase causes regression:
|
|
473
|
+
- Phase 1: Remove `navigationInProgressRef` checks → reverts to current cascade behavior
|
|
474
|
+
- Phase 2: Revert `itemPositionsRef` to state, remove debounce helpers
|
|
475
|
+
- Phase 3: Remove trim logic, increase cap back to 500
|
|
476
|
+
- Phase 4: Revert to `CommonUtils.clone()` and direct `rebuildMessageIndex()`
|
|
477
|
+
|
|
478
|
+
No database migrations, no API changes, no prop changes. Pure internal refactor.
|