@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
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Helpers for the user-level Saved Messages surface (§6.4).
3
+ *
4
+ * The interesting part is `sourceLabelFor`. The design doc's recipe assumed rows
5
+ * might arrive without conversation context, and prescribed a lazy hydrate showing
6
+ * a raw id in the meantime. Verified against staging 2026-07-30: saved rows DO
7
+ * carry `conversationId`, `receiver`, `receiverType` and `sender`, so the label is
8
+ * derivable synchronously and no hydration call is needed. That deletes the whole
9
+ * placeholder-then-refresh path the doc called for.
10
+ *
11
+ * @module SavedMessagesHelper
12
+ */
13
+ import { CometChat } from "@cometchat/chat-sdk-react-native";
14
+
15
+ /** What a saved row needs to render its "where did this come from" line. */
16
+ export interface SavedMessageSource {
17
+ /** `group` | `user` — drives the sigil and the open-conversation call. */
18
+ receiverType: string;
19
+ /** guid, or the uid of the OTHER party in a 1-1. */
20
+ receiverId: string;
21
+ /** Display text, e.g. `#engineering` or `@alice`. */
22
+ label: string;
23
+ /** Plain display name with no sigil — what the row TITLE shows. */
24
+ name: string;
25
+ /** Group icon or user avatar URL, when the payload carries a hydrated party. */
26
+ avatar?: string;
27
+ }
28
+
29
+ const RECEIVER_TYPE = { user: "user", group: "group" };
30
+
31
+ /**
32
+ * Best display name for a User/Group, falling back to its id.
33
+ *
34
+ * A parsed message hands back a hydrated object, but a degenerate payload can
35
+ * leave `receiver` as a bare string id — hence the typeof branch rather than
36
+ * assuming the object shape.
37
+ */
38
+ const nameOf = (party: any, fallbackId: string): string => {
39
+ try {
40
+ if (!party) return fallbackId;
41
+ if (typeof party === "string") return party;
42
+ if (typeof party.getName === "function" && party.getName()) return party.getName();
43
+ if (typeof party.getUid === "function" && party.getUid()) return party.getUid();
44
+ if (typeof party.getGuid === "function" && party.getGuid()) return party.getGuid();
45
+ return fallbackId;
46
+ } catch {
47
+ return fallbackId;
48
+ }
49
+ };
50
+
51
+ /**
52
+ * Avatar/icon URL for a User or Group, or undefined.
53
+ *
54
+ * Same defensive shape as nameOf: a degenerate payload can leave the party as a
55
+ * bare id string, which has neither accessor.
56
+ */
57
+ const avatarOf = (party: any): string | undefined => {
58
+ try {
59
+ if (!party || typeof party === "string") return undefined;
60
+ if (typeof party.getAvatar === "function" && party.getAvatar()) return party.getAvatar();
61
+ if (typeof party.getIcon === "function" && party.getIcon()) return party.getIcon();
62
+ return undefined;
63
+ } catch {
64
+ return undefined;
65
+ }
66
+ };
67
+
68
+ /**
69
+ * Icon + label for a message type, for the row's subtitle.
70
+ *
71
+ * Mirrors the conversation list's preview vocabulary so a saved row reads the same
72
+ * as the chat it came from. `label` is a LOCALE KEY, not display text — the caller
73
+ * translates, because this module has no theme or translator of its own.
74
+ *
75
+ * A caption, when present, replaces the generic label: the design shows
76
+ * "🖼 Check this out from yesterday!" rather than "🖼 Image".
77
+ */
78
+ export const PREVIEW_BY_TYPE: Record<string, { icon: string; labelKey: string }> = {
79
+ image: { icon: "photo-fill", labelKey: "MESSAGE_IMAGE" },
80
+ video: { icon: "videocam-fill", labelKey: "MESSAGE_VIDEO" },
81
+ audio: { icon: "mic-fill", labelKey: "MESSAGE_AUDIO" },
82
+ file: { icon: "description-fill", labelKey: "MESSAGE_FILE" },
83
+ extension_sticker: { icon: "sticker-fill", labelKey: "CUSTOM_MESSAGE_STICKER" },
84
+ extension_poll: { icon: "poll-fill", labelKey: "CUSTOM_MESSAGE_POLL" },
85
+ extension_document: { icon: "description-fill", labelKey: "CUSTOM_MESSAGE_DOCUMENT" },
86
+ extension_whiteboard: { icon: "description-fill", labelKey: "CUSTOM_MESSAGE_DOCUMENT" },
87
+ };
88
+
89
+ /** What a saved row's subtitle should render. */
90
+ export interface SavedMessagePreview {
91
+ /** Icon name, or null for a plain-text row which shows no glyph. */
92
+ icon: string | null;
93
+ /** Locale key to translate, or null when `text` is already display-ready. */
94
+ labelKey: string | null;
95
+ /** Literal text — a text message's body, or a media caption. */
96
+ text: string | null;
97
+ }
98
+
99
+ /**
100
+ * The subtitle content for a saved row. Never throws; an unrecognised type falls
101
+ * back to the generic document glyph rather than rendering an empty line.
102
+ */
103
+ export const previewFor = (message?: CometChat.BaseMessage | null): SavedMessagePreview => {
104
+ const empty: SavedMessagePreview = { icon: "description-fill", labelKey: null, text: null };
105
+ try {
106
+ if (!message) return empty;
107
+
108
+ if (message instanceof CometChat.TextMessage) {
109
+ return { icon: null, labelKey: null, text: message.getText() ?? "" };
110
+ }
111
+
112
+ const entry = PREVIEW_BY_TYPE[message.getType()];
113
+ const caption =
114
+ message instanceof CometChat.MediaMessage ? (message.getCaption() ?? "").trim() : "";
115
+
116
+ if (caption) return { icon: entry?.icon ?? empty.icon, labelKey: null, text: caption };
117
+ if (entry) return { icon: entry.icon, labelKey: entry.labelKey, text: null };
118
+
119
+ // Unknown custom type: show the glyph and let the caller fall back to the type
120
+ // string, which is more useful than a blank subtitle.
121
+ return { icon: empty.icon, labelKey: null, text: message.getType() ?? null };
122
+ } catch {
123
+ return empty;
124
+ }
125
+ };
126
+
127
+ /**
128
+ * The source conversation for a saved row, or null when the payload is unusable.
129
+ *
130
+ * Pass `loggedInUserUid` for correct 1-1 labelling. On an INCOMING 1-1 message the
131
+ * receiver is the logged-in user, so labelling purely by receiver would render
132
+ * every received row as "@me"; when the receiver is us, the counterparty is the
133
+ * sender. Groups need no such flip.
134
+ *
135
+ * Never throws, and never returns a half-built label: a row whose source cannot be
136
+ * determined still renders — the caller just omits the source line — rather than
137
+ * being dropped, per the design doc's first rule.
138
+ */
139
+ /**
140
+ * Who wrote this saved row, as the subtitle prefix — `"You"`, a sender name, or null
141
+ * for no prefix at all.
142
+ *
143
+ * Returns the NAME, not the punctuation: the component owns the `": "` so a
144
+ * localisation that separates differently has one place to change.
145
+ *
146
+ * Three outcomes, and the asymmetry is the point:
147
+ * - **You wrote it** → `"You"`, in a 1-1 as much as in a group. Without this a DM row
148
+ * you sent and a DM row you received render identically — same avatar, same title,
149
+ * same date — and only the preview text tells them apart.
150
+ * - **Someone else, in a group** → their name. There are many possible authors, so
151
+ * the row is ambiguous without it.
152
+ * - **Someone else, in a 1-1** → null. There is exactly one other author and the row
153
+ * TITLE already names them; repeating it in the subtitle is noise.
154
+ */
155
+ export const subtitlePrefixNameFor = (
156
+ message?: CometChat.BaseMessage | null,
157
+ loggedInUserUid?: string | null,
158
+ youLabel: string = "You"
159
+ ): string | null => {
160
+ try {
161
+ if (!message) return null;
162
+ const senderUid = message.getSender?.()?.getUid?.();
163
+ if (senderUid && loggedInUserUid && senderUid === loggedInUserUid) return youLabel;
164
+ if (message.getReceiverType?.() !== RECEIVER_TYPE.group) return null;
165
+ return message.getSender?.()?.getName?.() || null;
166
+ } catch {
167
+ return null;
168
+ }
169
+ };
170
+
171
+ export const sourceLabelFor = (
172
+ message?: CometChat.BaseMessage | null,
173
+ loggedInUserUid?: string | null
174
+ ): SavedMessageSource | null => {
175
+ try {
176
+ if (!message) return null;
177
+
178
+ const receiverType = message.getReceiverType?.();
179
+ if (receiverType !== RECEIVER_TYPE.user && receiverType !== RECEIVER_TYPE.group) return null;
180
+
181
+ const receiver = message.getReceiver?.();
182
+ const receiverId = message.getReceiverId?.() ?? "";
183
+
184
+ if (receiverType === RECEIVER_TYPE.group) {
185
+ const name = nameOf(receiver, receiverId);
186
+ return { receiverType, receiverId, label: `#${name}`, name, avatar: avatarOf(receiver) };
187
+ }
188
+
189
+ // 1-1: flip to the sender when the row was addressed to us.
190
+ if (loggedInUserUid && receiverId === loggedInUserUid) {
191
+ const sender = message.getSender?.();
192
+ const senderUid = sender && typeof sender.getUid === "function" ? sender.getUid() : "";
193
+ if (senderUid) {
194
+ const name = nameOf(sender, senderUid);
195
+ return {
196
+ receiverType,
197
+ receiverId: senderUid,
198
+ label: `@${name}`,
199
+ name,
200
+ avatar: avatarOf(sender),
201
+ };
202
+ }
203
+ }
204
+
205
+ const name = nameOf(receiver, receiverId);
206
+ return { receiverType, receiverId, label: `@${name}`, name, avatar: avatarOf(receiver) };
207
+ } catch {
208
+ return null;
209
+ }
210
+ };
211
+
212
+ /**
213
+ * A fresh request for the logged-in user's saved messages, newest save first.
214
+ *
215
+ * The ordinary messages request, filtered to saved rows. Deliberately carries NO
216
+ * uid/guid: `saved=1` is account-wide, and scoping it to a conversation would turn
217
+ * this cross-conversation inbox into a per-chat list. Paging is the ordinary sentAt
218
+ * cursor walk — setSavedOnly() changes what the list contains, not how it pages.
219
+ *
220
+ * Single-use by design — build a new one to refresh. The server caps the whole set
221
+ * at 100.
222
+ */
223
+ export const buildSavedMessagesRequest = (limit?: number) => {
224
+ const builder = new CometChat.MessagesRequestBuilder().setSavedOnly(true);
225
+ // ALWAYS set. The SDK has no default: MessagesRequestBuilder.limit stays undefined
226
+ // unless setLimit() is called, and makeAPICall() then rejects with
227
+ // SET_LIMIT_IS_COMPULSORY *before* any request goes out — an error screen with an
228
+ // empty network log. 30 matches the SDK's own DEFAULT_VALUES.MSGS_LIMIT.
229
+ builder.setLimit(limit ?? 30);
230
+ return builder.build();
231
+ };
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Kit-side thread subscription — the feature gate, the toggle both entry points call
3
+ * (thread header §6.2, message action sheet §6.3), and the two local mirrors of the
4
+ * server's auto-subscribe behaviour.
5
+ *
6
+ * ── THE MODEL ─────────────────────────────────────────────────────────────────────────
7
+ *
8
+ * **The message object is the source of truth. There is no kit-side cache.**
9
+ *
10
+ * The SDK used to keep a subscription store, infer changes and emit events. It no longer
11
+ * does any of it: it reports the server's flag on the message (`isThreadSubscribed()`) and
12
+ * offers a local setter (`setThreadSubscribed()`) plus two server calls. The mistake the SDK
13
+ * just removed is not one this file reintroduces — every surface reads the flag off the
14
+ * message object it is holding, and when the kit learns of a change it writes the flag back
15
+ * onto the objects it holds so the next read, including one after a remount, is correct.
16
+ *
17
+ * Surfaces do not share message instances (the list, the thread header's parent and a bubble
18
+ * may each hold a copy), so a write to one is invisible to the others. That is what
19
+ * `ccThreadSubscriptionChanged` is for: whoever changes state publishes, and every surface
20
+ * both re-renders and stamps the objects it holds.
21
+ *
22
+ * ── THE ONE RULE ──────────────────────────────────────────────────────────────────────
23
+ *
24
+ * `threadSubscribed` is only populated on responses to requests that ASKED for it. A
25
+ * socket-delivered message carries no flag and reads `false`.
26
+ *
27
+ * **`false` means "the server did not tell me", NOT "the user is unsubscribed".**
28
+ *
29
+ * The one exception is the logged-in user's OWN message, fetched: the author is subscribed
30
+ * by default, so a `false` there is an explicit unsubscribe and nothing may override it.
31
+ *
32
+ * That rule bites hardest on a thread REPLY arriving over the socket — its own flag is
33
+ * `false` whatever the truth, so its bubble would offer "Subscribe" on a thread the user
34
+ * already follows. `applyIncomingReply` fixes it by stamping each arriving reply from the
35
+ * parent, which is the authority.
36
+ *
37
+ * ── THE FOUR CASES ────────────────────────────────────────────────────────────────────
38
+ *
39
+ * 1. **Manual toggle** — `toggleThreadSubscription`. The only case that writes to the server.
40
+ * 2. **You authored the message** — the server subscribes you outright. Stamped locally by
41
+ * `applySentMessage`, because the SEND RESPONSE omits the flag.
42
+ * 3. **A reply @-mentions you** — `applyIncomingReply`. Mirror only.
43
+ * 4. **You sent a reply** — same rule as 2, same call.
44
+ *
45
+ * Cases 2 and 4 collapsed into one when author-subscribed-by-default shipped (staging,
46
+ * 2026-08-19): any message you send subscribes you to its thread. The old "first reply to
47
+ * your own root" mirror was deleted with it — it was a workaround for the author NOT being
48
+ * subscribed until someone replied, and keeping it would risk reviving a subscription the
49
+ * author had cancelled.
50
+ *
51
+ * ── WHO OWNS WHAT ─────────────────────────────────────────────────────────────────────
52
+ *
53
+ * The API sets `threadSubscribed` on FETCHED messages only (confirmed with the backend team,
54
+ * 2026-08-19). Send responses and realtime frames never carry it. So:
55
+ *
56
+ * fetched message → the flag on the object IS the answer. Read it, never override it.
57
+ * sent message → the kit stamps it (applySentMessage).
58
+ * realtime message → the kit stamps it from the parent (applyIncomingReply).
59
+ *
60
+ * Every mirror below exists to cover the two paths the API deliberately does not populate.
61
+ * None of them is waiting on a backend change.
62
+ *
63
+ * Cases 3 and 4 mirror server-side truths for immediate feedback; they never call
64
+ * `subscribeToThread`. Where a mirror and a later fetched flag disagree, the fetched flag
65
+ * wins — it overwrites the object the surface reads.
66
+ */
67
+ import { CometChat } from "@cometchat/chat-sdk-react-native";
68
+ import { CometChatUIEventHandler } from "../events/CometChatUIEventHandler/CometChatUIEventHandler";
69
+ import { MessageEvents } from "../events/messages";
70
+
71
+ /** ≥400 ms per §7.6, so a double-tap can't fire two writes. */
72
+ const DEBOUNCE_MS = 400;
73
+
74
+ /**
75
+ * A11: there is no plan gate, no feature flag and no capability flag in
76
+ * init/app-settings, so the client cannot feature-detect. This boolean is not a
77
+ * temporary scaffold — it is the only control that will ever exist.
78
+ *
79
+ * Default OFF: the integrator opts in. Gate off means NEITHER surface renders,
80
+ * whatever the two per-component visibility flags say.
81
+ */
82
+ export class ThreadSubscriptionConfig {
83
+ /**
84
+ * ON by default, to match the React UI Kit.
85
+ *
86
+ * React has no equivalent switch at all: it ships `hideThreadSubscriptionOption` (default
87
+ * false) on the message list and a matching toggle prop on the thread header, so the feature
88
+ * is visible unless an integrator opts OUT. RN carried an extra global gate defaulting to
89
+ * false on top of those same two props, which meant the identical integration code showed the
90
+ * control on web and nothing on mobile — and the only way to find out was to read the source.
91
+ *
92
+ * The per-instance props remain the real control surface and are ANDed with this, so anyone
93
+ * already calling setEnabled(false) keeps that behaviour.
94
+ */
95
+ private static enabled: boolean = true;
96
+
97
+ public static setEnabled(enabled: boolean): void {
98
+ ThreadSubscriptionConfig.enabled = !!enabled;
99
+ }
100
+
101
+ public static isEnabled(): boolean {
102
+ return ThreadSubscriptionConfig.enabled;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * One in-flight write per parentMessageId, and the last tap time for the debounce.
108
+ *
109
+ * This is NOT subscription state — it is request bookkeeping, and it is deliberately the
110
+ * only module-level map left in this file.
111
+ */
112
+ const inFlight: { [messageId: string]: boolean } = {};
113
+ const lastToggleAt: { [messageId: string]: number } = {};
114
+
115
+ /**
116
+ * The id of the thread a message belongs to — a reply carries its parent's id, a root
117
+ * message IS the thread.
118
+ *
119
+ * Used for exactly two things: the id sent to the server, and matching a
120
+ * `ccThreadSubscriptionChanged` event so one follow flips every bubble in the thread. It is
121
+ * NEVER used to decide which object to read state from — every message carries its own flag
122
+ * and each surface reads its own (§5.7).
123
+ */
124
+ export function getThreadIdFor(message: CometChat.BaseMessage): number {
125
+ const parentId = Number(message?.getParentMessageId?.() ?? 0);
126
+ return parentId > 0 ? parentId : Number(message?.getId?.() ?? 0);
127
+ }
128
+
129
+ /**
130
+ * Does the user follow this message's thread?
131
+ *
132
+ * Reads the message and nothing else. The server stamps `threadSubscribed` on EVERY fetched
133
+ * message in a thread — parent and replies alike — so a fetched reply answers correctly off
134
+ * its own object, exactly like its parent does.
135
+ */
136
+ export function isThreadSubscribed(message: CometChat.BaseMessage): boolean {
137
+ try {
138
+ return message?.isThreadSubscribed?.() === true;
139
+ } catch {
140
+ // A message model older than the accessor renders un-followed rather than throwing;
141
+ // this runs during render, where a throw is a blank screen.
142
+ return false;
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Write the flag onto a message object the caller is holding. Local only — this is the
148
+ * SDK's `setThreadSubscribed`, which never touches the network.
149
+ *
150
+ * Every surface calls this from its `ccThreadSubscriptionChanged` handler, so the objects it
151
+ * holds stay coherent with what it just rendered.
152
+ */
153
+ export function stampThreadSubscribed(
154
+ message: CometChat.BaseMessage | null | undefined,
155
+ subscribed: boolean
156
+ ): void {
157
+ try {
158
+ (message as any)?.setThreadSubscribed?.(subscribed === true);
159
+ } catch {
160
+ // Older model, or a plain object from a path that skipped the parser. Nothing to sync.
161
+ }
162
+ }
163
+
164
+ /** Emitted on the optimistic flip, on the server's answer, and on a revert. */
165
+ function emitChanged(parentMessageId: number, subscribed: boolean, inProgress: boolean): void {
166
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccThreadSubscriptionChanged, {
167
+ parentMessageId: Number(parentMessageId),
168
+ subscribed,
169
+ inProgress,
170
+ });
171
+ }
172
+
173
+ /**
174
+ * Stamp the message the caller is holding and tell every other surface, in one place so the
175
+ * two cannot drift. Mirrors only ever raise to `true` (§ the one rule): a socket frame's
176
+ * silence is not a negative answer, so nothing here may clear a known `true`.
177
+ */
178
+ function mirrorSubscribed(parentMessageId: number, message?: CometChat.BaseMessage): void {
179
+ if (!parentMessageId) return;
180
+ stampThreadSubscribed(message, true);
181
+ emitChanged(parentMessageId, true, false);
182
+ }
183
+
184
+ /**
185
+ * Flips the subscription for a thread. Case 1 — the only path that writes to the server.
186
+ *
187
+ * Resolves with the state that ended up applying — the caller does not need to revert
188
+ * anything itself, but SHOULD show the `thread_subscription_failed` snackbar when this
189
+ * rejects. There is no queue and no retry (§7.6): a Follow tapped offline fails visibly
190
+ * and reverts. Both server calls are idempotent, so a duplicate never errors.
191
+ *
192
+ * @returns {Promise<boolean>} true if the user is now following the thread
193
+ */
194
+ export function toggleThreadSubscription(message: CometChat.BaseMessage): Promise<boolean> {
195
+ const threadId = getThreadIdFor(message);
196
+ const key = String(threadId);
197
+ const now = Date.now();
198
+
199
+ // Debounce and in-flight guard. Both resolve with the CURRENT state rather than
200
+ // rejecting: the tap was ignored, nothing failed.
201
+ if (inFlight[key] || (lastToggleAt[key] && now - lastToggleAt[key] < DEBOUNCE_MS)) {
202
+ return Promise.resolve(isThreadSubscribed(message));
203
+ }
204
+ lastToggleAt[key] = now;
205
+ inFlight[key] = true;
206
+
207
+ const wasSubscribed = isThreadSubscribed(message);
208
+ const optimistic = !wasSubscribed;
209
+
210
+ // Flip the UI first, and stamp the object we were handed with it — there is no cache
211
+ // behind this, so the message IS what the surfaces read.
212
+ stampThreadSubscribed(message, optimistic);
213
+ emitChanged(threadId, optimistic, true);
214
+
215
+ const write = optimistic
216
+ ? CometChat.subscribeToThread(threadId)
217
+ : CometChat.unsubscribeFromThread(threadId);
218
+
219
+ return write.then(
220
+ () => {
221
+ inFlight[key] = false;
222
+ // The resolved call IS the acknowledgement; no event follows it.
223
+ emitChanged(threadId, optimistic, false);
224
+ return optimistic;
225
+ },
226
+ (error: any) => {
227
+ inFlight[key] = false;
228
+ stampThreadSubscribed(message, wasSubscribed);
229
+ emitChanged(threadId, wasSubscribed, false);
230
+ throw error;
231
+ }
232
+ );
233
+ }
234
+
235
+ /**
236
+ * Cases 2 and 4 — you sent a message, so the server subscribed you to its thread.
237
+ *
238
+ * ONE rule covers both now: **any message you send subscribes you to the thread it belongs
239
+ * to** — the parent's, if it is a reply; its own, if it is a root message that may grow one.
240
+ * That is exactly the server's behaviour since the author-subscribed-by-default change
241
+ * (verified on staging 2026-08-19: a fetched message with zero replies reads `true` for its
242
+ * sender, in groups and 1-1 alike, and `false` for everybody else).
243
+ *
244
+ * ⚠️ THIS IS PERMANENT, not a workaround. The API populates `threadSubscribed` on FETCHED
245
+ * messages only — confirmed with the backend team (Siva, 2026-08-19) and measured the same
246
+ * day: neither the plain nor the threaded send response carries it, and neither does a
247
+ * realtime frame. That is the agreed division of responsibility, so covering the send and
248
+ * socket paths is the UI Kit's job and always will be.
249
+ *
250
+ * Do not delete this on the reasoning that "the server subscribes the author now". It does —
251
+ * but it only SAYS so on a fetch, and the sender's own screen is holding a send response.
252
+ *
253
+ * Your own sends never arrive on a listener, so this is the only place the kit learns of them.
254
+ */
255
+ export function applySentMessage(sent: CometChat.BaseMessage): void {
256
+ try {
257
+ const threadId = getThreadIdFor(sent);
258
+ if (threadId > 0) mirrorSubscribed(threadId, sent);
259
+ } catch {
260
+ // A malformed send response must not take the send path down.
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Cases 2b and 4b — a message YOU sent, arriving from ANOTHER of your devices.
266
+ *
267
+ * Sending subscribes you to the thread, wherever you sent it from. But the copy that reaches
268
+ * your other devices comes over the socket, and a socket frame carries no `threadSubscribed`
269
+ * — so without this the message you just wrote on your phone shows "Subscribe to thread" on
270
+ * your tablet until something refetches it.
271
+ *
272
+ * Applies to ROOT messages as much as replies: authoring subscribes you to the thread the
273
+ * message may later grow, so the root case is not a no-op (that was the gap — the incoming
274
+ * path only ever looked at replies, and a root message has no parentMessageId to notice).
275
+ *
276
+ * Deliberately the same call as a local send: "I sent this" is one rule, and where the bytes
277
+ * came from does not change it.
278
+ *
279
+ * @returns true when it handled the message, so the caller can skip the incoming-reply rules
280
+ */
281
+ export function applyOwnIncomingMessage(
282
+ message: CometChat.BaseMessage,
283
+ loggedInUid: string | null
284
+ ): boolean {
285
+ try {
286
+ if (!loggedInUid) return false;
287
+ if (message?.getSender?.()?.getUid?.() !== loggedInUid) return false;
288
+ applySentMessage(message);
289
+ return true;
290
+ } catch {
291
+ return false;
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Case 5 — a message was EDITED to mention you, so the server subscribed you to its thread.
297
+ *
298
+ * Covers all three shapes the edit can take, because it only ever asks the one question the
299
+ * server asks — does the message, as it now stands, mention me:
300
+ *
301
+ * 5a you edit your own message to mention yourself
302
+ * 5b somebody else edits theirs to mention you
303
+ * 5c an edit that PRESERVES an existing mention while changing other text — the mention
304
+ * still stands afterwards, so the subscription still applies. Nothing here compares
305
+ * against the previous version, which is exactly why this case falls out for free.
306
+ *
307
+ * Subscribes to the thread the edited message BELONGS to — its parent's if it is a reply, its
308
+ * own if it is a root — via the same getThreadIdFor() every other path uses.
309
+ *
310
+ * ⚠️ Call this from the EDIT listeners, never from the shared list-replace helper: deletes and
311
+ * reaction updates travel through that same helper, and neither should subscribe anybody.
312
+ */
313
+ export function applyEditedMessage(
314
+ edited: CometChat.BaseMessage,
315
+ loggedInUid: string | null
316
+ ): void {
317
+ try {
318
+ if (!loggedInUid) return;
319
+ if ((edited as any)?.getDeletedAt?.()) return;
320
+ const mentioned = edited?.getMentionedUsers?.() ?? [];
321
+ if (!Array.isArray(mentioned)) return;
322
+ if (!mentioned.some((user: any) => user?.getUid?.() === loggedInUid)) return;
323
+ const threadId = getThreadIdFor(edited);
324
+ if (threadId > 0) mirrorSubscribed(threadId, edited);
325
+ } catch {
326
+ // Mirroring is a nicety; the next fetch corrects it regardless.
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Case 3, plus the socket-`false` correction — an incoming reply from somebody else.
332
+ *
333
+ * ONE server behaviour is mirrored: **you were @mentioned** in the reply, so the server
334
+ * subscribed you.
335
+ *
336
+ * The old "you wrote the parent and this is the FIRST reply" rule is GONE. It existed only
337
+ * because the author was not subscribed until someone replied; since the
338
+ * author-subscribed-by-default change (staging, 2026-08-19) authoring subscribes you
339
+ * outright, applySentMessage stamps that locally at send time, and any refetch confirms it.
340
+ * Re-deriving it from a reply would now be strictly worse — it could resurrect a
341
+ * subscription the author had deliberately cancelled in between.
342
+ *
343
+ * Every OTHER reply changes nothing about the subscription — but it still arrives with
344
+ * `threadSubscribed: false` because it came off the socket, and rendering that verbatim
345
+ * would offer "Subscribe" inside a thread the user already follows. So it inherits the
346
+ * parent's current state. This is why the parent must be held as a whole message and not
347
+ * just an id: an id cannot answer "is this thread followed right now".
348
+ *
349
+ * Nothing here ever writes `false`. A socket frame carries no flag and its silence is not a
350
+ * negative answer.
351
+ *
352
+ * @param reply the incoming reply, from the message listener
353
+ * @param parentMessage the reply's parent, as the consumer has it rendered — pass null if it
354
+ * is not on screen, in which case only the mention rule can fire
355
+ * @param loggedInUid the logged-in user's uid
356
+ */
357
+ export function applyIncomingReply(
358
+ reply: CometChat.BaseMessage,
359
+ parentMessage: CometChat.BaseMessage | null,
360
+ loggedInUid: string | null
361
+ ): void {
362
+ try {
363
+ const parentId = Number(reply?.getParentMessageId?.() ?? 0);
364
+ if (!parentId) return;
365
+
366
+ // Case 3 — mentioned. Stamp both, tell everyone, and MAKE IT STICK.
367
+ const mentioned = reply?.getMentionedUsers?.() ?? [];
368
+ if (
369
+ loggedInUid &&
370
+ Array.isArray(mentioned) &&
371
+ mentioned.some((user: any) => user?.getUid?.() === loggedInUid)
372
+ ) {
373
+ // Read the state BEFORE the mirror below overwrites it — this is what decides whether
374
+ // the server still needs telling.
375
+ const wasSubscribed = parentMessage ? isThreadSubscribed(parentMessage) : false;
376
+
377
+ stampThreadSubscribed(reply, true);
378
+ mirrorSubscribed(parentId, parentMessage ?? undefined);
379
+
380
+ // ENG-38880 — the stamp above is LOCAL. The server does not subscribe you when you are
381
+ // mentioned, so it was the only thing holding the flip, and any refetch replaced it
382
+ // with the server's `false`. The user hit that on the worst possible path: the mention
383
+ // sends them a push, they open the app FROM it, the list loads from a fetch, and the
384
+ // thread they were just pulled into reads "Subscribe to thread".
385
+ //
386
+ // So write it through instead of pretending. The rule — a mention subscribes you — is
387
+ // the product's, stated in the kit's own copy ("Notifications are off until you reply
388
+ // or are mentioned"); this makes the server agree with it.
389
+ //
390
+ // Skipped when the thread is already followed, so an active thread does not fire a
391
+ // write per mention. The call is idempotent, so the fallback when the parent is not on
392
+ // screen (and `wasSubscribed` is unknowable) is simply to send it.
393
+ if (!wasSubscribed) {
394
+ try {
395
+ const write = CometChat.subscribeToThread(parentId);
396
+ // Fire and forget: this is a correction, not the user's action. A failure leaves the
397
+ // optimistic flip in place and the next fetch settles it — the pre-existing
398
+ // behaviour, so failing here is never worse than not having tried.
399
+ if (write && typeof (write as any).catch === "function") {
400
+ (write as any).catch(() => {});
401
+ }
402
+ } catch {
403
+ // An SDK build without the method must not take the message listener down.
404
+ }
405
+ }
406
+ return;
407
+ }
408
+
409
+ if (!parentMessage) return;
410
+
411
+ // Everything else: correct the socket `false` from the authority, without publishing —
412
+ // nothing about the subscription changed, only this object's knowledge of it.
413
+ stampThreadSubscribed(reply, isThreadSubscribed(parentMessage));
414
+ } catch {
415
+ // Mirroring is a nicety; the next fetch corrects it regardless.
416
+ }
417
+ }
418
+
419
+ /**
420
+ * Only for tests — the in-flight/debounce guards are process-wide by design (one user, one
421
+ * session), which otherwise leaks state between test cases.
422
+ * @internal
423
+ */
424
+ export function resetThreadSubscriptionGuards(): void {
425
+ Object.keys(inFlight).forEach((key) => delete inFlight[key]);
426
+ Object.keys(lastToggleAt).forEach((key) => delete lastToggleAt[key]);
427
+ }
@@ -7,6 +7,7 @@ import { CometChatUIKit } from "../CometChatUiKit";
7
7
  import { CometChatTheme } from "../../theme/type";
8
8
  import { JSX } from "react";
9
9
  import { getCometChatTranslation } from "../resources/CometChatLocalizeNew/LocalizationManager";
10
+ import { stripMarkdown } from "./MarkdownUtils";
10
11
 
11
12
  const t = getCometChatTranslation();
12
13
 
@@ -28,7 +29,13 @@ export function attachmentCountLabel(type: string, count: number): string {
28
29
  // (Multi-attachment messages are summarized upstream in getLastConversationMessage.)
29
30
  function captionSuffix(message: CometChat.BaseMessage): string {
30
31
  const raw = typeof (message as any).getCaption === "function" ? (message as any).getCaption() : "";
31
- const caption = typeof raw === "string" ? raw.trim() : "";
32
+ // Strip the wire markup. A caption is serialized exactly like a text message, so it can carry
33
+ // `<color=#rrggbb>`, `**bold**`, backticks — and every branch that calls this returns a JSX
34
+ // element, so the conversation list's own stripMarkdown pass (string subtitles only) never runs
35
+ // on it. Without this a single photo captioned in red reads "Photo · <color=#e11d48>hi</color>"
36
+ // in the list. Same defect ENG-38258 reported for a multi-attachment batch; that fix landed in
37
+ // MessageDataSource.getLastConversationMessage and did not cover the single-attachment path.
38
+ const caption = typeof raw === "string" ? stripMarkdown(raw.trim()).trim() : "";
32
39
  return caption ? ` · ${caption}` : "";
33
40
  }
34
41