@cometchat/chat-uikit-react-native 5.5.1 → 5.5.2

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 (66) hide show
  1. package/android/.gradle/7.4/checksums/checksums.lock +0 -0
  2. package/android/.gradle/7.4/fileChanges/last-build.bin +0 -0
  3. package/android/.gradle/7.4/fileHashes/fileHashes.lock +0 -0
  4. package/android/.gradle/7.4/gc.properties +0 -0
  5. package/android/.gradle/vcs-1/gc.properties +0 -0
  6. package/android/build.gradle +23 -89
  7. package/android/gradle.properties +5 -5
  8. package/android/src/main/java/com/reactnativecometchatuikit/CometChatSoundModule.java +5 -1
  9. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +52 -0
  10. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +17 -4
  11. package/ios/FileManager.m +77 -3
  12. package/ios/RichTextEditorView.swift +9 -1
  13. package/package.json +4 -4
  14. package/react-native-cometchat-ui-kit.podspec +5 -19
  15. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +31 -27
  16. package/src/CometChatConversations/CometChatConversations.tsx +4 -0
  17. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +35 -28
  18. package/src/CometChatMessageList/CometChatMessageList.tsx +20 -18
  19. package/src/CometChatRichTextEditor/index.tsx +2 -1
  20. package/src/CometChatSearch/CometChatSearch.tsx +10 -5
  21. package/src/calls/CometChatOngoingCall/CometChatOngoingCall.tsx +56 -17
  22. package/src/calls/CometChatOutgoingCall/CometChatOutgoingCall.tsx +12 -9
  23. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +13 -10
  24. package/src/extensions/LinkPreview/LinkPreviewExtensionDecorator.tsx +34 -27
  25. package/src/extensions/Polls/Polls.tsx +7 -7
  26. package/src/extensions/Polls/PollsBubble.tsx +2 -2
  27. package/src/globals.d.ts +6 -0
  28. package/src/shared/constants/textPatterns.ts +20 -2
  29. package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +22 -11
  30. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +26 -14
  31. package/src/shared/formatters/CometChatUrlsFormatter/index.tsx +8 -0
  32. package/src/shared/formatters/codeElements.ts +21 -0
  33. package/src/shared/helper/types/index.ts +5 -0
  34. package/src/shared/libs/ImageZoom/ReactNativeZoomableView.tsx +4 -4
  35. package/src/shared/libs/ImageZoom/types/index.ts +2 -0
  36. package/src/shared/resources/CometChatSoundManager/sound.js +2 -3
  37. package/src/shared/services/UploadQueueService.ts +7 -0
  38. package/src/shared/utils/CometChatMessageHelper/index.ts +3 -0
  39. package/src/shared/utils/MarkdownUtils.ts +11 -4
  40. package/src/shared/utils/MessageUtils.tsx +7 -5
  41. package/src/shared/utils/groupMemberAddedRows.ts +28 -0
  42. package/src/shared/utils/linkPreviewSelection.ts +109 -0
  43. package/src/shared/utils/mentionTokens.ts +77 -0
  44. package/src/shared/utils/runAfterInteractions.ts +26 -0
  45. package/src/shared/utils/stripRichText.ts +2 -1
  46. package/src/shared/utils/tapGesture.ts +23 -0
  47. package/src/shared/utils/videoThumbnail.ts +74 -0
  48. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTile.tsx +21 -13
  49. package/src/shared/views/CometChatAudioBubble/CometChatAudioBubble.tsx +13 -15
  50. package/src/shared/views/CometChatEmojiKeyboard/CometChatEmojiKeyboard.tsx +1 -1
  51. package/src/shared/views/CometChatFileBubble/CometChatFileBubble.tsx +2 -1
  52. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +2 -1
  53. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +3 -26
  54. package/src/shared/views/CometChatInlineAudioRecorder/useAudioRecorder.ts +4 -2
  55. package/src/shared/views/CometChatList/Header.tsx +1 -1
  56. package/src/shared/views/CometChatMediaRecorder/CometChatAudioPreview/CometChatAudioPreview.tsx +2 -1
  57. package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +28 -8
  58. package/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx +3 -4
  59. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +36 -4
  60. package/src/shared/views/CometChatVideoBubble/CometChatVideoBubble.tsx +2 -1
  61. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +57 -30
  62. package/src/CometChatMessageList/PERFORMANCE_ARCHITECTURE.md +0 -478
  63. package/src/CometChatMessageList/SEARCH_NAV_PERF_PLAN.md +0 -613
  64. package/src/CometChatMessageList/SEARCH_NAV_SLOWNESS_FINDINGS_AND_FIX.md +0 -313
  65. package/src/shared/CometChatUiKit/CometChatUIKit.changes.md +0 -76
  66. package/src/shared/CometChatUiKit/checkAuthSettings-review.md +0 -211
