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

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 (104) hide show
  1. package/android/.gradle/7.4/checksums/checksums.lock +0 -0
  2. package/android/.gradle/7.4/fileHashes/fileHashes.lock +0 -0
  3. package/android/build.gradle +23 -89
  4. package/android/gradle.properties +5 -5
  5. package/android/src/main/java/com/reactnativecometchatuikit/CometChatSoundModule.java +5 -1
  6. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +52 -0
  7. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +37 -4
  8. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorViewManager.kt +9 -1
  9. package/ios/FileManager.m +77 -3
  10. package/ios/RichTextEditorView.swift +52 -1
  11. package/ios/RichTextEditorViewManager.m +1 -0
  12. package/ios/RichTextEditorViewManager.swift +8 -0
  13. package/package.json +8 -5
  14. package/react-native-cometchat-ui-kit.podspec +5 -19
  15. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +69 -36
  16. package/src/CometChatConversations/CometChatConversations.tsx +12 -1
  17. package/src/CometChatGroupMembers/CometChatGroupMembers.tsx +2 -2
  18. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +50 -31
  19. package/src/CometChatMessageInformation/CometChatMessageInformation.tsx +10 -1
  20. package/src/CometChatMessageList/CometChatMessageList.tsx +24 -19
  21. package/src/CometChatMessageList/components/MessageOptionsSheet.tsx +7 -8
  22. package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +43 -19
  23. package/src/CometChatRichTextEditor/index.tsx +6 -1
  24. package/src/CometChatRichTextEditor/types.ts +2 -0
  25. package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +251 -14
  26. package/src/CometChatSearch/CometChatSearch.tsx +39 -11
  27. package/src/calls/CometChatOngoingCall/CometChatOngoingCall.tsx +56 -17
  28. package/src/calls/CometChatOutgoingCall/CometChatOutgoingCall.tsx +12 -9
  29. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +13 -10
  30. package/src/extensions/LinkPreview/LinkPreviewExtensionDecorator.tsx +34 -27
  31. package/src/extensions/Polls/Polls.tsx +7 -7
  32. package/src/extensions/Polls/PollsBubble.tsx +2 -2
  33. package/src/globals.d.ts +6 -0
  34. package/src/shared/CometChatUiKit/CometChatUIKit.ts +2 -1
  35. package/src/shared/constants/UIKitConstants.ts +3 -17
  36. package/src/shared/constants/textPatterns.ts +45 -0
  37. package/src/shared/events/CometChatUIEventHandler/CometChatUIEventHandler.ts +25 -259
  38. package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +22 -11
  39. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +56 -32
  40. package/src/shared/formatters/CometChatTextFormatter.ts +22 -0
  41. package/src/shared/formatters/CometChatUrlsFormatter/index.tsx +8 -0
  42. package/src/shared/formatters/applyRawFormatters.ts +31 -0
  43. package/src/shared/formatters/codeElements.ts +21 -0
  44. package/src/shared/framework/MessageDataSource.tsx +14 -8
  45. package/src/shared/helper/types/index.ts +5 -0
  46. package/src/shared/libs/ImageZoom/ReactNativeZoomableView.tsx +4 -4
  47. package/src/shared/libs/ImageZoom/types/index.ts +2 -0
  48. package/src/shared/resources/CometChatLocalizeNew/CometChatI18nProvider.tsx +15 -30
  49. package/src/shared/resources/CometChatLocalizeNew/CometChatLocalizationHelper.ts +138 -19
  50. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +74 -1
  51. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +0 -1
  52. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +54 -1
  53. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +54 -1
  54. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +54 -1
  55. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +54 -1
  56. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +54 -1
  57. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +54 -1
  58. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +54 -1
  59. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +54 -1
  60. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +54 -1
  61. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +54 -1
  62. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +54 -1
  63. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +54 -1
  64. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +54 -1
  65. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +54 -1
  66. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +54 -1
  67. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +54 -1
  68. package/src/shared/resources/CometChatSoundManager/sound.js +2 -3
  69. package/src/shared/services/UploadQueueService.ts +7 -0
  70. package/src/shared/utils/CometChatMessageHelper/index.ts +3 -0
  71. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +11 -0
  72. package/src/shared/utils/MarkdownUtils.ts +42 -5
  73. package/src/shared/utils/MessageUtils.tsx +7 -5
  74. package/src/shared/utils/PinnedMessagesHelper.ts +65 -0
  75. package/src/shared/utils/SavedMessagesHelper.ts +42 -6
  76. package/src/shared/utils/__testUtils__/messagesRequestBuilderMock.ts +37 -0
  77. package/src/shared/utils/cloneRequestBuilder.ts +25 -0
  78. package/src/shared/utils/groupMemberAddedRows.ts +28 -0
  79. package/src/shared/utils/linkPreviewSelection.ts +109 -0
  80. package/src/shared/utils/mentionTokens.ts +77 -0
  81. package/src/shared/utils/runAfterInteractions.ts +26 -0
  82. package/src/shared/utils/stripRichText.ts +2 -1
  83. package/src/shared/utils/tapGesture.ts +23 -0
  84. package/src/shared/utils/videoThumbnail.ts +74 -0
  85. package/src/shared/views/ClipboardPasteHandler/ClipboardPasteHandler.ts +15 -4
  86. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTile.tsx +21 -13
  87. package/src/shared/views/CometChatAudioBubble/CometChatAudioBubble.tsx +13 -15
  88. package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +5 -0
  89. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +4 -1
  90. package/src/shared/views/CometChatCaptionText/CometChatCaptionText.tsx +8 -1
  91. package/src/shared/views/CometChatEmojiKeyboard/CometChatEmojiKeyboard.tsx +1 -1
  92. package/src/shared/views/CometChatFileBubble/CometChatFileBubble.tsx +2 -1
  93. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +7 -1
  94. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +8 -26
  95. package/src/shared/views/CometChatInlineAudioRecorder/useAudioRecorder.ts +4 -2
  96. package/src/shared/views/CometChatList/Header.tsx +9 -3
  97. package/src/shared/views/CometChatMediaRecorder/CometChatAudioPreview/CometChatAudioPreview.tsx +2 -1
  98. package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +28 -8
  99. package/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx +3 -4
  100. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +36 -4
  101. package/src/shared/views/CometChatVideoBubble/CometChatVideoBubble.tsx +2 -1
  102. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +62 -30
  103. package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +5 -0
  104. package/src/CometChatMessageList/MANUAL_TEST_CASES.md +0 -154
