@cometchat/chat-uikit-react-native 5.4.0 → 5.5.0

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 (72) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/CometChatClipboardModule.kt +34 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +605 -6
  3. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorViewManager.kt +20 -1
  4. package/ios/CometChatClipboardModule.m +5 -0
  5. package/ios/CometChatClipboardModule.swift +22 -0
  6. package/ios/RichTextEditorView.swift +648 -35
  7. package/ios/RichTextEditorViewManager.m +2 -0
  8. package/ios/RichTextEditorViewManager.swift +16 -0
  9. package/package.json +2 -1
  10. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +245 -55
  11. package/src/CometChatCompactMessageComposer/index.ts +2 -0
  12. package/src/CometChatConversations/CometChatConversations.tsx +291 -14
  13. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +181 -12
  14. package/src/CometChatMessageList/CometChatMessageList.tsx +568 -15
  15. package/src/CometChatMessageList/components/MessageModals.tsx +30 -0
  16. package/src/CometChatMessageList/components/MessageOptionsSheet.tsx +14 -1
  17. package/src/CometChatMessageList/components/MessageQuickActions.tsx +162 -0
  18. package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +940 -0
  19. package/src/CometChatPinnedMessages/index.ts +5 -0
  20. package/src/CometChatPinnedMessages/style.ts +216 -0
  21. package/src/CometChatRichTextEditor/RichTextEditorViewNativeComponent.ts +5 -0
  22. package/src/CometChatRichTextEditor/index.tsx +27 -1
  23. package/src/CometChatRichTextEditor/types.ts +19 -1
  24. package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +634 -0
  25. package/src/CometChatSavedMessages/index.ts +5 -0
  26. package/src/CometChatSavedMessages/style.ts +159 -0
  27. package/src/CometChatSearch/CometChatSearch.tsx +47 -340
  28. package/src/CometChatThreadHeader/CometChatThreadHeader.tsx +22 -2
  29. package/src/index.ts +60 -0
  30. package/src/shared/CometChatUiKit/CometChatUIKit.ts +16 -0
  31. package/src/shared/base/Types.ts +5 -0
  32. package/src/shared/constants/UIKitConstants.ts +13 -0
  33. package/src/shared/events/CometChatUIEventHandler/CometChatUIEventHandler.ts +34 -0
  34. package/src/shared/events/CometChatUIEventHandler/Listener.ts +37 -0
  35. package/src/shared/events/ListenerInitializer.ts +20 -1
  36. package/src/shared/events/messages.ts +18 -0
  37. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +95 -8
  38. package/src/shared/formatters/index.ts +14 -0
  39. package/src/shared/formatters/richTextWireFormat.ts +165 -0
  40. package/src/shared/framework/MessageDataSource.tsx +296 -3
  41. package/src/shared/icons/components/thread-follow.tsx +13 -0
  42. package/src/shared/icons/components/thread-unfollow.tsx +13 -0
  43. package/src/shared/icons/components/unsave.tsx +13 -0
  44. package/src/shared/icons/icon-mapping.tsx +6 -0
  45. package/src/shared/index.ts +37 -0
  46. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +54 -0
  47. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +2 -1
  48. package/src/shared/utils/MarkdownUtils.ts +25 -4
  49. package/src/shared/utils/MessageUtils.tsx +80 -5
  50. package/src/shared/utils/PinConversationHelper.ts +245 -0
  51. package/src/shared/utils/PinSaveFeatureGates.ts +178 -0
  52. package/src/shared/utils/PinSaveHelper.ts +549 -0
  53. package/src/shared/utils/SavedMessagesHelper.ts +231 -0
  54. package/src/shared/utils/ThreadSubscriptionHelper.ts +427 -0
  55. package/src/shared/utils/conversationUtils.ts +8 -1
  56. package/src/shared/utils/elementType.tsx +38 -0
  57. package/src/shared/utils/stripRichText.ts +7 -0
  58. package/src/shared/views/ClipboardPasteHandler/ClipboardPasteHandler.ts +21 -0
  59. package/src/shared/views/ClipboardPasteHandler/NativeCometChatClipboardModule.ts +6 -0
  60. package/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +4 -0
  61. package/src/shared/views/CometChatAvatar/CometChatAvatar.tsx +17 -5
  62. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +28 -14
  63. package/src/shared/views/CometChatConfirmDialog/CometChatConfirmDialog.tsx +2 -0
  64. package/src/shared/views/CometChatConversationStarter/CometChatConversationStarter.tsx +91 -20
  65. package/src/shared/views/CometChatList/CometChatList.tsx +6 -1
  66. package/src/shared/views/CometChatListItem/CometChatListItem.tsx +4 -0
  67. package/src/shared/views/CometChatRetryButton/CometChatRetryButton.tsx +1 -0
  68. package/src/shared/views/CometChatSuggestionList/CometChatSuggestionList.tsx +4 -0
  69. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +4 -3
  70. package/src/shared/views/ErrorEmptyView/ErrorEmptyView.tsx +4 -1
  71. package/src/theme/default/default.ts +6 -0
  72. package/src/theme/type.ts +4 -0