@@ -115,7 +115,8 @@ export const CometChatVideoBubble = (props: CometChatVideoBubbleInterface) => {
115
115
  };
116
116
 
117
117
  useEffect(() => {
118
- statusListener = eventEmitter.addListener("status", (data) => {
118
+ statusListener = eventEmitter.addListener("status", (event) => {
119
+ const data = event as { url?: string; state?: string };
119
120
  if (data["url"] == videoUrl && data["state"] == "downloading") {
120
121
  setOpening(true);
121
122
  }
@@ -1,4 +1,4 @@
1
- import React, { useEffect, useMemo, useState } from 'react';
1
+ import React, { useEffect, useMemo, useRef, useState } from 'react';
2
2
  import { Image, ImageStyle, StyleProp, StyleSheet, Text, TextStyle, TouchableOpacity, View, ViewStyle } from 'react-native';
3
3
  import { CometChat } from '@cometchat/chat-sdk-react-native';
4
4
  import { CometChatTheme } from '../../../theme/type';
@@ -8,10 +8,10 @@ import { deepMerge } from '../../helper/helperFunctions';
8
8
  import { Icon } from '../../icons/Icon';
9
9
  import { getExtensionData } from '../../../extensions/ExtensionModerator';
10
10
  import { CometChatUIKit } from '../../CometChatUiKit';
11
- import { CometChatMessageEvents } from '../../events/CometChatMessageEvents';
12
11
  import { CometChatMediaViewer } from '../CometChatMediaViewer';
13
12
  import { CometChatCaptionText } from '../CometChatCaptionText';
14
13
  import { isVideoMime } from '../CometChatMediaViewer/mediaViewerUtils';
14
+ import { useLocalVideoThumbnail } from '../../utils/videoThumbnail';
15
15
  import { AdditionalParams } from "../../base/Types";
16
16
 
17
17
  // ---------------------------------------------------------------------------
@@ -54,6 +54,8 @@ interface VideoCellProps {
54
54
  testID?: string;
55
55
  overflowCount?: number;
56
56
  thumbnailUrl?: string;
57
+ /** Retry a failed server thumbnail — only for a just-sent message, whose thumbnail may not exist yet. */
58
+ retryThumbnail?: boolean;
57
59
  cellStyle?: StyleProp<ViewStyle>;
58
60
  playButtonStyle?: StyleProp<ViewStyle>;
59
61
  playIconStyle?: ImageStyle;
@@ -63,6 +65,14 @@ interface VideoCellProps {
63
65
  overflowTextStyle?: TextStyle;
64
66
  }
65
67
 
68
+ // The thumbnail-generation extension puts the thumbnail URL on the message at send time but creates the
69
+ // image a few seconds later, so an early load of it fails. The sender's own device shows its local
70
+ // first-frame thumbnail meanwhile — only when that URL exists, so the dashboard setting still decides.
71
+ // Anyone else (another of the sender's devices, a very fast receiver) re-checks the URL with back-off.
72
+ // Older messages never retry — their thumbnail exists or never will.
73
+ const THUMBNAIL_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000];
74
+ const THUMBNAIL_RETRY_WINDOW_SECS = 120;
75
+
66
76
  const VideoCell = ({
67
77
  attachment,
68
78
  aspectRatio = 1,
@@ -71,6 +81,7 @@ const VideoCell = ({
71
81
  testID,
72
82
  overflowCount,
73
83
  thumbnailUrl,
84
+ retryThumbnail,
74
85
  cellStyle,
75
86
  playButtonStyle,
76
87
  playIconStyle,
@@ -81,6 +92,29 @@ const VideoCell = ({
81
92
  }: VideoCellProps) => {
82
93
  const theme = useTheme();
83
94
  const duration = getDuration(attachment);
95
+ // Only stand in for a server thumbnail that is on its way: no `thumbnailUrl` means the Thumbnail
96
+ // Generation extension is off in the dashboard (or failed for this file), and then no thumbnail shows.
97
+ const localThumbnail = useLocalVideoThumbnail({ remoteUrl: thumbnailUrl ? attachment.getUrl?.() : undefined });
98
+ // Bumped once a retried thumbnail is fetched, to remount the <Image> onto the now-cached file.
99
+ const [thumbnailKey, setThumbnailKey] = useState(0);
100
+ const retry = useRef<{ attempt: number; timer?: ReturnType<typeof setTimeout> }>({ attempt: 0 });
101
+ useEffect(() => {
102
+ retry.current = { attempt: 0 };
103
+ return () => clearTimeout(retry.current.timer);
104
+ }, [thumbnailUrl]);
105
+ const onThumbnailError = () => {
106
+ if (!retryThumbnail || localThumbnail || !thumbnailUrl) return;
107
+ const check = () => {
108
+ Image.prefetch(thumbnailUrl)
109
+ .then((ok) => (ok ? setThumbnailKey((k) => k + 1) : scheduleNext()))
110
+ .catch(scheduleNext);
111
+ };
112
+ const scheduleNext = () => {
113
+ const delay = THUMBNAIL_RETRY_DELAYS_MS[retry.current.attempt++];
114
+ if (delay != null) retry.current.timer = setTimeout(check, delay);
115
+ };
116
+ scheduleNext();
117
+ };
84
118
  // A VIDEO bubble previews videos only. Anything else (image / audio / file) is unsupported here →
85
119
  // a "no preview" placeholder cell (tapping it opens the "No preview available" fullscreen). Gate on a
86
120
  // KNOWN non-video kind (a proper "type/subtype" mime that isn't video/*): an empty / bare-extension
@@ -108,7 +142,7 @@ const VideoCell = ({
108
142
  >
109
143
  <View
110
144
  testID="grid-cell-nopreview"
111
- style={[StyleSheet.absoluteFillObject, borderStyle, { backgroundColor: theme.color.neutral200, justifyContent: 'center', alignItems: 'center' }]}
145
+ style={[StyleSheet.absoluteFill, borderStyle, { backgroundColor: theme.color.neutral200, justifyContent: 'center', alignItems: 'center' }]}
112
146
  >
113
147
  <Icon name="unknown-file-type" size={theme.spacing.spacing.s12} />
114
148
  </View>
@@ -116,7 +150,7 @@ const VideoCell = ({
116
150
  <View
117
151
  testID="grid-overflow"
118
152
  pointerEvents="none"
119
- style={[StyleSheet.absoluteFillObject, { backgroundColor: theme.color.mediaOverlay, justifyContent: 'center', alignItems: 'center' }, overflowOverlayStyle]}
153
+ style={[StyleSheet.absoluteFill, { backgroundColor: theme.color.mediaOverlay, justifyContent: 'center', alignItems: 'center' }, overflowOverlayStyle]}
120
154
  >
121
155
  <Text style={[{ ...theme.typography.heading1.bold, color: theme.color.staticWhite, letterSpacing: -0.5 }, overflowTextStyle]}>{`+${overflowCount}`}</Text>
122
156
  </View>
@@ -134,13 +168,24 @@ const VideoCell = ({
134
168
  accessibilityRole="button"
135
169
  accessibilityLabel={attachment.getName()}
136
170
  >
137
- <View style={[StyleSheet.absoluteFillObject, { backgroundColor: theme.color.mediaScrim }, borderStyle]} />
171
+ <View style={[StyleSheet.absoluteFill, { backgroundColor: theme.color.mediaScrim }, borderStyle]} />
172
+ {localThumbnail ? (
173
+ <Image source={{ uri: localThumbnail }} style={[StyleSheet.absoluteFill, borderStyle]} resizeMode="cover" />
174
+ ) : null}
175
+ {/* The server thumbnail draws over the local one once it loads; until then (or if it fails)
176
+ the local thumbnail shows through. */}
138
177
  {thumbnailUrl ? (
139
- <Image source={{ uri: thumbnailUrl }} style={[StyleSheet.absoluteFillObject, borderStyle]} resizeMode="cover" />
178
+ <Image
179
+ key={thumbnailKey}
180
+ source={{ uri: thumbnailUrl }}
181
+ style={[StyleSheet.absoluteFill, borderStyle]}
182
+ resizeMode="cover"
183
+ onError={onThumbnailError}
184
+ />
140
185
  ) : null}
141
186
 
142
187
  {!overflowCount && (
143
- <View pointerEvents="none" style={StyleSheet.absoluteFillObject}>
188
+ <View pointerEvents="none" style={StyleSheet.absoluteFill}>
144
189
  <View style={styles.centerFill}>
145
190
  <View
146
191
  style={[{
@@ -182,7 +227,7 @@ const VideoCell = ({
182
227
  <View
183
228
  testID="grid-overflow"
184
229
  pointerEvents="none"
185
- style={[StyleSheet.absoluteFillObject, { backgroundColor: theme.color.mediaOverlay, justifyContent: 'center', alignItems: 'center' }, overflowOverlayStyle]}
230
+ style={[StyleSheet.absoluteFill, { backgroundColor: theme.color.mediaOverlay, justifyContent: 'center', alignItems: 'center' }, overflowOverlayStyle]}
186
231
  >
187
232
  <Text style={[{ ...theme.typography.heading1.bold, color: theme.color.staticWhite, letterSpacing: -0.5 }, overflowTextStyle]}>{`+${overflowCount}`}</Text>
188
233
  </View>
@@ -196,6 +241,7 @@ const VideoCell = ({
196
241
  const VideoGrid = ({
197
242
  attachments,
198
243
  thumbnailUrls,
244
+ retryThumbnail,
199
245
  onAttachmentPress,
200
246
  containerStyle,
201
247
  cellStyle,
@@ -208,6 +254,7 @@ const VideoGrid = ({
208
254
  }: {
209
255
  attachments: CometChat.Attachment[];
210
256
  thumbnailUrls?: string[];
257
+ retryThumbnail?: boolean;
211
258
  onAttachmentPress: (attachment: CometChat.Attachment, index: number) => void;
212
259
  containerStyle?: StyleProp<ViewStyle>;
213
260
  cellStyle?: StyleProp<ViewStyle>;
@@ -232,6 +279,7 @@ const VideoGrid = ({
232
279
  radii={radii}
233
280
  overflowCount={overflowCount}
234
281
  thumbnailUrl={thumbnailUrls?.[i]}
282
+ retryThumbnail={retryThumbnail}
235
283
  onPress={() => onAttachmentPress(attachments[i], i)}
236
284
  cellStyle={cellStyle}
237
285
  playButtonStyle={playButtonStyle}
@@ -354,28 +402,6 @@ export function CometChatVideosBubble({
354
402
  });
355
403
  }, [message, allAttachments]);
356
404
 
357
- // §8.7 — refresh the local copy when the server edits the message in (async thumbnails).
358
- useEffect(() => {
359
- const listenerId = `VideosBubble_${message.getId?.() ?? message.getMuid?.() ?? Date.now()}`;
360
- CometChatMessageEvents.addListener(
361
- CometChatMessageEvents.messageEdited,
362
- listenerId,
363
- (edited: CometChat.BaseMessage) => {
364
- const editedId = edited.getId?.();
365
- const editedMuid = edited.getMuid?.();
366
- const myId = message.getId?.();
367
- const myMuid = message.getMuid?.();
368
- if (
369
- edited instanceof CometChat.MediaMessage &&
370
- ((myId && editedId && myId === editedId) || (myMuid && editedMuid && myMuid === editedMuid))
371
- ) {
372
- setMessage(edited);
373
- }
374
- }
375
- );
376
- return () => CometChatMessageEvents.removeListener(CometChatMessageEvents.messageEdited, listenerId);
377
- }, []);
378
-
379
405
  useEffect(() => {
380
406
  setMessage(initialMessage);
381
407
  }, [initialMessage]);
@@ -387,6 +413,7 @@ export function CometChatVideosBubble({
387
413
  <VideoGrid
388
414
  attachments={allAttachments}
389
415
  thumbnailUrls={thumbnailUrls}
416
+ retryThumbnail={Date.now() / 1000 - (message.getSentAt?.() ?? 0) < THUMBNAIL_RETRY_WINDOW_SECS}
390
417
  containerStyle={s.containerStyle}
391
418
  cellStyle={s.cellStyle}
392
419
  playButtonStyle={s.playButtonStyle}
@@ -1,478 +0,0 @@
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.