@@ -11,6 +11,7 @@
11
11
  * @module SavedMessagesHelper
12
12
  */
13
13
  import { CometChat } from "@cometchat/chat-sdk-react-native";
14
+ import { cloneRequestBuilder } from "./cloneRequestBuilder";
14
15
 
15
16
  /** What a saved row needs to render its "where did this come from" line. */
16
17
  export interface SavedMessageSource {
@@ -100,6 +101,11 @@ export interface SavedMessagePreview {
100
101
  * The subtitle content for a saved row. Never throws; an unrecognised type falls
101
102
  * back to the generic document glyph rather than rendering an empty line.
102
103
  */
104
+ /**
105
+ * Returns the preview's RAW text — inline formatting included. The component renders
106
+ * it through CometChatRichTextFormatter, the same way the conversation list does, so
107
+ * a coloured message reads coloured in the row rather than as `<color=#e11d48>`.
108
+ */
103
109
  export const previewFor = (message?: CometChat.BaseMessage | null): SavedMessagePreview => {
104
110
  const empty: SavedMessagePreview = { icon: "description-fill", labelKey: null, text: null };
105
111
  try {
@@ -220,12 +226,42 @@ export const sourceLabelFor = (
220
226
  * Single-use by design — build a new one to refresh. The server caps the whole set
221
227
  * at 100.
222
228
  */
223
- export const buildSavedMessagesRequest = (limit?: number) => {
224
- const builder = new CometChat.MessagesRequestBuilder().setSavedOnly(true);
225
- // ALWAYS set. The SDK has no default: MessagesRequestBuilder.limit stays undefined
226
- // unless setLimit() is called, and makeAPICall() then rejects with
229
+ export const buildSavedMessagesRequest = (
230
+ limit?: number,
231
+ messagesRequestBuilder?: CometChat.MessagesRequestBuilder
232
+ ) => {
233
+ // A COPY of the integrator's builder, never their object. They may hand the same
234
+ // instance to CometChatPinnedMessages too, and the invariants below are contradictory
235
+ // between the two panels — mutating in place would make whichever built second
236
+ // corrupt the first. See cloneRequestBuilder for why the copy is prototype-preserving.
237
+ const builder = messagesRequestBuilder
238
+ ? cloneRequestBuilder(messagesRequestBuilder)
239
+ : new CometChat.MessagesRequestBuilder();
240
+
241
+ // The full invariant, not just half of it. setSavedOnly alone is not enough: a builder
242
+ // carrying pinnedOnly=true makes the SDK reject the request with
243
+ // PINNED_AND_SAVED_BOTH_SET before any network call, and the panel shows its error
244
+ // state instead of the saved list.
245
+ builder.setSavedOnly(true);
246
+ builder.setPinnedOnly(false);
247
+
248
+ // ALWAYS set, on every path. The SDK has no default: MessagesRequestBuilder.limit
249
+ // stays undefined unless setLimit() is called, and makeAPICall() then rejects with
227
250
  // SET_LIMIT_IS_COMPULSORY *before* any request goes out — an error screen with an
228
- // empty network log. 30 matches the SDK's own DEFAULT_VALUES.MSGS_LIMIT.
229
- builder.setLimit(limit ?? 30);
251
+ // empty network log. So a passed-in builder cannot be trusted to have set one.
252
+ // Precedence: the `limit` argument, else the builder's own, else 30 (the SDK's
253
+ // DEFAULT_VALUES.MSGS_LIMIT).
254
+ const builderLimit = (builder as unknown as { limit?: number }).limit;
255
+ builder.setLimit(limit ?? builderLimit ?? 30);
256
+
257
+ // Deliberately NO uid/guid: `saved=1` is account-wide, and scoping it to one
258
+ // conversation would turn this cross-conversation inbox into a per-chat list. The
259
+ // JSDoc asks callers not to set them; this enforces it, because a builder shared with
260
+ // the pinned panel arrives already carrying one. Cleared on our copy, so the caller's
261
+ // own builder keeps whatever scope they gave it. There is no setter that unsets these.
262
+ const scope = builder as unknown as { uid?: string; guid?: string };
263
+ scope.uid = undefined;
264
+ scope.guid = undefined;
265
+
230
266
  return builder.build();
231
267
  };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The SDK stub both request-builder helpers test against.
3
+ *
4
+ * build() MUTATES, like the real SDK 4.1.0 — it folds `category` into `categories`.
5
+ * That line is the point of the stub: a kinder mock let a shallow clone through,
6
+ * because the copy shared the caller's array and the push landed on THEIR builder.
7
+ */
8
+ export const messagesRequestBuilderMock = () => ({
9
+ CometChat: {
10
+ MessagesRequestBuilder: class {
11
+ limit?: number;
12
+ savedOnly?: boolean;
13
+ pinnedOnly?: boolean;
14
+ uid?: string;
15
+ guid?: string;
16
+ category?: string;
17
+ categories?: string[];
18
+ setLimit(l: number) { this.limit = l; return this; }
19
+ setSavedOnly(v: boolean) { this.savedOnly = v; return this; }
20
+ setPinnedOnly(v: boolean) { this.pinnedOnly = v; return this; }
21
+ setUID(u: string) { this.uid = u; return this; }
22
+ setGUID(g: string) { this.guid = g; return this; }
23
+ setCategory(c: string) { this.category = c; return this; }
24
+ setCategories(c: string[]) { this.categories = c; return this; }
25
+ build() {
26
+ if (this.category && this.categories) this.categories.push(this.category);
27
+ return {
28
+ __limit: this.limit,
29
+ __savedOnly: this.savedOnly,
30
+ __pinnedOnly: this.pinnedOnly,
31
+ __uid: this.uid,
32
+ __guid: this.guid,
33
+ };
34
+ }
35
+ },
36
+ },
37
+ });
@@ -0,0 +1,25 @@
1
+ import { CometChat } from "@cometchat/chat-sdk-react-native";
2
+
3
+ /**
4
+ * A copy of an integrator's request builder, so a panel can assert its own invariants
5
+ * without writing to the caller's object. See PinnedMessagesHelper for why that matters.
6
+ *
7
+ * Prototype-preserving, so the copy keeps its methods — `{ ...builder }` would not.
8
+ *
9
+ * Arrays are re-pointed, not shared. Every SETTER replaces its array, so sharing looks
10
+ * safe — but `build()` is not a setter and it mutates: SDK 4.1.0 runs
11
+ * `this.categories.push(this.category)` and the same for types. A shallow copy therefore
12
+ * grows the CALLER's array once per build.
13
+ *
14
+ * Dependency-free on purpose: CommonUtils.clone drags the constants barrel (and its
15
+ * CometChat.CALL_STATUS read) into a leaf helper and breaks every narrow SDK mock.
16
+ */
17
+ export const cloneRequestBuilder = (
18
+ builder: CometChat.MessagesRequestBuilder
19
+ ): CometChat.MessagesRequestBuilder => {
20
+ const copy = Object.assign(Object.create(Object.getPrototypeOf(builder)), builder);
21
+ for (const [key, value] of Object.entries(copy)) {
22
+ if (Array.isArray(value)) (copy as unknown as Record<string, unknown>)[key] = [...value];
23
+ }
24
+ return copy;
25
+ };
@@ -0,0 +1,28 @@
1
+ import { CommonUtils } from './CommonUtils';
2
+ import { getUnixTimestamp, uniqueMuid } from './CometChatMessageHelper';
3
+
4
+ /**
5
+ * The "added X" rows to show for one ccGroupMemberAdded event: one copy per member, each with its own
6
+ * muid (members added in the same second shared a timestamp muid and were merged into one row).
7
+ * Accepts both shapes that reach the list: { message } from apps that emit once per member, and
8
+ * { messages } (one action per member) from CometChatUIKitHelper.onGroupMemberAdded.
9
+ */
10
+ export function groupMemberAddedRows(
11
+ event: { message?: object; messages?: object[]; usersAdded?: any[] },
12
+ loggedInUserName: string | undefined
13
+ ): any[] {
14
+ const users = event.usersAdded ?? [];
15
+ const rows: any[] = [];
16
+ users.forEach((user, i) => {
17
+ const base = event.messages?.[i] ?? event.message ?? event.messages?.[0];
18
+ if (!base) return;
19
+ const row: any = CommonUtils.clone(base);
20
+ row['message'] = `${loggedInUserName} added ${user.name}`;
21
+ row['muid'] = uniqueMuid();
22
+ row['sentAt'] = getUnixTimestamp();
23
+ row['actionOn'] = user;
24
+ row['action'] = 'added';
25
+ rows.push(row);
26
+ });
27
+ return rows;
28
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Which of a message's link previews to show.
3
+ *
4
+ * The server scans the raw text and returns a preview for every address it finds, in order, with
5
+ * no idea what the text means. Taking `links[0]` therefore showed a card for an address the link
6
+ * never opens: `[www.google.com](https://drive…)` got a Google card although it opens Drive, and
7
+ * `` `https://google.com` `` — code, not a link — still got a card.
8
+ *
9
+ * A preview is shown for a DESTINATION: a markdown link's address, or a bare address outside code
10
+ * and outside a link label. Label and code addresses are never destinations. The server reports
11
+ * an address after redirects and can keep a stray `)` from markdown, so addresses are compared
12
+ * loosely, and a preview that matches nothing is still shown when the text has a destination (it
13
+ * is most likely that destination, redirected) — just never one known to be a label or code.
14
+ */
15
+ import { markdownLinkPattern, urlPattern } from "../constants/textPatterns";
16
+
17
+ /** A link-preview entry as the extension delivers it (url, title, image, favicon, description…). */
18
+ type Preview = Record<string, any>;
19
+
20
+ const count = (s: string, ch: string) => s.split(ch).length - 1;
21
+
22
+ /**
23
+ * Drops trailing `)` that have no matching `(`. The server's scanner does not stop at markdown
24
+ * punctuation, so `[Mercury](…/Mercury_(planet))` comes back as `…/Mercury_(planet))` — a card
25
+ * that shows, and opens, an address that does not exist.
26
+ */
27
+ export const trimStrayParens = (url: string): string => {
28
+ let u = (url || "").trim();
29
+ while (u.endsWith(")") && count(u, ")") > count(u, "(")) u = u.slice(0, -1);
30
+ return u;
31
+ };
32
+
33
+ /** Loose form for comparing addresses: no scheme, no `www.`, no trailing `/`, no stray `)`. */
34
+ export const normalizePreviewUrl = (url: string): string =>
35
+ trimStrayParens(url).toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//, "").replace(/^www\./, "").replace(/\/+$/, "");
36
+
37
+ const addressesIn = (text: string): string[] => text.match(new RegExp(urlPattern, "gi")) || [];
38
+
39
+ /** What the text links to (destinations) and addresses it only shows as a label or code (excluded). */
40
+ function classify(text: string | undefined | null) {
41
+ const destinations: string[] = [];
42
+ const notDestinations: string[] = [];
43
+ let rest = text || "";
44
+
45
+ rest = rest.replace(/```[\s\S]*?```|`[^`\n]*`/g, (code) => {
46
+ // The fences aren't word boundaries for urlPattern (`https://a.com` read as "https://a"): blank them.
47
+ notDestinations.push(...addressesIn(code.replace(/`/g, " ")));
48
+ return " ";
49
+ });
50
+ rest = rest.replace(new RegExp(markdownLinkPattern, "g"), (_m, label: string, address: string) => {
51
+ notDestinations.push(...addressesIn(label));
52
+ destinations.push(address);
53
+ return " ";
54
+ });
55
+ destinations.push(...addressesIn(rest));
56
+
57
+ const wanted = new Set(destinations.map(normalizePreviewUrl));
58
+ const excluded = new Set(notDestinations.map(normalizePreviewUrl).filter((u) => !wanted.has(u)));
59
+ return { wanted, excluded };
60
+ }
61
+
62
+ /** The single card to stand for a message (list row type, search thumbnail). */
63
+ export function selectLinkPreview<T extends Preview>(links: T[] | undefined | null, text: string | undefined | null): T | undefined {
64
+ if (!links || links.length === 0) return undefined;
65
+ const { wanted, excluded } = classify(text);
66
+ const exact = links.find((link) => link?.url && wanted.has(normalizePreviewUrl(link.url)));
67
+ if (exact) return exact;
68
+
69
+ // Nothing in the text is a destination, but some addresses are code or labels: no card.
70
+ if (wanted.size === 0 && excluded.size > 0) return undefined;
71
+ return links.find((link) => !link?.url || !excluded.has(normalizePreviewUrl(link.url)));
72
+ }
73
+
74
+ /**
75
+ * Every card the bubble shows: one per destination, in the server's order — like React UI Kit's
76
+ * selectDestinationPreviews. `https://www.google.com and https://www.facebook.com` gets both cards.
77
+ */
78
+ export function selectLinkPreviews<T extends Preview>(links: T[] | undefined | null, text: string | undefined | null): T[] {
79
+ if (!links || links.length === 0) return [];
80
+ const { wanted, excluded } = classify(text);
81
+ if (wanted.size === 0 && excluded.size > 0) return [];
82
+ // One card per site: the server can return the same page twice (the label's
83
+ // http://www.x.com and the link's https://www.x.com). Keep one, in first-seen
84
+ // order, preferring https — the card opens its url.
85
+ const kept: T[] = [];
86
+ const slot = new Map<string, number>();
87
+ for (const link of links) {
88
+ if (!link?.url) { kept.push(link); continue; }
89
+ if (excluded.has(normalizePreviewUrl(link.url))) continue;
90
+ const key = siteKey(link.url);
91
+ const i = slot.get(key);
92
+ if (i === undefined) { slot.set(key, kept.length); kept.push(link); }
93
+ else if (/^https:/i.test(link.url) && !/^https:/i.test(kept[i].url)) kept[i] = link;
94
+ }
95
+ return kept;
96
+ }
97
+
98
+ /** Dedup key: scheme and `www.` dropped, host lowercased, path kept as is (paths are case-sensitive). */
99
+ function siteKey(url: string): string {
100
+ const u = trimStrayParens(url).replace(/^[a-z][a-z0-9+.-]*:\/\//i, "").replace(/\/+$/, "");
101
+ const cut = u.search(/[/?#]/);
102
+ const host = (cut < 0 ? u : u.slice(0, cut)).toLowerCase().replace(/^www\./, "");
103
+ return host + (cut < 0 ? "" : u.slice(cut));
104
+ }
105
+
106
+ /** The card image: empty when the server sent none, or only the site's favicon. */
107
+ export function previewImage(image?: string | null, favicon?: string | null): string {
108
+ return !image || image === favicon ? "" : image;
109
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Mention markup a user TYPED or PASTED, as opposed to a mention picked from the suggestion list.
3
+ *
4
+ * `<@uid:…>` / `<@all:…>` in a message's text is the only signal that a mention is real — there
5
+ * is no other metadata for `@all`. So text a user typed that happens to look like a token was
6
+ * sent verbatim and every platform rendered it as a live mention: `<@all:everyone> hi` became an
7
+ * @everyone chip. The cross-platform contract (shared with the React UI Kit) is to store a typed
8
+ * token's `<` as `&lt;` — `&lt;@all:everyone> hi` — and to show that as `<@all:everyone> hi`
9
+ * only after mentions have been resolved, so it can never turn back into a chip.
10
+ */
11
+
12
+ import React from "react";
13
+
14
+ const TYPED_TOKEN_REGEX = /<(@(?:uid|all):)/g;
15
+ const ESCAPED_TOKEN_REGEX = /&lt;(@(?:uid|all):)/g;
16
+
17
+ /** Escapes token-looking text a user typed: `<@all:x>` → `&lt;@all:x>`. */
18
+ export const escapeTypedMentionTokens = (text: string): string =>
19
+ text.indexOf("<@") < 0 ? text : text.replace(TYPED_TOKEN_REGEX, "&lt;$1");
20
+
21
+ /** Display form of an escaped typed token: `&lt;@all:x>` → `<@all:x>`. Run AFTER mention parsing. */
22
+ export const unescapeTypedMentionTokens = (text: string): string =>
23
+ text.indexOf("&lt;@") < 0 ? text : text.replace(ESCAPED_TOKEN_REGEX, "<$1");
24
+
25
+ const hasEscapedToken = (node: any): boolean => {
26
+ if (typeof node === "string") return node.indexOf("&lt;@") >= 0;
27
+ if (Array.isArray(node)) return node.some(hasEscapedToken);
28
+ if (React.isValidElement(node)) return hasEscapedToken((node as React.ReactElement<any>).props.children);
29
+ return false;
30
+ };
31
+
32
+ const unescapeTree = (node: any): any => {
33
+ if (typeof node === "string") return unescapeTypedMentionTokens(node);
34
+ if (Array.isArray(node)) return node.map(unescapeTree);
35
+ if (React.isValidElement(node) && hasEscapedToken(node)) {
36
+ const children = (node as React.ReactElement<any>).props.children;
37
+ return React.cloneElement(node as React.ReactElement<any>, {
38
+ children: Array.isArray(children) ? children.map(unescapeTree) : unescapeTree(children),
39
+ });
40
+ }
41
+ return node;
42
+ };
43
+
44
+ /**
45
+ * {@link unescapeTypedMentionTokens} over every string of a rendered tree. Only the branches
46
+ * holding an escaped token are rebuilt; any other tree — nearly every message — is returned as
47
+ * the same object, so rendering it costs nothing and changes nothing.
48
+ */
49
+ export const unescapeTypedMentionTokensInTree = (node: any): any =>
50
+ hasEscapedToken(node) ? unescapeTree(node) : node;
51
+
52
+ /**
53
+ * Builds the text to send: real mentions (character ranges `"start_end"` in `text`, from the
54
+ * composer's mention map) become their tokens, and everything the user typed between them is
55
+ * escaped. Ranges are applied in position order, whatever order the map holds them in.
56
+ */
57
+ export const insertMentionTokens = (
58
+ text: string,
59
+ mentions: Iterable<[string, { underlyingText: string }]>
60
+ ): string => {
61
+ const ranges = [...mentions]
62
+ .map(([key, value]) => {
63
+ const [start, end] = key.split("_").map(Number);
64
+ return { start, end, token: value.underlyingText };
65
+ })
66
+ .filter((r) => Number.isFinite(r.start) && Number.isFinite(r.end))
67
+ .sort((a, b) => a.start - b.start);
68
+
69
+ let out = "";
70
+ let last = 0;
71
+ for (const { start, end, token } of ranges) {
72
+ if (start < last) continue; // overlapping range — skip it rather than corrupt the text
73
+ out += escapeTypedMentionTokens(text.substring(last, start)) + token;
74
+ last = end;
75
+ }
76
+ return out + escapeTypedMentionTokens(text.substring(last));
77
+ };
@@ -0,0 +1,26 @@
1
+ import { Platform } from "react-native";
2
+
3
+ /**
4
+ * Stand-in for `InteractionManager.runAfterInteractions`, which React Native 0.87 removed
5
+ * (touching it throws in dev and is `undefined` in release).
6
+ *
7
+ * - RN < 0.82: `InteractionManager` still waits for running animations and navigation
8
+ * transitions, so it is used as before and apps on older RN keep the exact old timing.
9
+ * - RN >= 0.82: it had already stopped honouring interaction handles, so all it did was
10
+ * defer the callback past the current JS turn. That is what `setTimeout(task, 0)` does,
11
+ * without touching the removed module. `requestIdleCallback` is deliberately not used: it
12
+ * can hold the callback back for a long time, and these call sites move the caret or clear
13
+ * the input right after an edit.
14
+ */
15
+ const rnVersion = Platform.constants?.reactNativeVersion;
16
+ const hasLegacyInteractionManager =
17
+ !!rnVersion && rnVersion.major === 0 && rnVersion.minor < 82;
18
+
19
+ export function runAfterInteractions(task: () => void): void {
20
+ if (hasLegacyInteractionManager) {
21
+ // Required lazily: on RN 0.87 even reading this export throws.
22
+ require("react-native").InteractionManager.runAfterInteractions(task);
23
+ return;
24
+ }
25
+ setTimeout(task, 0);
26
+ }
@@ -7,6 +7,7 @@
7
7
  * as "make a <product>" or "5 < 10" is preserved.
8
8
  */
9
9
  import { stripColorTags } from "../formatters/richTextWireFormat";
10
+ import { markdownLinkPattern } from "../constants/textPatterns";
10
11
 
11
12
  export const stripRichText = (input?: string | null): string => {
12
13
  if (!input) return "";
@@ -41,7 +42,7 @@ export const stripRichText = (input?: string | null): string => {
41
42
  .replace(/(^|[^A-Za-z0-9_])_\s*(.+?)\s*_(?![A-Za-z0-9_])/g, "$1$2") // _italic_
42
43
  .replace(/~~(.+?)~~/g, "$1") // ~~strikethrough~~
43
44
  .replace(/`([^`]+)`/g, "$1") // `inline code`
44
- .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1"); // [label](url) -> label
45
+ .replace(new RegExp(markdownLinkPattern, "g"), "$1"); // [label](url) -> label
45
46
 
46
47
  // 3. Collapse leftover whitespace into a single clean line.
47
48
  return text.replace(/\s+/g, " ").trim();
@@ -0,0 +1,23 @@
1
+ import { GestureResponderEvent } from 'react-native';
2
+
3
+ // Same tolerances as React Native's Pressability: a touch is still a tap within 10pt of where it started.
4
+ export const TAP_SLOP = 10;
5
+ // A longer hold is a long-press (the bubble's message options), not a tap.
6
+ export const TAP_MAX_MS = 500;
7
+
8
+ export interface TouchStart {
9
+ x: number;
10
+ y: number;
11
+ at: number;
12
+ }
13
+
14
+ export const touchStartOf = (e: GestureResponderEvent, now = Date.now()): TouchStart => ({
15
+ x: e.nativeEvent.pageX,
16
+ y: e.nativeEvent.pageY,
17
+ at: now,
18
+ });
19
+
20
+ export const movedBeyondSlop = (start: TouchStart, e: GestureResponderEvent): boolean =>
21
+ Math.abs(e.nativeEvent.pageX - start.x) > TAP_SLOP || Math.abs(e.nativeEvent.pageY - start.y) > TAP_SLOP;
22
+
23
+ export const isTapDuration = (start: TouchStart, now = Date.now()): boolean => now - start.at < TAP_MAX_MS;
@@ -0,0 +1,74 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { NativeModules } from 'react-native';
3
+
4
+ const { FileManager } = NativeModules;
5
+
6
+ // Long edge of the generated JPEG — tray tiles and grid cells are at most ~200pt, so this stays sharp
7
+ // on 3x screens while keeping each file a few KB.
8
+ const THUMBNAIL_MAX_SIZE = 480;
9
+
10
+ // Local video uri → its thumbnail (in flight or done), so the tray tile and the bubble share one native call.
11
+ const byLocalUri = new Map<string, Promise<string | null>>();
12
+ // Resolved thumbnails, so a component can render the thumbnail on its first frame instead of after a tick.
13
+ const resolved = new Map<string, string>();
14
+ // Uploaded video url (without the signed query string) → the local file it came from.
15
+ const localUriByRemoteUrl = new Map<string, string>();
16
+
17
+ const withoutQuery = (url: string) => url.split('?')[0];
18
+
19
+ /** First-frame JPEG of a LOCAL video file, generated natively. Resolves null when unavailable. */
20
+ export function getLocalVideoThumbnail(localUri: string): Promise<string | null> {
21
+ const cached = byLocalUri.get(localUri);
22
+ if (cached) return cached;
23
+ const pending: Promise<string | null> = typeof FileManager?.getVideoThumbnail === 'function'
24
+ ? FileManager.getVideoThumbnail(localUri, THUMBNAIL_MAX_SIZE)
25
+ .then((thumbnailUri: string) => {
26
+ resolved.set(localUri, thumbnailUri);
27
+ return thumbnailUri;
28
+ })
29
+ .catch(() => null)
30
+ : Promise.resolve(null);
31
+ byLocalUri.set(localUri, pending);
32
+ return pending;
33
+ }
34
+
35
+ /**
36
+ * Remembers which local file an uploaded video came from, so the sender's bubble (which only knows the
37
+ * uploaded url) can show the local thumbnail straight away. Also starts generating it.
38
+ */
39
+ export function linkUploadedVideo(remoteUrl: string | undefined, localUri: string | undefined): void {
40
+ if (!remoteUrl || !localUri) return;
41
+ localUriByRemoteUrl.set(withoutQuery(remoteUrl), localUri);
42
+ getLocalVideoThumbnail(localUri);
43
+ }
44
+
45
+ function localUriFor(source: { localUri?: string; remoteUrl?: string }): string | undefined {
46
+ if (source.localUri) return source.localUri;
47
+ return source.remoteUrl ? localUriByRemoteUrl.get(withoutQuery(source.remoteUrl)) : undefined;
48
+ }
49
+
50
+ /**
51
+ * Local first-frame thumbnail for a video, by its local file uri (tray) or its uploaded url (a bubble
52
+ * this device sent). `undefined` while generating, `null` when there is none — no local file (e.g. a
53
+ * video received from someone else), generation failed, or the native method isn't available.
54
+ */
55
+ export function useLocalVideoThumbnail(source: { localUri?: string; remoteUrl?: string }): string | null | undefined {
56
+ const localUri = localUriFor(source);
57
+ const [thumbnail, setThumbnail] = useState<string | null | undefined>(() =>
58
+ localUri ? resolved.get(localUri) : null
59
+ );
60
+ useEffect(() => {
61
+ if (!localUri) {
62
+ setThumbnail(null);
63
+ return;
64
+ }
65
+ let active = true;
66
+ getLocalVideoThumbnail(localUri).then((uri) => {
67
+ if (active) setThumbnail(uri);
68
+ });
69
+ return () => {
70
+ active = false;
71
+ };
72
+ }, [localUri]);
73
+ return thumbnail;
74
+ }
@@ -1,7 +1,9 @@
1
1
  import Clipboard from '@react-native-clipboard/clipboard';
2
2
  import NativeCometChatClipboardModule from './NativeCometChatClipboardModule';
3
3
  import type { ClipboardImageResult } from './NativeCometChatClipboardModule';
4
- import { stripColorTags } from '../../formatters/richTextWireFormat';
4
+ import { stripMarkdown } from '../../utils/MarkdownUtils';
5
+ import { applyRawFormatters } from '../../formatters/applyRawFormatters';
6
+ import type { CometChatTextFormatter } from '../../formatters/CometChatTextFormatter';
5
7
 
6
8
  export type { ClipboardImageResult };
7
9
 
@@ -36,13 +38,22 @@ export const ClipboardPasteHandler = {
36
38
  * chat app. Falls back to a plain copy when the native module is unavailable — the text
37
39
  * still lands on the clipboard, just without colour.
38
40
  */
39
- copyMessageText(raw: string): void {
40
- const plain = stripColorTags(raw);
41
+ copyMessageText(raw: string, textFormatters?: Array<CometChatTextFormatter>): void {
42
+ // A consumer's own wire token is rewritten into UI Kit markup first. Without this the strip below
43
+ // does not recognise it, so the token leaks verbatim into Notes or another chat app, and pasting
44
+ // back into our own composer brings it in as literal text instead of styled text.
45
+ const wire = applyRawFormatters(raw, textFormatters);
46
+ // stripMarkdown, not stripColorTags: colour was the only case anyone checked, so `<u>`, `<b>`,
47
+ // `<i>`, `<s>` and every markdown marker went to Notes and mail verbatim — QA saw
48
+ // `<u>fbebf</u>` pasted from a message that read "fbebf" on screen. stripMarkdown removes HTML
49
+ // tags and markdown AND colour, and unlike stripRichText it keeps line breaks, which a copied
50
+ // multi-line message must retain.
51
+ const plain = stripMarkdown(wire);
41
52
  if (!NativeCometChatClipboardModule?.setRichText) {
42
53
  Clipboard.setString(plain);
43
54
  return;
44
55
  }
45
- NativeCometChatClipboardModule.setRichText(plain, raw).catch(() => {
56
+ NativeCometChatClipboardModule.setRichText(plain, wire).catch(() => {
46
57
  Clipboard.setString(plain);
47
58
  });
48
59
  },
@@ -22,6 +22,7 @@ import { deepMerge } from '../../helper/helperFunctions';
22
22
  import { SelectedAttachment } from '../../modals/SelectedAttachment';
23
23
  import { Icon } from '../../icons/Icon';
24
24
  import { getFileTypeIcon } from '../../constants/UIKitConstants';
25
+ import { useLocalVideoThumbnail } from '../../utils/videoThumbnail';
25
26
 
26
27
  const { SoundPlayer } = NativeModules;
27
28
 
@@ -459,6 +460,8 @@ export const CometChatAttachmentTile = ({
459
460
  style ?? {}
460
461
  );
461
462
  const { fileId, file, uploadState, uploadProgress } = attachment;
463
+ const isVideo = file.type.startsWith('video/');
464
+ const videoThumbnail = useLocalVideoThumbnail({ localUri: isVideo ? file.uri : undefined });
462
465
 
463
466
  // Audio (audio/*) renders as a player card (play/pause + seek + time), not the file card.
464
467
  if (file.type.startsWith('audio/')) {
@@ -670,24 +673,29 @@ export const CometChatAttachmentTile = ({
670
673
  borderColor: theme.color.error,
671
674
  }, s.mediaTileStyle]}
672
675
  >
673
- {file.type.startsWith('video/') ? (
674
- // A local video file can't render as an <Image>, so show its FIRST FRAME via a paused,
675
- // muted react-native-video (no controls, never plays) as the thumbnail. The dark scrim
676
- // sits behind it so the tile reads as a video before the frame decodes.
676
+ {isVideo ? (
677
+ // A local video file can't render as an <Image>: show its natively generated first-frame
678
+ // JPEG. Only if that isn't available, fall back to a paused, muted react-native-video
679
+ // (a full player per tile — heavy with several videos). The dark scrim sits behind so
680
+ // the tile reads as a video before either appears.
677
681
  <>
678
682
  <View
679
683
  pointerEvents="none"
680
684
  style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: theme.color.mediaScrim }}
681
685
  />
682
- <Video
683
- source={{ uri: file.uri }}
684
- paused
685
- muted
686
- repeat={false}
687
- controls={false}
688
- resizeMode="cover"
689
- style={styles.fill}
690
- />
686
+ {videoThumbnail ? (
687
+ <Image source={{ uri: videoThumbnail }} style={styles.fill} resizeMode="cover" />
688
+ ) : videoThumbnail === null ? (
689
+ <Video
690
+ source={{ uri: file.uri }}
691
+ paused
692
+ muted
693
+ repeat={false}
694
+ controls={false}
695
+ resizeMode="cover"
696
+ style={styles.fill}
697
+ />
698
+ ) : null}
691
699
  </>
692
700
  ) : (
693
701
  <Image
@@ -1,11 +1,11 @@
1
1
  import React, { JSX, useCallback, useEffect, useRef, useState } from "react";
2
2
  import {
3
3
  EmitterSubscription,
4
+ GestureResponderEvent,
4
5
  ImageSourcePropType,
5
6
  ImageStyle,
6
7
  NativeEventEmitter,
7
8
  NativeModules,
8
- Platform,
9
9
  StyleProp,
10
10
  Text,
11
11
  TextStyle,
@@ -15,6 +15,7 @@ import {
15
15
  import { Icon } from "../../icons/Icon";
16
16
  import { AnimatedAudioWaves } from "./AnimatedAudioWaves";
17
17
  import { audioPlaybackCoordinator } from "../../utils/audioPlaybackCoordinator";
18
+ import { TouchStart, isTapDuration, movedBeyondSlop, touchStartOf } from "../../utils/tapGesture";
18
19
 
19
20
  const { SoundPlayer } = NativeModules;
20
21
  const eventEmitter = new NativeEventEmitter(SoundPlayer);
@@ -128,7 +129,8 @@ export const CometChatAudioBubble = ({
128
129
  // Native fires soundPlayStatus on natural completion AND when a new play() replaces this clip.
129
130
  // Interrupt echo (we were interrupted) → ignore; genuine finish → reset to idle.
130
131
  useEffect(() => {
131
- subRef.current = eventEmitter.addListener("soundPlayStatus", (data) => {
132
+ subRef.current = eventEmitter.addListener("soundPlayStatus", (event) => {
133
+ const data = event as { url?: string };
132
134
  if (audioUrl !== data.url) return;
133
135
  if (wasInterruptedRef.current) return;
134
136
  setStatus("");
@@ -173,25 +175,21 @@ export const CometChatAudioBubble = ({
173
175
  if (audioUrl) play(currentTimeRef.current || 0);
174
176
  };
175
177
 
176
- const pressTime = useRef<number | null>(0);
178
+ // Raw touches (not a Touchable) so the bubble's long-press and the list's scroll keep working.
179
+ // A finger always moves a little during a tap: only a move past the slop cancels it (a scroll).
180
+ const press = useRef<TouchStart | null>(null);
177
181
 
178
- const handleTouchStart = () => {
179
- pressTime.current = Date.now();
182
+ const handleTouchStart = (e: GestureResponderEvent) => {
183
+ press.current = touchStartOf(e);
180
184
  };
181
185
 
182
186
  const handleTouchEnd = () => {
183
- if (pressTime.current === null && Platform.OS === "ios") return;
184
- const endTime = Date.now();
185
- const pressDuration = endTime - (pressTime.current ?? 0);
186
- if (pressDuration < 500) {
187
- playPauseAudio();
188
- }
187
+ if (press.current && isTapDuration(press.current)) playPauseAudio();
188
+ press.current = null;
189
189
  };
190
190
 
191
- const onTouchMove = () => {
192
- if (Platform.OS === "ios") {
193
- pressTime.current = null;
194
- }
191
+ const onTouchMove = (e: GestureResponderEvent) => {
192
+ if (press.current && movedBeyondSlop(press.current, e)) press.current = null;
195
193
  };
196
194
 
197
195
  const displayDuration = useCallback(