@@ -228,6 +228,13 @@
228
228
  "NO_STICKERS_FOUND": "No stickers found",
229
229
  "REPLY_TO_THREAD": "Reply to thread",
230
230
  "REPLY_IN_THREAD": "Reply in thread",
231
+ "THREAD_SUBSCRIPTION_SUBSCRIBE": "Subscribe to thread",
232
+ "THREAD_SUBSCRIPTION_UNSUBSCRIBE": "Unsubscribe from thread",
233
+ "THREAD_SUBSCRIPTION_SUBSCRIBED_TOAST": "Subscribed. You'll be notified about new replies in this thread.",
234
+ "THREAD_SUBSCRIPTION_UNSUBSCRIBED_TOAST": "Unsubscribed. Notifications are off until you reply or are mentioned.",
235
+ "THREAD_SUBSCRIPTION_SUBSCRIBED": "Subscribed",
236
+ "THREAD_SUBSCRIPTION_FAILED": "Couldn't update. Please try again.",
237
+ "THREAD_UNAVAILABLE": "You no longer have access to this thread.",
231
238
  "VIEW": "View",
232
239
  "DELETE_MESSAGE": "Delete message",
233
240
  "EDIT_MESSAGE": "Edit message",
@@ -298,6 +305,53 @@
298
305
  "VIEW_PROFILE": "View Profile",
299
306
  "SEND_MESSAGE_IN_PRIVATE": "Send message privately",
300
307
  "DELETE": "Delete",
