@cometchat/chat-uikit-react-native 5.2.3 → 5.2.5

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 (75) hide show
  1. package/package.json +1 -1
  2. package/src/CometChatConversations/CometChatConversations.tsx +167 -86
  3. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +312 -116
  4. package/src/CometChatMessageComposer/styles.tsx +2 -1
  5. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +83 -17
  6. package/src/CometChatMessageList/CometChatMessageList.tsx +675 -122
  7. package/src/CometChatMessageList/style.ts +4 -2
  8. package/src/CometChatSearch/CometChatSearch.tsx +2165 -0
  9. package/src/CometChatSearch/SearchConstants.ts +46 -0
  10. package/src/CometChatSearch/Skeleton.tsx +192 -0
  11. package/src/CometChatSearch/index.ts +1 -0
  12. package/src/CometChatSearch/style.ts +414 -0
  13. package/src/extensions/CollaborativeDocument/CollaborativeDocumentExtensionDecorator.tsx +43 -7
  14. package/src/extensions/CollaborativeWhiteboard/CollaborativeWhiteboardExtensionDecorator.tsx +45 -7
  15. package/src/extensions/Polls/Polls.tsx +36 -2
  16. package/src/extensions/Polls/PollsBubble.tsx +13 -9
  17. package/src/extensions/Polls/PollsDecorator.tsx +13 -1
  18. package/src/extensions/Stickers/StickersExtensionDecorator.tsx +50 -11
  19. package/src/extensions/Stickers/style.ts +0 -1
  20. package/src/index.ts +5 -0
  21. package/src/shared/base/Types.ts +8 -0
  22. package/src/shared/constants/UIKitConstants.ts +2 -0
  23. package/src/shared/events/CometChatMessageEvents/index.ts +8 -7
  24. package/src/shared/events/CometChatUIEventHandler/Listener.ts +4 -0
  25. package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +158 -27
  26. package/src/shared/framework/DataSource.ts +7 -0
  27. package/src/shared/framework/DataSourceDecorator.tsx +12 -0
  28. package/src/shared/framework/MessageDataSource.tsx +182 -1
  29. package/src/shared/helper/functions.js +0 -67
  30. package/src/shared/helper/helperFunctions.ts +72 -0
  31. package/src/shared/icons/components/documents.tsx +23 -0
  32. package/src/shared/icons/components/empty-search.tsx +52 -0
  33. package/src/shared/icons/components/message-blocked.tsx +1 -1
  34. package/src/shared/icons/components/unread.tsx +29 -0
  35. package/src/shared/icons/icon-mapping.tsx +7 -0
  36. package/src/shared/index.ts +2 -1
  37. package/src/shared/modals/CometChatMessageTemplate.ts +23 -0
  38. package/src/shared/resources/CometChatLocalizeNew/CometChatLocalizationHelper.ts +4 -4
  39. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +17 -1
  40. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +70 -34
  41. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +60 -24
  42. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +37 -1
  43. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +60 -24
  44. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +37 -1
  45. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +37 -1
  46. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +37 -1
  47. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +37 -1
  48. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +40 -4
  49. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +37 -1
  50. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +37 -1
  51. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +37 -1
  52. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +37 -1
  53. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +38 -2
  54. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +37 -1
  55. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +37 -1
  56. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +40 -4
  57. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +274 -23
  58. package/src/shared/utils/MessageUtils.tsx +0 -1
  59. package/src/shared/views/CometChatAudioBubble/style.ts +0 -2
  60. package/src/shared/views/CometChatFileBubble/style.ts +0 -4
  61. package/src/shared/views/CometChatImageBubble/CometChatImageLoader.tsx +1 -0
  62. package/src/shared/views/CometChatList/CometChatList.tsx +12 -0
  63. package/src/shared/views/CometChatList/Header.tsx +79 -49
  64. package/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx +14 -4
  65. package/src/shared/views/CometChatReportDialog/CometChatReportDialog.tsx +390 -0
  66. package/src/shared/views/CometChatReportDialog/index.ts +3 -0
  67. package/src/shared/views/CometChatReportDialog/style.ts +164 -0
  68. package/src/shared/views/CometChatStatusIndicator/private.png +0 -0
  69. package/src/shared/views/CometChatStatusIndicator/protected.png +0 -0
  70. package/src/shared/views/CometChatStatusIndicator/styles.ts +2 -2
  71. package/src/shared/views/CometChatSuggestionList/CometChatSuggestionList.tsx +18 -2
  72. package/src/shared/views/index.ts +6 -0
  73. package/src/theme/default/default.ts +3 -0
  74. package/src/theme/provider.tsx +23 -12
  75. package/src/theme/type.ts +2 -0
