@cometchat/chat-uikit-react-native 5.4.1 → 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 (80) hide show
  1. package/android/.gradle/7.4/checksums/checksums.lock +0 -0
  2. package/android/.gradle/7.4/fileChanges/last-build.bin +0 -0
  3. package/android/.gradle/7.4/fileHashes/fileHashes.lock +0 -0
  4. package/android/.gradle/7.4/gc.properties +0 -0
  5. package/android/.gradle/vcs-1/gc.properties +0 -0
  6. package/android/src/main/java/com/reactnativecometchatuikit/CometChatClipboardModule.kt +34 -0
  7. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +542 -5
  8. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorViewManager.kt +20 -1
  9. package/ios/CometChatClipboardModule.m +5 -0
  10. package/ios/CometChatClipboardModule.swift +22 -0
  11. package/ios/RichTextEditorView.swift +593 -31
  12. package/ios/RichTextEditorViewManager.m +2 -0
  13. package/ios/RichTextEditorViewManager.swift +16 -0
  14. package/package.json +1 -1
  15. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +245 -55
  16. package/src/CometChatCompactMessageComposer/index.ts +2 -0
  17. package/src/CometChatConversations/CometChatConversations.tsx +291 -14
  18. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +181 -12
  19. package/src/CometChatMessageList/CometChatMessageList.tsx +568 -15
  20. package/src/CometChatMessageList/MANUAL_TEST_CASES.md +154 -0
  21. package/src/CometChatMessageList/components/MessageModals.tsx +30 -0
  22. package/src/CometChatMessageList/components/MessageOptionsSheet.tsx +14 -1
  23. package/src/CometChatMessageList/components/MessageQuickActions.tsx +162 -0
  24. package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +940 -0
  25. package/src/CometChatPinnedMessages/index.ts +5 -0
  26. package/src/CometChatPinnedMessages/style.ts +216 -0
  27. package/src/CometChatRichTextEditor/RichTextEditorViewNativeComponent.ts +5 -0
  28. package/src/CometChatRichTextEditor/index.tsx +27 -1
  29. package/src/CometChatRichTextEditor/types.ts +19 -1
  30. package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +634 -0
  31. package/src/CometChatSavedMessages/index.ts +5 -0
  32. package/src/CometChatSavedMessages/style.ts +159 -0
  33. package/src/CometChatSearch/CometChatSearch.tsx +47 -340
  34. package/src/CometChatThreadHeader/CometChatThreadHeader.tsx +22 -2
  35. package/src/index.ts +60 -0
  36. package/src/shared/CometChatUiKit/CometChatUIKit.ts +16 -0
  37. package/src/shared/base/Types.ts +5 -0
  38. package/src/shared/constants/UIKitConstants.ts +13 -0
  39. package/src/shared/events/CometChatUIEventHandler/CometChatUIEventHandler.ts +34 -0
  40. package/src/shared/events/CometChatUIEventHandler/Listener.ts +37 -0
  41. package/src/shared/events/ListenerInitializer.ts +20 -1
  42. package/src/shared/events/messages.ts +18 -0
  43. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +92 -6
  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 +296 -3
  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/resources/en/translation.json +54 -0
  53. package/src/shared/utils/MarkdownUtils.ts +25 -4
  54. package/src/shared/utils/MessageUtils.tsx +80 -5
  55. package/src/shared/utils/PinConversationHelper.ts +245 -0
  56. package/src/shared/utils/PinSaveFeatureGates.ts +178 -0
  57. package/src/shared/utils/PinSaveHelper.ts +549 -0
  58. package/src/shared/utils/SavedMessagesHelper.ts +231 -0
  59. package/src/shared/utils/ThreadSubscriptionHelper.ts +427 -0
  60. package/src/shared/utils/conversationUtils.ts +8 -1
  61. package/src/shared/utils/stripRichText.ts +7 -0
  62. package/src/shared/views/ClipboardPasteHandler/ClipboardPasteHandler.ts +21 -0
  63. package/src/shared/views/ClipboardPasteHandler/NativeCometChatClipboardModule.ts +6 -0
  64. package/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +4 -0
  65. package/src/shared/views/CometChatAvatar/CometChatAvatar.tsx +17 -5
  66. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +1 -0
  67. package/src/shared/views/CometChatConfirmDialog/CometChatConfirmDialog.tsx +2 -0
  68. package/src/shared/views/CometChatConversationStarter/CometChatConversationStarter.tsx +91 -20
  69. package/src/shared/views/CometChatList/CometChatList.tsx +6 -1
  70. package/src/shared/views/CometChatListItem/CometChatListItem.tsx +4 -0
  71. package/src/shared/views/CometChatRetryButton/CometChatRetryButton.tsx +1 -0
  72. package/src/shared/views/CometChatSuggestionList/CometChatSuggestionList.tsx +4 -0
  73. package/src/shared/views/ErrorEmptyView/ErrorEmptyView.tsx +4 -1
  74. package/src/theme/default/default.ts +6 -0
  75. package/src/theme/type.ts +4 -0
  76. package/src/CometChatMessageList/PERFORMANCE_ARCHITECTURE.md +0 -478
  77. package/src/CometChatMessageList/SEARCH_NAV_PERF_PLAN.md +0 -613
  78. package/src/CometChatMessageList/SEARCH_NAV_SLOWNESS_FINDINGS_AND_FIX.md +0 -313
  79. package/src/shared/CometChatUiKit/CometChatUIKit.changes.md +0 -76
  80. package/src/shared/CometChatUiKit/checkAuthSettings-review.md +0 -211
