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

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 (105) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/CometChatClipboardModule.kt +34 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +562 -5
  3. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorViewManager.kt +28 -1
  4. package/ios/CometChatClipboardModule.m +5 -0
  5. package/ios/CometChatClipboardModule.swift +22 -0
  6. package/ios/RichTextEditorView.swift +636 -31
  7. package/ios/RichTextEditorViewManager.m +3 -0
  8. package/ios/RichTextEditorViewManager.swift +24 -0
  9. package/package.json +5 -2
  10. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +283 -64
  11. package/src/CometChatCompactMessageComposer/index.ts +2 -0
  12. package/src/CometChatConversations/CometChatConversations.tsx +299 -15
  13. package/src/CometChatGroupMembers/CometChatGroupMembers.tsx +2 -2
  14. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +15 -3
  15. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +181 -12
  16. package/src/CometChatMessageInformation/CometChatMessageInformation.tsx +10 -1
  17. package/src/CometChatMessageList/CometChatMessageList.tsx +572 -16
  18. package/src/CometChatMessageList/components/MessageModals.tsx +30 -0
  19. package/src/CometChatMessageList/components/MessageOptionsSheet.tsx +21 -9
  20. package/src/CometChatMessageList/components/MessageQuickActions.tsx +162 -0
  21. package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +964 -0
  22. package/src/CometChatPinnedMessages/index.ts +5 -0
  23. package/src/CometChatPinnedMessages/style.ts +216 -0
  24. package/src/CometChatRichTextEditor/RichTextEditorViewNativeComponent.ts +5 -0
  25. package/src/CometChatRichTextEditor/index.tsx +31 -1
  26. package/src/CometChatRichTextEditor/types.ts +21 -1
  27. package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +871 -0
  28. package/src/CometChatSavedMessages/index.ts +5 -0
  29. package/src/CometChatSavedMessages/style.ts +159 -0
  30. package/src/CometChatSearch/CometChatSearch.tsx +71 -341
  31. package/src/CometChatThreadHeader/CometChatThreadHeader.tsx +22 -2
  32. package/src/index.ts +60 -0
  33. package/src/shared/CometChatUiKit/CometChatUIKit.ts +18 -1
  34. package/src/shared/base/Types.ts +5 -0
  35. package/src/shared/constants/UIKitConstants.ts +16 -17
  36. package/src/shared/constants/textPatterns.ts +27 -0
  37. package/src/shared/events/CometChatUIEventHandler/CometChatUIEventHandler.ts +25 -225
  38. package/src/shared/events/CometChatUIEventHandler/Listener.ts +37 -0
  39. package/src/shared/events/ListenerInitializer.ts +20 -1
  40. package/src/shared/events/messages.ts +18 -0
  41. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +123 -25
  42. package/src/shared/formatters/CometChatTextFormatter.ts +22 -0
  43. package/src/shared/formatters/applyRawFormatters.ts +31 -0
  44. package/src/shared/formatters/index.ts +14 -0
  45. package/src/shared/formatters/richTextWireFormat.ts +165 -0
  46. package/src/shared/framework/MessageDataSource.tsx +309 -10
  47. package/src/shared/icons/components/thread-follow.tsx +13 -0
  48. package/src/shared/icons/components/thread-unfollow.tsx +13 -0
  49. package/src/shared/icons/components/unsave.tsx +13 -0
  50. package/src/shared/icons/icon-mapping.tsx +6 -0
  51. package/src/shared/index.ts +37 -0
  52. package/src/shared/resources/CometChatLocalizeNew/CometChatI18nProvider.tsx +15 -30
  53. package/src/shared/resources/CometChatLocalizeNew/CometChatLocalizationHelper.ts +138 -19
  54. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +74 -1
  55. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +54 -1
  56. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +54 -1
  57. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +54 -1
  58. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +54 -1
  59. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +54 -1
  60. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +54 -1
  61. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +54 -1
  62. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +54 -1
  63. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +54 -1
  64. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +54 -1
  65. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +54 -1
  66. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +54 -1
  67. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +54 -1
  68. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +54 -1
  69. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +54 -1
  70. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +54 -1
  71. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +54 -1
  72. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +11 -0
  73. package/src/shared/utils/MarkdownUtils.ts +57 -6
  74. package/src/shared/utils/MessageUtils.tsx +80 -5
  75. package/src/shared/utils/PinConversationHelper.ts +245 -0
  76. package/src/shared/utils/PinSaveFeatureGates.ts +178 -0
  77. package/src/shared/utils/PinSaveHelper.ts +549 -0
  78. package/src/shared/utils/PinnedMessagesHelper.ts +65 -0
  79. package/src/shared/utils/SavedMessagesHelper.ts +267 -0
  80. package/src/shared/utils/ThreadSubscriptionHelper.ts +427 -0
  81. package/src/shared/utils/__testUtils__/messagesRequestBuilderMock.ts +37 -0
  82. package/src/shared/utils/cloneRequestBuilder.ts +25 -0
  83. package/src/shared/utils/conversationUtils.ts +8 -1
  84. package/src/shared/utils/stripRichText.ts +7 -0
  85. package/src/shared/views/ClipboardPasteHandler/ClipboardPasteHandler.ts +32 -0
  86. package/src/shared/views/ClipboardPasteHandler/NativeCometChatClipboardModule.ts +6 -0
  87. package/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +4 -0
  88. package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +5 -0
  89. package/src/shared/views/CometChatAvatar/CometChatAvatar.tsx +17 -5
  90. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +5 -1
  91. package/src/shared/views/CometChatCaptionText/CometChatCaptionText.tsx +8 -1
  92. package/src/shared/views/CometChatConfirmDialog/CometChatConfirmDialog.tsx +2 -0
  93. package/src/shared/views/CometChatConversationStarter/CometChatConversationStarter.tsx +91 -20
  94. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +5 -0
  95. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +5 -0
  96. package/src/shared/views/CometChatList/CometChatList.tsx +6 -1
  97. package/src/shared/views/CometChatList/Header.tsx +8 -2
  98. package/src/shared/views/CometChatListItem/CometChatListItem.tsx +4 -0
  99. package/src/shared/views/CometChatRetryButton/CometChatRetryButton.tsx +1 -0
  100. package/src/shared/views/CometChatSuggestionList/CometChatSuggestionList.tsx +4 -0
  101. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +5 -0
  102. package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +5 -0
  103. package/src/shared/views/ErrorEmptyView/ErrorEmptyView.tsx +4 -1
  104. package/src/theme/default/default.ts +6 -0
  105. package/src/theme/type.ts +4 -0