308
+ "PIN_MESSAGE": "Pin message",
309
+ "UNPIN_MESSAGE": "Unpin message",
310
+ "SAVE_MESSAGE": "Save message",
311
+ "UNSAVE_MESSAGE": "Unsave message",
312
+ "PIN_MESSAGE_TITLE": "Pin Message",
313
+ "PIN_MESSAGE_CONFIRM": "Do you want to pin this message to this conversation?",
314
+ "UNPIN_MESSAGE_TITLE": "Unpin Message",
315
+ "UNPIN_MESSAGE_CONFIRM": "Do you want to unpin this message from this conversation?",
316
+ "SAVE_MESSAGE_TITLE": "Save Message",
317
+ "SAVE_MESSAGE_CONFIRM": "Do you want to save this message?",
318
+ "UNSAVE_MESSAGE_TITLE": "Unsave Message",
319
+ "UNSAVE_MESSAGE_CONFIRM": "Do you want to remove this message from your saved messages?",
320
+ "PIN": "Pin",
321
+ "UNPIN": "Unpin",
322
+ "SAVE": "Save",
323
+ "UNSAVE": "Unsave",
324
+ "MESSAGE_PINNED": "Message pinned",
325
+ "MESSAGE_UNPINNED": "Message unpinned",
326
+ "MESSAGE_SAVED": "Message saved",
327
+ "MESSAGE_UNSAVED": "Message unsaved",
328
+ "PINNED": "Pinned",
329
+ "SAVED": "Saved",
330
+ "SAVED_MESSAGES": "Saved Messages",
331
+ "PINNED_MESSAGES": "Pinned Messages",
332
+ "PIN_CONVERSATION": "Pin",
333
+ "UNPIN_CONVERSATION": "Unpin",
334
+ "CONVERSATION_PINNED": "Conversation pinned",
335
+ "CONVERSATION_UNPINNED": "Conversation unpinned",
336
+ "PIN_CONVERSATION_LIMIT_REACHED": "You can only pin {limit} chats. Unpin one to pin another.",
337
+ "PIN_CONVERSATION_LIMIT_REACHED_NO_COUNT": "You've reached your pinned chats limit. Unpin one to pin another.",
338
+ "CONVERSATION_NOT_PINNABLE": "This conversation can't be pinned yet.",
339
+ "UNPIN_CONVERSATION_TITLE": "Unpin Conversation",
340
+ "UNPIN_CONVERSATION_CONFIRM": "Do you want to unpin this conversation from the top of your list?",
341
+ "NO_SAVED_MESSAGES": "No saved messages yet",
342
+ "NO_SAVED_MESSAGES_SUBTITLE": "Save messages to keep them handy whenever you need them.",
343
+ "BACK": "Back",
344
+ "NO_PINNED_MESSAGES": "No pinned messages yet",
345
+ "NO_PINNED_MESSAGES_SUBTITLE": "Pin important messages to keep them easy to find.",
346
+ "PIN_LIMIT_REACHED": "You can only pin {limit} messages. Unpin one to pin another.",
347
+ "SAVE_LIMIT_REACHED": "You can save up to {limit} messages.",
348
+ "PIN_LIMIT_REACHED_NO_COUNT": "You've reached your pinned messages limit. Unpin one to pin another.",
349
+ "SAVE_LIMIT_REACHED_NO_COUNT": "You've reached your limit for saved messages.",
350
+ "PIN_NOT_ALLOWED": "You don't have permission to pin messages here.",
351
+ "PIN_SAVE_MODERATION_PENDING": "This message is still being checked. Try again in a moment.",
352
+ "PIN_SAVE_FEATURE_OFF": "This feature isn't available for this app.",
353
+ "PIN_SAVE_GENERIC_ERROR": "Something went wrong. Please try again.",
354
+ "MESSAGE_NO_LONGER_AVAILABLE": "This message is no longer available.",
301
355
  "DELETE_CONFIRM": "Are you sure you want to delete?",
302
356
  "DELETE_CHAT": "Delete this chat?",
303
357
  "SURE_TO_DELETE_CHAT": "Are you sure you want to delete this chat? This action cannot be undone.",
@@ -9,6 +9,7 @@ import { stripMarkdown, preparePreviewText } from "../MarkdownUtils";
9
9
  import { CometChatRichTextFormatter } from "../../formatters/CometChatRichTextFormatter";
10
10
  import { applyMentionsFormatting } from "../MessageUtils";
11
11
  import { attachmentCountLabel } from "../conversationUtils";
12
+ import { isViewElement } from "../elementType";
12
13
 
13
14
  const t = getCometChatTranslation();
14
15
 