@@ -0,0 +1,940 @@
1
+ /**
2
+ * CometChatPinnedMessages — the per-conversation pinned list (§6.3).
3
+ *
4
+ * Opened from the chat-header ⋮. Conversation-scoped and PUBLIC: every member sees
5
+ * the same list regardless of who pinned what, and role-gating applies to unpinning,
6
+ * not to reading. Ordered `pinnedAt DESC`. Full-screen route on RN (§6.9).
7
+ *
8
+ * Deliberately shaped like CometChatSavedMessages without sharing an abstraction:
9
+ * the data source, the row action, the title and the empty copy all differ, and a
10
+ * config-driven single component would be fought by both callers. The design doc
11
+ * also specifies two public components, which the other four platforms mirror.
12
+ *
13
+ * Read-only w.r.t. unread state (§7.7): no markAsRead, no receipts, no counts.
14
+ *
15
+ * Two interactions per row:
16
+ * tap → `onItemPress`, which the host turns into a jump-to-message
17
+ * long-press → MessageOptionsSheet — the SAME sheet the message list opens, over
18
+ * an allow-list of options (see PANEL_OPTIONS)
19
+ *
20
+ * @module CometChatPinnedMessages
21
+ */
22
+ import { CometChat } from "@cometchat/chat-sdk-react-native";
23
+ import Clipboard from "@react-native-clipboard/clipboard";
24
+ import React, { JSX, useCallback, useEffect, useMemo, useRef, useState } from "react";
25
+ import { FlatList, NativeModules, Pressable, Text, View } from "react-native";
26
+ import { ChatConfigurator } from "../shared";
27
+ import { MessageOptionsSheet } from "../CometChatMessageList/components/MessageOptionsSheet";
28
+ import { MessageOptionConstants } from "../shared/constants/UIKitConstants";
29
+ import { CometChatMessageOption } from "../shared/modals/CometChatMessageOption";
30
+ import { CometChatMessageTemplate } from "../shared/modals/CometChatMessageTemplate";
31
+ import { MessageUtils } from "../shared/utils/MessageUtils";
32
+ import { useCompTheme, useTheme } from "../theme/hook";
33
+ import { deepMerge } from "../shared/helper/helperFunctions";
34
+ import { DeepPartial } from "../shared/helper/types";
35
+ import { PinnedMessagesStyle } from "./style";
36
+ import { CometChatTheme } from "../theme/type";
37
+ import { Icon } from "../shared/icons/Icon";
38
+ import { CometChatAvatar } from "../shared/views/CometChatAvatar";
39
+ import { CometChatDate } from "../shared/views/CometChatDate";
40
+ import { ErrorEmptyView } from "../shared/views/ErrorEmptyView/ErrorEmptyView";
41
+ import { CometChatConfirmDialog } from "../shared/views/CometChatConfirmDialog";
42
+ import { CometChatRetryButton } from "../shared/views/CometChatRetryButton/CometChatRetryButton";
43
+ import { useCometChatTranslation } from "../shared/resources/CometChatLocalizeNew";
44
+ import { useToast } from "../shared/helper/useToast";
45
+ import {
46
+ applyPinSaveAnswer,
47
+ canPin,
48
+ carryPinSaveAttrs,
49
+ isMessageGoneError,
50
+ isSaved,
51
+ isSystemPin,
52
+ saveMessage,
53
+ unpinMessage,
54
+ unsaveMessage,
55
+ sameMessageId,
56
+ } from "../shared/utils/PinSaveHelper";
57
+ import { CometChatUIEventHandler } from "../shared/events/CometChatUIEventHandler/CometChatUIEventHandler";
58
+ import { MessageEvents } from "../shared/events/messages";
59
+
60
+ /**
61
+ * The options this panel is willing to show, as an ALLOW-LIST.
62
+ *
63
+ * A deny-list would be the obvious choice and is the wrong one. Options arrive from
64
+ * the DataSource as pure descriptors — `{id, title, icon}` with NO `onPress`; the
65
+ * message list binds every handler itself. So an option this panel does not
66
+ * explicitly wire renders as a dead menu row. A deny-list silently acquires those
67
+ * every time someone adds an option upstream; an allow-list fails closed.
68
+ *
69
+ * Excluded on purpose:
70
+ * - delete / edit / reply / replyInThread — product decision, this is a reference
71
+ * surface, not a place to author from.
72
+ * - replyPrivately / sendPrivately — same class as reply; they need a composer,
73
+ * which does not exist here.
74
+ * - markAsUnread — §7.7 makes this panel read-only w.r.t. unread state.
75
+ * - reactToMessage — needs the reaction sheet plus live row rebinding.
76
+ * - translateMessage — per-row in-place render state.
77
+ * - reportMessage — needs the report dialog; add it when it is asked for.
78
+ * - threadSubscription — NOT a product decision, a correctness one. `threadSubscribed`
79
+ * is only populated on responses to requests that asked for it, and a pinned thread
80
+ * message can be appended to this list in realtime off a websocket frame, which
81
+ * carries no flag. The option would render "Subscribe" on a thread the user already
82
+ * follows, and tapping it would unfollow them. Absent is the honest state here.
83
+ */
84
+ const PANEL_OPTIONS: string[] = [
85
+ MessageOptionConstants.messageInformation,
86
+ MessageOptionConstants.copyMessage,
87
+ MessageOptionConstants.shareMessage,
88
+ MessageOptionConstants.unpinMessage,
89
+ MessageOptionConstants.saveMessage,
90
+ MessageOptionConstants.unsaveMessage,
91
+ ];
92
+
93
+ const templateKey = (category: string, type: string) => `${category}_${type}`;
94
+
95
+ /** Plain text for copy/share. Empty for anything without a text body. */
96
+ const textOf = (message: CometChat.BaseMessage): string => {
97
+ if (message instanceof CometChat.TextMessage) return message.getText() ?? "";
98
+ if (message instanceof CometChat.MediaMessage) return message.getCaption() ?? "";
99
+ return "";
100
+ };
101
+
102
+ export interface CometChatPinnedMessagesInterface {
103
+ /** 1-1 conversation. Mutually exclusive with `group`. */
104
+ user?: CometChat.User;
105
+ /** Group conversation. Mutually exclusive with `user`. */
106
+ group?: CometChat.Group;
107
+ /** Page size. Defaults to 30; the server caps a conversation at 100. */
108
+ limit?: number;
109
+ /** Closes the panel — rendered as the ✕ in the header. */
110
+ onBack?: () => void;
111
+ /** Tapping a row — the host jumps its message list to this message. */
112
+ onItemPress?: (message: CometChat.BaseMessage) => void;
113
+ /**
114
+ * Hide the unpin option in the long-press sheet. Named per design doc §6.7,
115
+ * which lists the same four flags for the action sheet — the panel mirrors that
116
+ * vocabulary rather than inventing a shorter one.
117
+ */
118
+ hideUnpinMessageOption?: boolean;
119
+ /** Hide Save in the long-press sheet (§6.7). */
120
+ hideSaveMessageOption?: boolean;
121
+ /** Hide Copy. Named to match CometChatMessageList's flag of the same purpose. */
122
+ hideCopyMessageOption?: boolean;
123
+ /** Hide Share. Named to match CometChatMessageList's flag of the same purpose. */
124
+ hideShareMessageOption?: boolean;
125
+ /** Hide Info. Named to match CometChatMessageList's flag of the same purpose. */
126
+ hideMessageInfoOption?: boolean;
127
+ /** Hide Unsave in the long-press sheet (§6.7). */
128
+ hideUnsaveMessageOption?: boolean;
129
+ ItemView?: (message: CometChat.BaseMessage) => JSX.Element;
130
+ title?: string;
131
+ /** Per-instance style overrides, merged over the theme's pinnedMessagesStyles. */
132
+ style?: DeepPartial<PinnedMessagesStyle>;
133
+ }
134
+
135
+ type ListState = "loading" | "loaded" | "error" | "empty";
136
+
137
+ export const CometChatPinnedMessages = (props: CometChatPinnedMessagesInterface) => {
138
+ const {
139
+ user,
140
+ group,
141
+ limit,
142
+ onBack,
143
+ onItemPress,
144
+ hideUnpinMessageOption = false,
145
+ hideSaveMessageOption = false,
146
+ hideUnsaveMessageOption = false,
147
+ hideCopyMessageOption = false,
148
+ hideShareMessageOption = false,
149
+ hideMessageInfoOption = false,
150
+ ItemView,
151
+ title,
152
+ style,
153
+ } = props;
154
+
155
+ const theme = useTheme() as CometChatTheme;
156
+ const compTheme = useCompTheme();
157
+ const { t } = useCometChatTranslation();
158
+
159
+ /** theme → component-level override → per-instance prop, the kit's usual order. */
160
+ const styles = useMemo(
161
+ () => deepMerge(theme.pinnedMessagesStyles, compTheme.pinnedMessagesStyles ?? {}, style ?? {}),
162
+ [theme.pinnedMessagesStyles, compTheme.pinnedMessagesStyles, style]
163
+ );
164
+ const { showToast, ToastElement } = useToast();
165
+
166
+ const [messages, setMessagesRaw] = useState<CometChat.BaseMessage[]>([]);
167
+ const [state, setStateRaw] = useState<ListState>("loading");
168
+ const loggedInUser = useRef<CometChat.User | null>(null);
169
+
170
+ /**
171
+ * These panels are full-screen routes, so popping one while a fetch or a post-confirm
172
+ * write is still in flight lands a setState on an unmounted component — the React Native
173
+ * warning, plus work nobody will see. Guarding at the SETTER rather than at each of the
174
+ * async resolvers keeps every existing call site unchanged and cannot be forgotten at a
175
+ * new one.
176
+ */
177
+ const mounted = useRef(true);
178
+ useEffect(() => () => { mounted.current = false; }, []);
179
+ const setMessages: typeof setMessagesRaw = useCallback(
180
+ value => { if (mounted.current) setMessagesRaw(value); },
181
+ []
182
+ );
183
+ const setState: typeof setStateRaw = useCallback(
184
+ value => { if (mounted.current) setStateRaw(value); },
185
+ []
186
+ );
187
+
188
+ /** Long-press sheet state, mirroring what CometChatMessageList keeps. */
189
+ const [sheetOptions, setSheetOptions] = useState<CometChatMessageOption[]>([]);
190
+ const [selectedMessage, setSelectedMessage] = useState<CometChat.BaseMessage | null>(null);
191
+ const [showInfo, setShowInfo] = useState(false);
192
+ /** The row awaiting unpin/unsave confirmation, or null. */
193
+ const [confirm, setConfirm] = useState<{
194
+ message: CometChat.BaseMessage;
195
+ action: "unpin" | "unsave";
196
+ } | null>(null);
197
+ const infoObject = useRef<CometChat.BaseMessage | null | undefined>(null);
198
+ const sheetRef = useRef<{ togglePanel: () => void } | null>(null);
199
+
200
+ /**
201
+ * MessageOptionsSheet takes these because the message list drives delete and
202
+ * report through them. This panel offers neither, so they stay inert — they exist
203
+ * to satisfy the contract, not to be read.
204
+ */
205
+ const deleteItem = useRef<CometChat.BaseMessage | undefined>(undefined);
206
+ const pendingReportRef = useRef(false);
207
+
208
+ /** Single-use and accumulates its own paging state, so it lives for the screen. */
209
+ const request = useRef<CometChat.MessagesRequest | null>(null);
210
+ const fetching = useRef(false);
211
+ /**
212
+ * The end of a cursor-paged list is an empty page — there is nothing to ask the request
213
+ * for beforehand. Latch it here, or every further scroll-to-end fires a round trip that
214
+ * can only come back empty again.
215
+ */
216
+ const exhausted = useRef(false);
217
+
218
+ /**
219
+ * The ordinary messages request, filtered to pinned rows. Paging is the ordinary
220
+ * cursor walk — setPinnedOnly() only changes the field the cursor rides on, from
221
+ * sentAt to pinnedAt, because that is the order the server returns pins in.
222
+ *
223
+ * A factory rather than an inline build: a request is single-use, so retrying after
224
+ * an error needs a fresh one.
225
+ */
226
+ const buildRequest = useCallback(() => {
227
+ const builder = new CometChat.MessagesRequestBuilder().setPinnedOnly(true);
228
+ // ALWAYS set. The SDK has no default: a request that never called setLimit() is
229
+ // rejected with SET_LIMIT_IS_COMPULSORY before any network call. 30 matches the
230
+ // SDK's own DEFAULT_VALUES.MSGS_LIMIT.
231
+ builder.setLimit(limit ?? 30);
232
+ // Exactly one of these; the SDK rejects neither-set.
233
+ if (group) builder.setGUID(group.getGuid());
234
+ else if (user) builder.setUID(user.getUid());
235
+ return builder.build();
236
+ }, [limit, group, user]);
237
+
238
+ if (request.current === null) request.current = buildRequest();
239
+
240
+ const loadNext = useCallback(async () => {
241
+ if (fetching.current || exhausted.current || !request.current) return;
242
+ fetching.current = true;
243
+ try {
244
+ // fetchPrevious(), not fetchNext() — "previous" is older, which is the direction
245
+ // this list scrolls. Same call CometChatMessageList makes to load history.
246
+ const rows = await request.current.fetchPrevious();
247
+ if (rows.length > 0) {
248
+ // Dedupe on append (ENG-38891). A realtime pin/save PREPENDS its row the moment the
249
+ // event lands; the same message then comes back inside a later fetched page, and a
250
+ // plain concat lists it twice — which is how a five-pin cap rendered six rows.
251
+ setMessages(prev => {
252
+ const seen = new Set(prev.map(m => String(m.getId())));
253
+ return [...prev, ...rows.filter(r => !seen.has(String(r.getId())))];
254
+ });
255
+ setState("loaded");
256
+ } else {
257
+ exhausted.current = true;
258
+ setState(prev => (prev === "loading" ? "empty" : prev));
259
+ }
260
+ } catch (e) {
261
+ // Log it — a bare `catch {}` hides client-side rejections that never reach the
262
+ // network, leaving a generic error screen and an empty network log to debug from.
263
+ console.error("CometChatPinnedMessages: failed to fetch pinned messages", e);
264
+ setState(prev => (prev === "loading" ? "error" : prev));
265
+ } finally {
266
+ fetching.current = false;
267
+ }
268
+ }, []);
269
+
270
+ /**
271
+ * Keep loading while the rows do not fill the viewport.
272
+ *
273
+ * onEndReached is the only paging trigger, and it needs a scroll to fire. When the first page
274
+ * is shorter than the screen there is nothing to scroll, so the list stops at page one and the
275
+ * rest is unreachable — verified with limit=2 against 4 pinned messages: `loadNext` ran once,
276
+ * returned 2 rows, and was never called again while the panel sat half empty.
277
+ *
278
+ * The default page size fills a phone screen, which is why this hid; `limit` is a public prop,
279
+ * so any integrator who lowers it hits a permanently incomplete list. loadNext already guards
280
+ * on `fetching`/`exhausted`, so this tops up at most one request at a time and stops on its own.
281
+ */
282
+ const viewportHeight = useRef(0);
283
+ const contentHeight = useRef(0);
284
+ const fillViewport = useCallback(() => {
285
+ if (exhausted.current || fetching.current) return;
286
+ if (viewportHeight.current <= 0 || contentHeight.current <= 0) return;
287
+ if (contentHeight.current < viewportHeight.current) loadNext();
288
+ }, [loadNext]);
289
+
290
+ /**
291
+ * Retry after an error. The request is single-use and has already consumed whatever
292
+ * paging state it got to, so this builds a fresh one rather than re-calling the old —
293
+ * a retried request must start from the top of the list, not from a half-walked cursor.
294
+ */
295
+ const reload = useCallback(() => {
296
+ request.current = buildRequest();
297
+ exhausted.current = false;
298
+ fetching.current = false;
299
+ setMessages([]);
300
+ setState("loading");
301
+ loadNext();
302
+ }, [buildRequest, loadNext]);
303
+
304
+ useEffect(() => {
305
+ CometChat.getLoggedinUser()
306
+ .then(u => {
307
+ loggedInUser.current = u ?? null;
308
+ })
309
+ .catch(() => {
310
+ loggedInUser.current = null;
311
+ })
312
+ .finally(() => {
313
+ loadNext();
314
+ });
315
+ }, [loadNext]);
316
+
317
+ /**
318
+ * Keep the panel in step with pins made anywhere else — the message list next to it,
319
+ * this user's other device, or another participant over the socket.
320
+ *
321
+ * Without this the list is a snapshot taken on mount: unpin a message from the
322
+ * conversation and its row sits here until the screen is reopened.
323
+ *
324
+ * Two event families, deliberately both:
325
+ * - cc* — emitted by the device that PERFORMED the action. Covers the local case,
326
+ * and 1-1 conversations, where the server emits no socket frame at all.
327
+ * - on* — the socket echo, i.e. somebody else's pin. Groups AND 1-1: the DM
328
+ * case was confirmed at the handler on 1 Sep (receiverType='user'),
329
+ * so this panel accepts BOTH directions of a 1-1 frame.
330
+ * The payload shapes differ (cc* wraps in {message}), hence the unwrap.
331
+ */
332
+ useEffect(() => {
333
+ const id = "pinned-messages-panel";
334
+
335
+ const belongsHere = (message: CometChat.BaseMessage): boolean => {
336
+ const receiver = message.getReceiverId?.();
337
+ if (group) return receiver === group.getGuid();
338
+ if (!user) return false;
339
+
340
+ // A 1-1 frame is NOT symmetric: on an INCOMING pin — the counterparty pinned it —
341
+ // getReceiverId() is the logged-in user's own uid, not theirs. Matching on the
342
+ // receiver alone therefore accepted only the pins this device sent and silently
343
+ // dropped the other participant's, which is the case this listener exists for.
344
+ // Match either direction, and require receiverType 'user' so a group message from
345
+ // that same person cannot leak into a 1-1 panel.
346
+ if (message.getReceiverType?.() !== CometChat.RECEIVER_TYPE.USER) return false;
347
+ const uid = user.getUid();
348
+ return receiver === uid || message.getSender?.()?.getUid?.() === uid;
349
+ };
350
+
351
+ const unwrap = (payload: any): CometChat.BaseMessage | null =>
352
+ payload?.message ?? payload ?? null;
353
+
354
+ const added = (payload: any) => {
355
+ const message = unwrap(payload);
356
+ if (!message || !belongsHere(message)) return;
357
+ setMessages(prev => {
358
+ if (prev.some(m => sameMessageId(m.getId(), message.getId()))) return prev;
359
+ // Newest pin first — the list is ordered by pinnedAt, and this one is now the
360
+ // most recent.
361
+ return [message, ...prev];
362
+ });
363
+ setState("loaded");
364
+ };
365
+
366
+ const removed = (payload: any) => {
367
+ const message = unwrap(payload);
368
+ if (!message) return;
369
+ setMessages(prev => {
370
+ const next = prev.filter(m => !sameMessageId(m.getId(), message.getId()));
371
+ if (next.length === prev.length) return prev;
372
+ // Only claim empty once the first page has actually been read; an event that
373
+ // arrives mid-load would otherwise replace the spinner with "no pinned messages".
374
+ if (next.length === 0 && exhausted.current) setState("empty");
375
+ return next;
376
+ });
377
+ };
378
+
379
+ /**
380
+ * ENG-38177 — an edit rewrites the row in place.
381
+ *
382
+ * A pinned message stays pinned when it is edited, so the row must survive and show the
383
+ * new content. Without this the panel serves whatever text was pinned, indefinitely.
384
+ *
385
+ * The edit response carries no pinnedAt (verified on staging 2026-08-14), so replacing
386
+ * the row wholesale would strip the very attribute this list is built on — hence
387
+ * carryPinSaveAttrs. Rows not already in the list are ignored: an edit is not a pin.
388
+ */
389
+ const edited = (payload: any) => {
390
+ const message = unwrap(payload);
391
+ if (!message) return;
392
+ setMessages(prev => {
393
+ const index = prev.findIndex(m => sameMessageId(m.getId(), message.getId()));
394
+ if (index === -1) return prev;
395
+ const next = [...prev];
396
+ next[index] = carryPinSaveAttrs(message, prev[index]);
397
+ return next;
398
+ });
399
+ };
400
+
401
+ /**
402
+ * ENG-38181 — a deleted message cannot stay in the pinned list.
403
+ *
404
+ * The server drops it from the pinned set, so a row left behind is one the user can tap
405
+ * into nothing. Reuses `removed`, which already handles the last-row empty state.
406
+ */
407
+ const deleted = (payload: any) => removed(payload);
408
+
409
+ /**
410
+ * A save or unsave made ANYWHERE rewrites the bookmark on the row in place.
411
+ *
412
+ * The row stays either way — `savedAt` is a private per-viewer flag with no bearing on
413
+ * whether the message is pinned — so this is not `added`/`removed`, it is an update.
414
+ *
415
+ * applyPinSaveAnswer, NOT carryPinSaveAttrs (which `edited` above uses): on this path the
416
+ * response IS the answer, and an ABSENT savedAt means "no longer saved". Carrying the old
417
+ * value across would leave the bookmark on screen for ever, which is the exact mistake
418
+ * the edit path has to make in the opposite direction.
419
+ */
420
+ const savedChanged = (payload: any) => {
421
+ const message = unwrap(payload);
422
+ if (!message) return;
423
+ setMessages(prev => {
424
+ const index = prev.findIndex(m => sameMessageId(m.getId(), message.getId()));
425
+ if (index === -1) return prev;
426
+ const next = [...prev];
427
+ next[index] = applyPinSaveAnswer(prev[index], message);
428
+ return next;
429
+ });
430
+ };
431
+
432
+ // The keys must be written out literally. emitMessageEvent dispatches by matching
433
+ // the event name against each callback's inferred function NAME, which an anonymous
434
+ // arrow gets from its property key — passing `added` by reference would register a
435
+ // function named "added" and never match anything.
436
+ CometChatUIEventHandler.addMessageListener(id, {
437
+ ccMessagePinned: (payload: any) => added(payload),
438
+ onMessagePinned: (payload: any) => added(payload),
439
+ ccMessageUnpinned: (payload: any) => removed(payload),
440
+ onMessageUnpinned: (payload: any) => removed(payload),
441
+ ccMessageEdited: (payload: any) => edited(payload),
442
+ onMessageEdited: (payload: any) => edited(payload),
443
+ ccMessageSaved: (payload: any) => savedChanged(payload),
444
+ onMessageSaved: (payload: any) => savedChanged(payload),
445
+ ccMessageUnsaved: (payload: any) => savedChanged(payload),
446
+ onMessageUnsaved: (payload: any) => savedChanged(payload),
447
+ ccMessageDeleted: (payload: any) => deleted(payload),
448
+ onMessageDeleted: (payload: any) => deleted(payload),
449
+ });
450
+
451
+ return () => CometChatUIEventHandler.removeMessageListener(id);
452
+ }, [group, user]);
453
+
454
+ /**
455
+ * Clearing a conversation deletes its messages FOR THIS VIEWER, pinned ones included.
456
+ * The server is consistent about it — the pinned list comes back empty and every id
457
+ * behind the old rows returns ERR_MESSAGE_ID_NOT_FOUND — but this panel had no idea it
458
+ * had happened, so it kept rendering rows for messages that no longer existed and every
459
+ * unpin from them 404'd.
460
+ *
461
+ * Emptying rather than refetching: there is nothing left to fetch, and a request here
462
+ * would race the delete and could repopulate from a stale read.
463
+ */
464
+ useEffect(() => {
465
+ const id = "pinned-messages-panel-conversation";
466
+
467
+ CometChatUIEventHandler.addConversationListener(id, {
468
+ ccConversationDeleted: ({ conversation }: { conversation: CometChat.Conversation }) => {
469
+ const cleared = conversation?.getConversationWith?.();
470
+ if (!cleared) return;
471
+ const clearedId =
472
+ cleared instanceof CometChat.Group ? cleared.getGuid() : (cleared as CometChat.User).getUid();
473
+ const mine = group ? group.getGuid() : user ? user.getUid() : null;
474
+ if (!mine || clearedId !== mine) return;
475
+
476
+ setMessages([]);
477
+ exhausted.current = true;
478
+ setState("empty");
479
+ },
480
+ });
481
+
482
+ return () => CometChatUIEventHandler.removeConversationListener(id);
483
+ }, [group, user]);
484
+
485
+ const templates: CometChatMessageTemplate[] = useMemo(
486
+ () => ChatConfigurator.dataSource.getAllMessageTemplates(theme),
487
+ [theme]
488
+ );
489
+
490
+ const templatesMap = useMemo(() => {
491
+ const map = new Map<string, CometChatMessageTemplate>();
492
+ templates.forEach(tpl => map.set(templateKey(tpl.category, tpl.type), tpl));
493
+ return map;
494
+ }, [templates]);
495
+
496
+ const closeSheet = useCallback(() => {
497
+ setSheetOptions([]);
498
+ setSelectedMessage(null);
499
+ infoObject.current = null;
500
+ setShowInfo(false);
501
+ }, []);
502
+
503
+ /**
504
+ * Unpin and unsave ASK first (Jitvar, 2026-08-04) — the removing half of each pair
505
+ * confirms, on every surface it appears. Unpin especially: the pin may not be yours,
506
+ * and nothing on this panel offers it back.
507
+ */
508
+ const onUnpin = (message: CometChat.BaseMessage) => setConfirm({ message, action: "unpin" });
509
+
510
+ const runUnpin = (message: CometChat.BaseMessage) => {
511
+ const id = message.getId();
512
+ setMessages(prev => {
513
+ const next = prev.filter(m => !sameMessageId(m.getId(), id));
514
+ if (next.length === 0) setState("empty");
515
+ return next;
516
+ });
517
+ unpinMessage(id)
518
+ .then((updated) => {
519
+ // Tell the other surfaces (ENG-38884). This panel sits ON TOP of the message list,
520
+ // which holds its own copy of the message — without this the bubble behind kept its
521
+ // pin glyph until a fetch rebuilt the list, so the message read as still pinned.
522
+ // The server's response is the authoritative answer; the row we held is the fallback
523
+ // for the case where it comes back empty.
524
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageUnpinned, {
525
+ message: updated ?? message,
526
+ });
527
+ showToast(t("MESSAGE_UNPINNED") ?? "Message unpinned");
528
+ })
529
+ .catch((error: any) => {
530
+ // A message that no longer exists must STAY removed. Reinstating the row — which is
531
+ // right when the write merely failed — leaves the user tapping Unpin forever on
532
+ // something the server will never accept. Clearing a chat with pinned messages does
533
+ // exactly this: the rows survive in the open panel, but every id behind them is gone.
534
+ if (isMessageGoneError(error)) {
535
+ setMessages(prev => {
536
+ if (prev.length === 0 && exhausted.current) setState("empty");
537
+ return prev;
538
+ });
539
+ showToast(t("MESSAGE_NO_LONGER_AVAILABLE") ?? "This message is no longer available.");
540
+ return;
541
+ }
542
+ setMessages(prev => [message, ...prev]);
543
+ setState("loaded");
544
+ showToast(t("PIN_SAVE_GENERIC_ERROR") ?? "Something went wrong. Please try again.");
545
+ });
546
+ };
547
+
548
+ /**
549
+ * Save/unsave from inside the panel. Unlike unpin, the row STAYS — `savedAt` is a
550
+ * private per-viewer flag and has no bearing on whether a message is pinned.
551
+ * Swaps in the settled server row so the bookmark indicator re-renders off it.
552
+ */
553
+ const onToggleSave = (message: CometChat.BaseMessage, save: boolean) => {
554
+ // Saving is additive and runs straight away; unsaving asks.
555
+ if (!save) {
556
+ setConfirm({ message, action: "unsave" });
557
+ return;
558
+ }
559
+ runToggleSave(message, true);
560
+ };
561
+
562
+ const runToggleSave = (message: CometChat.BaseMessage, save: boolean) => {
563
+ const id = message.getId();
564
+ const call = save ? saveMessage : unsaveMessage;
565
+ call(id)
566
+ .then(updated => {
567
+ setMessages(prev => prev.map(m => (sameMessageId(m.getId(), id) ? (updated ?? m) : m)));
568
+ // Same reason as the unpin above — the bookmark on the bubble behind this panel is a
569
+ // second copy of the same state and has to be told.
570
+ CometChatUIEventHandler.emitMessageEvent(
571
+ save ? MessageEvents.ccMessageSaved : MessageEvents.ccMessageUnsaved,
572
+ { message: updated ?? message }
573
+ );
574
+ showToast(
575
+ save
576
+ ? (t("MESSAGE_SAVED") ?? "Message saved")
577
+ : (t("MESSAGE_UNSAVED") ?? "Message unsaved")
578
+ );
579
+ })
580
+ .catch(() =>
581
+ showToast(t("PIN_SAVE_GENERIC_ERROR") ?? "Something went wrong. Please try again.")
582
+ );
583
+ };
584
+
585
+ const onCopy = (message: CometChat.BaseMessage) => {
586
+ // ponytail: raw text, not the mention-resolved string the message list copies via
587
+ // its local getPlainString (not exported). Copying "@uid" instead of "@Name" is
588
+ // the known ceiling; lift it by extracting that helper into shared/utils.
589
+ Clipboard.setString(textOf(message));
590
+ // Deferred like the message list does: unmounting the Modal while Clipboard is
591
+ // still touching views crashes Fabric on iOS.
592
+ requestAnimationFrame(closeSheet);
593
+ };
594
+
595
+ const onShare = (message: CometChat.BaseMessage) => {
596
+ const attachment =
597
+ message instanceof CometChat.MediaMessage ? message.getAttachment() : undefined;
598
+ const fileUrl = attachment?.getUrl() ?? "";
599
+ const shareObj = {
600
+ message: textOf(message),
601
+ type: message.getType(),
602
+ mediaName: attachment?.getName() ?? "",
603
+ fileUrl,
604
+ mimeType: attachment?.getMimeType() ?? "",
605
+ };
606
+ closeSheet();
607
+ // Same 600ms as the message list: presenting the native share sheet before the
608
+ // modal finishes dismissing freezes the screen on iOS/Fabric.
609
+ setTimeout(() => {
610
+ NativeModules?.FileManager?.shareMessage?.(shareObj, () => {});
611
+ }, 600);
612
+ };
613
+
614
+ /**
615
+ * Unpin is offered only to Admin/Moderator/Owner — the same gate as the
616
+ * action-sheet option, so the panel cannot become a back door to an action the
617
+ * message list refuses. A system pin (`app_system`) is never user-unpinnable.
618
+ */
619
+ const mayUnpin = (message: CometChat.BaseMessage) =>
620
+ !hideUnpinMessageOption && !isSystemPin(message) && canPin(loggedInUser.current, group ?? null);
621
+
622
+ /**
623
+ * Takes the DataSource's options for this message, keeps only the allow-listed
624
+ * ones, and binds a handler to each. Anything left unbound is dropped rather than
625
+ * shown inert — the switch's default is the safety net for PANEL_OPTIONS drifting
626
+ * ahead of the handlers below.
627
+ */
628
+ const buildOptions = (message: CometChat.BaseMessage): CometChatMessageOption[] => {
629
+ const template = templatesMap.get(templateKey(message.getCategory(), message.getType()));
630
+ // No logged-in user means no options at all rather than an unauthenticated menu.
631
+ const raw =
632
+ template?.options && loggedInUser.current
633
+ ? (template.options(loggedInUser.current, message, theme, group) ?? [])
634
+ : [];
635
+
636
+ const bound: CometChatMessageOption[] = [];
637
+ raw
638
+ .filter(option => PANEL_OPTIONS.includes(option.id))
639
+ .forEach(option => {
640
+ switch (option.id) {
641
+ case MessageOptionConstants.messageInformation:
642
+ if (hideMessageInfoOption) break;
643
+ bound.push({
644
+ ...option,
645
+ onPress: () => {
646
+ infoObject.current = message;
647
+ setShowInfo(true);
648
+ },
649
+ });
650
+ break;
651
+ case MessageOptionConstants.copyMessage:
652
+ if (hideCopyMessageOption) break;
653
+ bound.push({ ...option, onPress: () => onCopy(message) });
654
+ break;
655
+ case MessageOptionConstants.shareMessage:
656
+ if (hideShareMessageOption) break;
657
+ bound.push({ ...option, onPress: () => onShare(message) });
658
+ break;
659
+ case MessageOptionConstants.unpinMessage:
660
+ if (!mayUnpin(message)) break;
661
+ bound.push({
662
+ ...option,
663
+ onPress: () => {
664
+ closeSheet();
665
+ onUnpin(message);
666
+ },
667
+ });
668
+ break;
669
+ case MessageOptionConstants.saveMessage:
670
+ if (hideSaveMessageOption) break;
671
+ bound.push({
672
+ ...option,
673
+ onPress: () => {
674
+ closeSheet();
675
+ onToggleSave(message, true);
676
+ },
677
+ });
678
+ break;
679
+ case MessageOptionConstants.unsaveMessage:
680
+ if (hideUnsaveMessageOption) break;
681
+ bound.push({
682
+ ...option,
683
+ onPress: () => {
684
+ closeSheet();
685
+ onToggleSave(message, false);
686
+ },
687
+ });
688
+ break;
689
+ default:
690
+ break;
691
+ }
692
+ });
693
+ return bound;
694
+ };
695
+
696
+ const onLongPressRow = (message: CometChat.BaseMessage) => {
697
+ const options = buildOptions(message);
698
+ if (options.length === 0) return;
699
+ setSelectedMessage(message);
700
+ setSheetOptions(options);
701
+ };
702
+
703
+ const renderRow = ({ item, index }: { item: CometChat.BaseMessage; index: number }) => {
704
+ const sender = item.getSender();
705
+ const avatar = sender?.getAvatar();
706
+ const isSelf = sender?.getUid() === loggedInUser.current?.getUid();
707
+
708
+ return (
709
+ <Pressable
710
+ testID={`PinnedMessages.row-${index}`}
711
+ onPress={() => onItemPress?.(item)}
712
+ onLongPress={() => onLongPressRow(item)}
713
+ accessibilityRole='button'
714
+ style={styles.itemStyle?.containerStyle}
715
+ >
716
+ <View style={styles.itemStyle?.headerContainerStyle}>
717
+ <CometChatAvatar
718
+ // getAvatar() is a URL string; the avatar wraps bare strings into {uri}
719
+ // at runtime but types the prop as ImageSourcePropType, so wrap it here.
720
+ image={avatar ? { uri: avatar } : undefined}
721
+ name={sender?.getName() ?? ""}
722
+ style={styles.itemStyle?.avatarStyle}
723
+ />
724
+ {/* No source label here, unlike the saved list — every row is from THIS
725
+ conversation, so it would be identical on every row and pure noise. */}
726
+ <Text
727
+ numberOfLines={1}
728
+ style={styles.itemStyle?.senderNameStyle}
729
+ >
730
+ {isSelf ? (t("YOU") ?? "You") : (sender?.getName() ?? "")}
731
+ </Text>
732
+ <Text
733
+ style={styles.itemStyle?.separatorStyle}
734
+ >
735
+ {"•"}
736
+ </Text>
737
+ <CometChatDate
738
+ timeStamp={item.getSentAt() * 1000}
739
+ pattern='dayDateFormat'
740
+ style={styles.itemStyle?.dateStyle}
741
+ />
742
+
743
+ {/* A saved-too row shows the bookmark, so state reads consistently with the
744
+ message list. The pin glyph lives in the bubble's own meta row. */}
745
+ {isSaved(item) ? (
746
+ <View
747
+ accessible={true}
748
+ accessibilityLabel={t("SAVED") ?? "Saved"}
749
+ style={styles.itemStyle?.savedIndicatorContainerStyle}
750
+ >
751
+ <Icon
752
+ name='bookmark-fill'
753
+ color={styles.itemStyle?.savedIndicatorStyle?.tintColor}
754
+ height={styles.itemStyle?.savedIndicatorStyle?.height}
755
+ width={styles.itemStyle?.savedIndicatorStyle?.width}
756
+ />
757
+ </View>
758
+ ) : null}
759
+ </View>
760
+
761
+ {/* pointerEvents none so the bubble never swallows the row's tap/long-press. */}
762
+ <View pointerEvents='none' style={styles.itemStyle?.bubbleContainerStyle}>
763
+ {ItemView
764
+ ? ItemView(item)
765
+ : MessageUtils.getMessageView({
766
+ message: item,
767
+ templates,
768
+ alignment: "left",
769
+ theme,
770
+ // The row header above already carries the avatar and the sender
771
+ // name. Both of the bubble's own copies are group-only, so leaving
772
+ // these on printed each of them twice in a group.
773
+ avatarVisibility: false,
774
+ headerVisibility: false,
775
+ })}
776
+ </View>
777
+ </Pressable>
778
+ );
779
+ };
780
+
781
+ return (
782
+ <View style={styles.containerStyle}>
783
+ {/* Back arrow LEADING the title, matching Group Info / User Info. This is a pushed
784
+ full-screen route, not a modal, so a leading back is the right affordance — a
785
+ trailing ✕ read as "dismiss a sheet". */}
786
+ <View style={styles.headerContainerStyle}>
787
+ {onBack ? (
788
+ <Pressable
789
+ testID='PinnedMessages.back'
790
+ onPress={onBack}
791
+ accessibilityRole='button'
792
+ accessibilityLabel={t("BACK") ?? "Back"}
793
+ hitSlop={8}
794
+ >
795
+ <Icon
796
+ name='arrow-back'
797
+ icon={styles.closeButtonIcon}
798
+ color={styles.closeButtonIconStyle?.tintColor}
799
+ height={styles.closeButtonIconStyle?.height}
800
+ width={styles.closeButtonIconStyle?.width}
801
+ />
802
+ </Pressable>
803
+ ) : null}
804
+ <Text style={styles.titleStyle}>
805
+ {/* Static, matching the mobile mock. The web spec puts the count inline
806
+ (§6.0), but there is no count field on the server — it would be a
807
+ fetch-all-and-count that ticks upward as pages load, so the title would
808
+ visibly change under the user while they scroll. */}
809
+ {title ?? (t("PINNED_MESSAGES") ?? "Pinned Messages")}
810
+ </Text>
811
+ </View>
812
+
813
+ {state === "empty" ? (
814
+ <ErrorEmptyView
815
+ testID='PinnedMessages.empty'
816
+ // ErrorEmptyView carries no layout of its own — everything comes from these props.
817
+ containerStyle={styles.emptyStateStyle?.containerStyle}
818
+ title={t("NO_PINNED_MESSAGES") ?? "No pinned messages yet"}
819
+ titleStyle={styles.emptyStateStyle?.titleStyle}
820
+ subTitle={
821
+ t("NO_PINNED_MESSAGES_SUBTITLE") ??
822
+ "Pin important messages to keep them easy to find."
823
+ }
824
+ subTitleStyle={styles.emptyStateStyle?.subTitleStyle}
825
+ Icon={
826
+ // Filled, matching the design and the saved screen's bookmark-fill — an empty state
827
+ // is an illustration, not the outline glyph used inline as metadata.
828
+ <Icon
829
+ name='keep-fill'
830
+ color={styles.emptyStateStyle?.iconStyle?.tintColor}
831
+ height={styles.emptyStateStyle?.iconStyle?.height}
832
+ width={styles.emptyStateStyle?.iconStyle?.width}
833
+ />
834
+ }
835
+ />
836
+ ) : state === "error" ? (
837
+ // The house error state, same as the conversation list: error-state illustration,
838
+ // Oops! / went wrong / try again, and a Retry button. A bare sentence in the
839
+ // default text style was the only thing here before, which read as a broken
840
+ // screen rather than a recoverable one.
841
+ <ErrorEmptyView
842
+ testID='PinnedMessages.error'
843
+ containerStyle={styles.errorStateStyle?.containerStyle}
844
+ title={t("OOPS") ?? "Oops!"}
845
+ titleStyle={styles.errorStateStyle?.titleStyle}
846
+ subTitle={t("SOMETHING_WENT_WRONG") ?? "Looks like something went wrong."}
847
+ tertiaryTitle={t("WRONG_TEXT_TRY_AGAIN") ?? "Please try again."}
848
+ subTitleStyle={styles.errorStateStyle?.subTitleStyle}
849
+ Icon={
850
+ <Icon
851
+ name='error-state'
852
+ height={styles.errorStateStyle?.iconStyle?.height}
853
+ width={styles.errorStateStyle?.iconStyle?.width}
854
+ containerStyle={{ marginBottom: styles.errorStateStyle?.iconStyle?.marginBottom }}
855
+ />
856
+ }
857
+ RetryView={<CometChatRetryButton onPress={reload} />}
858
+ />
859
+ ) : (
860
+ <FlatList
861
+ testID='PinnedMessages.list'
862
+ data={messages}
863
+ keyExtractor={item => String(item.getId())}
864
+ renderItem={renderRow}
865
+ onEndReachedThreshold={0.5}
866
+ onEndReached={loadNext}
867
+ onLayout={event => {
868
+ viewportHeight.current = event.nativeEvent.layout.height;
869
+ fillViewport();
870
+ }}
871
+ onContentSizeChange={(_width, height) => {
872
+ contentHeight.current = height;
873
+ fillViewport();
874
+ }}
875
+ />
876
+ )}
877
+
878
+ {/* The message list's own sheet, so the panel's long-press looks and behaves
879
+ identically. Reactions are off — this panel does not wire them. */}
880
+ <MessageOptionsSheet
881
+ bottomSheetRef={sheetRef}
882
+ isOpen={sheetOptions.length > 0 || showInfo}
883
+ showMessageOptions={sheetOptions}
884
+ ExtensionsComponent={null}
885
+ messageInfo={showInfo}
886
+ infoObject={infoObject}
887
+ selectedMessage={selectedMessage}
888
+ hideReactionOption={true}
889
+ templatesMap={templatesMap}
890
+ mergedTheme={theme}
891
+ deleteItem={deleteItem}
892
+ pendingReportRef={pendingReportRef}
893
+ onClose={closeSheet}
894
+ onReactionPress={() => {}}
895
+ onAddReactionPress={() => {}}
896
+ setShowDeleteModal={() => {}}
897
+ setShowReportDialog={() => {}}
898
+ setShowMessageOptions={setSheetOptions}
899
+ setExtensionsComponent={() => {}}
900
+ setMessageInfo={setShowInfo}
901
+ setShowEmojiKeyboard={() => {}}
902
+ />
903
+
904
+ <CometChatConfirmDialog
905
+ titleText={
906
+ confirm?.action === "unpin"
907
+ ? (t("UNPIN_MESSAGE_TITLE") ?? "Unpin Message")
908
+ : (t("UNSAVE_MESSAGE_TITLE") ?? "Unsave Message")
909
+ }
910
+ icon={
911
+ <Icon
912
+ name={confirm?.action === "unpin" ? "keep-off" : "unsave"}
913
+ size={theme.spacing.spacing.s12}
914
+ color={theme.color.error}
915
+ />
916
+ }
917
+ cancelButtonText={t("CANCEL") ?? "Cancel"}
918
+ confirmButtonText={
919
+ confirm?.action === "unpin" ? (t("UNPIN") ?? "Unpin") : (t("UNSAVE") ?? "Unsave")
920
+ }
921
+ messageText={
922
+ confirm?.action === "unpin"
923
+ ? (t("UNPIN_MESSAGE_CONFIRM") ??
924
+ "Do you want to unpin this message from this conversation?")
925
+ : (t("UNSAVE_MESSAGE_CONFIRM") ??
926
+ "Do you want to remove this message from your saved messages?")
927
+ }
928
+ isOpen={confirm != null}
929
+ onCancel={() => setConfirm(null)}
930
+ onConfirm={() => {
931
+ if (confirm?.action === "unpin") runUnpin(confirm.message);
932
+ else if (confirm) runToggleSave(confirm.message, false);
933
+ setConfirm(null);
934
+ }}
935
+ />
936
+
937
+ {ToastElement}
938
+ </View>
939
+ );
940
+ };