@@ -0,0 +1,549 @@
1
+ /**
2
+ * The kit's single seam onto the SDK's pin/save surface.
3
+ *
4
+ * Front-end Design Doc §4.1/§6.1/§6.5. Everything the kit needs to know about
5
+ * pin and save lives here: how to read the state off a message, who is allowed
6
+ * to pin, what the SDK calls are, and where the server-owned cap comes from.
7
+ * Components import from this file and never reach for `getPinnedAt()` directly
8
+ * — when the SDK contract shifts, this is the only edit.
9
+ *
10
+ * @module PinSaveHelper
11
+ */
12
+ import { CometChat } from "@cometchat/chat-sdk-react-native";
13
+ import { getModerationStatus } from "./MessageUtils";
14
+
15
+ /**
16
+ * The pin/save options stay hidden until an integrator opts in.
17
+ *
18
+ * Same shape as the other kit-side feature gates: a module-level switch rather
19
+ * than a prop, because the DataSource that builds the option list has no props.
20
+ */
21
+ export const PinSaveConfig = {
22
+ _pinEnabled: false,
23
+ _saveEnabled: false,
24
+
25
+ /** Enable the Pin/Unpin options. Call once at app start. */
26
+ enablePin(enabled: boolean = true) {
27
+ this._pinEnabled = enabled;
28
+ },
29
+ /** Enable the Save/Unsave options. Call once at app start. */
30
+ enableSave(enabled: boolean = true) {
31
+ this._saveEnabled = enabled;
32
+ },
33
+ isPinEnabled(): boolean {
34
+ return this._pinEnabled;
35
+ },
36
+ isSaveEnabled(): boolean {
37
+ return this._saveEnabled;
38
+ },
39
+ };
40
+
41
+ /** An admin/global pin arrives under this uid instead of a real member's. */
42
+ export const SYSTEM_PINNER = "app_system";
43
+
44
+ /**
45
+ * Whether an action asks before it runs.
46
+ *
47
+ * The REMOVING half of each pair confirms; the adding half runs straight away.
48
+ * Cross-platform decision (Jitvar, 2026-08-04) — all five kits follow it, so this is
49
+ * not a per-kit preference to tune.
50
+ *
51
+ * The asymmetry is deliberate: pinning or saving is additive and its own undo sits
52
+ * one tap away in the same menu, whereas unpinning or unsaving discards something
53
+ * deliberately put there — on a conversation-wide pin, possibly by someone else —
54
+ * and nothing on screen offers it back.
55
+ *
56
+ * Conversations follow the same rule: unpin asks, pin does not.
57
+ */
58
+ export const pinSaveNeedsConfirm = (
59
+ action: "pin" | "unpin" | "save" | "unsave"
60
+ ): boolean => action === "unpin" || action === "unsave";
61
+
62
+ /**
63
+ * True when the message is pinned to its conversation.
64
+ *
65
+ * The PRESENCE of the timestamp is the flag — the SDK deletes the attribute
66
+ * rather than zeroing it, so this must never be written as `getPinnedAt() > 0`
67
+ * or, worse, `!!getPinnedAt()` against a value that might legitimately be 0.
68
+ */
69
+ /**
70
+ * Deleting a message unpins and unsaves it SERVER-SIDE — verified on staging 2026-08-17: the
71
+ * row leaves the pinned list and a fresh fetch carries neither `pinnedAt` nor `savedAt`.
72
+ *
73
+ * The client can still be holding an object that predates the delete, because the delete
74
+ * response carries no pin/save fields at all — their absence is not a signal, so nothing
75
+ * downstream clears them. That left "This message was deleted" rendering with a pin glyph
76
+ * beside the timestamp (ENG-38181).
77
+ *
78
+ * Answering the question here rather than at each render site means every surface agrees, and
79
+ * a new one cannot forget: the two indicator rows (MessageUtils and CometChatMessageList's own
80
+ * copy) both read these, as does the option list.
81
+ */
82
+ const isGone = (message?: CometChat.BaseMessage | null): boolean => {
83
+ try {
84
+ const deletedAt = message?.getDeletedAt?.();
85
+ return deletedAt !== undefined && deletedAt !== null;
86
+ } catch {
87
+ return false;
88
+ }
89
+ };
90
+
91
+ export const isPinned = (message?: CometChat.BaseMessage | null): boolean => {
92
+ try {
93
+ if (isGone(message)) return false;
94
+ return message?.getPinnedAt?.() !== undefined && message?.getPinnedAt?.() !== null;
95
+ } catch {
96
+ return false;
97
+ }
98
+ };
99
+
100
+ /** True when the logged-in user has saved the message. Per-viewer and private. */
101
+ export const isSaved = (message?: CometChat.BaseMessage | null): boolean => {
102
+ try {
103
+ if (isGone(message)) return false;
104
+ return message?.getSavedAt?.() !== undefined && message?.getSavedAt?.() !== null;
105
+ } catch {
106
+ return false;
107
+ }
108
+ };
109
+
110
+ /**
111
+ * Carry the fields a pin/save/edit response forgets onto the fresher copy of the message
112
+ * (ENG-38183, ENG-38176).
113
+ *
114
+ * Three endpoints return a DIFFERENT, smaller message than the one you already hold, and the
115
+ * kit replaces the held object with what came back. Whatever the response omits disappears
116
+ * from the UI until the next fetch. Verified on staging 2026-08-17:
117
+ *
118
+ * - **PUT /messages/{id}** (edit) drops `pinnedAt`, `pinnedBy`, `savedAt` — the pin and save
119
+ * indicators vanish off an edited message (ENG-38183).
120
+ * - **POST /messages/{id}/pin** drops `quotedMessage` — pinning a reply erases the quote it
121
+ * was replying to, leaving bare text (ENG-38176). Send and fetch both carry it, so this
122
+ * is an omission on the pin response specifically.
123
+ *
124
+ * Absence in the fresher copy means "not mentioned", NOT "removed": a real unpin, unsave or
125
+ * quote removal arrives as its own event, never as a silent omission. So this only ever
126
+ * fills gaps — a value present on `fresh` always wins, which keeps it correct the day these
127
+ * endpoints start returning complete messages.
128
+ */
129
+ const carryFields = <T>(fresh: T, previous: any, keys: readonly string[]): T => {
130
+ try {
131
+ if (!fresh || !previous) return fresh;
132
+ const target = fresh as any;
133
+ // Copied straight off the object rather than via setters: the SDK exposes no
134
+ // setPinnedAt/setSavedAt, and these are the field names the parser writes.
135
+ keys.forEach((key) => {
136
+ if (target[key] === undefined || target[key] === null) {
137
+ if (previous[key] !== undefined && previous[key] !== null) target[key] = previous[key];
138
+ }
139
+ });
140
+ return fresh;
141
+ } catch {
142
+ return fresh;
143
+ }
144
+ };
145
+
146
+
147
+ /**
148
+ * Never let a NON-FETCH payload downgrade a known subscription to `false`.
149
+ *
150
+ * The generic carry above cannot do this job, because it fills only what is `undefined` —
151
+ * and `threadSubscribed` is never undefined. The SDK normalises the wire value at the single
152
+ * parse site, so a payload that simply does not mention the field arrives as an explicit
153
+ * `false`. Absent and "genuinely unsubscribed" are therefore indistinguishable by presence,
154
+ * and the generic rule silently did nothing.
155
+ *
156
+ * What DOES distinguish them is the payload. Edit, pin, save and send responses never carry
157
+ * the flag at all (the API populates it on FETCHED messages only), so a `false` arriving on
158
+ * one of those paths is silence, not an answer — and silence must not clear a known `true`.
159
+ * This is the "never write false off a frame" rule, enforced where the object is replaced
160
+ * rather than merely stated in a comment.
161
+ *
162
+ * A fetched message never goes through here: fetch results replace the list wholesale, so a
163
+ * real unsubscribe still lands normally on the next load.
164
+ */
165
+ const preserveThreadSubscribed = <T>(fresh: T, previous: any): T => {
166
+ try {
167
+ if (!fresh || !previous) return fresh;
168
+ if ((previous as any).threadSubscribed === true && (fresh as any).threadSubscribed !== true) {
169
+ (fresh as any).threadSubscribed = true;
170
+ }
171
+ return fresh;
172
+ } catch {
173
+ return fresh;
174
+ }
175
+ };
176
+
177
+ /**
178
+ * For the EDIT path. The edit response says nothing about pin/save state, so carry it.
179
+ *
180
+ * ⚠️ NOT for the pin/save path — see carryQuotedMessage. On an UNPIN the response omits
181
+ * `pinnedAt` because the message is no longer pinned, and copying the old value back leaves
182
+ * the glyph on screen forever. The e2e "a lingering one is the bug" exists for that.
183
+ */
184
+ /**
185
+ * The replacement to use when a pin/save ACTION or frame is the answer — pin, unpin, save, unsave.
186
+ *
187
+ * Do NOT swap the response into the list. It is a PARTIAL message: it carries the pin attrs but
188
+ * no muid, and the list keys its rows `${id}_${muid}`. Swapping it in changed that key from
189
+ * `123_abc` to `id_123`, so React unmounted the row and mounted a fresh one instead of updating
190
+ * it — remounting the media bubble and reloading every image. Pinning visibly rebuilt the bubble.
191
+ *
192
+ * So we keep the copy we already hold (complete: attachments, quote, muid, reactions) and take
193
+ * ONLY the three pin/save fields off the response. The copy is SHALLOW and keeps the prototype,
194
+ * so getId()/getSender() still work and every nested object — attachments above all — keeps its
195
+ * identity. Only the top-level identity changes, which is precisely what MessageListItem's
196
+ * `prevProps.item === nextProps.item` memo needs to redraw the row for the new indicator.
197
+ */
198
+ export const applyPinSaveAnswer = <T>(held: T, response?: CometChat.BaseMessage | null): T => {
199
+ try {
200
+ if (!held) return held;
201
+ const next: any = Object.create(
202
+ Object.getPrototypeOf(held as any),
203
+ Object.getOwnPropertyDescriptors(held as any)
204
+ );
205
+ if (!response) return next;
206
+ (["pinnedAt", "pinnedBy", "savedAt"] as const).forEach((key) => {
207
+ const value = (response as any)[key];
208
+ // Absence IS the answer here: a response silent on pinnedAt means "no longer pinned".
209
+ if (value === undefined || value === null) delete next[key];
210
+ else next[key] = value;
211
+ });
212
+ return next;
213
+ } catch {
214
+ return held;
215
+ }
216
+ };
217
+
218
+ export const carryPinSaveAttrs = <T>(fresh: T, previous?: CometChat.BaseMessage | null): T =>
219
+ preserveThreadSubscribed(
220
+ carryFields(
221
+ fresh,
222
+ previous,
223
+ // A DELETE arrives through the same messageEdited path as an edit, and deleting unpins
224
+ // and unsaves server-side. Carrying the attributes there would copy a pin onto a message
225
+ // the server has just unpinned, which is how "This message was deleted" ended up wearing
226
+ // a pin glyph. The quote still rides along — a deleted bubble no longer renders it, and
227
+ // dropping it here would lose it on any other path that reuses this.
228
+ // threadSubscribed rides along on EVERY branch. No edit, pin, save or socket payload
229
+ // carries it — the API populates it on FETCHED messages only — so dropping it here would
230
+ // silently unsubscribe the user in the UI every time any message in the thread was
231
+ // edited, pinned or saved. It is the same omission class as quotedMessage.
232
+ isGone(fresh as any)
233
+ ? ["quotedMessage", "quotedMessageId"]
234
+ : ["pinnedAt", "pinnedBy", "savedAt", "quotedMessage", "quotedMessageId"]
235
+ ), previous);
236
+
237
+ /**
238
+ * For the PIN/SAVE path (ENG-38176). Carries the quote and nothing else.
239
+ *
240
+ * `POST /messages/{id}/pin` returns a message with the pin attributes set but `quotedMessage`
241
+ * dropped (verified on staging 2026-08-17 — send and fetch both carry it). So pinning a reply
242
+ * replaced the held message with one that had no quote, and the bubble rendered as bare text.
243
+ *
244
+ * Pin/save attributes are deliberately NOT carried here: on this path the response IS the
245
+ * answer about pin/save state, including the absence that means "no longer pinned".
246
+ */
247
+ export const carryQuotedMessage = <T>(fresh: T, previous?: CometChat.BaseMessage | null): T =>
248
+ preserveThreadSubscribed(carryFields(fresh, previous, ["quotedMessage", "quotedMessageId"]), previous);
249
+
250
+ /**
251
+ * True for an admin/global pin, which renders without a "pinned by" attribution.
252
+ * Only meaningful when isPinned() is already true.
253
+ */
254
+ export const isSystemPin = (message?: CometChat.BaseMessage | null): boolean => {
255
+ try {
256
+ return isPinned(message) && message?.getPinnedBy?.() === SYSTEM_PINNER;
257
+ } catch {
258
+ return false;
259
+ }
260
+ };
261
+
262
+ /**
263
+ * Whether a message can be pinned or saved AT ALL, before any role question.
264
+ *
265
+ * The backend API reference (ENG-37690) is explicit: "Moderation
266
+ * pending/disapproved messages cannot be pinned" and a missing/deleted message
267
+ * returns ERR_MESSAGE_ID_NOT_FOUND. Offering the option anyway means the user
268
+ * taps through a confirm modal to earn an error toast, so the gate belongs here
269
+ * rather than being left to the server to refuse.
270
+ *
271
+ * Three exclusions:
272
+ * - no server id yet. An in-flight message is keyed by muid until it reconciles;
273
+ * pinning it would address an id the server has never seen.
274
+ * - deleted.
275
+ * - a moderation verdict other than clean-or-pending. Checked as an explicit
276
+ * allow-list rather than "not disapproved", so a status nobody has seen yet
277
+ * still fails CLOSED instead of silently becoming pinnable.
278
+ *
279
+ * PENDING IS ALLOWED THROUGH, deliberately (ENG-38901). The server does refuse a
280
+ * pin or save while moderation is pending — measured 2026-09-04, both return
281
+ * `403 ERR_MESSAGE_NO_ACCESS` — so hiding the options was defensible and is what
282
+ * the React kit does. It is still the wrong trade here, for two reasons:
283
+ *
284
+ * - The window is ~2 seconds and it runs from SEND, not from the long-press. By
285
+ * the time someone opens the sheet, reads it and taps, moderation has usually
286
+ * already approved, so the action simply succeeds. Hiding the option optimised
287
+ * for the rarer case.
288
+ * - The failure it avoided was invisible; the one it caused was not. Pin and Save
289
+ * were missing from your own message, then present after reopening the
290
+ * conversation, with nothing on screen explaining why. That reads as broken —
291
+ * it was filed as a bug twice.
292
+ *
293
+ * So the options stay put and a genuinely early tap earns a real explanation from
294
+ * the server, which isPermissionError() already turns into a specific toast. This
295
+ * is the same rule canPin() settled on for role permissions: offer the option, let
296
+ * the server decide, render the refusal.
297
+ */
298
+ export const isPinSaveEligible = (message?: CometChat.BaseMessage | null): boolean => {
299
+ try {
300
+ if (!message) return false;
301
+
302
+ const id = message.getId?.();
303
+ if (id === undefined || id === null || Number(id) <= 0) return false;
304
+
305
+ if (message.getDeletedAt?.()) return false;
306
+
307
+ const status = getModerationStatus(message);
308
+ if (status !== "unmoderated" && status !== "approved" && status !== "pending") {
309
+ return false;
310
+ }
311
+
312
+ return true;
313
+ } catch {
314
+ return false;
315
+ }
316
+ };
317
+
318
+ /**
319
+ * Whether to OFFER pin/unpin to the logged-in user. The server is the authority (ENG-38197).
320
+ *
321
+ * This used to hard-code the §6.5 rule — owner/admin/moderator in a group, nobody else — on
322
+ * the reasoning that "until RBAC ships, hiding the option IS the enforcement". That reasoning
323
+ * was wrong on both halves, measured on staging 2026-08-17:
324
+ *
325
+ * - a plain **participant** can pin AND unpin a group message over the API, so the client
326
+ * was hiding an action the server grants; and
327
+ * - permission is not client-readable anyway. It is not in `/settings` (no per-role pin key
328
+ * among the 305 parameters), `/roles` is admin-key-only and carries no policy, and the SDK
329
+ * exposes no capability surface. There is nothing to feature-detect against.
330
+ *
331
+ * So the honest gate is no gate: offer the option, let the server decide, and render the
332
+ * refusal. `isPermissionError()` already recognises ERR_PERMISSION_DENIED and the message list
333
+ * already toasts "You don't have permission to pin messages here" — that path was written and
334
+ * then made unreachable by this function.
335
+ *
336
+ * This also makes groups consistent with 1-1, which has always taken exactly this line:
337
+ * guessing "no" hides the option from someone entitled to it, and an over-optimistic option
338
+ * is corrected by the server.
339
+ *
340
+ * The function stays as the seam. When RBAC ships a readable policy, it goes back in HERE and
341
+ * nowhere else.
342
+ */
343
+ export const canPin = (
344
+ loggedInUser?: CometChat.User | null,
345
+ _group?: CometChat.Group | null
346
+ ): boolean => {
347
+ try {
348
+ // The one thing still worth asserting locally: there is somebody to act as.
349
+ return !!loggedInUser;
350
+ } catch {
351
+ return false;
352
+ }
353
+ };
354
+
355
+ /**
356
+ * Server error codes, as they ACTUALLY exist in the backend.
357
+ *
358
+ * The design doc named `ERR_ACTION_NOT_ALLOWED`, `ERR_MESSAGE_NOT_FOUND` and
359
+ * `ERR_MESSAGE_NOT_ACCESSIBLE`. The backend team confirmed (ENG-37690,
360
+ * 2026-07-29) that none of those exist. These are the real ones — matching on
361
+ * the doc's names would have silently fallen through to generic copy forever.
362
+ */
363
+ export const PinSaveErrors = {
364
+ PIN_LIMIT: "ERR_PINNED_MESSAGES_LIMIT_EXCEEDED",
365
+ SAVE_LIMIT: "ERR_SAVED_MESSAGES_LIMIT_EXCEEDED",
366
+ /** RBAC denial. Carries params {action, role, restrictionSource, guid, scope}. */
367
+ PERMISSION_DENIED: "ERR_PERMISSION_DENIED",
368
+ /** Caller cannot access the message at all. */
369
+ NO_ACCESS: "ERR_MESSAGE_NO_ACCESS",
370
+ /** Moderation pending/disapproved — NOT a role problem. */
371
+ MODERATION: "ERR_MESSAGE_ACTION_NOT_ALLOWED",
372
+ /** The app's feature flag is off. */
373
+ FEATURE_OFF: "ERR_FEATURE_NOT_ACCESSIBLE",
374
+ NOT_FOUND: "ERR_MESSAGE_ID_NOT_FOUND",
375
+ } as const;
376
+
377
+ /**
378
+ * True when the message is GONE for this viewer — cleared conversation, deleted message,
379
+ * or a row that outlived the thing it points at.
380
+ *
381
+ * This one must not be treated like an ordinary failure. The generic catch reinstates the
382
+ * row it optimistically removed, on the assumption that the write did not take. Here the
383
+ * write did not need to take: there is nothing left to unpin. Restoring the row leaves the
384
+ * user tapping Unpin forever on a message the server will never accept.
385
+ *
386
+ * Reproduced on staging 2026-08-10: clear a chat that has pinned messages, then unpin one
387
+ * from the panel — ERR_MESSAGE_ID_NOT_FOUND, and the row comes straight back.
388
+ */
389
+ export const isMessageGoneError = (error: any): boolean => {
390
+ try {
391
+ return error?.code === PinSaveErrors.NOT_FOUND;
392
+ } catch {
393
+ return false;
394
+ }
395
+ };
396
+
397
+ /** True when the rejection is a cap breach, whichever of the two caps it was. */
398
+ export const isCapError = (error: any): boolean => {
399
+ try {
400
+ return error?.code === PinSaveErrors.PIN_LIMIT || error?.code === PinSaveErrors.SAVE_LIMIT;
401
+ } catch {
402
+ return false;
403
+ }
404
+ };
405
+
406
+ /**
407
+ * The server-owned cap from a rejected pin/save, or null when the error does not
408
+ * carry one — which is the COMMON case: the backend documents the caps as
409
+ * tenant-overridable settings (`limits.messages.pinnedPerConversation`) and never
410
+ * promises them on the error payload. Only RBAC denials are documented as
411
+ * carrying params.
412
+ *
413
+ * So callers must handle null by showing copy WITHOUT a number rather than
414
+ * printing a guess. Read off `errorParams` when present; never scraped out of the
415
+ * message string, because the cap is the server's to change, not ours to parse.
416
+ */
417
+
418
+ /**
419
+ * The server-owned cap for a pin/save action, or null when it is unknown.
420
+ *
421
+ * Two sources, in order of trust:
422
+ * 1. `errorParams.limit` on the rejection — documented, but rarely present;
423
+ * 2. app settings, via the SDK's typed getters (ENG-37790).
424
+ *
425
+ * (2) replaced a regex that scraped the number out of the error PROSE — the only place
426
+ * it appeared before settings carried it. That was fragile by construction: the server
427
+ * owns that sentence and could reword it in any release, silently reverting every caller
428
+ * to the no-count copy. Do not bring it back.
429
+ *
430
+ * Still returns null rather than 0 when the cap is genuinely unknown. The SDK is careful
431
+ * about the same distinction: an absent setting resolves false, and Number(false) is 0,
432
+ * which would read as "0 pins allowed" and hide the feature outright.
433
+ */
434
+ export const resolveCapLimit = async (
435
+ error: any,
436
+ action: "pin" | "save"
437
+ ): Promise<number | null> => {
438
+ const fromError = readCapLimit(error);
439
+ if (fromError !== null) return fromError;
440
+ try {
441
+ // Reads the CACHED app settings, deliberately (ENG-38180).
442
+ //
443
+ // Still no refresh on THIS path: it runs with a rejected tap already on screen, and a
444
+ // network round trip here would sit between the user's action and the toast explaining
445
+ // it. The staleness that made this print an out-of-date cap is fixed a level up instead
446
+ // — refreshPinSaveFeatures() now re-fetches the app settings on every reconnection, so
447
+ // the cache these getters read is current by the time anything needs to print it.
448
+ //
449
+ // What remains unfixable from here: a limit changed in the dashboard while the socket
450
+ // stays connected is not seen until the next reconnect. That is the same contract the
451
+ // feature flags have, and it is a bounded, self-correcting staleness rather than one
452
+ // that lasts until logout.
453
+ const limit =
454
+ action === "pin"
455
+ ? await CometChat.getPinMessageLimit()
456
+ : await CometChat.getSaveMessageLimit();
457
+ return typeof limit === "number" && isFinite(limit) && limit > 0 ? limit : null;
458
+ } catch {
459
+ return null;
460
+ }
461
+ };
462
+
463
+ /** The cap as carried ON the rejection, or null. Usually absent — see resolveCapLimit. */
464
+ export const readCapLimit = (error: any): number | null => {
465
+ try {
466
+ const raw = error?.errorParams?.limit;
467
+ if (typeof raw !== "number" && typeof raw !== "string") return null;
468
+ const limit = Number(raw);
469
+ return isFinite(limit) && limit > 0 ? limit : null;
470
+ } catch {
471
+ return null;
472
+ }
473
+ };
474
+
475
+ /**
476
+ * True when the rejection is the server refusing on role or access, as opposed to
477
+ * a cap breach or a moderation verdict. Moderation is deliberately excluded — it
478
+ * is not a permission problem and telling the user "you don't have permission"
479
+ * when their message is awaiting moderation would be simply wrong.
480
+ */
481
+ export const isPermissionError = (error: any): boolean => {
482
+ try {
483
+ return (
484
+ error?.code === PinSaveErrors.PERMISSION_DENIED ||
485
+ error?.code === PinSaveErrors.NO_ACCESS
486
+ );
487
+ } catch {
488
+ return false;
489
+ }
490
+ };
491
+
492
+ /**
493
+ * Do these two ids refer to the same message?
494
+ *
495
+ * Compared as STRINGS, because a message id does not have one type in this codebase
496
+ * (ENG-38891). A row read off a fetch and the same message arriving on a socket frame or
497
+ * an action response can carry `123` and `"123"`, and `===` calls those different messages.
498
+ * CometChatMessageList has always compared ids with a loose `==` for exactly this reason;
499
+ * the panels used `===` and so were the surfaces where it bit.
500
+ *
501
+ * A silently failed comparison is worse than a wrong one here: in a DEDUPE it lets the same
502
+ * pin be listed twice, which is how the pinned panel came to show six rows for a five-pin
503
+ * cap. In a removal it makes an unpin do nothing at all.
504
+ */
505
+ export const sameMessageId = (a: unknown, b: unknown): boolean => {
506
+ if (a === undefined || a === null || b === undefined || b === null) return false;
507
+ return String(a) === String(b);
508
+ };
509
+
510
+ /**
511
+ * Is this message still waiting on moderation?
512
+ *
513
+ * The server refuses a pin or save with `403 ERR_MESSAGE_NO_ACCESS` while a message is
514
+ * pending, which is the SAME code it uses for a genuine permission refusal. Without this
515
+ * the user is told "you don't have permission", which is both wrong and unactionable —
516
+ * they have permission, the message simply is not cleared yet, and it will be in a moment.
517
+ */
518
+ export const isModerationPending = (message?: CometChat.BaseMessage | null): boolean => {
519
+ try {
520
+ return getModerationStatus(message) === "pending";
521
+ } catch {
522
+ return false;
523
+ }
524
+ };
525
+
526
+ /** True when the app has the feature flag switched off server-side. */
527
+ export const isFeatureOffError = (error: any): boolean => {
528
+ try {
529
+ return error?.code === PinSaveErrors.FEATURE_OFF;
530
+ } catch {
531
+ return false;
532
+ }
533
+ };
534
+
535
+ /** Pins a message to its conversation. Resolves the full updated message. */
536
+ export const pinMessage = (messageId: number | string): Promise<CometChat.BaseMessage> =>
537
+ CometChat.pinMessage(String(messageId));
538
+
539
+ /** Unpins a message. Resolves the full updated message, pin attrs cleared. */
540
+ export const unpinMessage = (messageId: number | string): Promise<CometChat.BaseMessage> =>
541
+ CometChat.unpinMessage(String(messageId));
542
+
543
+ /** Saves a message for the logged-in user. */
544
+ export const saveMessage = (messageId: number | string): Promise<CometChat.BaseMessage> =>
545
+ CometChat.saveMessage(String(messageId));
546
+
547
+ /** Unsaves a message for the logged-in user. */
548
+ export const unsaveMessage = (messageId: number | string): Promise<CometChat.BaseMessage> =>
549
+ CometChat.unsaveMessage(String(messageId));
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Building the pinned panel's request — the twin of buildSavedMessagesRequest.
3
+ *
4
+ * Extracted from the component so the invariants below can be tested without mounting
5
+ * a screen, and kept dependency-free so a test can stub CometChat narrowly.
6
+ */
7
+ import { CometChat } from "@cometchat/chat-sdk-react-native";
8
+ import { cloneRequestBuilder } from "./cloneRequestBuilder";
9
+
10
+ /**
11
+ * The ordinary messages request, filtered to pinned rows. Paging is the ordinary cursor
12
+ * walk — setPinnedOnly() only changes the field the cursor rides on, from sentAt to
13
+ * pinnedAt, because that is the order the server returns pins in.
14
+ *
15
+ * Single-use by design — build a new one to refresh.
16
+ */
17
+ export const buildPinnedMessagesRequest = ({
18
+ user,
19
+ group,
20
+ limit,
21
+ messagesRequestBuilder,
22
+ }: {
23
+ user?: CometChat.User;
24
+ group?: CometChat.Group;
25
+ limit?: number;
26
+ messagesRequestBuilder?: CometChat.MessagesRequestBuilder;
27
+ }) => {
28
+ // A COPY of the integrator's builder, never their object. They may hand the same
29
+ // instance to CometChatSavedMessages too, whose invariants contradict these —
30
+ // mutating in place would make whichever panel built second corrupt the first.
31
+ // See cloneRequestBuilder for why the copy is prototype-preserving.
32
+ const builder = messagesRequestBuilder
33
+ ? cloneRequestBuilder(messagesRequestBuilder)
34
+ : new CometChat.MessagesRequestBuilder();
35
+
36
+ // The full invariant, not just half of it. setPinnedOnly alone is not enough: a
37
+ // builder carrying savedOnly=true makes the SDK reject the request with
38
+ // PINNED_AND_SAVED_BOTH_SET before any network call, and this panel shows its error
39
+ // state instead of the pinned list.
40
+ builder.setPinnedOnly(true);
41
+ builder.setSavedOnly(false);
42
+
43
+ // ALWAYS set, on every path. The SDK has no default: a request that never called
44
+ // setLimit() is rejected with SET_LIMIT_IS_COMPULSORY *before* any network call —
45
+ // an error screen with an empty network log. So we cannot simply trust a passed-in
46
+ // builder to have set one. Precedence: the `limit` prop, else whatever the builder
47
+ // already carries, else 30 (the SDK's own DEFAULT_VALUES.MSGS_LIMIT).
48
+ const builderLimit = (builder as unknown as { limit?: number }).limit;
49
+ builder.setLimit(limit ?? builderLimit ?? 30);
50
+
51
+ // Exactly one of these; the SDK rejects neither-set. Clear the OTHER first: setGUID and
52
+ // setUID only write their own field, and createEndpoint() prefers guid when both are set,
53
+ // so a caller's stale guid would make this 1-1 panel list that GROUP's pins. Only cleared
54
+ // when we have a scope to put in its place, so a builder-only scope still stands.
55
+ const scope = builder as unknown as { uid?: string; guid?: string };
56
+ if (group) {
57
+ scope.uid = undefined;
58
+ builder.setGUID(group.getGuid());
59
+ } else if (user) {
60
+ scope.guid = undefined;
61
+ builder.setUID(user.getUid());
62
+ }
63
+
64
+ return builder.build();
65
+ };