@@ -331,7 +332,7 @@ const CometChatMessagePreview = (props: CometChatMessagePreviewProps) => {
331
332
  // Detect if the formatter returned a View root (block-level content that
332
333
  // slipped through preparePreviewText). View can't nest inside Text, so we
333
334
  // render it in a height-constrained View wrapper instead.
334
- const isViewRoot = isRichSubtitle && React.isValidElement(messageText) && (messageText as React.ReactElement<any>).type === View;
335
+ const isViewRoot = isRichSubtitle && React.isValidElement(messageText) && isViewElement(messageText);
335
336
 
336
337
  return (
337
338
  <View style={containerStyle}>
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Utility functions for markdown text processing.
3
3
  */
4
+ import { stripColorTags } from "../formatters/richTextWireFormat";
4
5
 
5
6
  /**
6
7
  * Strips markdown syntax characters from text, returning clean readable content.
@@ -17,12 +18,17 @@
17
18
  * - Numbered lists: 1. text → text
18
19
  *
19
20
  * @param text - The markdown text to strip
21
+ * @param keepColorTags - Keep the `<color=#rrggbb>…</color>` wire tokens instead of removing
22
+ * them, for sinks that render colour themselves (search previews) rather than plain text.
20
23
  * @returns Clean text without markdown syntax characters
21
24
  */
22
- export function stripMarkdown(text: string): string {
25
+ export function stripMarkdown(text: string, keepColorTags = false): string {
23
26
  if (!text) return text;
24
27
 
25
- let result = text;
28
+ // 0. Remove the rich-text wire format's colour tokens. Not markdown and not HTML, so no
29
+ // rule below matches them — without this they reach every plain-text sink verbatim
30
+ // (share sheet, search subtitles, previews).
31
+ let result = keepColorTags ? text : stripColorTags(text);
26
32
 
27
33
  // 1. Remove code block fences (``` on their own lines or inline ```)
28
34
  result = result.replace(/```[\s\S]*?```/g, (match) => {
@@ -63,7 +69,19 @@ export function stripMarkdown(text: string): string {
63
69
  // 10. Strip HTML tags (e.g., <u>, <b>, <i>, <s>, <em>, <strong>, <del>, <br>, etc.)
64
70
  // Preserve CometChat mention tokens <@uid:xxx> and <@all:xxx> which look like HTML tags
65
71
  result = result.replace(/<br\s*\/?>/gi, '\n');
66
- result = result.replace(/<(?!@(?:uid|all):)[^>]+>/g, '');
72
+ // Require something that actually looks like a tag name after the `<`. The old `<[^>]+>` ate any
73
+ // `<`…`>` pair, so ordinary prose lost text: "a < b and c > d" became "a d". Captions and message
74
+ // previews are user text and legitimately contain comparisons and "<3". A tag must now start with
75
+ // a letter (optionally after `/`), which still strips <u>/<b>/<br>/<div class="x">/</strong> and
76
+ // still leaves CometChat's <@uid:…> / <@all:…> mention tokens alone — those start with `@`.
77
+ // `</color>` looks exactly like a closing HTML tag, so it is exempted when the caller asked
78
+ // to keep the colour tokens (`<color=…>` never matches — `=` follows the tag name).
79
+ result = result.replace(
80
+ keepColorTags
81
+ ? /<(?!\/color>)\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^>]*)?\/?>/g
82
+ : /<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^>]*)?\/?>/g,
83
+ ''
84
+ );
67
85
 
68
86
  // 11. Remove any remaining backslash escapes (e.g., \* \_ \` \~)
69
87
  result = result.replace(/\\([*_`~>\\])/g, '$1');
@@ -112,7 +130,10 @@ export function preparePreviewText(text: string): PreviewTextResult {
112
130
  const afterOpen = trimmed.substring(3);
113
131
  const closeIdx = afterOpen.indexOf('```');
114
132
  let firstLine: string;
115
- if (closeIdx > 0) {
133
+ // `>= 0`, not `> 0`: an empty code block (six backticks) closes at offset 0. Treating it as
134
+ // unterminated made the preview scan ON to the next line and show text that is not in the
135
+ // code block at all (ENG-38253).
136
+ if (closeIdx >= 0) {
116
137
  firstLine = afterOpen.substring(0, closeIdx).trim();
117
138
  } else {
118
139
  firstLine = '';
@@ -21,7 +21,12 @@ import { deepMerge } from "../helper/helperFunctions";
21
21
  import { CometChatDate } from "../views/CometChatDate";
22
22
  import { CometChatAvatar, CometChatReceipt } from "../views";
23
23
  import { useCometChatTranslation } from "../resources/CometChatLocalizeNew";
24
+ import { getCometChatTranslation } from "../resources/CometChatLocalizeNew/LocalizationManager";
24
25
  import { useTheme } from "../../theme";
26
+ import { isPinned, isSaved } from "./PinSaveHelper";
27
+
28
+ /** Module-scope translator — getStatusInfoView is a plain function, not a component. */
29
+ const translate = getCometChatTranslation();
25
30
 
26
31
  type MessageViewParamsType = {
27
32
  message: CometChat.BaseMessage;
@@ -32,6 +37,13 @@ type MessageViewParamsType = {
32
37
  datePattern?: (message: CometChat.BaseMessage) => string;
33
38
  receiptsVisibility?: boolean;
34
39
  avatarVisibility?: boolean;
40
+ /**
41
+ * Sender-name header inside the bubble. Symmetric with `avatarVisibility`, and
42
+ * exists for the same reason: a surface that already names the sender above the
43
+ * bubble (the pinned/saved panels) would otherwise print it twice on group
44
+ * messages, since both views are group-only.
45
+ */
46
+ headerVisibility?: boolean;
35
47
  };
36
48
 
37
49
  const getOverridenBubbleStyles = (theme: CometChatTheme) => {
@@ -49,14 +61,43 @@ const getOverridenBubbleStyles = (theme: CometChatTheme) => {
49
61
  outgoing: deepMerge(outgoingBubbleStyles, outgoingBubbleStyles.imageBubbleStyles ?? {}),
50
62
  });
51
63
 
64
+ /**
65
+ * File and audio bubbles carry a FIXED containerStyle.height sized to the player
66
+ * alone. CometChatMessageBubble renders the content wrapper with `overflow:
67
+ * hidden`, and the StatusInfoView sits after ContentView inside it — so the fixed
68
+ * height clips the whole meta row away: no pin indicator, no saved indicator, no
69
+ * timestamp, on every audio and file bubble.
70
+ *
71
+ * CometChatMessageList already drops the height for exactly these two types
72
+ * (its own overridenBubbleStyles), which is why the main chat looks right and
73
+ * every surface going through MessageUtils — both pin/save panels and
74
+ * CometChatMessageInformation — did not. Kept in sync deliberately; the two
75
+ * copies of this map are a standing hazard.
76
+ */
77
+ const fileIncoming = deepMerge(incomingBubbleStyles, incomingBubbleStyles.fileBubbleStyles ?? {});
78
+ if (fileIncoming.containerStyle) fileIncoming.containerStyle.height = undefined;
79
+ const fileOutgoing = deepMerge(outgoingBubbleStyles, outgoingBubbleStyles.fileBubbleStyles ?? {});
80
+ if (fileOutgoing.containerStyle) fileOutgoing.containerStyle.height = undefined;
81
+
52
82
  styleCache.set(MessageTypeConstants.file, {
53
- incoming: deepMerge(incomingBubbleStyles, incomingBubbleStyles.fileBubbleStyles ?? {}),
54
- outgoing: deepMerge(outgoingBubbleStyles, outgoingBubbleStyles.fileBubbleStyles ?? {}),
83
+ incoming: fileIncoming,
84
+ outgoing: fileOutgoing,
55
85
  });
56
86
 
87
+ const audioIncoming = deepMerge(
88
+ incomingBubbleStyles,
89
+ incomingBubbleStyles.audioBubbleStyles ?? {}
90
+ );
91
+ if (audioIncoming.containerStyle) audioIncoming.containerStyle.height = undefined;
92
+ const audioOutgoing = deepMerge(
93
+ outgoingBubbleStyles,
94
+ outgoingBubbleStyles.audioBubbleStyles ?? {}
95
+ );
96
+ if (audioOutgoing.containerStyle) audioOutgoing.containerStyle.height = undefined;
97
+
57
98
  styleCache.set(MessageTypeConstants.audio, {
58
- incoming: deepMerge(incomingBubbleStyles, incomingBubbleStyles.audioBubbleStyles ?? {}),
59
- outgoing: deepMerge(outgoingBubbleStyles, outgoingBubbleStyles.audioBubbleStyles ?? {}),
99
+ incoming: audioIncoming,
100
+ outgoing: audioOutgoing,
60
101
  });
61
102
 
62
103
  styleCache.set(MessageTypeConstants.messageDeleted, {
@@ -246,10 +287,41 @@ const getStatusInfoView = (
246
287
  flexDirection: "row",
247
288
  justifyContent: "flex-end",
248
289
  alignSelf: "flex-end",
290
+ // Media bubbles size their content to the attachment, which left this row
291
+ // baseline-misaligned against the glyphs below on an audio/file bubble.
292
+ alignItems: "center",
249
293
  },
250
294
  _style.dateReceiptContainerStyle,
251
295
  ]}
252
296
  >
297
+ {/* Pin & Save indicators (§6.2), before the timestamp in the same meta-row
298
+ slot the message list uses. CometChatMessageList has its OWN copy of this
299
+ view and the indicators were added only there, so every surface rendering
300
+ through MessageUtils — both panels and CometChatMessageInformation —
301
+ silently showed media and text bubbles with no pin/save state at all.
302
+ Icon-only, matching the design, so each needs an accessibilityLabel or a
303
+ screen reader announces nothing (§6.8). Colour comes from the date token so
304
+ the group reads as one piece of metadata rather than as an action. */}
305
+ {isPinned(item) && (
306
+ <View accessible={true} accessibilityLabel={translate("PINNED") ?? "Pinned"}>
307
+ <Icon
308
+ name='keep-fill'
309
+ color={_style.dateStyles?.textStyle?.color}
310
+ height={14}
311
+ width={14}
312
+ />
313
+ </View>
314
+ )}
315
+ {isSaved(item) && (
316
+ <View accessible={true} accessibilityLabel={translate("SAVED") ?? "Saved"}>
317
+ <Icon
318
+ name='bookmark-fill'
319
+ color={_style.dateStyles?.textStyle?.color}
320
+ height={14}
321
+ width={14}
322
+ />
323
+ </View>
324
+ )}
253
325
  <CometChatDate
254
326
  timeStamp={(item.getDeletedAt() || item.getSentAt()) * 1000 || getSentAtTimestamp(item)}
255
327
  pattern={"timeFormat"}
@@ -285,6 +357,7 @@ export const MessageUtils = {
285
357
  datePattern,
286
358
  receiptsVisibility,
287
359
  avatarVisibility,
360
+ headerVisibility = true,
288
361
  } = params;
289
362
  const templatesMap = getTemplatesMap(templates ?? []);
290
363
  const baseStyle = getBubbleStyle(message, theme);
@@ -331,7 +404,9 @@ export const MessageUtils = {
331
404
  : undefined
332
405
  }
333
406
  HeaderView={
334
- message.getReceiverType() === "group" ? getHeaderView(message, theme) : undefined
407
+ headerVisibility && message.getReceiverType() === "group"
408
+ ? getHeaderView(message, theme)
409
+ : undefined
335
410
  }
336
411
  BottomView={
337
412
  DefaultModerationBottomView ||
@@ -0,0 +1,245 @@
1
+ /**
2
+ * The kit's seam onto the SDK's conversation-pin surface.
3
+ *
4
+ * Separate from PinSaveHelper on purpose: pinning a CONVERSATION and pinning a
5
+ * MESSAGE share a name and nothing else. Different endpoints, a different cap
6
+ * (5, not 100), a different feature flag, no role gate, and a different failure
7
+ * mode. Folding them together would invite carrying one's rules onto the other.
8
+ *
9
+ * @module PinConversationHelper
10
+ */
11
+ import { CometChat } from "@cometchat/chat-sdk-react-native";
12
+
13
+ /** Off until an integrator opts in — same shape as PinSaveConfig. */
14
+ export const PinConversationConfig = {
15
+ _enabled: false,
16
+ enable(enabled: boolean = true) {
17
+ this._enabled = enabled;
18
+ },
19
+ isEnabled(): boolean {
20
+ return this._enabled;
21
+ },
22
+ };
23
+
24
+ /** An admin/global conversation pin. Users may not unpin these. */
25
+ export const SYSTEM_PINNER = "app_system";
26
+
27
+ /** Server error codes specific to conversation pinning. */
28
+ export const PinConversationErrors = {
29
+ LIMIT: "ERR_PINNED_CONVERSATIONS_LIMIT_EXCEEDED",
30
+ /** Never-messaged or hidden conversation — cannot be newly pinned. */
31
+ NOT_ACCESSIBLE: "ERR_CONVERSATION_NOT_ACCESSIBLE",
32
+ FEATURE_OFF: "ERR_FEATURE_NOT_ACCESSIBLE",
33
+ } as const;
34
+
35
+ /**
36
+ * True when the conversation is pinned. PRESENCE of the timestamp is the flag —
37
+ * the SDK deletes rather than zeroes, so never write this as `!!getPinnedAt()`.
38
+ */
39
+ export const isConversationPinned = (conversation?: CometChat.Conversation | null): boolean => {
40
+ try {
41
+ return (
42
+ conversation?.getPinnedAt?.() !== undefined && conversation?.getPinnedAt?.() !== null
43
+ );
44
+ } catch {
45
+ return false;
46
+ }
47
+ };
48
+
49
+ /**
50
+ * True for an admin/global pin. A user cannot unpin one, so the affordance is
51
+ * hidden rather than shown and then refused by the server.
52
+ */
53
+ export const isSystemPinnedConversation = (
54
+ conversation?: CometChat.Conversation | null
55
+ ): boolean => {
56
+ try {
57
+ return isConversationPinned(conversation) && conversation?.getPinnedBy?.() === SYSTEM_PINNER;
58
+ } catch {
59
+ return false;
60
+ }
61
+ };
62
+
63
+ /** The uid/guid and type a pin call needs, or null when the row is unusable. */
64
+ export const targetOf = (
65
+ conversation?: CometChat.Conversation | null
66
+ ): { id: string; type: string } | null => {
67
+ try {
68
+ if (!conversation) return null;
69
+ const type = conversation.getConversationType?.();
70
+ const other: any = conversation.getConversationWith?.();
71
+ if (!type || !other) return null;
72
+ const id =
73
+ type === "group"
74
+ ? typeof other.getGuid === "function" && other.getGuid()
75
+ : typeof other.getUid === "function" && other.getUid();
76
+ return id ? { id: String(id), type } : null;
77
+ } catch {
78
+ return null;
79
+ }
80
+ };
81
+
82
+ /** Last-message time for ordering, 0 when the conversation has never had one. */
83
+ const recencyOf = (conversation: any): number => {
84
+ try {
85
+ return conversation?.getLastMessage?.()?.getSentAt?.() ?? 0;
86
+ } catch {
87
+ return 0;
88
+ }
89
+ };
90
+
91
+ /** Pin time, or -1 when not pinned. Newest pin sorts first within a tier. */
92
+ const pinnedAtOf = (conversation: any): number => {
93
+ try {
94
+ const v = conversation?.getPinnedAt?.();
95
+ return v === undefined || v === null ? -1 : Number(v);
96
+ } catch {
97
+ return -1;
98
+ }
99
+ };
100
+
101
+ /**
102
+ * Which of the three ordering tiers a conversation belongs to. Lower wins.
103
+ *
104
+ * 0 SYSTEM pin — set from the dashboard (`pinnedBy: app_system`). Highest
105
+ * priority: it outranks a user's own pin no matter how much
106
+ * more recently the user pinned theirs. A user cannot unpin one.
107
+ * 1 USER pin — this user pinned it themselves.
108
+ * 2 unpinned — ordinary recency ordering.
109
+ */
110
+ export const TIER = { SYSTEM_PIN: 0, USER_PIN: 1, UNPINNED: 2 };
111
+
112
+ export const tierOf = (conversation: any): number => {
113
+ try {
114
+ if (!isConversationPinned(conversation)) return TIER.UNPINNED;
115
+ return isSystemPinnedConversation(conversation) ? TIER.SYSTEM_PIN : TIER.USER_PIN;
116
+ } catch {
117
+ return TIER.UNPINNED;
118
+ }
119
+ };
120
+
121
+ /**
122
+ * Where a conversation belongs in the list — the single ordering rule used by pin,
123
+ * unpin, an incoming message, AND a conversation appearing for the first time.
124
+ *
125
+ * Three blocks, in this order:
126
+ * 1. dashboard/system pins, newest pin first
127
+ * 2. the user's own pins, newest pin first
128
+ * 3. everything else, most recent message first
129
+ *
130
+ * Consequences worth stating, because each was a bug at some point:
131
+ * - a pinned row KEEPS its slot when a message arrives. Pinned order is by when it
132
+ * was pinned, not by who messaged last, so a busy pinned chat must not climb.
133
+ * - a brand-new or previously-deleted conversation goes into tier 3, NOT to index
134
+ * 0. A message in a deleted chat must not surface above the user's pins.
135
+ * - a user pin never outranks a dashboard pin, whatever the timestamps say.
136
+ *
137
+ * @param conversation the row being placed
138
+ * @param all the current list INCLUDING it — filtered out here
139
+ * @returns the index to insert at
140
+ */
141
+ export const conversationInsertIndex = (conversation: any, all: Array<any>): number => {
142
+ try {
143
+ if (!conversation || !Array.isArray(all)) return 0;
144
+ const id = String(conversation.getConversationId?.() ?? "");
145
+ const others = all.filter(o => String(o?.getConversationId?.() ?? "") !== id);
146
+
147
+ const myTier = tierOf(conversation);
148
+ const myPin = pinnedAtOf(conversation);
149
+ const myRecency = recencyOf(conversation);
150
+
151
+ let index = 0;
152
+ for (let i = 0; i < others.length; i++) {
153
+ const other = others[i];
154
+ const otherTier = tierOf(other);
155
+
156
+ // A higher tier always sits above, regardless of timestamps.
157
+ if (otherTier < myTier) {
158
+ index = i + 1;
159
+ continue;
160
+ }
161
+ if (otherTier > myTier) break;
162
+
163
+ // Same tier: pins compare by pinnedAt, unpinned rows by message recency.
164
+ const mine = myTier === TIER.UNPINNED ? myRecency : myPin;
165
+ const theirs = otherTier === TIER.UNPINNED ? recencyOf(other) : pinnedAtOf(other);
166
+ if (theirs > mine) {
167
+ index = i + 1;
168
+ continue;
169
+ }
170
+ break;
171
+ }
172
+ return index;
173
+ } catch {
174
+ return 0;
175
+ }
176
+ };
177
+
178
+ export const isConversationCapError = (error: any): boolean => {
179
+ try {
180
+ return error?.code === PinConversationErrors.LIMIT;
181
+ } catch {
182
+ return false;
183
+ }
184
+ };
185
+
186
+ export const isConversationNotPinnable = (error: any): boolean => {
187
+ try {
188
+ return error?.code === PinConversationErrors.NOT_ACCESSIBLE;
189
+ } catch {
190
+ return false;
191
+ }
192
+ };
193
+
194
+ export const isConversationFeatureOff = (error: any): boolean => {
195
+ try {
196
+ return error?.code === PinConversationErrors.FEATURE_OFF;
197
+ } catch {
198
+ return false;
199
+ }
200
+ };
201
+
202
+ /**
203
+ * The server-owned cap, when the error carries it. Usually absent — the backend
204
+ * documents caps as tenant settings and does not promise them on the payload — so
205
+ * callers must render copy without a number rather than printing a guess.
206
+ */
207
+
208
+ /**
209
+ * The conversation cap, or null when unknown. Same two sources as the message-level
210
+ * resolveCapLimit: `errorParams.limit` first, then app settings via the SDK getter
211
+ * (ENG-37790). This replaced a regex over the server's error prose — see the note there.
212
+ */
213
+ export const resolveConversationCapLimit = async (error: any): Promise<number | null> => {
214
+ const fromError = readConversationCapLimit(error);
215
+ if (fromError !== null) return fromError;
216
+ try {
217
+ const limit = await CometChat.getPinConversationLimit();
218
+ return typeof limit === "number" && isFinite(limit) && limit > 0 ? limit : null;
219
+ } catch {
220
+ return null;
221
+ }
222
+ };
223
+
224
+ /** The cap as carried ON the rejection, or null. See resolveConversationCapLimit. */
225
+ export const readConversationCapLimit = (error: any): number | null => {
226
+ try {
227
+ const raw = error?.errorParams?.limit;
228
+ if (typeof raw !== "number" && typeof raw !== "string") return null;
229
+ const limit = Number(raw);
230
+ return isFinite(limit) && limit > 0 ? limit : null;
231
+ } catch {
232
+ return null;
233
+ }
234
+ };
235
+
236
+ /**
237
+ * Both resolve the FULL updated Conversation, verified on staging 2026-07-30 — not
238
+ * an ack string, which is what these were originally typed as. A caller can apply
239
+ * the resolved row straight into its list instead of trusting its optimistic guess.
240
+ */
241
+ export const pinConversation = (id: string, type: string): Promise<CometChat.Conversation> =>
242
+ CometChat.pinConversation(id, type);
243
+
244
+ export const unpinConversation = (id: string, type: string): Promise<CometChat.Conversation> =>
245
+ CometChat.unpinConversation(id, type);