@@ -0,0 +1,2165 @@
1
+ import React, { useCallback, useEffect, useReducer, useRef, useState, useMemo } from 'react';
2
+ import { View, TextInput, TouchableOpacity, Text, Image, ImageBackground, FlatList, ImageSourcePropType } from 'react-native';
3
+ import { CometChat } from '@cometchat/chat-sdk-react-native';
4
+ import {
5
+ CometChatAvatar,
6
+ CometChatStatusIndicator,
7
+ CometChatBadge,
8
+ CometChatDate,
9
+ useTheme
10
+ } from '@cometchat/chat-uikit-react-native';
11
+ import { Icon } from '../shared/icons/Icon';
12
+ import { GroupTypeConstants, ReceiverTypeConstants, MessageCategoryConstants, MessageTypeConstants } from '@cometchat/chat-uikit-react-native/src/shared/constants/UIKitConstants';
13
+ import { CometChatSearchScope, CometChatSearchFilter, States } from './SearchConstants';
14
+ import { Skeleton } from './Skeleton';
15
+ import { SearchStyle, getSearchStyleLight, getSearchStyleDark } from './style';
16
+ import { deepMerge } from '../shared/helper/helperFunctions';
17
+ import { DeepPartial } from '../shared/helper/types';
18
+ import { getCometChatTranslation } from '../shared/resources/CometChatLocalizeNew/LocalizationManager';
19
+ import { CommonUtils } from '../shared/utils/CommonUtils';
20
+ import { ExtensionConstants } from '../extensions/ExtensionConstants';
21
+ import { getExtensionData } from '../extensions/ExtensionModerator';
22
+
23
+
24
+ // ERROR HANDLER
25
+ function useCometChatErrorHandler(onError?: (error: CometChat.CometChatException) => void) {
26
+ return useCallback(
27
+ (error: any, source?: string) => {
28
+ console.error(`CometChat Error${source ? ` in ${source}` : ''}:`, error);
29
+
30
+ if (onError && error instanceof CometChat.CometChatException) {
31
+ onError(error);
32
+ }
33
+ },
34
+ [onError]
35
+ );
36
+ }
37
+
38
+ // SEARCH UTILITIES
39
+ function hasValidConversationSearchCriteria(searchKeyword: string, filters: CometChatSearchFilter[]): boolean {
40
+ if (searchKeyword && searchKeyword.trim() !== "") {
41
+ return true;
42
+ }
43
+
44
+ const validFilters = [
45
+ CometChatSearchFilter.Unread,
46
+ CometChatSearchFilter.Groups,
47
+ CometChatSearchFilter.Conversations
48
+ ];
49
+
50
+ if (filters.length === 0) {
51
+ return false;
52
+ }
53
+
54
+ return filters.every(filter => validFilters.includes(filter));
55
+ }
56
+
57
+ function hasValidMessageSearchCriteria(searchKeyword: string, filters: CometChatSearchFilter[]): boolean {
58
+ if (searchKeyword && searchKeyword.trim() !== "") {
59
+ return true;
60
+ }
61
+
62
+ const validMessageFilters = [
63
+ CometChatSearchFilter.Photos,
64
+ CometChatSearchFilter.Videos,
65
+ CometChatSearchFilter.Documents,
66
+ CometChatSearchFilter.Audio,
67
+ CometChatSearchFilter.Links
68
+ ];
69
+
70
+ if (filters.length === 0) {
71
+ return false;
72
+ }
73
+
74
+ return filters.some(filter => validMessageFilters.includes(filter));
75
+ }
76
+
77
+ interface SearchState {
78
+ searchText: string;
79
+ conversations: CometChat.Conversation[];
80
+ messages: CometChat.BaseMessage[];
81
+ fetchState: States;
82
+ activeFilters: CometChatSearchFilter[];
83
+ }
84
+
85
+ type SearchAction =
86
+ | { type: "setSearchText"; searchText: string }
87
+ | { type: "setResults"; conversations?: CometChat.Conversation[]; messages?: CometChat.BaseMessage[] }
88
+ | { type: "clearResults" }
89
+ | { type: "setFetchState"; fetchState: States }
90
+ | { type: "setActiveFilter"; filterId: CometChatSearchFilter }
91
+ | { type: "resetActiveFilters" };
92
+
93
+ const initialState: SearchState = {
94
+ searchText: "",
95
+ conversations: [],
96
+ messages: [],
97
+ fetchState: States.loaded,
98
+ activeFilters: [],
99
+ };
100
+
101
+ function searchStateReducer(state: SearchState, action: SearchAction): SearchState {
102
+ switch (action.type) {
103
+ case "setSearchText":
104
+ return { ...state, searchText: action.searchText };
105
+
106
+ case "setResults":
107
+ return {
108
+ ...state,
109
+ conversations: action.conversations ?? state.conversations,
110
+ messages: action.messages ?? state.messages,
111
+ fetchState: States.loaded,
112
+ };
113
+
114
+ case "clearResults":
115
+ return { ...state, conversations: [], messages: [] };
116
+
117
+ case "setFetchState":
118
+ return { ...state, fetchState: action.fetchState };
119
+
120
+ case "setActiveFilter": {
121
+ const newActiveFilters = [...state.activeFilters];
122
+ const filterIndex = newActiveFilters.findIndex(f => f === action.filterId);
123
+
124
+ // Define filter pairs
125
+ const filterPairs = {
126
+ conversationPair: [CometChatSearchFilter.Unread, CometChatSearchFilter.Groups],
127
+ photosVideosPair: [CometChatSearchFilter.Photos, CometChatSearchFilter.Videos],
128
+ audioDocumentsPair: [CometChatSearchFilter.Audio, CometChatSearchFilter.Documents],
129
+ linkStandalone: [CometChatSearchFilter.Links]
130
+ };
131
+
132
+ if (filterIndex >= 0) {
133
+ // If filter is already active, remove it
134
+ newActiveFilters.splice(filterIndex, 1);
135
+ } else {
136
+ // Clear incompatible filters before adding new one
137
+
138
+ // If selecting Links (standalone), clear all other filters
139
+ if (action.filterId === CometChatSearchFilter.Links) {
140
+ newActiveFilters.length = 0; // Clear all filters
141
+ }
142
+ // If selecting conversation pair filter, clear other pairs
143
+ else if (filterPairs.conversationPair.includes(action.filterId)) {
144
+ // Remove all non-conversation filters
145
+ const filtersToRemove = [
146
+ ...filterPairs.photosVideosPair,
147
+ ...filterPairs.audioDocumentsPair,
148
+ ...filterPairs.linkStandalone
149
+ ];
150
+ filtersToRemove.forEach(filter => {
151
+ const idx = newActiveFilters.findIndex(f => f === filter);
152
+ if (idx >= 0) newActiveFilters.splice(idx, 1);
153
+ });
154
+ }
155
+ // If selecting photos/videos pair filter, clear other pairs
156
+ else if (filterPairs.photosVideosPair.includes(action.filterId)) {
157
+ const filtersToRemove = [
158
+ ...filterPairs.conversationPair,
159
+ ...filterPairs.audioDocumentsPair,
160
+ ...filterPairs.linkStandalone
161
+ ];
162
+ filtersToRemove.forEach(filter => {
163
+ const idx = newActiveFilters.findIndex(f => f === filter);
164
+ if (idx >= 0) newActiveFilters.splice(idx, 1);
165
+ });
166
+ }
167
+ // If selecting audio/documents pair filter, clear other pairs
168
+ else if (filterPairs.audioDocumentsPair.includes(action.filterId)) {
169
+ const filtersToRemove = [
170
+ ...filterPairs.conversationPair,
171
+ ...filterPairs.photosVideosPair,
172
+ ...filterPairs.linkStandalone
173
+ ];
174
+ filtersToRemove.forEach(filter => {
175
+ const idx = newActiveFilters.findIndex(f => f === filter);
176
+ if (idx >= 0) newActiveFilters.splice(idx, 1);
177
+ });
178
+ }
179
+
180
+ newActiveFilters.push(action.filterId);
181
+ }
182
+
183
+ return { ...state, activeFilters: newActiveFilters };
184
+ }
185
+
186
+ case "resetActiveFilters":
187
+ return { ...state, activeFilters: [] };
188
+
189
+ default:
190
+ return state;
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Props for the CometChatSearch component
196
+ */
197
+ interface CometChatSearchProps {
198
+ /**
199
+ * Callback triggered when the back button is clicked
200
+ * Use this to handle navigation when user clicks the back button
201
+ */
202
+ onBack?: () => void;
203
+
204
+ /**
205
+ * Whether to hide the back button
206
+ */
207
+ hideBackButton?: boolean;
208
+
209
+ /**
210
+ * Callback triggered when a conversation is clicked in search results
211
+ * @param conversation - The conversation that was clicked
212
+ * @param searchKeyword - The keyword that was used in the search
213
+ */
214
+ onConversationClicked?: (conversation: CometChat.Conversation, searchKeyword?: string) => void;
215
+
216
+ /**
217
+ * Callback triggered when a message is clicked in search results
218
+ * @param message - The message that was clicked
219
+ * @param searchKeyword - The keyword that was used in the search
220
+ */
221
+ onMessageClicked?: (message: CometChat.BaseMessage, searchKeyword?: string) => void;
222
+
223
+ /**
224
+ * Array of search filters to display in the filter bar
225
+ */
226
+ searchFilters?: Array<CometChatSearchFilter>;
227
+
228
+ /**
229
+ * Filter that should be active by default when the component loads
230
+ */
231
+ initialSearchFilter?: CometChatSearchFilter;
232
+
233
+ /**
234
+ * Scopes to search in (Conversations, Messages, or both)
235
+ */
236
+ searchIn?: Array<CometChatSearchScope>;
237
+
238
+ /**
239
+ * Request builder for conversations search
240
+ */
241
+ conversationsRequestBuilder?: CometChat.ConversationsRequestBuilder;
242
+
243
+ /**
244
+ * Request builder for messages search
245
+ */
246
+ messagesRequestBuilder?: CometChat.MessagesRequestBuilder;
247
+
248
+ /**
249
+ * Custom error handler for search operations
250
+ */
251
+ onError?: (error: CometChat.CometChatException) => void;
252
+
253
+ /**
254
+ * User ID to search within specific user's messages
255
+ */
256
+ uid?: string;
257
+
258
+ /**
259
+ * Group ID to search within specific group's messages
260
+ */
261
+ guid?: string;
262
+
263
+ /**
264
+ * Search placeholder text
265
+ */
266
+ searchPlaceholder?: string;
267
+
268
+ /**
269
+ * Custom styles for the component
270
+ */
271
+ style?: DeepPartial<SearchStyle>;
272
+
273
+ /**
274
+ * Custom loading view component that will be shown during search operations
275
+ */
276
+ loadingView?: () => React.ReactElement;
277
+
278
+ /**
279
+ * Custom empty state view component that will be shown when no results are found
280
+ */
281
+ emptyView?: () => React.ReactElement;
282
+
283
+ /**
284
+ * Custom error state view component that will be shown when search fails
285
+ */
286
+ errorView?: () => React.ReactElement;
287
+
288
+ /**
289
+ * Custom view component for conversation items (both unread and group conversations)
290
+ * @param conversation - The conversation object to render
291
+ * @param searchKeyword - The search keyword used
292
+ */
293
+ conversationItemView?: (conversation: CometChat.Conversation, searchKeyword?: string) => React.ReactElement;
294
+
295
+ /**
296
+ * Custom view component for text message items
297
+ * @param message - The text message object to render
298
+ * @param searchKeyword - The search keyword used
299
+ */
300
+ textMessageItemView?: (message: CometChat.BaseMessage, searchKeyword?: string) => React.ReactElement;
301
+
302
+ /**
303
+ * Custom view component for image message items
304
+ * @param message - The image message object to render
305
+ * @param searchKeyword - The search keyword used
306
+ */
307
+ imageMessageItemView?: (message: CometChat.BaseMessage, searchKeyword?: string) => React.ReactElement;
308
+
309
+ /**
310
+ * Custom view component for audio message items
311
+ * @param message - The audio message object to render
312
+ * @param searchKeyword - The search keyword used
313
+ */
314
+ audioMessageItemView?: (message: CometChat.BaseMessage, searchKeyword?: string) => React.ReactElement;
315
+
316
+ /**
317
+ * Custom view component for video message items
318
+ * @param message - The video message object to render
319
+ * @param searchKeyword - The search keyword used
320
+ */
321
+ videoMessageItemView?: (message: CometChat.BaseMessage, searchKeyword?: string) => React.ReactElement;
322
+
323
+ /**
324
+ * Custom view component for document/file message items
325
+ * @param message - The document message object to render
326
+ * @param searchKeyword - The search keyword used
327
+ */
328
+ documentMessageItemView?: (message: CometChat.BaseMessage, searchKeyword?: string) => React.ReactElement;
329
+
330
+ /**
331
+ * Custom view component for link message items (text messages with link previews)
332
+ * @param message - The link message object to render
333
+ * @param searchKeyword - The search keyword used
334
+ */
335
+ linkMessageItemView?: (message: CometChat.BaseMessage, searchKeyword?: string) => React.ReactElement;
336
+ }
337
+ const t = getCometChatTranslation();
338
+
339
+ interface LinkPreviewImageProps {
340
+ uri: string;
341
+ mergedStyles: any;
342
+ theme: any;
343
+ }
344
+
345
+ const LinkPreviewImage: React.FC<LinkPreviewImageProps> = ({ uri, mergedStyles, theme }) => {
346
+ const [imageError, setImageError] = useState(false);
347
+
348
+ if (imageError) {
349
+ return (
350
+ <View style={mergedStyles.messageItemStyle?.iconContainerStyle}>
351
+ <Icon
352
+ name='link-fill'
353
+ size={48}
354
+ height={48}
355
+ width={48}
356
+ color={theme.color.iconSecondary}
357
+ />
358
+ </View>
359
+ );
360
+ }
361
+
362
+ return (
363
+ <View style={mergedStyles.messageItemStyle?.iconContainerStyle}>
364
+ <Image
365
+ source={{ uri }}
366
+ style={mergedStyles.messageItemStyle?.linkPreviewImageStyle}
367
+ resizeMode="cover"
368
+ onError={() => setImageError(true)}
369
+ />
370
+ </View>
371
+ );
372
+ };
373
+
374
+ // Helper function to check for extension-generated thumbnails
375
+ const checkThumbnail = (message: CometChat.MediaMessage): { uri: string } => {
376
+ let image: { uri: string } = { uri: "" };
377
+ const thumbnailData = getExtensionData(message, ExtensionConstants.thumbnailGeneration);
378
+
379
+ if (thumbnailData == undefined) {
380
+ // Fallback to attachment thumbnail for videos
381
+ if (message.getType() === "video") {
382
+ const attachment = message.getAttachment();
383
+ const thumbnailUrl = attachment && ((attachment as any).thumbnail || (attachment as any).url);
384
+ image = thumbnailUrl ? { uri: thumbnailUrl } : image;
385
+ }
386
+ } else {
387
+ // Extension-generated thumbnail exists
388
+ const attachmentData = thumbnailData["attachments"];
389
+ if (attachmentData && attachmentData.length) {
390
+ const dataObj = attachmentData[0];
391
+ if (!dataObj["error"]) {
392
+ const imageLink = dataObj?.["data"]?.["thumbnails"]?.["url_small"];
393
+ if (imageLink) {
394
+ image = { uri: dataObj["data"]["thumbnails"]["url_small"] };
395
+ }
396
+ }
397
+ }
398
+ }
399
+
400
+ return image;
401
+ };
402
+
403
+ interface VideoThumbnailProps {
404
+ thumbnailUrl: ImageSourcePropType;
405
+ mergedStyles: any;
406
+ }
407
+
408
+ const VideoThumbnail = React.memo(({ thumbnailUrl, mergedStyles, }: VideoThumbnailProps) => {
409
+
410
+ const [imageSource, setImageSource] = useState<ImageSourcePropType>(thumbnailUrl);
411
+
412
+ useEffect(() => {
413
+ if (thumbnailUrl && typeof thumbnailUrl === "object" && "uri" in thumbnailUrl) {
414
+ CommonUtils.prefetchThumbnail((thumbnailUrl as any).uri).then((success) => {
415
+ if (success) {
416
+ // console.log("success", thumbnailUrl);
417
+ setImageSource(thumbnailUrl);
418
+
419
+ }
420
+ }).catch((error) => {
421
+ console.log("error", error);
422
+ });
423
+ }
424
+ }, [thumbnailUrl]);
425
+
426
+ return (
427
+ <View
428
+ style={mergedStyles.messageItemStyle?.previewContainerStyle}
429
+ renderToHardwareTextureAndroid={true}
430
+ shouldRasterizeIOS={true}
431
+ >
432
+ <ImageBackground
433
+ source={imageSource}
434
+ style={mergedStyles.messageItemStyle?.previewVideoStyle}
435
+ resizeMode="cover"
436
+ progressiveRenderingEnabled={true}
437
+ fadeDuration={0}
438
+ >
439
+ <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
440
+ <View style={mergedStyles.messageItemStyle?.videoPlayIconStyle}>
441
+ <Icon
442
+ name='play-arrow'
443
+ size={16}
444
+ height={16}
445
+ width={16}
446
+ color="white"
447
+ />
448
+ </View>
449
+ </View>
450
+ </ImageBackground>
451
+ </View>
452
+ );
453
+ },
454
+
455
+ /** Custom comparison function */
456
+ (prev, next) => {
457
+ const prevUri = (prev.thumbnailUrl as any)?.uri;
458
+ const nextUri = (next.thumbnailUrl as any)?.uri;
459
+
460
+ return prevUri === nextUri;
461
+ }
462
+ );
463
+
464
+ // Memoized Conversation Item Component
465
+ interface ConversationItemProps {
466
+ conversation: CometChat.Conversation;
467
+ searchText: string;
468
+ onPress: (conversation: CometChat.Conversation, searchText: string) => void;
469
+ mergedStyles: any;
470
+ theme: any;
471
+ conversationItemView?: (conversation: CometChat.Conversation, searchKeyword?: string) => React.ReactElement;
472
+ }
473
+
474
+ const ConversationItem = React.memo<ConversationItemProps>((
475
+ { conversation, searchText, onPress, mergedStyles, theme, conversationItemView }
476
+ ) => {
477
+ const getStatusIndicator = () => {
478
+ const withObj = conversation.getConversationWith();
479
+
480
+ if (withObj instanceof CometChat.Group) {
481
+ if (withObj.getType() === GroupTypeConstants.password) return "password";
482
+ if (withObj.getType() === GroupTypeConstants.private) return "private";
483
+ } else if (withObj instanceof CometChat.User) {
484
+ if (withObj.getStatus() === 'online' && !withObj.getHasBlockedMe() && !withObj.getBlockedByMe()) {
485
+ return "online";
486
+ }
487
+ return "offline";
488
+ }
489
+ return undefined;
490
+ };
491
+
492
+ const renderLeadingView = () => {
493
+ const withObj = conversation.getConversationWith();
494
+ const avatarURL = withObj instanceof CometChat.User ? withObj.getAvatar() : withObj.getIcon();
495
+ const name = withObj.getName();
496
+
497
+ return (
498
+ <View style={{ position: 'relative' }}>
499
+ <View style={{ height: 48, width: 48 }}>
500
+ <CometChatAvatar
501
+ image={{ uri: avatarURL }}
502
+ name={name}
503
+ />
504
+ <View style={{
505
+ position: 'absolute',
506
+ bottom: 0,
507
+ right: 0,
508
+ }}>
509
+ <CometChatStatusIndicator
510
+ type={getStatusIndicator()}
511
+ />
512
+ </View>
513
+ </View>
514
+ </View>
515
+ );
516
+ };
517
+
518
+ const renderTrailingView = () => {
519
+ const timestamp = conversation.getLastMessage()?.getSentAt();
520
+ if (!timestamp) return null;
521
+
522
+ return (
523
+ <View style={mergedStyles.conversationItemStyle?.trailingContainerStyle}>
524
+ <CometChatDate
525
+ timeStamp={timestamp * 1000}
526
+ pattern={"conversationDate"}
527
+ />
528
+ <CometChatBadge
529
+ count={conversation.getUnreadMessageCount()}
530
+ />
531
+ </View>
532
+ );
533
+ };
534
+
535
+ const formatMentionsInText = (rawText: any, message?: CometChat.BaseMessage) => {
536
+ if (typeof rawText !== 'string') return rawText;
537
+
538
+ let text = rawText.replace(/<@all:(.*?)>/g, '@$1');
539
+
540
+ try {
541
+ const mentionedUsers: CometChat.User[] = (message && (message).getMentionedUsers && (message).getMentionedUsers()) || [];
542
+ if (mentionedUsers && mentionedUsers.length > 0) {
543
+ mentionedUsers.forEach((u: CometChat.User) => {
544
+ const uid = u.getUid();
545
+ const name = u.getName();
546
+ if (uid && name) {
547
+ const uidRegex = new RegExp(`<@uid:${uid}>`, 'g');
548
+ text = text.replace(uidRegex, `@${name}`);
549
+ }
550
+ });
551
+ }
552
+ } catch (e) {
553
+ console.log(e)
554
+ }
555
+
556
+ return text;
557
+ };
558
+
559
+ if (conversationItemView) {
560
+ return (
561
+ <TouchableOpacity onPress={() => onPress(conversation, searchText)}>
562
+ {conversationItemView(conversation, searchText)}
563
+ </TouchableOpacity>
564
+ );
565
+ }
566
+
567
+ return (
568
+ <TouchableOpacity
569
+ style={mergedStyles.conversationItemStyle?.containerStyle}
570
+ onPress={() => onPress(conversation, searchText)}
571
+ >
572
+ {renderLeadingView()}
573
+ <View style={mergedStyles.conversationItemStyle?.contentStyle}>
574
+ <Text style={mergedStyles.conversationItemStyle?.titleStyle} numberOfLines={1}>
575
+ {conversation.getConversationWith().getName()}
576
+ </Text>
577
+ <Text style={mergedStyles.conversationItemStyle?.subtitleStyle} numberOfLines={2}>
578
+ {formatMentionsInText((conversation.getLastMessage())?.getText?.(), conversation.getLastMessage())}
579
+ </Text>
580
+ </View>
581
+ {renderTrailingView()}
582
+ </TouchableOpacity>
583
+ );
584
+ }, (prevProps, nextProps) => {
585
+ // Only re-render if conversation ID or search text changes
586
+ return prevProps.conversation.getConversationId() === nextProps.conversation.getConversationId() &&
587
+ prevProps.searchText === nextProps.searchText;
588
+ });
589
+
590
+ ConversationItem.displayName = 'ConversationItem';
591
+
592
+ /**
593
+ * CometChatSearch component for searching conversations and messages in CometChat
594
+ */
595
+ export const CometChatSearch: React.FC<CometChatSearchProps> = ({
596
+ onBack = () => { },
597
+ hideBackButton = false,
598
+ onConversationClicked,
599
+ onMessageClicked,
600
+ searchFilters = [
601
+ CometChatSearchFilter.Unread,
602
+ CometChatSearchFilter.Groups,
603
+ CometChatSearchFilter.Photos,
604
+ CometChatSearchFilter.Videos,
605
+ CometChatSearchFilter.Links,
606
+ CometChatSearchFilter.Documents,
607
+ CometChatSearchFilter.Audio
608
+ ],
609
+ initialSearchFilter,
610
+ searchIn = [],
611
+ conversationsRequestBuilder,
612
+ messagesRequestBuilder,
613
+ onError,
614
+ uid,
615
+ guid,
616
+ searchPlaceholder = t("SEARCH_PLACEHOLDER") || "Search...",
617
+ style,
618
+ loadingView,
619
+ emptyView,
620
+ errorView,
621
+ conversationItemView,
622
+ textMessageItemView,
623
+ imageMessageItemView,
624
+ audioMessageItemView,
625
+ videoMessageItemView,
626
+ documentMessageItemView,
627
+ linkMessageItemView
628
+ }) => {
629
+ const [searchState, dispatch] = useReducer(searchStateReducer, initialState);
630
+ const [searchValue, setSearchValue] = useState("");
631
+ const [loggedInUser, setLoggedInUser] = useState<CometChat.User | null>(null);
632
+
633
+ const theme = useTheme();
634
+ const errorHandler = useCometChatErrorHandler(onError);
635
+ const timeoutIdRef = useRef<any | null>(null);
636
+ const searchInputRef = useRef<TextInput>(null);
637
+
638
+ // Merge theme styles with provided style overrides
639
+ const mergedStyles = useMemo(() => {
640
+ const baseStyles = getSearchStyleLight(theme.color, theme.spacing, theme.typography);
641
+ return deepMerge(baseStyles, style ?? {});
642
+ }, [theme, style]);
643
+
644
+ // Initialize active filters with initial filter if provided
645
+ useEffect(() => {
646
+ if (searchState.activeFilters.length === 0 && initialSearchFilter) {
647
+ dispatch({ type: "setActiveFilter", filterId: initialSearchFilter });
648
+ }
649
+ }, [initialSearchFilter, searchState.activeFilters.length]);
650
+
651
+ // Get logged in user
652
+ useEffect(() => {
653
+ const getLoggedInUser = async () => {
654
+ try {
655
+ const user = await CometChat.getLoggedinUser();
656
+ setLoggedInUser(user);
657
+ } catch (error) {
658
+ errorHandler(error as CometChat.CometChatException, "getLoggedInUser");
659
+ }
660
+ };
661
+
662
+ getLoggedInUser();
663
+ }, [errorHandler]);
664
+
665
+ // Handle search input changes with debouncing
666
+ const handleSearch = useCallback((text: string) => {
667
+ setSearchValue(text);
668
+ const newSearchText = text.trim();
669
+
670
+ if (timeoutIdRef.current) {
671
+ clearTimeout(timeoutIdRef.current);
672
+ }
673
+
674
+ timeoutIdRef.current = setTimeout(() => {
675
+ dispatch({ type: "setSearchText", searchText: newSearchText });
676
+ timeoutIdRef.current = null;
677
+ }, 500);
678
+ }, []);
679
+
680
+ // Clear search
681
+ const handleClearSearch = useCallback(() => {
682
+ setSearchValue("");
683
+ dispatch({ type: "setSearchText", searchText: "" });
684
+ dispatch({ type: "resetActiveFilters" });
685
+ dispatch({ type: "clearResults" });
686
+ }, []);
687
+
688
+ // Toggle filter
689
+ const toggleFilter = useCallback((filterId: CometChatSearchFilter) => {
690
+ dispatch({ type: "setActiveFilter", filterId });
691
+ }, []);
692
+
693
+ // Auto-focus the search input when component mounts
694
+ useEffect(() => {
695
+ const timer = setTimeout(() => {
696
+ if (searchInputRef.current) {
697
+ searchInputRef.current.focus();
698
+ }
699
+ }, 100);
700
+ return () => clearTimeout(timer);
701
+ }, []);
702
+
703
+ // Cleanup timeout on unmount
704
+ useEffect(() => {
705
+ return () => {
706
+ if (timeoutIdRef.current) {
707
+ clearTimeout(timeoutIdRef.current);
708
+ }
709
+ };
710
+ }, []);
711
+
712
+ const renderHeader = () => (
713
+ <View style={[mergedStyles.headerStyle]}>
714
+ {!hideBackButton && (
715
+ <TouchableOpacity
716
+ style={[mergedStyles.backButtonStyle]}
717
+ onPress={onBack}
718
+ >
719
+ <Icon
720
+ name='arrow-back'
721
+ imageStyle={mergedStyles.backButtonIconStyle}
722
+ color={mergedStyles?.backButtonIconStyle?.tintColor}
723
+ />
724
+ </TouchableOpacity>
725
+ )}
726
+ <View style={[mergedStyles.searchContainerStyle]}>
727
+ <View style={[mergedStyles.searchInputContainerStyle]}>
728
+ <TextInput
729
+ ref={searchInputRef}
730
+ style={[mergedStyles.searchInputStyle]}
731
+ value={searchValue}
732
+ onChangeText={handleSearch}
733
+ placeholder={searchPlaceholder}
734
+ placeholderTextColor={theme.color.textTertiary}
735
+ />
736
+
737
+ <TouchableOpacity
738
+ style={[mergedStyles.clearButtonStyle]}
739
+ onPress={handleClearSearch}
740
+ accessibilityLabel="Clear search"
741
+ >
742
+ <Icon
743
+ name='close'
744
+ imageStyle={mergedStyles.clearButtonIconStyle}
745
+ />
746
+ </TouchableOpacity>
747
+ </View>
748
+ </View>
749
+ </View>
750
+ );
751
+
752
+ const getVisibleFilters = useCallback(() => {
753
+ const conversationFilters = [
754
+ CometChatSearchFilter.Conversations,
755
+ CometChatSearchFilter.Unread,
756
+ CometChatSearchFilter.Groups
757
+ ];
758
+
759
+ const messageFilters = [
760
+ CometChatSearchFilter.Messages,
761
+ CometChatSearchFilter.Photos,
762
+ CometChatSearchFilter.Videos,
763
+ CometChatSearchFilter.Documents,
764
+ CometChatSearchFilter.Audio,
765
+ CometChatSearchFilter.Links
766
+ ];
767
+
768
+ // Define filter pairs
769
+ const filterPairs = {
770
+ conversationPair: [CometChatSearchFilter.Unread, CometChatSearchFilter.Groups],
771
+ photosVideosPair: [CometChatSearchFilter.Photos, CometChatSearchFilter.Videos],
772
+ audioDocumentsPair: [CometChatSearchFilter.Audio, CometChatSearchFilter.Documents],
773
+ linkStandalone: [CometChatSearchFilter.Links]
774
+ };
775
+
776
+ // If searchIn is empty, search in both conversations and messages
777
+ const effectiveSearchIn = searchIn.length === 0
778
+ ? [CometChatSearchScope.Conversations, CometChatSearchScope.Messages]
779
+ : searchIn;
780
+
781
+ let availableFilters: CometChatSearchFilter[] = [];
782
+
783
+ // Add filters based on searchIn scope
784
+ if (effectiveSearchIn.includes(CometChatSearchScope.Conversations)) {
785
+ availableFilters.push(...conversationFilters);
786
+ }
787
+ if (effectiveSearchIn.includes(CometChatSearchScope.Messages)) {
788
+ availableFilters.push(...messageFilters);
789
+ }
790
+
791
+ // Filter the searchFilters prop to only include available filters
792
+ let filteredAvailableFilters = searchFilters.filter(filter => availableFilters.includes(filter));
793
+
794
+ // Filter out conversation filters if uid or guid is present
795
+ if (uid || guid) {
796
+ filteredAvailableFilters = filteredAvailableFilters.filter(filter => !conversationFilters.includes(filter));
797
+ }
798
+
799
+ // If no filters are selected, return filtered available filters
800
+ if (searchState.activeFilters.length === 0) {
801
+ return filteredAvailableFilters;
802
+ }
803
+
804
+ // Handle pairing logic
805
+ const activeFilters = searchState.activeFilters;
806
+
807
+ // Check which pair is active
808
+ const hasConversationPair = activeFilters.some(filter => filterPairs.conversationPair.includes(filter));
809
+ const hasPhotosVideosPair = activeFilters.some(filter => filterPairs.photosVideosPair.includes(filter));
810
+ const hasAudioDocumentsPair = activeFilters.some(filter => filterPairs.audioDocumentsPair.includes(filter));
811
+ const hasLinkStandalone = activeFilters.includes(CometChatSearchFilter.Links);
812
+
813
+ // If conversation pair is active, show only conversation filters
814
+ if (hasConversationPair && effectiveSearchIn.includes(CometChatSearchScope.Conversations) && !uid && !guid) {
815
+ return filterPairs.conversationPair.filter(filter => filteredAvailableFilters.includes(filter));
816
+ }
817
+
818
+ // If photos/videos pair is active, show only photos and videos
819
+ if (hasPhotosVideosPair) {
820
+ return filterPairs.photosVideosPair.filter(filter => filteredAvailableFilters.includes(filter));
821
+ }
822
+
823
+ // If audio/documents pair is active, show only audio and documents
824
+ if (hasAudioDocumentsPair) {
825
+ return filterPairs.audioDocumentsPair.filter(filter => filteredAvailableFilters.includes(filter));
826
+ }
827
+
828
+ // If links is active (standalone), show only links
829
+ if (hasLinkStandalone) {
830
+ return filterPairs.linkStandalone.filter(filter => filteredAvailableFilters.includes(filter));
831
+ }
832
+
833
+ // Fallback: return filtered available filters
834
+ return filteredAvailableFilters;
835
+ }, [searchState.activeFilters, searchFilters, searchIn, uid, guid]);
836
+
837
+ const getFilterText = (filterId: CometChatSearchFilter): string => {
838
+ const filterTextMap = {
839
+ [CometChatSearchFilter.Audio]: t("SEARCH_FILTER_AUDIO") || "Audio",
840
+ [CometChatSearchFilter.Conversations]: t("SEARCH_FILTER_CONVERSATIONS") || "Conversations",
841
+ [CometChatSearchFilter.Documents]: t("SEARCH_FILTER_DOCUMENTS") || "Documents",
842
+ [CometChatSearchFilter.Groups]: t("SEARCH_FILTER_GROUPS") || "Groups",
843
+ [CometChatSearchFilter.Links]: t("SEARCH_FILTER_LINKS") || "Links",
844
+ [CometChatSearchFilter.Messages]: t("SEARCH_FILTER_MESSAGES") || "Messages",
845
+ [CometChatSearchFilter.Photos]: t("SEARCH_FILTER_PHOTOS") || "Photos",
846
+ [CometChatSearchFilter.Unread]: t("SEARCH_FILTER_UNREAD") || "Unread",
847
+ [CometChatSearchFilter.Videos]: t("SEARCH_FILTER_VIDEOS") || "Videos",
848
+ };
849
+ return filterTextMap[filterId] || "";
850
+ };
851
+
852
+ const getFilterIcon = (filterId: CometChatSearchFilter) => {
853
+ const filterIconMap = {
854
+ [CometChatSearchFilter.Audio]: "mic-fill" as const,
855
+ [CometChatSearchFilter.Documents]: "documents" as const,
856
+ [CometChatSearchFilter.Groups]: "group" as const,
857
+ [CometChatSearchFilter.Links]: "link" as const,
858
+ [CometChatSearchFilter.Messages]: "chat" as const,
859
+ [CometChatSearchFilter.Photos]: "photo" as const,
860
+ [CometChatSearchFilter.Unread]: "unread" as const,
861
+ [CometChatSearchFilter.Videos]: "videocam" as const,
862
+ [CometChatSearchFilter.Conversations]: "chat" as const,
863
+ };
864
+ return filterIconMap[filterId];
865
+ };
866
+
867
+ const renderFilters = () => {
868
+ const visibleFilters = getVisibleFilters();
869
+
870
+ if (visibleFilters.length === 0) {
871
+ return null;
872
+ }
873
+
874
+ return (
875
+ <View style={[mergedStyles.filtersContainerStyle]}>
876
+ <View style={mergedStyles.filtersContentStyle}>
877
+ {visibleFilters.map((filterId) => {
878
+ const isActive = searchState.activeFilters.includes(filterId);
879
+ const iconName = getFilterIcon(filterId);
880
+ return (
881
+ <TouchableOpacity
882
+ key={filterId}
883
+ style={[
884
+ mergedStyles.filterButtonStyle,
885
+ isActive && mergedStyles.filterButtonActiveStyle
886
+ ]}
887
+ onPress={() => toggleFilter(filterId)}
888
+ >
889
+ <View style={mergedStyles.filterButtonContentStyle}>
890
+ {iconName && (
891
+ <Icon
892
+ name={iconName}
893
+ imageStyle={[
894
+ mergedStyles.filterButtonIconStyle,
895
+ isActive && mergedStyles.filterButtonIconActiveStyle
896
+ ]}
897
+ width={16}
898
+ height={16}
899
+ />
900
+ )}
901
+ <Text style={[
902
+ mergedStyles.filterButtonTextStyle,
903
+ isActive && mergedStyles.filterButtonTextActiveStyle
904
+ ]}>
905
+ {getFilterText(filterId)}
906
+ </Text>
907
+ </View>
908
+ </TouchableOpacity>
909
+ );
910
+ })}
911
+ </View>
912
+ </View>
913
+ );
914
+ };
915
+
916
+ // ============================================================================
917
+ // CONVERSATIONS SEARCH LOGIC (moved from useCometChatSearchConversationsList.ts)
918
+ // ============================================================================
919
+ const [conversationState, setConversationState] = useState({
920
+ conversationList: [] as CometChat.Conversation[],
921
+ fetchState: States.loaded,
922
+ hasMoreResults: false,
923
+ });
924
+
925
+ const conversationRequestRef = useRef<CometChat.ConversationsRequest | null>(null);
926
+ const lastConversationSearchKeyword = useRef<string>(searchState.searchText);
927
+ const lastConversationActiveFilters = useRef<CometChatSearchFilter[]>(searchState.activeFilters);
928
+ const isConversationMoreResultsLoading = useRef<boolean>(false);
929
+
930
+ // ============================================================================
931
+ // MESSAGES SEARCH LOGIC (moved from useCometChatSearchMessagesList.ts)
932
+ // ============================================================================
933
+ const [messageState, setMessageState] = useState({
934
+ messageList: [] as CometChat.BaseMessage[],
935
+ fetchState: States.loaded,
936
+ hasMoreResults: false,
937
+ });
938
+
939
+ const messageRequestRef = useRef<CometChat.MessagesRequest | null>(null);
940
+ const lastMessageSearchKeyword = useRef<string>(searchState.searchText);
941
+ const lastMessageActiveFilters = useRef<CometChatSearchFilter[]>(searchState.activeFilters);
942
+ const isMessageMoreResultsLoading = useRef<boolean>(false);
943
+
944
+ // ============================================================================
945
+ // CONVERSATION SEARCH FUNCTIONS
946
+ // ============================================================================
947
+ const buildConversationsRequest = useCallback(() => {
948
+ let builder = conversationsRequestBuilder
949
+ ? Object.assign(Object.create(Object.getPrototypeOf(conversationsRequestBuilder)), conversationsRequestBuilder)
950
+ : new CometChat.ConversationsRequestBuilder();
951
+
952
+ if (searchState.searchText && searchState.searchText.trim() !== "") {
953
+ builder = builder.setSearchKeyword(searchState.searchText);
954
+ }
955
+
956
+ const limit = (guid || uid || searchState.activeFilters.length > 0) ? 30 : 3;
957
+ builder = builder.setLimit(limit);
958
+
959
+ // Apply filters - both can be active simultaneously for unread group conversations
960
+ if (searchState.activeFilters.includes(CometChatSearchFilter.Unread)) {
961
+ builder = builder.setUnread(true);
962
+ }
963
+
964
+ if (searchState.activeFilters.includes(CometChatSearchFilter.Groups)) {
965
+ builder = builder.setConversationType(ReceiverTypeConstants.group);
966
+ }
967
+
968
+ return builder.build();
969
+ }, [conversationsRequestBuilder, searchState.searchText, searchState.activeFilters, guid, uid]);
970
+
971
+ const loadMoreConversations = useCallback(async () => {
972
+ if (isConversationMoreResultsLoading.current || !conversationRequestRef.current || !conversationState.hasMoreResults) {
973
+ return;
974
+ }
975
+
976
+ try {
977
+ isConversationMoreResultsLoading.current = true;
978
+ const moreConversations = await conversationRequestRef.current.fetchNext();
979
+
980
+ if (moreConversations.length > 0) {
981
+ setConversationState(prev => ({
982
+ ...prev,
983
+ conversationList: [...prev.conversationList, ...moreConversations],
984
+ hasMoreResults: moreConversations.length === 3 || moreConversations.length === 30 // Check if more results might be available
985
+ }));
986
+ } else {
987
+ setConversationState(prev => ({
988
+ ...prev,
989
+ hasMoreResults: false
990
+ }));
991
+ }
992
+ } catch (error) {
993
+ errorHandler(error, "loadMoreConversations");
994
+ } finally {
995
+ isConversationMoreResultsLoading.current = false;
996
+ }
997
+ }, [errorHandler, conversationState.hasMoreResults]);
998
+
999
+ const searchConversations = useCallback(async () => {
1000
+ try {
1001
+ setConversationState(prev => ({ ...prev, fetchState: States.loading }));
1002
+
1003
+ if (!hasValidConversationSearchCriteria(searchState.searchText, searchState.activeFilters)) {
1004
+ setConversationState(prev => ({
1005
+ ...prev,
1006
+ conversationList: [],
1007
+ fetchState: States.loaded,
1008
+ hasMoreResults: false
1009
+ }));
1010
+ return;
1011
+ }
1012
+
1013
+ conversationRequestRef.current = buildConversationsRequest();
1014
+ const conversations = await conversationRequestRef.current!.fetchNext();
1015
+
1016
+ if (conversations.length > 0) {
1017
+ const limit = (guid || uid || searchState.activeFilters.length > 0) ? 30 : 3;
1018
+ setConversationState({
1019
+ conversationList: conversations,
1020
+ fetchState: States.loaded,
1021
+ hasMoreResults: conversations.length >= limit,
1022
+ });
1023
+ } else {
1024
+ setConversationState({
1025
+ conversationList: [],
1026
+ fetchState: States.loaded,
1027
+ hasMoreResults: false,
1028
+ });
1029
+ }
1030
+ } catch (error) {
1031
+ errorHandler(error, "searchConversations");
1032
+ setConversationState(prev => ({ ...prev, fetchState: States.error }));
1033
+ }
1034
+ }, [searchState.searchText, searchState.activeFilters, buildConversationsRequest, guid, uid, errorHandler]);
1035
+
1036
+ // ============================================================================
1037
+ // MESSAGE SEARCH FUNCTIONS
1038
+ // ============================================================================
1039
+ const buildMessagesRequest = useCallback(() => {
1040
+ let builder = messagesRequestBuilder
1041
+ ? Object.assign(Object.create(Object.getPrototypeOf(messagesRequestBuilder)), messagesRequestBuilder)
1042
+ : new CometChat.MessagesRequestBuilder();
1043
+
1044
+ builder = builder.hideDeletedMessages(true);
1045
+ const limit = (guid || uid || searchState.activeFilters.length > 0) ? 30 : 3;
1046
+
1047
+ if (!messagesRequestBuilder) {
1048
+ builder = builder
1049
+ .setCategories([MessageCategoryConstants.message, MessageCategoryConstants.custom])
1050
+ .setTypes([MessageTypeConstants.text, MessageTypeConstants.image, MessageTypeConstants.video, MessageTypeConstants.audio, MessageTypeConstants.file])
1051
+ .setLimit(limit);
1052
+ }
1053
+
1054
+ if (searchState.searchText && searchState.searchText.trim() !== "") {
1055
+ builder = builder.setSearchKeyword(searchState.searchText);
1056
+ }
1057
+
1058
+ if (uid) {
1059
+ builder = builder.setUID(uid);
1060
+ } else if (guid) {
1061
+ builder = builder.setGUID(guid);
1062
+ }
1063
+
1064
+ if (searchState.activeFilters && searchState.activeFilters.length > 0) {
1065
+ if (searchState.activeFilters.includes(CometChatSearchFilter.Links)) {
1066
+ builder = builder.hasLinks(true);
1067
+ }
1068
+
1069
+ const attachmentTypeMap = {
1070
+ [CometChatSearchFilter.Photos]: CometChat.AttachmentType.IMAGE,
1071
+ [CometChatSearchFilter.Videos]: CometChat.AttachmentType.VIDEO,
1072
+ [CometChatSearchFilter.Documents]: CometChat.AttachmentType.FILE,
1073
+ [CometChatSearchFilter.Audio]: CometChat.AttachmentType.AUDIO,
1074
+ };
1075
+
1076
+ // Collect all attachment types for active filters
1077
+ const activeAttachmentTypes: CometChat.AttachmentType[] = [];
1078
+ for (const [filter, attachmentType] of Object.entries(attachmentTypeMap)) {
1079
+ if (searchState.activeFilters.includes(filter as CometChatSearchFilter)) {
1080
+ activeAttachmentTypes.push(attachmentType);
1081
+ }
1082
+ }
1083
+
1084
+ // Set all active attachment types (supports multiple types for paired filters)
1085
+ if (activeAttachmentTypes.length > 0) {
1086
+ builder = builder.setAttachmentTypes(activeAttachmentTypes);
1087
+ }
1088
+ }
1089
+
1090
+ return builder.build();
1091
+ }, [messagesRequestBuilder, searchState.activeFilters, searchState.searchText, uid, guid]);
1092
+
1093
+ const loadMoreMessages = useCallback(async () => {
1094
+ if (isMessageMoreResultsLoading.current || !messageRequestRef.current || !messageState.hasMoreResults) {
1095
+ return;
1096
+ }
1097
+
1098
+ try {
1099
+ isMessageMoreResultsLoading.current = true;
1100
+ const moreMessages = await messageRequestRef.current.fetchPrevious();
1101
+
1102
+ if (moreMessages.length > 0) {
1103
+
1104
+ const filteredMoreMessages = moreMessages.filter(msg => {
1105
+ const isDeleted = (msg as any).getDeletedAt && (msg as any).getDeletedAt() > 0;
1106
+ const isActionMessage = msg.getCategory() === MessageCategoryConstants.action;
1107
+ return !isDeleted && !isActionMessage;
1108
+ });
1109
+
1110
+ setMessageState(prev => ({
1111
+ ...prev,
1112
+ messageList: [...prev.messageList, ...filteredMoreMessages],
1113
+ hasMoreResults: moreMessages.length === 3 || moreMessages.length === 30 // Check if more results might be available
1114
+ }));
1115
+ } else {
1116
+ setMessageState(prev => ({
1117
+ ...prev,
1118
+ hasMoreResults: false
1119
+ }));
1120
+ }
1121
+ } catch (error) {
1122
+ errorHandler(error, "loadMoreMessages");
1123
+ } finally {
1124
+ isMessageMoreResultsLoading.current = false;
1125
+ }
1126
+ }, [errorHandler, messageState.hasMoreResults]);
1127
+
1128
+ const searchMessages = useCallback(async () => {
1129
+ try {
1130
+ setMessageState(prev => ({ ...prev, fetchState: States.loading }));
1131
+
1132
+ if (!hasValidMessageSearchCriteria(searchState.searchText, searchState.activeFilters)) {
1133
+ setMessageState(prev => ({
1134
+ ...prev,
1135
+ messageList: [],
1136
+ fetchState: States.loaded,
1137
+ hasMoreResults: false
1138
+ }));
1139
+ return;
1140
+ }
1141
+
1142
+ messageRequestRef.current = buildMessagesRequest();
1143
+ const messages = await messageRequestRef.current!.fetchPrevious();
1144
+
1145
+ if (messages.length > 0) {
1146
+ const reversedList = messages.reverse();
1147
+
1148
+ const filteredMessages = reversedList.filter(msg => {
1149
+ const isDeleted = (msg as any).getDeletedAt && (msg as any).getDeletedAt() > 0;
1150
+ const isActionMessage = msg.getCategory() === MessageCategoryConstants.action;
1151
+ return !isDeleted && !isActionMessage;
1152
+ });
1153
+
1154
+ const limit = (guid || uid || searchState.activeFilters.length > 0) ? 30 : 3;
1155
+ setMessageState({
1156
+ messageList: filteredMessages,
1157
+ fetchState: States.loaded,
1158
+ hasMoreResults: messages.length >= limit,
1159
+ });
1160
+ } else {
1161
+ setMessageState({
1162
+ messageList: [],
1163
+ fetchState: States.loaded,
1164
+ hasMoreResults: false,
1165
+ });
1166
+ }
1167
+ } catch (error) {
1168
+ errorHandler(error, "searchMessages");
1169
+ setMessageState(prev => ({ ...prev, fetchState: States.error }));
1170
+ }
1171
+ }, [searchState.searchText, searchState.activeFilters, buildMessagesRequest, guid, uid, errorHandler]);
1172
+
1173
+ // ============================================================================
1174
+ // SEARCH EFFECTS - Trigger searches when search text or filters change
1175
+ // ============================================================================
1176
+ useEffect(() => {
1177
+ const hasKeywordChanged = searchState.searchText !== lastConversationSearchKeyword.current;
1178
+ const haveFiltersChanged = JSON.stringify(searchState.activeFilters) !== JSON.stringify(lastConversationActiveFilters.current);
1179
+
1180
+ if (hasKeywordChanged || haveFiltersChanged) {
1181
+ lastConversationSearchKeyword.current = searchState.searchText;
1182
+ lastConversationActiveFilters.current = [...searchState.activeFilters];
1183
+ searchConversations();
1184
+ }
1185
+ }, [searchState.searchText, searchState.activeFilters, searchConversations]);
1186
+
1187
+ useEffect(() => {
1188
+ const hasKeywordChanged = searchState.searchText !== lastMessageSearchKeyword.current;
1189
+ const haveFiltersChanged = JSON.stringify(searchState.activeFilters) !== JSON.stringify(lastMessageActiveFilters.current);
1190
+
1191
+ if (hasKeywordChanged || haveFiltersChanged) {
1192
+ lastMessageSearchKeyword.current = searchState.searchText;
1193
+ lastMessageActiveFilters.current = [...searchState.activeFilters];
1194
+ searchMessages();
1195
+ }
1196
+ }, [searchState.searchText, searchState.activeFilters, searchMessages]);
1197
+
1198
+ const shouldRenderConversations = useCallback(() => {
1199
+ // If searchIn is empty, search in both conversations and messages
1200
+ const effectiveSearchIn = searchIn.length === 0
1201
+ ? [CometChatSearchScope.Conversations, CometChatSearchScope.Messages]
1202
+ : searchIn;
1203
+
1204
+ // Don't render conversations if searchIn doesn't include conversations scope
1205
+ if (!effectiveSearchIn.includes(CometChatSearchScope.Conversations)) {
1206
+ return false;
1207
+ }
1208
+
1209
+ // Don't render conversations if uid or guid is present (searching within specific user/group)
1210
+ if (uid || guid) {
1211
+ return false;
1212
+ }
1213
+
1214
+ // Define conversation filters
1215
+ const conversationFilters = [CometChatSearchFilter.Unread, CometChatSearchFilter.Groups];
1216
+
1217
+ if (searchState.searchText && searchState.searchText.trim() !== "" && searchState.activeFilters.length === 0) {
1218
+ return true;
1219
+ }
1220
+
1221
+ if (searchState.activeFilters.length > 0) {
1222
+ return searchState.activeFilters.some(filter => conversationFilters.includes(filter));
1223
+ }
1224
+
1225
+ return false;
1226
+ }, [searchState.activeFilters, searchState.searchText, uid, guid, searchIn]);
1227
+
1228
+ const shouldRenderMessages = useCallback(() => {
1229
+ // If searchIn is empty, search in both conversations and messages
1230
+ const effectiveSearchIn = searchIn.length === 0
1231
+ ? [CometChatSearchScope.Conversations, CometChatSearchScope.Messages]
1232
+ : searchIn;
1233
+
1234
+ // Don't render messages if searchIn doesn't include messages scope
1235
+ if (!effectiveSearchIn.includes(CometChatSearchScope.Messages)) {
1236
+ return false;
1237
+ }
1238
+
1239
+ // Always render messages if uid or guid is present (searching within specific user/group)
1240
+ if (uid || guid) {
1241
+ return true;
1242
+ }
1243
+
1244
+ // Define message filters
1245
+ const messageFilters = [
1246
+ CometChatSearchFilter.Photos,
1247
+ CometChatSearchFilter.Videos,
1248
+ CometChatSearchFilter.Documents,
1249
+ CometChatSearchFilter.Audio,
1250
+ CometChatSearchFilter.Links
1251
+ ];
1252
+
1253
+ // Define conversation filters
1254
+ const conversationFilters = [CometChatSearchFilter.Unread, CometChatSearchFilter.Groups];
1255
+
1256
+ if (searchState.searchText && searchState.searchText.trim() !== "" && searchState.activeFilters.length === 0) {
1257
+ return true;
1258
+ }
1259
+
1260
+ if (searchState.activeFilters.length > 0) {
1261
+ // Show messages if any message filter is selected and no conversation filter is selected
1262
+ return searchState.activeFilters.some(filter => messageFilters.includes(filter)) &&
1263
+ !searchState.activeFilters.some(filter => conversationFilters.includes(filter));
1264
+ }
1265
+
1266
+ return false;
1267
+ }, [searchState.activeFilters, searchState.searchText, uid, guid, searchIn]);
1268
+
1269
+ // Handle scroll-based fetching for messages
1270
+ const handleScrollEnd = useCallback((event: any) => {
1271
+ if (!shouldRenderMessages() || !messageState.hasMoreResults) return;
1272
+
1273
+ const contentOffsetY = event.nativeEvent.contentOffset.y;
1274
+ const contentHeight = event.nativeEvent.contentSize.height;
1275
+ const layoutHeight = event.nativeEvent.layoutMeasurement.height;
1276
+
1277
+ if (contentOffsetY + layoutHeight >= contentHeight - 10) {
1278
+ loadMoreMessages();
1279
+ }
1280
+ }, [shouldRenderMessages, messageState.hasMoreResults, loadMoreMessages]);
1281
+
1282
+ // Get status indicator for conversation
1283
+ const getStatusIndicator = (conv: CometChat.Conversation) => {
1284
+ const withObj = conv.getConversationWith();
1285
+
1286
+ if (withObj instanceof CometChat.Group) {
1287
+ if (withObj.getType() === GroupTypeConstants.password) return "password";
1288
+ if (withObj.getType() === GroupTypeConstants.private) return "private";
1289
+ } else if (withObj instanceof CometChat.User) {
1290
+ if (withObj.getStatus() === 'online' && !withObj.getHasBlockedMe() && !withObj.getBlockedByMe()) {
1291
+ return "online";
1292
+ }
1293
+ return "offline";
1294
+ }
1295
+ return undefined;
1296
+ };
1297
+
1298
+ // Render conversation avatar
1299
+ const renderConversationLeadingView = (conversation: CometChat.Conversation) => {
1300
+ const withObj = conversation.getConversationWith();
1301
+ const avatarURL = withObj instanceof CometChat.User ? withObj.getAvatar() : withObj.getIcon();
1302
+ const name = withObj.getName();
1303
+
1304
+ return (
1305
+ <View style={{ position: 'relative' }}>
1306
+ <View style={{ height: 48, width: 48 }}>
1307
+ <CometChatAvatar
1308
+ image={{ uri: avatarURL }}
1309
+ name={name}
1310
+ />
1311
+ <View style={{
1312
+ position: 'absolute',
1313
+ bottom: 0,
1314
+ right: 0,
1315
+ }}>
1316
+ <CometChatStatusIndicator
1317
+ type={getStatusIndicator(conversation)}
1318
+ />
1319
+ </View>
1320
+ </View>
1321
+ </View>
1322
+ );
1323
+ };
1324
+
1325
+ // Render conversation trailing view (date and badge)
1326
+ const renderConversationTrailingView = (conversation: CometChat.Conversation) => {
1327
+ const timestamp = conversation.getLastMessage()?.getSentAt();
1328
+ if (!timestamp) return null;
1329
+
1330
+ return (
1331
+ <View style={mergedStyles.conversationItemStyle?.trailingContainerStyle}>
1332
+ <CometChatDate
1333
+ timeStamp={timestamp * 1000}
1334
+ pattern={"conversationDate"}
1335
+ />
1336
+ <CometChatBadge
1337
+ count={conversation.getUnreadMessageCount()}
1338
+ />
1339
+ </View>
1340
+ );
1341
+ };
1342
+
1343
+ // Get file type icon based on file extension
1344
+ const getFileTypeIcon = (fileName: string): 'audio-file-type' | 'image-file-type' | 'video-file-type' | 'pdf-file-type' | 'presentation-file-type' | 'spreadsheet-file-type' | 'text-file-type' | 'zip-file-type' | 'document-file-type' | 'unknown-file-type' => {
1345
+ if (!fileName) return 'unknown-file-type';
1346
+
1347
+ const extension = fileName.toLowerCase().split('.').pop() || '';
1348
+
1349
+ // Audio files
1350
+ if (['mp3', 'wav', 'ogg', 'aac', 'm4a', 'flac'].includes(extension)) {
1351
+ return 'audio-file-type';
1352
+ }
1353
+
1354
+ // Image files
1355
+ if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'].includes(extension)) {
1356
+ return 'image-file-type';
1357
+ }
1358
+
1359
+ // Video files
1360
+ if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'].includes(extension)) {
1361
+ return 'video-file-type';
1362
+ }
1363
+
1364
+ // PDF files
1365
+ if (extension === 'pdf') {
1366
+ return 'pdf-file-type';
1367
+ }
1368
+
1369
+ // Presentation files
1370
+ if (['ppt', 'pptx', 'key'].includes(extension)) {
1371
+ return 'presentation-file-type';
1372
+ }
1373
+
1374
+ // Spreadsheet files
1375
+ if (['xls', 'xlsx', 'csv', 'numbers'].includes(extension)) {
1376
+ return 'spreadsheet-file-type';
1377
+ }
1378
+
1379
+ // Text/Document files
1380
+ if (['txt', 'rtf', 'doc', 'docx', 'pages'].includes(extension)) {
1381
+ return 'text-file-type';
1382
+ }
1383
+
1384
+ // ZIP/Archive files
1385
+ if (['zip', 'rar', '7z', 'tar', 'gz'].includes(extension)) {
1386
+ return 'zip-file-type';
1387
+ }
1388
+
1389
+ // Default document type for other files
1390
+ return 'document-file-type';
1391
+ };
1392
+
1393
+ // Format mentions in raw message text: convert <@all:alias> to @alias
1394
+ // and <@uid:UID> to @Name when message provides mentioned users
1395
+ const formatMentionsInText = (rawText: any, message?: CometChat.BaseMessage) => {
1396
+ if (typeof rawText !== 'string') return rawText;
1397
+
1398
+ let text = rawText.replace(/<@all:(.*?)>/g, '@$1');
1399
+
1400
+ try {
1401
+ const mentionedUsers: CometChat.User[] = (message && (message).getMentionedUsers && (message).getMentionedUsers()) || [];
1402
+ if (mentionedUsers && mentionedUsers.length > 0) {
1403
+ mentionedUsers.forEach((u: CometChat.User) => {
1404
+ const uid = u.getUid();
1405
+ const name = u.getName();
1406
+ if (uid && name) {
1407
+ const uidRegex = new RegExp(`<@uid:${uid}>`, 'g');
1408
+ text = text.replace(uidRegex, `@${name}`);
1409
+ }
1410
+ });
1411
+ }
1412
+ } catch (e) {
1413
+ console.log(e)
1414
+ }
1415
+
1416
+ return text;
1417
+ };
1418
+
1419
+ // Render message leading view (for audio/file icons)
1420
+ const renderMessageLeadingView = (message: CometChat.BaseMessage) => {
1421
+ const messageType = message.getType();
1422
+
1423
+ switch (messageType) {
1424
+ case 'audio': {
1425
+ return (
1426
+ <View style={mergedStyles.messageItemStyle?.iconContainerStyle}>
1427
+ <View style={[mergedStyles.messageItemStyle?.audioPreviewStyle, {
1428
+ backgroundColor: theme.color.primary,
1429
+ borderRadius: 1000,
1430
+ justifyContent: 'center',
1431
+ alignItems: 'center',
1432
+ height: 32,
1433
+ width: 32,
1434
+ }]}>
1435
+ <Icon
1436
+ name='play-arrow-fill'
1437
+ size={theme.spacing.spacing.s7}
1438
+ height={32}
1439
+ width={32}
1440
+ color={theme.color.staticWhite}
1441
+ />
1442
+ </View>
1443
+ </View>
1444
+ );
1445
+ }
1446
+
1447
+ case 'file': {
1448
+ const fileMessage = message as CometChat.MediaMessage;
1449
+ const attachment = fileMessage.getAttachment();
1450
+ const fileName = attachment?.getName?.() || '';
1451
+ const fileTypeIcon = getFileTypeIcon(fileName);
1452
+
1453
+ return (
1454
+ <View style={mergedStyles.messageItemStyle?.iconContainerStyle}>
1455
+ <Icon
1456
+ name={fileTypeIcon}
1457
+ size={48}
1458
+ height={48}
1459
+ width={48}
1460
+ color={theme.color.iconSecondary}
1461
+ />
1462
+ </View>
1463
+ );
1464
+ }
1465
+
1466
+ case 'text': {
1467
+ // Check if this is a text message with link metadata (link preview)
1468
+ const textMessage = message as CometChat.TextMessage;
1469
+ const metadata = textMessage.getMetadata();
1470
+ const linkPreview = metadata && (metadata as any)['@injected'] && (metadata as any)['@injected']['extensions'] && (metadata as any)['@injected']['extensions']['link-preview'];
1471
+
1472
+ if (linkPreview && linkPreview.links && linkPreview.links.length > 0) {
1473
+ const firstLink = linkPreview.links[0];
1474
+ const thumbnailUrl = firstLink.image || firstLink.favicon;
1475
+
1476
+ if (thumbnailUrl) {
1477
+ return (
1478
+ <LinkPreviewImage
1479
+ uri={thumbnailUrl}
1480
+ mergedStyles={mergedStyles}
1481
+ theme={theme}
1482
+ />
1483
+ );
1484
+ } else {
1485
+ // Fallback to link icon if no thumbnail
1486
+ return (
1487
+ <View style={mergedStyles.messageItemStyle?.iconContainerStyle}>
1488
+ <Icon
1489
+ name='link-fill'
1490
+ size={48}
1491
+ height={48}
1492
+ width={48}
1493
+ color={theme.color.iconSecondary}
1494
+ />
1495
+ </View>
1496
+ );
1497
+ }
1498
+ }
1499
+ return null;
1500
+ }
1501
+
1502
+ default:
1503
+ return null;
1504
+ }
1505
+ };
1506
+
1507
+ // Render message trailing view (content preview or date)
1508
+ const renderMessageTrailingView = (message: CometChat.BaseMessage) => {
1509
+ const timestamp = message.getSentAt();
1510
+ if (!timestamp) return null;
1511
+
1512
+ const messageType = message.getType();
1513
+
1514
+ // Handle different message types
1515
+ switch (messageType) {
1516
+ case 'image': {
1517
+ const imageMessage = message as CometChat.MediaMessage;
1518
+ const attachment = imageMessage.getAttachment();
1519
+ const imageUrl = attachment && (attachment as any).url;
1520
+ if (imageUrl) {
1521
+ return (
1522
+ <View style={mergedStyles.messageItemStyle?.previewContainerStyle}>
1523
+ <Image
1524
+ source={{ uri: imageUrl }}
1525
+ style={mergedStyles.messageItemStyle?.previewImageStyle}
1526
+ resizeMode="cover"
1527
+ progressiveRenderingEnabled={true}
1528
+ fadeDuration={0}
1529
+ />
1530
+ </View>
1531
+ );
1532
+ }
1533
+ break;
1534
+ }
1535
+
1536
+ case 'video': {
1537
+ const videoMessage = message as CometChat.MediaMessage;
1538
+ const thumbnailImage = checkThumbnail(videoMessage);
1539
+
1540
+ if (thumbnailImage.uri) {
1541
+ return (
1542
+ <VideoThumbnail
1543
+ thumbnailUrl={thumbnailImage}
1544
+ mergedStyles={mergedStyles}
1545
+ />
1546
+ );
1547
+ }
1548
+ break;
1549
+ }
1550
+
1551
+
1552
+
1553
+ default:
1554
+ // For text messages and other types, show timestamp
1555
+ return (
1556
+ <View style={mergedStyles.messageItemStyle?.trailingContainerStyle}>
1557
+ <CometChatDate
1558
+ timeStamp={timestamp * 1000}
1559
+ pattern={"dayDateFormat"}
1560
+ />
1561
+ </View>
1562
+ );
1563
+ }
1564
+
1565
+ // Fallback to timestamp
1566
+ return (
1567
+ <View style={mergedStyles.messageItemStyle?.trailingContainerStyle}>
1568
+ <CometChatDate
1569
+ timeStamp={timestamp * 1000}
1570
+ pattern={"dayDateFormat"}
1571
+ />
1572
+ </View>
1573
+ );
1574
+ };
1575
+
1576
+ // Memoized trailing view component
1577
+ const MemoizedTrailingView = React.memo(({ message }: { message: CometChat.BaseMessage }) =>
1578
+ renderMessageTrailingView(message),
1579
+ (prev, next) => prev.message.getId() === next.message.getId()
1580
+ );
1581
+
1582
+ // Render conversations section
1583
+ const renderConversationsSection = () => {
1584
+ const { conversationList, fetchState } = conversationState;
1585
+
1586
+ if (fetchState === States.loading && conversationList.length === 0) {
1587
+ return loadingView ? loadingView() : <Skeleton />;
1588
+ }
1589
+
1590
+ if (fetchState === States.empty || conversationList.length === 0) {
1591
+ return null; // Don't show empty conversations section
1592
+ }
1593
+
1594
+ if (fetchState === States.error) {
1595
+ if (errorView) {
1596
+ return errorView();
1597
+ }
1598
+
1599
+ return (
1600
+ <View style={[mergedStyles.errorStateStyle?.containerStyle]}>
1601
+ <Icon
1602
+ name="empty-search"
1603
+ size={120}
1604
+ height={120}
1605
+ width={120}
1606
+ imageStyle={mergedStyles.errorStateStyle?.iconStyle}
1607
+ containerStyle={mergedStyles.errorStateStyle?.iconContainerStyle}
1608
+ />
1609
+ <Text style={[mergedStyles.errorStateStyle?.titleStyle]}>
1610
+ {t("SEARCH_ERROR_LOADING_CONVERSATIONS") || "Error Loading Conversations"}
1611
+ </Text>
1612
+ <Text style={[mergedStyles.errorStateStyle?.subtitleStyle]}>
1613
+ {t("SEARCH_TRY_AGAIN") || "Please try again later"}
1614
+ </Text>
1615
+ </View>
1616
+ );
1617
+ }
1618
+
1619
+ return (
1620
+ <View>
1621
+ <Text style={mergedStyles.sectionTitleStyle}>{t("CHATS") || "Chats"}</Text>
1622
+ <FlatList
1623
+ data={conversationList}
1624
+ keyExtractor={(item) => item.getConversationId()}
1625
+ scrollEnabled={false}
1626
+ initialNumToRender={10}
1627
+ maxToRenderPerBatch={5}
1628
+ windowSize={5}
1629
+ removeClippedSubviews={true}
1630
+ updateCellsBatchingPeriod={50}
1631
+ renderItem={({ item: conversation }) => {
1632
+ // Use custom conversation item view if provided
1633
+ if (conversationItemView) {
1634
+ return (
1635
+ <TouchableOpacity
1636
+ onPress={() => onConversationClicked?.(conversation, searchState.searchText)}
1637
+ >
1638
+ {conversationItemView(conversation, searchState.searchText)}
1639
+ </TouchableOpacity>
1640
+ );
1641
+ }
1642
+
1643
+ // Default conversation item rendering
1644
+ return (
1645
+ <TouchableOpacity
1646
+ style={mergedStyles.conversationItemStyle?.containerStyle}
1647
+ onPress={() => onConversationClicked?.(conversation, searchState.searchText)}
1648
+ >
1649
+ {renderConversationLeadingView(conversation)}
1650
+ <View style={mergedStyles.conversationItemStyle?.contentStyle}>
1651
+ <Text style={mergedStyles.conversationItemStyle?.titleStyle} numberOfLines={1}>
1652
+ {conversation.getConversationWith().getName()}
1653
+ </Text>
1654
+ <Text style={mergedStyles.conversationItemStyle?.subtitleStyle} numberOfLines={2}>
1655
+ {formatMentionsInText((conversation.getLastMessage())?.getText?.(), conversation.getLastMessage())}
1656
+ </Text>
1657
+ </View>
1658
+ {renderConversationTrailingView(conversation)}
1659
+ </TouchableOpacity>
1660
+ );
1661
+ }}
1662
+ ListFooterComponent={
1663
+ conversationState.hasMoreResults ? (
1664
+ <TouchableOpacity
1665
+ style={mergedStyles.seeMoreButtonStyle}
1666
+ onPress={loadMoreConversations}
1667
+ disabled={isConversationMoreResultsLoading.current}
1668
+ >
1669
+ <Text style={mergedStyles.seeMoreTextStyle}>
1670
+ {isConversationMoreResultsLoading.current ? t("SEARCH_LOADING") || 'Loading...' : t("SEARCH_SEE_MORE") || 'See More'}
1671
+ </Text>
1672
+ </TouchableOpacity>
1673
+ ) : null
1674
+ }
1675
+ />
1676
+ </View>
1677
+ );
1678
+ };
1679
+
1680
+ // Helper to format date for headers
1681
+ const getDateHeaderDate = useCallback((timestamp: number) => {
1682
+ return new Date(timestamp * 1000).toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
1683
+ }, []);
1684
+
1685
+ // Render messages section
1686
+ const renderMessagesSection = () => {
1687
+ const { messageList, fetchState } = messageState;
1688
+
1689
+ if (fetchState === States.loading && messageList.length === 0) {
1690
+ return loadingView ? loadingView() : <Skeleton />;
1691
+ }
1692
+
1693
+ if (fetchState === States.empty || messageList.length === 0) {
1694
+ return null; // Don't show empty messages section
1695
+ }
1696
+
1697
+ if (fetchState === States.error) {
1698
+ if (errorView) {
1699
+ return errorView();
1700
+ }
1701
+
1702
+ return (
1703
+ <View style={[mergedStyles.errorStateStyle?.containerStyle]}>
1704
+ <Icon
1705
+ name="empty-search"
1706
+ size={120}
1707
+ height={120}
1708
+ width={120}
1709
+ imageStyle={mergedStyles.errorStateStyle?.iconStyle}
1710
+ containerStyle={mergedStyles.errorStateStyle?.iconContainerStyle}
1711
+ />
1712
+ <Text style={[mergedStyles.errorStateStyle?.titleStyle]}>
1713
+ {t("SEARCH_ERROR_LOADING_MESSAGES") || "Error Loading M essages"}
1714
+ </Text>
1715
+ <Text style={[mergedStyles.errorStateStyle?.subtitleStyle]}>
1716
+ {t("SEARCH_TRY_AGAIN") || "Please try again later"}
1717
+ </Text>
1718
+ </View>
1719
+ );
1720
+ }
1721
+
1722
+ return (
1723
+ <View>
1724
+ <Text style={mergedStyles.sectionTitleStyle}>{t("MESSAGES") || "Messages"}</Text>
1725
+ <FlatList
1726
+ data={messageList}
1727
+ keyExtractor={(item, index) => `${item.getId()}-${index}`}
1728
+ initialNumToRender={10}
1729
+ maxToRenderPerBatch={5}
1730
+ windowSize={5}
1731
+ removeClippedSubviews={true}
1732
+ updateCellsBatchingPeriod={50}
1733
+ renderItem={({ item: message, index }) => {
1734
+ const messageType = message.getType();
1735
+
1736
+ // Date header logic for media items
1737
+ let dateHeader: React.ReactNode = null;
1738
+ if (['image', 'video'].includes(messageType)) {
1739
+ const sentAt = message.getSentAt();
1740
+ const currentDateStr = getDateHeaderDate(sentAt);
1741
+ const prevMessage = index > 0 ? messageList[index - 1] : null;
1742
+ const prevDateStr = prevMessage ? getDateHeaderDate(prevMessage.getSentAt()) : null;
1743
+
1744
+ if (currentDateStr !== prevDateStr) {
1745
+ dateHeader = (
1746
+ <CometChatDate
1747
+ timeStamp={sentAt * 1000}
1748
+ customDateString={currentDateStr}
1749
+ style={{
1750
+ textStyle: mergedStyles.sectionTitleStyle
1751
+ }}
1752
+ />
1753
+ );
1754
+ }
1755
+ }
1756
+
1757
+ // Check if message is a text message with link preview
1758
+ const isLinkMessage = messageType === 'text' && (() => {
1759
+ const textMessage = message as CometChat.TextMessage;
1760
+ const metadata = textMessage.getMetadata();
1761
+ return metadata && (metadata as any)['@injected'] && (metadata as any)['@injected']['extensions'] && (metadata as any)['@injected']['extensions']['link-preview'];
1762
+ })();
1763
+
1764
+ // Determine which custom view to use based on message type
1765
+ let customView: (() => React.ReactElement) | undefined;
1766
+
1767
+ if (isLinkMessage && linkMessageItemView) {
1768
+ customView = () => linkMessageItemView(message, searchState.searchText);
1769
+ } else if (messageType === 'text' && textMessageItemView) {
1770
+ customView = () => textMessageItemView(message, searchState.searchText);
1771
+ } else if (messageType === 'image' && imageMessageItemView) {
1772
+ customView = () => imageMessageItemView(message, searchState.searchText);
1773
+ } else if (messageType === 'video' && videoMessageItemView) {
1774
+ customView = () => videoMessageItemView(message, searchState.searchText);
1775
+ } else if (messageType === 'audio' && audioMessageItemView) {
1776
+ customView = () => audioMessageItemView(message, searchState.searchText);
1777
+ } else if (messageType === 'file' && documentMessageItemView) {
1778
+ customView = () => documentMessageItemView(message, searchState.searchText);
1779
+ }
1780
+
1781
+ // Use custom view if available
1782
+ if (customView) {
1783
+ return (
1784
+ <View>
1785
+ {dateHeader}
1786
+ <TouchableOpacity
1787
+ onPress={() => onMessageClicked?.(message, searchState.searchText)}
1788
+ >
1789
+ {customView()}
1790
+ </TouchableOpacity>
1791
+ </View>
1792
+ );
1793
+ }
1794
+
1795
+ // Default message item rendering
1796
+ return (
1797
+ <View>
1798
+ {dateHeader}
1799
+ <TouchableOpacity
1800
+ style={mergedStyles.messageItemStyle?.containerStyle}
1801
+ onPress={() => onMessageClicked?.(message, searchState.searchText)}
1802
+ >
1803
+ {renderMessageLeadingView(message)}
1804
+ <View style={[
1805
+ mergedStyles.messageItemStyle?.contentStyle,
1806
+ (message.getType() === 'image' || message.getType() === 'video') && mergedStyles.messageItemStyle?.textContainerStyle
1807
+ ]}>
1808
+ <Text style={mergedStyles.messageItemStyle?.titleStyle} numberOfLines={1}>
1809
+ {message.getSender().getName()}
1810
+ </Text>
1811
+ <Text style={mergedStyles.messageItemStyle?.subtitleStyle} numberOfLines={2}>
1812
+ {(() => {
1813
+ const messageType = message.getType();
1814
+
1815
+ // For media messages (image, video, file, audio), show file name
1816
+ if (['image', 'video', 'file', 'audio'].includes(messageType)) {
1817
+ const mediaMessage = message as CometChat.MediaMessage;
1818
+ const attachment = mediaMessage.getAttachment?.();
1819
+ return attachment?.getName?.() || messageType;
1820
+ }
1821
+
1822
+ // For text messages, show the text content
1823
+ if (messageType === 'text') {
1824
+ const raw = (message as CometChat.TextMessage).getText?.();
1825
+ const formatted = formatMentionsInText(raw, message);
1826
+ return formatted || messageType || 'Message';
1827
+ }
1828
+
1829
+ // For custom messages, try to localize the type
1830
+ const customTypeKey = `CUSTOM_MESSAGE_${messageType.toUpperCase()}`;
1831
+ const localizedType = t(customTypeKey);
1832
+
1833
+ // If localization exists and is different from key, use it
1834
+ if (localizedType && localizedType !== customTypeKey) {
1835
+ return localizedType;
1836
+ }
1837
+
1838
+ // Handle specific extension types mapping to existing keys
1839
+ if (messageType === 'extension_poll') return t("CUSTOM_MESSAGE_POLL") || "Poll";
1840
+ if (messageType === 'extension_sticker') return t("CUSTOM_MESSAGE_STICKER") || "Sticker";
1841
+ if (messageType === 'extension_whiteboard') return t("CUSTOM_MESSAGE_WHITEBOARD") || "Whiteboard";
1842
+ if (messageType === 'extension_document') return t("CUSTOM_MESSAGE_DOCUMENT") || "Document";
1843
+ if (messageType === 'meeting') return t("meeting") || "Meeting";
1844
+
1845
+ return messageType || 'Message';
1846
+ })()}
1847
+ </Text>
1848
+ </View>
1849
+ <MemoizedTrailingView message={message} />
1850
+ </TouchableOpacity>
1851
+ </View>
1852
+ );
1853
+ }}
1854
+ />
1855
+ </View>
1856
+ );
1857
+ };
1858
+
1859
+ const renderResults = () => {
1860
+ const conversationsRendered = shouldRenderConversations();
1861
+ const messagesRendered = shouldRenderMessages();
1862
+
1863
+ // Initial empty state - no search text and no filters
1864
+ if ((!searchState.searchText || searchState.searchText.trim() === "") && searchState.activeFilters.length === 0) {
1865
+ if (emptyView) {
1866
+ return emptyView();
1867
+ }
1868
+
1869
+ return (
1870
+ <View style={[mergedStyles.emptyStateStyle?.containerStyle]}>
1871
+ <Icon
1872
+ name="empty-search"
1873
+ size={120}
1874
+ height={120}
1875
+ width={120}
1876
+ imageStyle={mergedStyles.emptyStateStyle?.iconStyle}
1877
+ containerStyle={mergedStyles.emptyStateStyle?.iconContainerStyle}
1878
+ />
1879
+ <Text style={[mergedStyles.emptyStateStyle?.titleStyle]}>
1880
+ {t("SEARCH_NO_RESULTS_TITLE") || "No Results"}
1881
+ </Text>
1882
+ <Text style={[mergedStyles.emptyStateStyle?.subtitleStyle]}>
1883
+ {t("SEARCH_NO_RESULTS_SUBTITLE") || "Start typing to search for messages and conversations"}
1884
+ </Text>
1885
+ </View>
1886
+ );
1887
+ }
1888
+
1889
+ // Show loading shimmer if we have search/filters active and both sections are loading
1890
+ if ((searchState.searchText.trim() !== "" || searchState.activeFilters.length > 0) &&
1891
+ (conversationState.fetchState === States.loading || messageState.fetchState === States.loading) &&
1892
+ conversationState.conversationList.length === 0 &&
1893
+ messageState.messageList.length === 0) {
1894
+ return loadingView ? loadingView() : <Skeleton />;
1895
+ }
1896
+
1897
+ // Check if we have search text or filters but no actual results
1898
+ if ((searchState.searchText.trim() !== "" || searchState.activeFilters.length > 0) &&
1899
+ conversationState.conversationList.length === 0 &&
1900
+ messageState.messageList.length === 0 &&
1901
+ conversationState.fetchState !== States.loading &&
1902
+ messageState.fetchState !== States.loading &&
1903
+ conversationState.fetchState !== States.error &&
1904
+ messageState.fetchState !== States.error) {
1905
+ // No results found state
1906
+ if (emptyView) {
1907
+ return emptyView();
1908
+ }
1909
+
1910
+ return (
1911
+ <View style={[mergedStyles.emptyStateStyle?.containerStyle]}>
1912
+ <Icon
1913
+ name="empty-search"
1914
+ size={120}
1915
+ height={120}
1916
+ width={120}
1917
+ imageStyle={mergedStyles.emptyStateStyle?.iconStyle}
1918
+ containerStyle={mergedStyles.emptyStateStyle?.iconContainerStyle}
1919
+ />
1920
+ <Text style={[mergedStyles.emptyStateStyle?.titleStyle]}>
1921
+ {t("SEARCH_NO_RESULTS_FOUND_TITLE") || "No Results Found"}
1922
+ </Text>
1923
+ <Text style={[mergedStyles.emptyStateStyle?.subtitleStyle]}>
1924
+ {t("SEARCH_NO_RESULTS_FOUND_SUBTITLE") || "We couldn't find any matches. Please try a different search keyword."}
1925
+ </Text>
1926
+ </View>
1927
+ );
1928
+ }
1929
+
1930
+ // Show search results with actual item lists - USING SINGLE FLATLIST FOR VIRTUALIZATION
1931
+ // Create combined data array with section headers
1932
+ type ListItem =
1933
+ | { type: 'conversation-header' }
1934
+ | { type: 'conversation'; data: CometChat.Conversation }
1935
+ | { type: 'conversation-footer' }
1936
+ | { type: 'message-header' }
1937
+ | { type: 'message'; data: CometChat.BaseMessage; index: number }
1938
+ | { type: 'message-footer' };
1939
+
1940
+ const combinedData: ListItem[] = [];
1941
+
1942
+ // Add conversations section if needed
1943
+ if (conversationsRendered && conversationState.conversationList.length > 0) {
1944
+ combinedData.push({ type: 'conversation-header' });
1945
+ conversationState.conversationList.forEach(conv => {
1946
+ combinedData.push({ type: 'conversation', data: conv });
1947
+ });
1948
+ if (conversationState.hasMoreResults) {
1949
+ combinedData.push({ type: 'conversation-footer' });
1950
+ }
1951
+ }
1952
+
1953
+ // Add messages section if needed
1954
+ if (messagesRendered && messageState.messageList.length > 0) {
1955
+ combinedData.push({ type: 'message-header' });
1956
+ messageState.messageList.forEach((msg, index) => {
1957
+ combinedData.push({ type: 'message', data: msg, index });
1958
+ });
1959
+ }
1960
+
1961
+ const keyExtractor = (item: ListItem, index: number) => {
1962
+ if (item.type === 'conversation') {
1963
+ return `conversation-${item.data.getConversationId()}`;
1964
+ } else if (item.type === 'message') {
1965
+ return `message-${item.data.getId()}-${index}`;
1966
+ }
1967
+ return `${item.type}-${index}`;
1968
+ };
1969
+
1970
+ const renderCombinedItem = ({ item }: { item: ListItem }) => {
1971
+ switch (item.type) {
1972
+ case 'conversation-header':
1973
+ return <Text style={mergedStyles.sectionTitleStyle}>{t("CHATS") || "Chats"}</Text>;
1974
+
1975
+ case 'conversation':
1976
+ return (
1977
+ <ConversationItem
1978
+ conversation={item.data}
1979
+ searchText={searchState.searchText}
1980
+ onPress={onConversationClicked || (() => {})}
1981
+ mergedStyles={mergedStyles}
1982
+ theme={theme}
1983
+ conversationItemView={conversationItemView}
1984
+ />
1985
+ );
1986
+
1987
+ case 'conversation-footer':
1988
+ return (
1989
+ <TouchableOpacity
1990
+ style={mergedStyles.seeMoreButtonStyle}
1991
+ onPress={loadMoreConversations}
1992
+ disabled={isConversationMoreResultsLoading.current}
1993
+ >
1994
+ <Text style={mergedStyles.seeMoreTextStyle}>
1995
+ {isConversationMoreResultsLoading.current ? t("SEARCH_LOADING") || 'Loading...' : t("SEARCH_SEE_MORE") || 'See More'}
1996
+ </Text>
1997
+ </TouchableOpacity>
1998
+ );
1999
+
2000
+ case 'message-header':
2001
+ return <Text style={mergedStyles.sectionTitleStyle}>{t("MESSAGES") || "Messages"}</Text>;
2002
+
2003
+ case 'message': {
2004
+ const message = item.data;
2005
+ const messageIndex = item.index;
2006
+ const messageType = message.getType();
2007
+
2008
+ // Date header logic for media items
2009
+ let dateHeader: React.ReactNode = null;
2010
+ if (['image', 'video'].includes(messageType)) {
2011
+ const sentAt = message.getSentAt();
2012
+ const currentDateStr = getDateHeaderDate(sentAt);
2013
+ const prevItem = messageIndex > 0 ? messageState.messageList[messageIndex - 1] : null;
2014
+ const prevDateStr = prevItem ? getDateHeaderDate(prevItem.getSentAt()) : null;
2015
+
2016
+ if (currentDateStr !== prevDateStr) {
2017
+ dateHeader = (
2018
+ <CometChatDate
2019
+ timeStamp={sentAt * 1000}
2020
+ customDateString={currentDateStr}
2021
+ style={{
2022
+ textStyle: mergedStyles.sectionTitleStyle
2023
+ }}
2024
+ />
2025
+ );
2026
+ }
2027
+ }
2028
+
2029
+ // Check if message is a text message with link preview
2030
+ const isLinkMessage = messageType === 'text' && (() => {
2031
+ const textMessage = message as CometChat.TextMessage;
2032
+ const metadata = textMessage.getMetadata();
2033
+ return metadata && (metadata as any)['@injected'] && (metadata as any)['@injected']['extensions'] && (metadata as any)['@injected']['extensions']['link-preview'];
2034
+ })();
2035
+
2036
+ // Determine which custom view to use based on message type
2037
+ let customView: (() => React.ReactElement) | undefined;
2038
+
2039
+ if (isLinkMessage && linkMessageItemView) {
2040
+ customView = () => linkMessageItemView(message, searchState.searchText);
2041
+ } else if (messageType === 'text' && textMessageItemView) {
2042
+ customView = () => textMessageItemView(message, searchState.searchText);
2043
+ } else if (messageType === 'image' && imageMessageItemView) {
2044
+ customView = () => imageMessageItemView(message, searchState.searchText);
2045
+ } else if (messageType === 'video' && videoMessageItemView) {
2046
+ customView = () => videoMessageItemView(message, searchState.searchText);
2047
+ } else if (messageType === 'audio' && audioMessageItemView) {
2048
+ customView = () => audioMessageItemView(message, searchState.searchText);
2049
+ } else if (messageType === 'file' && documentMessageItemView) {
2050
+ customView = () => documentMessageItemView(message, searchState.searchText);
2051
+ }
2052
+
2053
+ // Use custom view if available
2054
+ if (customView) {
2055
+ return (
2056
+ <View>
2057
+ {dateHeader}
2058
+ <TouchableOpacity
2059
+ onPress={() => onMessageClicked?.(message, searchState.searchText)}
2060
+ >
2061
+ {customView()}
2062
+ </TouchableOpacity>
2063
+ </View>
2064
+ );
2065
+ }
2066
+
2067
+ // Default message item rendering
2068
+ return (
2069
+ <View>
2070
+ {dateHeader}
2071
+ <TouchableOpacity
2072
+ style={mergedStyles.messageItemStyle?.containerStyle}
2073
+ onPress={() => onMessageClicked?.(message, searchState.searchText)}
2074
+ >
2075
+ {renderMessageLeadingView(message)}
2076
+ <View style={[
2077
+ mergedStyles.messageItemStyle?.contentStyle,
2078
+ (message.getType() === 'image' || message.getType() === 'video') && mergedStyles.messageItemStyle?.textContainerStyle
2079
+ ]}>
2080
+ <Text style={mergedStyles.messageItemStyle?.titleStyle} numberOfLines={1}>
2081
+ {message.getSender().getName()}
2082
+ </Text>
2083
+ <Text style={mergedStyles.messageItemStyle?.subtitleStyle} numberOfLines={2}>
2084
+ {(() => {
2085
+ const msgType = message.getType();
2086
+
2087
+ // For media messages (image, video, file, audio), show file name
2088
+ if (['image', 'video', 'file', 'audio'].includes(msgType)) {
2089
+ const mediaMessage = message as CometChat.MediaMessage;
2090
+ const attachment = mediaMessage.getAttachment?.();
2091
+ return attachment?.getName?.() || msgType;
2092
+ }
2093
+
2094
+ // For text messages, show the text content
2095
+ if (msgType === 'text') {
2096
+ const raw = (message as CometChat.TextMessage).getText?.();
2097
+ const formatted = formatMentionsInText(raw, message);
2098
+ return formatted || msgType || 'Message';
2099
+ }
2100
+
2101
+ // For custom messages, try to localize the type
2102
+ const customTypeKey = `CUSTOM_MESSAGE_${msgType.toUpperCase()}`;
2103
+ const localizedType = t(customTypeKey);
2104
+
2105
+ // If localization exists and is different from key, use it
2106
+ if (localizedType && localizedType !== customTypeKey) {
2107
+ return localizedType;
2108
+ }
2109
+
2110
+ // Handle specific extension types mapping to existing keys
2111
+ if (msgType === 'extension_poll') return t("CUSTOM_MESSAGE_POLL") || "Poll";
2112
+ if (msgType === 'extension_sticker') return t("CUSTOM_MESSAGE_STICKER") || "Sticker";
2113
+ if (msgType === 'extension_whiteboard') return t("CUSTOM_MESSAGE_WHITEBOARD") || "Whiteboard";
2114
+ if (msgType === 'extension_document') return t("CUSTOM_MESSAGE_DOCUMENT") || "Document";
2115
+ if (msgType === 'meeting') return t("meeting") || "Meeting";
2116
+
2117
+ return msgType || 'Message';
2118
+ })()}
2119
+ </Text>
2120
+ </View>
2121
+ <MemoizedTrailingView message={message} />
2122
+ </TouchableOpacity>
2123
+ </View>
2124
+ );
2125
+ }
2126
+
2127
+ default:
2128
+ return null;
2129
+ }
2130
+ };
2131
+
2132
+ return (
2133
+ <FlatList
2134
+ data={combinedData}
2135
+ keyExtractor={keyExtractor}
2136
+ renderItem={renderCombinedItem}
2137
+ style={[mergedStyles.resultsContainerStyle]}
2138
+ contentContainerStyle={{ paddingHorizontal: theme.spacing.padding.p4 }}
2139
+ showsVerticalScrollIndicator={false}
2140
+ initialNumToRender={10}
2141
+ maxToRenderPerBatch={10}
2142
+ windowSize={10}
2143
+ removeClippedSubviews={true}
2144
+ updateCellsBatchingPeriod={100}
2145
+ onEndReached={() => {
2146
+ // Load more messages if we're at the end and messages section is visible
2147
+ if (messagesRendered && messageState.hasMoreResults) {
2148
+ loadMoreMessages();
2149
+ }
2150
+ }}
2151
+ onEndReachedThreshold={0.5}
2152
+ />
2153
+ );
2154
+ };
2155
+
2156
+ return (
2157
+ <View style={[mergedStyles.containerStyle]}>
2158
+ {renderHeader()}
2159
+ {renderFilters()}
2160
+ {renderResults()}
2161
+ </View>
2162
+ );
2163
+ };
2164
+
2165
+ export default CometChatSearch;