@cometchat/chat-uikit-react-native 5.2.6 → 5.2.8

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.
File without changes
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cometchat/chat-uikit-react-native",
3
- "version": "5.2.6",
3
+ "version": "5.2.8",
4
4
  "description": "Ready-to-use Chat UI Components for React Native",
5
5
  "main": "src/index",
6
6
  "module": "src/index",
@@ -113,6 +113,22 @@ import { useCometChatTranslation } from "../shared/resources/CometChatLocalizeNe
113
113
 
114
114
  let _defaultRequestBuilder: CometChat.MessagesRequestBuilder;
115
115
 
116
+ /**
117
+ * Helper function to safely get message ID
118
+ * Prevents "undefined is not a function" errors in release builds
119
+ */
120
+ const safeGetId = (item: any): string | number | undefined => {
121
+ return typeof item?.getId === 'function' ? item.getId() : item?.id;
122
+ };
123
+
124
+ /**
125
+ * Helper function to safely get message MUID
126
+ * Prevents "undefined is not a function" errors in release builds
127
+ */
128
+ const safeGetMuid = (item: any): string | undefined => {
129
+ return typeof item?.getMuid === 'function' ? item.getMuid() : item?.muid;
130
+ };
131
+
116
132
  /**
117
133
  * Uses Inverted Flat List
118
134
  * Array needs to be reversed meaning the latest message will be at array[0]
@@ -1640,11 +1656,11 @@ export const CometChatMessageList = memo(
1640
1656
  // If found, update it in place instead of inserting again.
1641
1657
  if (!isAgenticUser) {
1642
1658
  try {
1643
- const incomingId = (newMessage as any)?.getId?.();
1644
- const incomingMuid = (newMessage as any)?.muid || (newMessage as any)?.getMuid?.();
1659
+ const incomingId = typeof (newMessage as any)?.getId === 'function' ? (newMessage as any).getId() : (newMessage as any)?.id;
1660
+ const incomingMuid = (newMessage as any)?.muid || (typeof (newMessage as any)?.getMuid === 'function' ? (newMessage as any).getMuid() : undefined);
1645
1661
  const existingIndex = messagesContentListRef.current.findIndex((m: any) => {
1646
- const mid = m?.getId?.();
1647
- const mmuid = m?.muid || m?.getMuid?.();
1662
+ const mid = typeof m?.getId === 'function' ? m.getId() : m?.id;
1663
+ const mmuid = m?.muid || (typeof m?.getMuid === 'function' ? m.getMuid() : undefined);
1648
1664
  return (
1649
1665
  (incomingId && mid && String(mid) === String(incomingId)) ||
1650
1666
  (incomingMuid && mmuid && String(mmuid) === String(incomingMuid))
@@ -1967,18 +1983,52 @@ export const CometChatMessageList = memo(
1967
1983
  setQueueCompletionCallback(
1968
1984
  runId,
1969
1985
  (aiAssistantMessage, aiToolResultMessage, aiToolArgumentMessage) => {
1970
- let replacement =
1971
- aiAssistantMessage || aiToolResultMessage || aiToolArgumentMessage;
1986
+ const replacement = aiAssistantMessage || aiToolResultMessage || aiToolArgumentMessage;
1972
1987
  if (!replacement) return;
1973
- const updatedList = messagesContentListRef.current.map((msg) => {
1974
- if (
1975
- (msg as any).isStreamMessage === true &&
1976
- (msg as any).targetMessageId === runId
1977
- ) {
1978
- return replacement;
1979
- }
1980
- return msg;
1988
+ console.log("replacement", replacement);
1989
+
1990
+ const replacementId = typeof (replacement as any)?.getId === 'function' ? (replacement as any).getId() : (replacement as any)?.id;
1991
+ const replacementRunId = (replacement as any)?.data?.runId;
1992
+
1993
+ if(messagesContentListRef.current?.[0]?.isStreamMessage && messagesContentListRef.current?.[0]?.targetMessageId === runId){
1994
+ latestMessageRef.current = replacement;
1995
+ }
1996
+
1997
+ const list = messagesContentListRef.current;
1998
+ let updatedList: any[];
1999
+
2000
+ // Find indices in one pass
2001
+ const existingIndex = list.findIndex((msg) => {
2002
+ const msgId = typeof (msg as any)?.getId === 'function' ? (msg as any).getId() : (msg as any)?.id;
2003
+ return msgId && String(msgId) === String(replacementId);
1981
2004
  });
2005
+
2006
+ const streamIndex = existingIndex === -1 ? list.findIndex((msg) =>
2007
+ (msg as any).isStreamMessage === true && (msg as any).targetMessageId === runId
2008
+ ) : -1;
2009
+
2010
+ const matchingIndex = (existingIndex === -1 && streamIndex === -1) ? list.findIndex((msg) => {
2011
+ const msgRunId = (msg as any)?.data?.runId;
2012
+ return msgRunId && String(msgRunId) === String(replacementRunId);
2013
+ }) : -1;
2014
+
2015
+ // Update list based on what we found
2016
+ if (existingIndex !== -1) {
2017
+ // Update existing message
2018
+ updatedList = list.map((msg, idx) => idx === existingIndex ? replacement : msg);
2019
+ } else if (streamIndex !== -1) {
2020
+ // Replace stream message
2021
+ updatedList = list.map((msg, idx) => idx === streamIndex ? replacement : msg);
2022
+ } else if (matchingIndex !== -1) {
2023
+ // Insert before matching message
2024
+ updatedList = [...list];
2025
+ updatedList.splice(matchingIndex, 0, replacement);
2026
+ } else {
2027
+ // Add at beginning
2028
+ updatedList = [replacement, ...list];
2029
+ }
2030
+
2031
+ console.log("updatedList", updatedList);
1982
2032
  messagesContentListRef.current = updatedList;
1983
2033
  setMessagesList(updatedList);
1984
2034
  onLoad && onLoad([...updatedList].reverse());
@@ -2140,13 +2190,15 @@ export const CometChatMessageList = memo(
2140
2190
  //todo show unsupported bubble
2141
2191
  },
2142
2192
  onAIAssistantMessageReceived: (aiAssistantMessage: CometChat.AIAssistantMessage) => {
2143
- const runId =
2144
- aiAssistantMessage.getAssistantMessageData?.()?.getRunId?.() ||
2145
- aiAssistantMessage.getId?.();
2193
+ const assistantData = typeof aiAssistantMessage.getAssistantMessageData === 'function' ? aiAssistantMessage.getAssistantMessageData() : null;
2194
+ const runIdFromData = assistantData && typeof assistantData.getRunId === 'function' ? assistantData.getRunId() : null;
2195
+ const runIdFromId = typeof aiAssistantMessage.getId === 'function' ? aiAssistantMessage.getId() : (aiAssistantMessage as any)?.id;
2196
+ const runId = runIdFromData || runIdFromId;
2146
2197
 
2198
+ const parentMsgId = typeof aiAssistantMessage.getParentMessageId === 'function' ? aiAssistantMessage.getParentMessageId() : (aiAssistantMessage as any)?.parentMessageId;
2147
2199
  if (
2148
2200
  parentMessageId &&
2149
- String(parentMessageId) !== String(aiAssistantMessage.getParentMessageId?.())
2201
+ String(parentMessageId) !== String(parentMsgId)
2150
2202
  ) {
2151
2203
  return;
2152
2204
  }
@@ -3294,8 +3346,11 @@ export const CometChatMessageList = memo(
3294
3346
  const index = idx;
3295
3347
  lastMessageDate.current = getSentAtTimestamp(item);
3296
3348
 
3349
+ const id = typeof item?.getId === 'function' ? item.getId() : (item as any)?.id;
3350
+ const muid = typeof item?.getMuid === 'function' ? item.getMuid() : (item as any)?.muid;
3351
+
3297
3352
  return (
3298
- <React.Fragment key={`${item.getId()}_${item.getMuid()}`}>
3353
+ <React.Fragment key={`${id}_${muid}`}>
3299
3354
  <MessageView message={item} currentIndex={index} />
3300
3355
  </React.Fragment>
3301
3356
  );
@@ -3303,13 +3358,31 @@ export const CometChatMessageList = memo(
3303
3358
  [mergedTheme, isAgenticUser, messagesList, getSentAtTimestamp, dateSeparatorPattern]
3304
3359
  );
3305
3360
 
3306
- const keyExtractor = useCallback((item: any) => {
3307
- const id = item?.getId();
3308
- const muid = item?.getMuid();
3309
- if (!id && !muid) {
3310
- console.log("item has no id or muid", item);
3361
+ const keyExtractor = useCallback((item: any, index: number) => {
3362
+ // Safely check if methods exist before calling them
3363
+ const id = typeof item?.getId === 'function' ? item.getId() : item?.id;
3364
+ const muid = typeof item?.getMuid === 'function' ? item.getMuid() : item?.muid;
3365
+
3366
+ // Use id + muid if both exist
3367
+ if (id && muid) {
3368
+ return `${id}_${muid}`;
3369
+ }
3370
+
3371
+ // Use muid if id doesn't exist (pending message)
3372
+ if (muid) {
3373
+ return `muid_${muid}`;
3374
+ }
3375
+
3376
+ // Use id if muid doesn't exist
3377
+ if (id) {
3378
+ return `id_${id}`;
3379
+ }
3380
+
3381
+ // Fallback to index if neither exist (should not happen, but prevents duplicates)
3382
+ if (__DEV__) {
3383
+ console.warn('[MessageList] Message without id or muid at index:', index, item);
3311
3384
  }
3312
- return `${id}_${muid}`;
3385
+ return `index_${index}`;
3313
3386
  }, []);
3314
3387
 
3315
3388
  const itemSeparator = useCallback(() => <View style={{ height: 8 }} />, []);
@@ -3685,7 +3758,8 @@ export const CometChatMessageList = memo(
3685
3758
  }
3686
3759
  }
3687
3760
  const ms = sentAtToMs(item) ?? Date.now();
3688
- const isHighlighted = highlightedMessageId === String(item.getId());
3761
+ const itemId = typeof item?.getId === 'function' ? item.getId() : (item as any)?.id;
3762
+ const isHighlighted = highlightedMessageId === String(itemId);
3689
3763
 
3690
3764
  const separatorHeight = showSeparator ? 40 : 0;
3691
3765
 
@@ -19,6 +19,9 @@ import { deepMerge } from "../shared/helper/helperFunctions";
19
19
  import { CommonUtils } from "../shared/utils/CommonUtils";
20
20
  import { DeepPartial } from "../shared/helper/types";
21
21
  import { useCometChatTranslation } from "../shared/resources/CometChatLocalizeNew";
22
+ import { ExtensionConstants } from "../extensions";
23
+ import { getExtensionData } from "../shared/helper/functions";
24
+ import { urlPattern } from "../shared/constants/UIKitConstants";
22
25
 
23
26
  /**
24
27
  * Unique UI event identifier for CometChatUIEventHandler.
@@ -234,10 +237,29 @@ export const CometChatThreadHeader = (props: CometChatThreadHeaderInterface): JS
234
237
  };
235
238
  }, []);
236
239
 
240
+ // Check if message has URLs (link preview or URLs in text)
241
+ const hasUrl = useMemo(() => {
242
+ // Check for link preview extension data
243
+ const linkData = getExtensionData(message, ExtensionConstants.linkPreview);
244
+ if (linkData && linkData.links && linkData.links.length > 0) {
245
+ return true;
246
+ }
247
+
248
+ // Check if text message contains URLs
249
+ if (message.getType() === "text") {
250
+ const textMessage = message as CometChat.TextMessage;
251
+ const text = textMessage.getText() || "";
252
+ const urlRegex = new RegExp(urlPattern);
253
+ return urlRegex.test(text);
254
+ }
255
+
256
+ return false;
257
+ }, [message]);
258
+
237
259
  return (
238
260
  <View style={[style?.containerStyle]}>
239
261
  <ScrollView style={style?.messageBubbleContainerStyle}>
240
- <View pointerEvents='none'>
262
+ <View pointerEvents={hasUrl ? 'auto' : 'none'}>
241
263
  {MessageUtils.getMessageView({
242
264
  message,
243
265
  templates:
@@ -1,4 +1,4 @@
1
- import React, { JSX, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
1
+ import React, { JSX, useCallback, useRef, useState } from "react";
2
2
  import {
3
3
  Alert,
4
4
  DimensionValue,
@@ -80,7 +80,6 @@ export const LinkPreviewBubble = (props: LinkPreviewBubbleInterface) => {
80
80
  * Handles the touch end event. If the press duration is less than 500ms, it triggers the onPress callback or opens the link.
81
81
  */
