@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,871 @@
1
+ /**
2
+ * CometChatSavedMessages — the USER-LEVEL saved messages surface (§6.4).
3
+ *
4
+ * Cross-conversation and private: this is the "star / bookmark" inbox, reached from
5
+ * app chrome (main nav, profile, settings), NOT from a conversation header. On RN it
6
+ * is a full-screen route, not a drawer (§6.9).
7
+ *
8
+ * Renders as a CONVERSATION-STYLE LIST — avatar, source name, preview subtitle,
9
+ * trailing date — not as full message bubbles. That is a deliberate divergence from
10
+ * CometChatPinnedMessages, which does show bubbles: a pinned list is scoped to one
11
+ * conversation where a bubble reads naturally, whereas this list spans every
12
+ * conversation and the question a reader asks first is "where is this from?".
13
+ *
14
+ * Read-only with respect to unread state (§7.7): nothing here calls markAsRead,
15
+ * emits receipts, or touches an unread count.
16
+ *
17
+ * @module CometChatSavedMessages
18
+ */
19
+ import { CometChat } from "@cometchat/chat-sdk-react-native";
20
+ import { CometChatRichTextFormatter } from "../shared/formatters/CometChatRichTextFormatter";
21
+ import { preparePreviewText, stripMarkdown } from "../shared/utils/MarkdownUtils";
22
+ import {
23
+ applyMentionsFormatting,
24
+ getMessagePreviewInternal,
25
+ } from "../shared/utils/MessageUtils";
26
+ import { MessageCategoryConstants } from "../shared/constants/UIKitConstants";
27
+ import React, { JSX, useCallback, useEffect, useMemo, useRef, useState } from "react";
28
+ import {
29
+ FlatList,
30
+ GestureResponderEvent,
31
+ Platform,
32
+ Pressable,
33
+ StyleSheet,
34
+ Text,
35
+ View,
36
+ } from "react-native";
37
+ import { useCompTheme, useTheme } from "../theme/hook";
38
+ import { deepMerge } from "../shared/helper/helperFunctions";
39
+ import { DeepPartial } from "../shared/helper/types";
40
+ import { SavedMessagesStyle } from "./style";
41
+ import { CometChatTheme } from "../theme/type";
42
+ import { Icon } from "../shared/icons/Icon";
43
+ import { IconName } from "../shared/icons/Icon";
44
+ import { CometChatDate } from "../shared/views/CometChatDate";
45
+ import { Skeleton } from "../CometChatConversations/Skeleton";
46
+ import { CometChatListItem } from "../shared/views/CometChatListItem";
47
+ import { CometChatTooltipMenu, MenuItemInterface } from "../shared/views/CometChatTooltipMenu";
48
+ import { ErrorEmptyView } from "../shared/views/ErrorEmptyView/ErrorEmptyView";
49
+ import { CometChatConfirmDialog } from "../shared/views/CometChatConfirmDialog";
50
+ import { CometChatRetryButton } from "../shared/views/CometChatRetryButton/CometChatRetryButton";
51
+ import { useCometChatTranslation } from "../shared/resources/CometChatLocalizeNew";
52
+ import { useToast } from "../shared/helper/useToast";
53
+ import {
54
+ buildSavedMessagesRequest,
55
+ previewFor,
56
+ sourceLabelFor,
57
+ subtitlePrefixNameFor,
58
+ SavedMessageSource,
59
+ } from "../shared/utils/SavedMessagesHelper";
60
+ import {
61
+ carryPinSaveAttrs,
62
+ isMessageGoneError,
63
+ unsaveMessage,
64
+ sameMessageId,
65
+ } from "../shared/utils/PinSaveHelper";
66
+ import { CometChatUIEventHandler } from "../shared/events/CometChatUIEventHandler/CometChatUIEventHandler";
67
+ import { MessageEvents } from "../shared/events/messages";
68
+ import { CometChatTextFormatter } from "../shared/formatters/CometChatTextFormatter";
69
+ import { applyRawFormatters } from "../shared/formatters/applyRawFormatters";
70
+
71
+ /**
72
+ * Module-level rich text formatter — reused across renders (no GC churn), mirroring
73
+ * CometChatConversations. A saved row shows the same preview a conversation row does,
74
+ * so it renders inline formatting rather than stripping it.
75
+ */
76
+ const savedRichTextFormatter = new CometChatRichTextFormatter();
77
+
78
+ export interface CometChatSavedMessagesInterface {
79
+ /** Page size. Defaults to 30; the server caps the whole set at 100. */
80
+ limit?: number;
81
+ /**
82
+ * Your own request builder, for anything `limit` alone cannot express — a search
83
+ * term, a category or type filter, a different page size.
84
+ *
85
+ * `setSavedOnly(true)` is re-asserted on whatever you pass, so a builder that
86
+ * forgets it still returns saved messages rather than ordinary history. Set it
87
+ * anyway to keep the intent readable.
88
+ *
89
+ * Do NOT scope it to a conversation: saved is account-wide, and a uid/guid would
90
+ * turn this cross-conversation list into a per-chat one.
91
+ *
92
+ * The `limit` prop wins: `limit={10}` with a builder that calls `setLimit(50)` pages
93
+ * in tens. Without the prop the builder's own limit is used, and with neither, 30.
94
+ */
95
+ messagesRequestBuilder?: CometChat.MessagesRequestBuilder;
96
+ /** Closes the surface — rendered as the ✕ in the header. */
97
+ onBack?: () => void;
98
+ /**
99
+ * Tapping a row. Receives the message and its resolved source so the host can
100
+ * open that conversation and jump to the message.
101
+ */
102
+ onItemPress?: (message: CometChat.BaseMessage, source: SavedMessageSource | null) => void;
103
+ /**
104
+ * Hide the unsave option in the long-press menu. Named per design doc §6.7,
105
+ * which lists the same four flags for the action sheet — the panel mirrors that
106
+ * vocabulary rather than inventing a shorter one.
107
+ */
108
+ hideUnsaveMessageOption?: boolean;
109
+ /** Replace the whole row body. */
110
+ ItemView?: (message: CometChat.BaseMessage) => JSX.Element;
111
+ /**
112
+ * Text formatters, same array the host passes to CometChatMessageList. Without them a consumer's
113
+ * own wire token is not UI Kit markup yet, so the formatter below has nothing to recognise and
114
+ * the row prints the token verbatim.
115
+ */
116
+ textFormatters?: Array<CometChatTextFormatter>;
117
+ title?: string;
118
+ /** Per-instance style overrides, merged over the theme's savedMessagesStyles. */
119
+ style?: DeepPartial<SavedMessagesStyle>;
120
+ }
121
+
122
+ type ListState = "loading" | "loaded" | "error" | "empty";
123
+
124
+ export const CometChatSavedMessages = (props: CometChatSavedMessagesInterface) => {
125
+ const {
126
+ limit,
127
+ messagesRequestBuilder,
128
+ onBack,
129
+ onItemPress,
130
+ hideUnsaveMessageOption = false,
131
+ ItemView,
132
+ textFormatters,
133
+ title,
134
+ style,
135
+ } = props;
136
+
137
+ const theme = useTheme() as CometChatTheme;
138
+
139
+ // Same inline-code treatment the conversation list gives its subtitle.
140
+ useMemo(() => {
141
+ savedRichTextFormatter.setStyle({
142
+ inlineCodeStyle: { color: theme.color.primary as string },
143
+ inlineCodeContainerStyle: {
144
+ backgroundColor: "rgba(120, 120, 128, 0.22)",
145
+ borderRadius: 4,
146
+ borderWidth: 0.5,
147
+ borderColor: "rgba(120, 120, 128, 0.35)",
148
+ paddingHorizontal: 4,
149
+ paddingVertical: 1,
150
+ },
151
+ });
152
+ }, [theme]);
153
+ const compTheme = useCompTheme();
154
+ const { t } = useCometChatTranslation();
155
+
156
+ /** theme → component-level override → per-instance prop, the kit's usual order. */
157
+ const styles = useMemo(
158
+ () => deepMerge(theme.savedMessagesStyles, compTheme.savedMessagesStyles ?? {}, style ?? {}),
159
+ [theme.savedMessagesStyles, compTheme.savedMessagesStyles, style]
160
+ );
161
+ const { showToast, ToastElement } = useToast();
162
+
163
+ const [messages, setMessagesRaw] = useState<CometChat.BaseMessage[]>([]);
164
+ const [state, setStateRaw] = useState<ListState>("loading");
165
+ const loggedInUser = useRef<CometChat.User | null>(null);
166
+
167
+ /**
168
+ * These panels are full-screen routes, so popping one while a fetch or a post-confirm
169
+ * write is still in flight lands a setState on an unmounted component — the React Native
170
+ * warning, plus work nobody will see. Guarding at the SETTER rather than at each of the
171
+ * async resolvers keeps every existing call site unchanged and cannot be forgotten at a
172
+ * new one.
173
+ */
174
+ const mounted = useRef(true);
175
+ useEffect(() => () => { mounted.current = false; }, []);
176
+ const setMessages: typeof setMessagesRaw = useCallback(
177
+ value => { if (mounted.current) setMessagesRaw(value); },
178
+ []
179
+ );
180
+ const setState: typeof setStateRaw = useCallback(
181
+ value => { if (mounted.current) setStateRaw(value); },
182
+ []
183
+ );
184
+
185
+ /**
186
+ * Long-press menu state. Anchored at the touch point via CometChatTooltipMenu —
187
+ * the SAME affordance the conversation list uses for its Pin/Delete menu, because
188
+ * these rows are conversation rows and should answer a long-press the same way.
189
+ */
190
+ const [menuVisible, setMenuVisible] = useState(false);
191
+ /** The row awaiting unsave confirmation, or null. */
192
+ const [confirmUnsave, setConfirmUnsave] = useState<CometChat.BaseMessage | null>(null);
193
+ const menuAnchor = useRef({ pageX: 0, pageY: 0 });
194
+ const menuTarget = useRef<CometChat.BaseMessage | null>(null);
195
+
196
+ /**
197
+ * The request is single-use and accumulates its own paging state, so it lives in
198
+ * a ref for the lifetime of the screen. Refreshing means building a NEW one.
199
+ *
200
+ * Built lazily below: a useRef ARGUMENT runs on every render and all but the first
201
+ * result is discarded, so the inline form built a request per render.
202
+ */
203
+ const request = useRef<CometChat.MessagesRequest | null>(null);
204
+ const fetching = useRef(false);
205
+ /**
206
+ * The end of a cursor-paged list is an empty page — there is nothing to ask the request
207
+ * for beforehand. Latch it here, or every further scroll-to-end fires a round trip that
208
+ * can only come back empty again.
209
+ */
210
+ const exhausted = useRef(false);
211
+
212
+ if (request.current === null) {
213
+ request.current = buildSavedMessagesRequest(limit, messagesRequestBuilder);
214
+ }
215
+
216
+ const loadNext = useCallback(async () => {
217
+ if (fetching.current || exhausted.current || !request.current) return;
218
+ fetching.current = true;
219
+ try {
220
+ // fetchPrevious(), not fetchNext() — "previous" is older, which is the direction
221
+ // this list scrolls. Same call CometChatMessageList makes to load history.
222
+ const rows = await request.current.fetchPrevious();
223
+ if (rows.length > 0) {
224
+ // Dedupe on append (ENG-38891). A realtime pin/save PREPENDS its row the moment the
225
+ // event lands; the same message then comes back inside a later fetched page, and a
226
+ // plain concat lists it twice — which is how a five-pin cap rendered six rows.
227
+ setMessages(prev => {
228
+ const seen = new Set(prev.map(m => String(m.getId())));
229
+ return [...prev, ...rows.filter(r => !seen.has(String(r.getId())))];
230
+ });
231
+ setState("loaded");
232
+ } else {
233
+ exhausted.current = true;
234
+ setState(prev => (prev === "loading" ? "empty" : prev));
235
+ }
236
+ } catch (e) {
237
+ // Log it. A bare `catch {}` here cost hours once: the list showed a generic error
238
+ // screen with an empty network log, and the actual cause (SET_LIMIT_IS_COMPULSORY,
239
+ // rejected client-side before any request) was unreachable from outside a debugger.
240
+ console.error("CometChatSavedMessages: failed to fetch saved messages", e);
241
+ // An empty first page is "empty", not "error" — only a real rejection is.
242
+ setState(prev => (prev === "loading" ? "error" : prev));
243
+ } finally {
244
+ fetching.current = false;
245
+ }
246
+ }, []);
247
+
248
+ /**
249
+ * Keep loading while the rows do not fill the viewport.
250
+ *
251
+ * onEndReached is the only paging trigger, and it needs a scroll to fire. When the first page
252
+ * is shorter than the screen there is nothing to scroll, so the list stops at page one and the
253
+ * rest is unreachable — verified with limit=2 against 4 pinned messages: `loadNext` ran once,
254
+ * returned 2 rows, and was never called again while the panel sat half empty.
255
+ *
256
+ * The default page size fills a phone screen, which is why this hid; `limit` is a public prop,
257
+ * so any integrator who lowers it hits a permanently incomplete list. loadNext already guards
258
+ * on `fetching`/`exhausted`, so this tops up at most one request at a time and stops on its own.
259
+ */
260
+ const viewportHeight = useRef(0);
261
+ const contentHeight = useRef(0);
262
+ const fillViewport = useCallback(() => {
263
+ if (exhausted.current || fetching.current) return;
264
+ if (viewportHeight.current <= 0 || contentHeight.current <= 0) return;
265
+ if (contentHeight.current < viewportHeight.current) loadNext();
266
+ }, [loadNext]);
267
+
268
+ /**
269
+ * Retry after an error. The request is single-use and has already consumed whatever
270
+ * paging state it got to, so this builds a fresh one rather than re-calling the old —
271
+ * a retried request must start from the top of the list, not from a half-walked cursor.
272
+ */
273
+ const reload = useCallback(() => {
274
+ request.current = buildSavedMessagesRequest(limit, messagesRequestBuilder);
275
+ exhausted.current = false;
276
+ fetching.current = false;
277
+ setMessages([]);
278
+ setState("loading");
279
+ loadNext();
280
+ // messagesRequestBuilder included: without it a retry after the prop changes rebuilds
281
+ // the request from the builder captured at mount.
282
+ }, [limit, messagesRequestBuilder, loadNext]);
283
+
284
+ useEffect(() => {
285
+ CometChat.getLoggedinUser()
286
+ .then(user => {
287
+ loggedInUser.current = user ?? null;
288
+ })
289
+ .catch(() => {
290
+ // A missing logged-in user only costs 1-1 label precision, so carry on.
291
+ loggedInUser.current = null;
292
+ })
293
+ .finally(() => {
294
+ loadNext();
295
+ });
296
+ }, [loadNext]);
297
+
298
+ /**
299
+ * Keep the panel in step with saves made anywhere else — the message list next to it,
300
+ * or this user's other device. Without it the list is a snapshot taken on mount.
301
+ *
302
+ * No conversation filter here, unlike the pinned panel: saved is per-viewer and spans
303
+ * every conversation, so any save of this user's belongs on this screen.
304
+ *
305
+ * Both event families: cc* from the device that performed the action, on* from the
306
+ * socket echo to this user's other devices. Save/unsave is private, which is why the
307
+ * SDK exempts it from the self-session guard. Payload shapes differ, hence the unwrap.
308
+ *
309
+ * Keys written out literally — emitMessageEvent matches on each callback's inferred
310
+ * function name, which an anonymous arrow takes from its property key.
311
+ */
312
+ useEffect(() => {
313
+ const id = "saved-messages-panel";
314
+
315
+ const unwrap = (payload: any): CometChat.BaseMessage | null =>
316
+ payload?.message ?? payload ?? null;
317
+
318
+ const added = (payload: any) => {
319
+ const message = unwrap(payload);
320
+ if (!message) return;
321
+ setMessages(prev => {
322
+ if (prev.some(m => sameMessageId(m.getId(), message.getId()))) return prev;
323
+ return [message, ...prev];
324
+ });
325
+ setState("loaded");
326
+ };
327
+
328
+ const removed = (payload: any) => {
329
+ const message = unwrap(payload);
330
+ if (!message) return;
331
+ setMessages(prev => {
332
+ const next = prev.filter(m => !sameMessageId(m.getId(), message.getId()));
333
+ if (next.length === prev.length) return prev;
334
+ // Only claim empty once the first page has been read, or an event arriving
335
+ // mid-load would replace the spinner with "no saved messages".
336
+ if (next.length === 0 && exhausted.current) setState("empty");
337
+ return next;
338
+ });
339
+ };
340
+
341
+ /**
342
+ * ENG-38177/38181 were filed against the pinned panel; this list has the same shape and
343
+ * therefore the same two defects. An edited saved message must show its new text, and a
344
+ * deleted one must leave — otherwise the row survives its own message.
345
+ *
346
+ * carryPinSaveAttrs is what keeps `savedAt` alive across the edit: the edit response is
347
+ * minimal and omits it (verified on staging 2026-08-14), so a straight replace would
348
+ * strip the attribute this whole list is filtered on.
349
+ */
350
+ const edited = (payload: any) => {
351
+ const message = unwrap(payload);
352
+ if (!message) return;
353
+ setMessages(prev => {
354
+ const index = prev.findIndex(m => sameMessageId(m.getId(), message.getId()));
355
+ if (index === -1) return prev;
356
+ const next = [...prev];
357
+ next[index] = carryPinSaveAttrs(message, prev[index]);
358
+ return next;
359
+ });
360
+ };
361
+
362
+ const deleted = (payload: any) => removed(payload);
363
+
364
+ CometChatUIEventHandler.addMessageListener(id, {
365
+ ccMessageSaved: (payload: any) => added(payload),
366
+ onMessageSaved: (payload: any) => added(payload),
367
+ ccMessageUnsaved: (payload: any) => removed(payload),
368
+ onMessageUnsaved: (payload: any) => removed(payload),
369
+ ccMessageEdited: (payload: any) => edited(payload),
370
+ onMessageEdited: (payload: any) => edited(payload),
371
+ ccMessageDeleted: (payload: any) => deleted(payload),
372
+ onMessageDeleted: (payload: any) => deleted(payload),
373
+ });
374
+
375
+ return () => CometChatUIEventHandler.removeMessageListener(id);
376
+ }, []);
377
+
378
+ /**
379
+ * Row chrome from the CONVERSATION list's own tokens, not this screen's.
380
+ *
381
+ * This surface is a conversation list in every visual respect — avatar, name,
382
+ * preview, date — so it must not grow a parallel set of row styles that drift.
383
+ * `containerStyle` in particular carries the `flexDirection: "row"` that makes a
384
+ * row a row; without it CometChatListItem stacks avatar, title and date
385
+ * vertically.
386
+ */
387
+ const itemStyle = theme.conversationStyles?.itemStyle;
388
+
389
+ const closeMenu = useCallback(() => {
390
+ setMenuVisible(false);
391
+ menuTarget.current = null;
392
+ }, []);
393
+
394
+ const removeRow = (messageId: number) => {
395
+ setMessages(prev => {
396
+ const next = prev.filter(m => !sameMessageId(m.getId(), messageId));
397
+ if (next.length === 0) setState("empty");
398
+ return next;
399
+ });
400
+ };
401
+
402
+ /**
403
+ * Unsave ASKS first (Jitvar, 2026-08-04): the removing half of each pair confirms,
404
+ * everywhere it appears. This panel used to act immediately — the message list already
405
+ * confirmed, so the same action asked or didn't depending on which screen you were on.
406
+ */
407
+ const onUnsave = (message: CometChat.BaseMessage) => {
408
+ setConfirmUnsave(message);
409
+ };
410
+
411
+ const runUnsave = (message: CometChat.BaseMessage) => {
412
+ const id = message.getId();
413
+ // Optimistic once confirmed: re-adding on failure is trivially correct because the
414
+ // row object is still in hand — EXCEPT when the message is gone, see below.
415
+ removeRow(id);
416
+ unsaveMessage(id)
417
+ .then((updated) => {
418
+ // Same omission as the pinned panel (ENG-38884): this list writes to the server and
419
+ // drops its own row, but the message's bubble in its conversation holds a separate
420
+ // copy and kept showing the bookmark. The bus is the only channel between them.
421
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageUnsaved, {
422
+ message: updated ?? message,
423
+ });
424
+ showToast(t("MESSAGE_UNSAVED") ?? "Message unsaved");
425
+ })
426
+ .catch((error: any) => {
427
+ // A message that no longer exists must STAY removed, or the user taps Unsave
428
+ // forever on something the server will never accept. This panel is especially
429
+ // exposed: it spans every conversation, so clearing ANY chat can strand rows here.
430
+ if (isMessageGoneError(error)) {
431
+ showToast(t("MESSAGE_NO_LONGER_AVAILABLE") ?? "This message is no longer available.");
432
+ return;
433
+ }
434
+ setMessages(prev => [message, ...prev]);
435
+ setState("loaded");
436
+ showToast(t("PIN_SAVE_GENERIC_ERROR") ?? "Something went wrong. Please try again.");
437
+ });
438
+ };
439
+
440
+ /**
441
+ * The long-press menu: Unsave, and nothing else.
442
+ *
443
+ * A saved row is a pointer to a message, not the message itself, so the only
444
+ * action that belongs on it is the one that removes it from THIS list. Copy,
445
+ * share, info and unpin all act on the message and belong where the message
446
+ * actually is — its conversation, or the pinned panel.
447
+ */
448
+ const menuItemsFor = (message: CometChat.BaseMessage): MenuItemInterface[] => {
449
+ if (hideUnsaveMessageOption) return [];
450
+ return [
451
+ {
452
+ text: t("UNSAVE_MESSAGE") ?? "Unsave message",
453
+ onPress: () => {
454
+ closeMenu();
455
+ onUnsave(message);
456
+ },
457
+ icon: (
458
+ // Same unsave glyph as the message action sheet — one action, one icon everywhere.
459
+ <Icon
460
+ name='unsave'
461
+ color={styles.menuIconStyle?.tintColor}
462
+ height={styles.menuIconStyle?.height}
463
+ width={styles.menuIconStyle?.width}
464
+ />
465
+ ),
466
+ },
467
+ ];
468
+ };
469
+
470
+ const onLongPressRow = (message: CometChat.BaseMessage, e?: GestureResponderEvent) => {
471
+ if (!e || !("nativeEvent" in e)) return;
472
+ menuTarget.current = message;
473
+ menuAnchor.current = { pageX: e.nativeEvent.pageX, pageY: e.nativeEvent.pageY };
474
+ setMenuVisible(true);
475
+ };
476
+
477
+ /**
478
+ * Subtitle: an optional author prefix, then the preview. Mirrors the conversation
479
+ * list's vocabulary so a saved row reads the same as the chat it came from.
480
+ *
481
+ * The prefix rule lives in the helper — it is the only thing distinguishing an
482
+ * outgoing 1-1 row from an incoming one, since this list shows no receipts and both
483
+ * directions resolve to the same avatar and title.
484
+ */
485
+ const renderSubtitle = (message: CometChat.BaseMessage) => {
486
+ const preview = previewFor(message);
487
+ const prefixName = subtitlePrefixNameFor(
488
+ message,
489
+ loggedInUser.current?.getUid() ?? null,
490
+ t("YOU") ?? "You"
491
+ );
492
+ const prefix = prefixName ? `${prefixName}: ` : "";
493
+
494
+ const rawLabel = preview.text ?? (preview.labelKey ? (t(preview.labelKey) ?? "") : "");
495
+
496
+ // Render inline formatting rather than printing the wire format. preparePreviewText
497
+ // reduces a multi-line or block message to one line — the formatter must not meet
498
+ // block-level markers — and reports which KIND of block it found. The four cases get
499
+ // the same treatment the conversation list gives them, so a saved row reads like the
500
+ // chat it came from.
501
+ //
502
+ // `prepared.text` is EMPTY for a code block: its content arrives in
503
+ // `codeBlockFirstLine`. Reading only `.text` rendered an empty subtitle for any
504
+ // message that was just a code block.
505
+ // The consumer's own token becomes UI Kit markup BEFORE any of the preparation below: run it
506
+ // after preparePreviewText or the rich formatter and the token has already been flattened into
507
+ // plain characters, with nothing left to colour.
508
+ const prepared = preparePreviewText(applyRawFormatters(rawLabel, textFormatters));
509
+ // The conversation list's pipeline, step for step, so the same message reads the
510
+ // same in Chats and in Saved Messages:
511
+ // text message -> rich formatter (colour, bold, italic, inline code)
512
+ // anything else -> stripMarkdown, as markers would render as literal characters
513
+ // then -> mentions resolved from "@uid" to the user's name
514
+ const format = (value: string): string | JSX.Element => {
515
+ const trimmed = value.trim();
516
+ const isPlainTextMessage =
517
+ message instanceof CometChat.TextMessage &&
518
+ message.getCategory() === MessageCategoryConstants.message;
519
+
520
+ let content: string | JSX.Element = isPlainTextMessage
521
+ ? (savedRichTextFormatter.getFormattedText(trimmed) ?? trimmed)
522
+ : stripMarkdown(trimmed);
523
+
524
+ content = applyMentionsFormatting(message, content, trimmed, undefined);
525
+ return content;
526
+ };
527
+
528
+ // A message that leads with a URL previews as a link chip rather than the raw
529
+ // address, matching the conversation list. Checked on the first 50 characters, as
530
+ // the list does, so a link mentioned late in a long message is not treated as one.
531
+ const leadsWithLink =
532
+ message instanceof CometChat.TextMessage &&
533
+ message.getCategory() === MessageCategoryConstants.message &&
534
+ (() => {
535
+ const raw = typeof message.getText === "function" ? message.getText() : undefined;
536
+ return typeof raw === "string" && !!raw.slice(0, 50).match(/https?:\/\//);
537
+ })();
538
+
539
+ // Whether `label` already brings its own wrapper element. The block branches below return a
540
+ // <View>, and a <View> nested inside a <Text> lays out on iOS but COLLAPSES on Android — the
541
+ // saved row showed a bare "…" for every code block and blockquote. CometChatConversations
542
+ // renders its equivalent bare for exactly this reason.
543
+ let labelIsSelfWrapped = false;
544
+ let label: string | JSX.Element;
545
+ if (leadsWithLink) {
546
+ label = getMessagePreviewInternal("link-fill", t("LINK") ?? "Link", { theme });
547
+ labelIsSelfWrapped = true;
548
+ } else if (prepared.codeBlockFirstLine !== null) {
549
+ label = (
550
+ <View style={localStyles.codeBlockRow}>
551
+ <View
552
+ style={[
553
+ localStyles.codeBlockBadge,
554
+ {
555
+ backgroundColor: (theme?.color?.background2 as string) || "#FAFAFA",
556
+ borderColor: (theme?.color?.borderDefault as string) || "#E8E8E8",
557
+ },
558
+ ]}
559
+ >
560
+ <Text
561
+ numberOfLines={1}
562
+ ellipsizeMode='tail'
563
+ style={[
564
+ localStyles.codeBlockText,
565
+ { color: (theme?.color?.textPrimary as string) || "#141414" },
566
+ ]}
567
+ >
568
+ {prepared.codeBlockFirstLine + ".."}
569
+ </Text>
570
+ </View>
571
+ </View>
572
+ );
573
+ labelIsSelfWrapped = true;
574
+ } else if (prepared.isBlockquote) {
575
+ label = (
576
+ <View style={localStyles.blockquoteRow}>
577
+ <View
578
+ style={[
579
+ localStyles.blockquoteBar,
580
+ { backgroundColor: theme?.color?.primary as string },
581
+ ]}
582
+ />
583
+ <Text
584
+ numberOfLines={1}
585
+ ellipsizeMode='tail'
586
+ style={[itemStyle?.subtitleStyle, localStyles.blockquoteText]}
587
+ >
588
+ {format(prepared.text)}
589
+ </Text>
590
+ </View>
591
+ );
592
+ labelIsSelfWrapped = true;
593
+ } else if (prepared.listPrefix) {
594
+ label = (
595
+ <Text numberOfLines={1} ellipsizeMode='tail' style={itemStyle?.subtitleStyle}>
596
+ {prepared.listPrefix}
597
+ {format(prepared.text)}
598
+ </Text>
599
+ );
600
+ labelIsSelfWrapped = true;
601
+ } else {
602
+ label = format(prepared.text);
603
+ }
604
+
605
+ return (
606
+ <View style={localStyles.subtitleRow}>
607
+ {prefix ? (
608
+ <Text
609
+ numberOfLines={1}
610
+ style={itemStyle?.subtitleStyle}
611
+ >
612
+ {prefix}
613
+ </Text>
614
+ ) : null}
615
+ {preview.icon ? (
616
+ <Icon
617
+ name={preview.icon as IconName}
618
+ color={styles.previewIconStyle?.tintColor}
619
+ height={styles.previewIconStyle?.height}
620
+ width={styles.previewIconStyle?.width}
621
+ containerStyle={styles.previewIconContainerStyle}
622
+ />
623
+ ) : null}
624
+ {labelIsSelfWrapped ? (
625
+ label
626
+ ) : (
627
+ <Text
628
+ numberOfLines={1}
629
+ ellipsizeMode='tail'
630
+ style={[itemStyle?.subtitleStyle, localStyles.subtitleText]}
631
+ >
632
+ {label}
633
+ </Text>
634
+ )}
635
+ </View>
636
+ );
637
+ };
638
+
639
+ const renderRow = ({ item, index }: { item: CometChat.BaseMessage; index: number }) => {
640
+ if (ItemView) return ItemView(item);
641
+
642
+ const source = sourceLabelFor(item, loggedInUser.current?.getUid() ?? null);
643
+ const name = source?.name ?? item.getSender()?.getName() ?? "";
644
+ const avatar = source?.avatar ?? item.getSender()?.getAvatar();
645
+
646
+ return (
647
+ <CometChatListItem
648
+ testID={`SavedMessages.row-${index}`}
649
+ id={item.getId()}
650
+ // A row whose source cannot be derived still renders (design doc §6.4 rule
651
+ // one) — it just falls back to the sender for identity.
652
+ avatarURL={avatar ? { uri: avatar } : undefined}
653
+ avatarName={name}
654
+ title={name}
655
+ // Row chrome comes from conversationStyles, the SAME source the conversation
656
+ // list uses, so a saved row is visually identical to the chat it came from.
657
+ // Without these the item has no flexDirection and the avatar, title and date
658
+ // stack vertically instead of forming a row.
659
+ containerStyle={itemStyle?.containerStyle}
660
+ titleStyle={itemStyle?.titleStyle}
661
+ avatarStyle={itemStyle?.avatarStyle}
662
+ headViewContainerStyle={localStyles.headViewContainer}
663
+ SubtitleView={renderSubtitle(item)}
664
+ // Date only. NO pin indicator: pinned is a property of a message within its
665
+ // conversation, and this list is not a conversation — surfacing it here just
666
+ // adds a signal the reader cannot act on and did not ask for. The pinned
667
+ // panel is where pin state belongs.
668
+ TrailingView={
669
+ <CometChatDate
670
+ timeStamp={item.getSentAt() * 1000}
671
+ pattern='conversationDate'
672
+ style={itemStyle?.dateStyle}
673
+ />
674
+ }
675
+ onPress={() => onItemPress?.(item, source)}
676
+ onLongPress={(_id: string | number, e: GestureResponderEvent) => onLongPressRow(item, e)}
677
+ />
678
+ );
679
+ };
680
+
681
+ return (
682
+ <View style={styles.containerStyle}>
683
+ {/* Back arrow LEADING the title, matching Group Info / User Info. This is a pushed
684
+ full-screen route, not a modal, so a leading back is the right affordance — a
685
+ trailing ✕ read as "dismiss a sheet". */}
686
+ <View style={styles.headerContainerStyle}>
687
+ {onBack ? (
688
+ <Pressable
689
+ testID='SavedMessages.back'
690
+ onPress={onBack}
691
+ accessibilityRole='button'
692
+ accessibilityLabel={t("BACK") ?? "Back"}
693
+ hitSlop={8}
694
+ >
695
+ <Icon
696
+ name='arrow-back'
697
+ icon={styles.closeButtonIcon}
698
+ color={styles.closeButtonIconStyle?.tintColor}
699
+ height={styles.closeButtonIconStyle?.height}
700
+ width={styles.closeButtonIconStyle?.width}
701
+ />
702
+ </Pressable>
703
+ ) : null}
704
+ <Text style={styles.titleStyle}>
705
+ {title ?? (t("SAVED_MESSAGES") ?? "Saved Messages")}
706
+ </Text>
707
+ </View>
708
+
709
+ {state === "loading" ? (
710
+ // The CONVERSATION skeleton, not a bespoke one: these rows are conversation
711
+ // rows, so the placeholder that matches them already exists and stays in step
712
+ // with them for free.
713
+ <Skeleton />
714
+ ) : state === "empty" ? (
715
+ <ErrorEmptyView
716
+ testID='SavedMessages.empty'
717
+ // ErrorEmptyView is an unstyled shell — it renders a bare View with whatever
718
+ // containerStyle it is handed. Without these three the block sat top-left in the
719
+ // default text style instead of centred in the space the list would have filled.
720
+ containerStyle={styles.emptyStateStyle?.containerStyle}
721
+ title={t("NO_SAVED_MESSAGES") ?? "No saved messages yet"}
722
+ titleStyle={styles.emptyStateStyle?.titleStyle}
723
+ subTitle={
724
+ t("NO_SAVED_MESSAGES_SUBTITLE") ??
725
+ "Save messages to keep them handy whenever you need them."
726
+ }
727
+ subTitleStyle={styles.emptyStateStyle?.subTitleStyle}
728
+ Icon={
729
+ <Icon
730
+ name='bookmark-fill'
731
+ color={styles.emptyStateStyle?.iconStyle?.tintColor}
732
+ height={styles.emptyStateStyle?.iconStyle?.height}
733
+ width={styles.emptyStateStyle?.iconStyle?.width}
734
+ />
735
+ }
736
+ />
737
+ ) : state === "error" ? (
738
+ // The house error state, same as the conversation list: error-state illustration,
739
+ // Oops! / went wrong / try again, and a Retry button. A bare sentence in the
740
+ // default text style was the only thing here before, which read as a broken
741
+ // screen rather than a recoverable one.
742
+ <ErrorEmptyView
743
+ testID='SavedMessages.error'
744
+ containerStyle={styles.errorStateStyle?.containerStyle}
745
+ title={t("OOPS") ?? "Oops!"}
746
+ titleStyle={styles.errorStateStyle?.titleStyle}
747
+ subTitle={t("SOMETHING_WENT_WRONG") ?? "Looks like something went wrong."}
748
+ tertiaryTitle={t("WRONG_TEXT_TRY_AGAIN") ?? "Please try again."}
749
+ subTitleStyle={styles.errorStateStyle?.subTitleStyle}
750
+ Icon={
751
+ <Icon
752
+ name='error-state'
753
+ height={styles.errorStateStyle?.iconStyle?.height}
754
+ width={styles.errorStateStyle?.iconStyle?.width}
755
+ containerStyle={{ marginBottom: styles.errorStateStyle?.iconStyle?.marginBottom }}
756
+ />
757
+ }
758
+ RetryView={<CometChatRetryButton onPress={reload} />}
759
+ />
760
+ ) : (
761
+ <FlatList
762
+ testID='SavedMessages.list'
763
+ data={messages}
764
+ keyExtractor={item => String(item.getId())}
765
+ renderItem={renderRow}
766
+ onEndReachedThreshold={0.5}
767
+ onEndReached={loadNext}
768
+ onLayout={event => {
769
+ viewportHeight.current = event.nativeEvent.layout.height;
770
+ fillViewport();
771
+ }}
772
+ onContentSizeChange={(_width, height) => {
773
+ contentHeight.current = height;
774
+ fillViewport();
775
+ }}
776
+ />
777
+ )}
778
+
779
+ <CometChatConfirmDialog
780
+ titleText={t("UNSAVE_MESSAGE_TITLE") ?? "Unsave Message"}
781
+ icon={<Icon name='unsave' size={theme.spacing.spacing.s12} color={theme.color.error} />}
782
+ cancelButtonText={t("CANCEL") ?? "Cancel"}
783
+ confirmButtonText={t("UNSAVE") ?? "Unsave"}
784
+ messageText={
785
+ t("UNSAVE_MESSAGE_CONFIRM") ??
786
+ "Do you want to remove this message from your saved messages?"
787
+ }
788
+ isOpen={confirmUnsave != null}
789
+ onCancel={() => setConfirmUnsave(null)}
790
+ onConfirm={() => {
791
+ if (confirmUnsave) runUnsave(confirmUnsave);
792
+ setConfirmUnsave(null);
793
+ }}
794
+ />
795
+
796
+ {/* The conversation list's own long-press affordance, anchored at the touch
797
+ point — the same component and the same shape as its Pin/Delete menu. */}
798
+ <CometChatTooltipMenu
799
+ visible={menuVisible}
800
+ onClose={closeMenu}
801
+ event={{ nativeEvent: menuAnchor.current }}
802
+ menuItems={menuTarget.current ? menuItemsFor(menuTarget.current) : []}
803
+ />
804
+
805
+ {ToastElement}
806
+ </View>
807
+ );
808
+ };
809
+
810
+ /**
811
+ * Static layout only — nothing here depends on the theme. Anything theme-derived
812
+ * lives in ./style.ts (or conversationStyles, for the row chrome) and is merged in.
813
+ */
814
+ const localStyles = StyleSheet.create({
815
+ // Block-preview styling, matching CometChatConversations so a saved row and a
816
+ // conversation row render the same message identically.
817
+ codeBlockRow: {
818
+ flexDirection: "row",
819
+ alignItems: "center",
820
+ flexShrink: 2,
821
+ },
822
+ codeBlockBadge: {
823
+ borderRadius: 4,
824
+ borderWidth: 1,
825
+ paddingHorizontal: 6,
826
+ paddingVertical: 2,
827
+ flexShrink: 1,
828
+ },
829
+ codeBlockText: {
830
+ fontFamily: Platform.OS === "ios" ? "Menlo" : "monospace",
831
+ fontSize: 11,
832
+ },
833
+ blockquoteRow: {
834
+ flexDirection: "row",
835
+ alignItems: "stretch",
836
+ backgroundColor: "rgba(104, 81, 214, 0.08)",
837
+ borderRadius: 6,
838
+ flexShrink: 2,
839
+ minHeight: 22,
840
+ paddingVertical: 1,
841
+ },
842
+ blockquoteBar: {
843
+ width: 3,
844
+ borderRadius: 1.5,
845
+ marginVertical: 3,
846
+ marginLeft: 4,
847
+ },
848
+ blockquoteText: {
849
+ flex: 1,
850
+ paddingHorizontal: 5,
851
+ lineHeight: 18,
852
+ },
853
+ subtitleRow: {
854
+ flexDirection: "row",
855
+ alignItems: "center",
856
+ flexShrink: 1,
857
+ // flex:1 so the row actually FILLS the list item's subtitle slot. Without it the row is
858
+ // content-sized, and the block children inside (the code-block badge, the blockquote bar +
859
+ // text) size from a Text whose `flex: 1` gives it a flex-basis of 0 — contributing nothing to
860
+ // the content width. On Android that collapses to zero and the row renders a bare "…".
861
+ // CometChatConversations avoids this by returning a FRAGMENT, so its children sit directly in
862
+ // the list item's subtitle container rather than inside an extra content-sized View.
863
+ flex: 1,
864
+ },
865
+ subtitleText: {
866
+ flexShrink: 1,
867
+ },
868
+ headViewContainer: {
869
+ marginHorizontal: 9,
870
+ },
871
+ });