82
82
  const handleTouchEnd = async () => {
83
- if (pressTime.current === null && Platform.OS === "ios") return;
84
83
  const endTime = Date.now();
85
84
  const pressDuration = endTime - (pressTime.current ?? 0);
86
85
  if (pressDuration < 500) {
@@ -138,7 +137,12 @@ export const LinkPreviewBubble = (props: LinkPreviewBubbleInterface) => {
138
137
  );
139
138
 
140
139
  return (
141
- <View style={{ flex: 1 }} onLayout={onLayoutHandler}>
140
+ <View
141
+ onLayout={onLayoutHandler}
142
+ onTouchStart={handleTouchStart}
143
+ onTouchEnd={handleTouchEnd}
144
+ onTouchMove={onTouchMove}
145
+ >
142
146
  <View
143
147
  style={style?.headerImageContainerStyle}
144
148
  onTouchStart={handleTouchStart}
@@ -167,7 +171,7 @@ export const LinkPreviewBubble = (props: LinkPreviewBubbleInterface) => {
167
171
  source={faviconSource}
168
172
  style={style?.bodyStyle?.faviconStyle}
169
173
  onError={(err) => {
170
- setImageSource(DefaultLinkPreview);
174
+ setFaviconSource(DefaultLinkPreview);
171
175
  }}
172
176
  />
173
177
  </View>
@@ -185,6 +189,7 @@ export const LinkPreviewBubble = (props: LinkPreviewBubbleInterface) => {
185
189
  style={{
186
190
  paddingVertical: theme.spacing.padding.p3,
187
191
  paddingHorizontal: style?.bodyStyle?.containerStyle.padding,
192
+ flexShrink: 0,
188
193
  }}
189
194
  >
190
195
  {ChildView && <ChildView />}
@@ -61,7 +61,6 @@ export const emailPattern =
61
61
  wordBoundary.start + `[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}` + wordBoundary.end;
62
62
 
63
63
  export const urlPattern =
64
- wordBoundary.start +
65
64
  `((https?://|www\\.|pic\\.)[-\\w;/?:@&=+$\\|\\_.!~*\\|'()\\[\\]%#,☺]+[\\w/#](\\(\\))?)` +
66
65
  wordBoundary.end;
67
66
 
@@ -19,6 +19,27 @@ export class CometChatUrlsFormatter extends CometChatTextFormatter {
19
19
  }
20
20
 
21
21
  private Link = ({ text, url, style }: any) => {
22
+ const handlePress = async () => {
23
+ try {
24
+ let finalUrl = url;
25
+ if (!url.match(/^(https?|mailto|tel):/i)) {
26
+ finalUrl = `http://${url}`;
27
+ }
28
+
29
+ const canOpen = await Linking.canOpenURL(finalUrl);
30
+ if (canOpen) {
31
+ Linking.openURL(finalUrl);
32
+ } else {
33
+ // Try opening anyway as fallback
34
+ Linking.openURL(finalUrl).catch((err) => {
35
+ console.log("Can not open link", finalUrl, err);
36
+ });
37
+ }
38
+ } catch (err) {
39
+ console.log("Error opening URL:", err);
40
+ }
41
+ };
42
+
22
43
  return (
23
44
  <Text
24
45
  style={{
@@ -26,20 +47,7 @@ export class CometChatUrlsFormatter extends CometChatTextFormatter {
26
47
  ...style?.linkTextFont,
27
48
  textDecorationLine: "underline",
28
49
  }}
29
- onPress={() => {
30
- let finalUrl = url.startsWith("http") ? url : `http://${url}`;
31
- Linking.canOpenURL(finalUrl)
32
- .then((res) => {
33
- if (res) {
34
- Linking.openURL(finalUrl);
35
- return;
36
- }
37
- console.log("Can not open link", finalUrl);
38
- })
39
- .catch((err) => {
40
- console.log("Error:", err);
41
- });
42
- }}
50
+ onPress={handlePress}
43
51
  >
44
52
  {text}
45
53
  </Text>
@@ -86,7 +94,7 @@ export class CometChatUrlsFormatter extends CometChatTextFormatter {
86
94
  if (phone) urlLink = "tel:";
87
95
  return (
88
96
  <Text>
89
- <Text>{pre} </Text>
97
+ <Text>{pre}</Text>
90
98
  {this.Link({
91
99
  text: resPart[0].trim(),
92
100
  url: urlLink.trim() + resPart[0].trim(),
@@ -52,13 +52,18 @@ let streamedMessages: { [runId: string]: string } = {};
52
52
  * Per-runId event queue, matching Android logic
53
53
  */
54
54
  const eventQueues: { [runId: string]: CometChat.AIAssistantBaseEvent[] } = {};
55
- let lastAIAssistantMessages: { [runId: string]: CometChat.AIAssistantMessage } = {};
55
+ let lastAIAssistantMessages: Array<{ runId: string, message: CometChat.AIAssistantMessage }> = [];
56
56
 
57
57
  /**
58
58
  * Store AIAssistantMessage for a runId
59
59
  */
60
60
  export const storeAIAssistantMessage = (runId: string, message: CometChat.AIAssistantMessage) => {
61
- lastAIAssistantMessages[runId] = message;
61
+ const existingIndex = lastAIAssistantMessages.findIndex(item => item.runId === runId);
62
+ if (existingIndex !== -1) {
63
+ lastAIAssistantMessages[existingIndex].message = message;
64
+ } else {
65
+ lastAIAssistantMessages.push({ runId, message });
66
+ }
62
67
  checkQueueEmptyStatus(runId);
63
68
  };
64
69
 
@@ -75,17 +80,16 @@ function checkQueueEmptyStatus(runId: string) {
75
80
  renderingComplete[runId] === true &&
76
81
  queueCompletionCallbacks[runId]
77
82
  ) {
78
- const aiMsg = lastAIAssistantMessages[runId];
79
- const toolResult = lastAIToolResultMessages[runId];
80
- const toolArg = lastAIToolArgumentMessages[runId];
83
+ const aiMsgEntry = lastAIAssistantMessages.find(item => item.runId === runId);
84
+ const aiMsg = aiMsgEntry?.message;
85
+ const toolResult = lastAIToolResultMessages[runId]?.message;
86
+ const toolArg = lastAIToolArgumentMessages[runId]?.message;
87
+ const indexToDelete = lastAIAssistantMessages.findIndex(item => item.runId === runId);
88
+ if (indexToDelete !== -1) {
89
+ lastAIAssistantMessages.splice(indexToDelete, 1);
90
+ }
81
91
  if (aiMsg || toolResult || toolArg) {
82
92
  queueCompletionCallbacks[runId](aiMsg, toolResult, toolArg);
83
- delete queueCompletionCallbacks[runId];
84
- delete lastAIAssistantMessages[runId];
85
- delete lastAIToolResultMessages[runId];
86
- delete lastAIToolArgumentMessages[runId];
87
- delete streamingComplete[runId];
88
- delete renderingComplete[runId];
89
93
  }
90
94
  }
91
95
  }
@@ -445,7 +449,7 @@ export const stopStreamingForRunId = (runId?: string) => {
445
449
  delete streamedMessages[runId];
446
450
  delete processedDeltas[runId];
447
451
  delete queueCompletionCallbacks[runId];
448
- delete lastAIAssistantMessages[runId];
452
+ lastAIAssistantMessages = lastAIAssistantMessages.filter(item => item.runId !== runId);
449
453
  delete lastAIToolResultMessages[runId];
450
454
  delete lastAIToolArgumentMessages[runId];
451
455
  delete streamingComplete[runId];
@@ -456,7 +460,7 @@ export const stopStreamingForRunId = (runId?: string) => {
456
460
  processedDeltas = {};
457
461
  streamingComplete = {};
458
462
  renderingComplete = {};
459
- lastAIAssistantMessages = {};
463
+ lastAIAssistantMessages = [];
460
464
  lastAIToolResultMessages = {};
461
465
  lastAIToolArgumentMessages = {};
462
466
  for (const key in queueCompletionCallbacks) {