@cometchat/chat-uikit-react-native 5.3.10 → 5.4.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 (132) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/CometChatClipboardModule.kt +52 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/CometchatUiKitPackage.java +1 -0
  3. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +95 -8
  4. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +300 -7
  5. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorViewManager.kt +2 -1
  6. package/android/src/main/java/com/reactnativecometchatuikit/SoundPlayer.java +85 -47
  7. package/ios/CometChatClipboardModule.m +11 -0
  8. package/ios/CometChatClipboardModule.swift +41 -0
  9. package/ios/FileManager.m +201 -39
  10. package/ios/RichTextEditorView.swift +367 -8
  11. package/ios/RichTextEditorViewManager.m +1 -0
  12. package/ios/SoundPlayer.m +18 -6
  13. package/package.json +10 -7
  14. package/react-native-cometchat-ui-kit.podspec +1 -0
  15. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +692 -107
  16. package/src/CometChatConversations/CometChatConversations.tsx +19 -6
  17. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +649 -49
  18. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +23 -4
  19. package/src/CometChatMessageList/CometChatMessageList.tsx +463 -54
  20. package/src/CometChatMessageList/SEARCH_NAV_SLOWNESS_FINDINGS_AND_FIX.md +313 -0
  21. package/src/CometChatMessageList/components/MessageListItem.tsx +30 -17
  22. package/src/CometChatMessageList/style.ts +33 -5
  23. package/src/CometChatRichTextEditor/RichTextEditorViewNativeComponent.ts +13 -0
  24. package/src/CometChatRichTextEditor/index.tsx +25 -0
  25. package/src/CometChatSearch/CometChatSearch.tsx +296 -154
  26. package/src/calls/CallingExtension.tsx +19 -13
  27. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +20 -1
  28. package/src/extensions/ThumbnailGeneration/ThumbnailGenerationDecorator.tsx +20 -9
  29. package/src/index.ts +39 -0
  30. package/src/shared/CometChatUiKit/CometChatUIKit.ts +40 -34
  31. package/src/shared/base/Types.ts +3 -0
  32. package/src/shared/constants/UIKitConstants.ts +15 -1
  33. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +3 -2
  34. package/src/shared/framework/DataSource.ts +14 -4
  35. package/src/shared/framework/DataSourceDecorator.tsx +17 -8
  36. package/src/shared/framework/MessageDataSource.tsx +307 -60
  37. package/src/shared/helper/useToast.tsx +29 -0
  38. package/src/shared/icons/components/audio-file-type.tsx +11 -22
  39. package/src/shared/icons/components/document-file-type.tsx +11 -24
  40. package/src/shared/icons/components/image-file-type.tsx +12 -21
  41. package/src/shared/icons/components/link-file-type.tsx +25 -0
  42. package/src/shared/icons/components/pdf-file-type.tsx +11 -22
  43. package/src/shared/icons/components/presentation-file-type.tsx +11 -24
  44. package/src/shared/icons/components/spreadsheet-file-type.tsx +11 -24
  45. package/src/shared/icons/components/text-file-type.tsx +11 -21
  46. package/src/shared/icons/components/unknown-file-type.tsx +21 -25
  47. package/src/shared/icons/components/video-file-type.tsx +11 -24
  48. package/src/shared/icons/components/zip-file-type.tsx +11 -24
  49. package/src/shared/icons/icon-mapping.tsx +2 -0
  50. package/src/shared/index.ts +28 -0
  51. package/src/shared/modals/AttachmentPickerConfiguration.ts +13 -0
  52. package/src/shared/modals/SelectedAttachment.ts +65 -0
  53. package/src/shared/modals/UploadState.ts +10 -0
  54. package/src/shared/modals/index.ts +4 -0
  55. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +42 -1
  56. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +42 -1
  57. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +43 -2
  58. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +43 -2
  59. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +43 -2
  60. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +43 -2
  61. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +43 -2
  62. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +43 -2
  63. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +43 -2
  64. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +43 -2
  65. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +43 -2
  66. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +43 -2
  67. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +43 -2
  68. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +43 -2
  69. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +43 -2
  70. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +43 -2
  71. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +43 -2
  72. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +43 -2
  73. package/src/shared/services/UploadQueueService.ts +145 -0
  74. package/src/shared/services/index.ts +2 -0
  75. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +44 -19
  76. package/src/shared/utils/MessageUtils.tsx +13 -4
  77. package/src/shared/utils/attachmentLimits.ts +156 -0
  78. package/src/shared/utils/audioPlaybackCoordinator.ts +28 -0
  79. package/src/shared/utils/batchMediaContext.tsx +30 -0
  80. package/src/shared/utils/conversationUtils.ts +26 -4
  81. package/src/shared/utils/elementType.tsx +38 -0
  82. package/src/shared/utils/groupAttachments.ts +93 -0
  83. package/src/shared/utils/index.ts +8 -0
  84. package/src/shared/utils/openMultiFileChooser.ts +123 -0
  85. package/src/shared/utils/partitionAttachmentsByKind.ts +44 -0
  86. package/src/shared/views/ClipboardPasteHandler/ClipboardPasteHandler.ts +28 -0
  87. package/src/shared/views/ClipboardPasteHandler/NativeCometChatClipboardModule.ts +16 -0
  88. package/src/shared/views/ClipboardPasteHandler/index.ts +2 -0
  89. package/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +1 -0
  90. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreview.style.ts +32 -0
  91. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreview.tsx +90 -0
  92. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentPreviewItem.tsx +276 -0
  93. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTile.tsx +827 -0
  94. package/src/shared/views/CometChatAttachmentPreview/CometChatAttachmentTray.tsx +110 -0
  95. package/src/shared/views/CometChatAttachmentPreview/StagedVideoDurationProbe.tsx +53 -0
  96. package/src/shared/views/CometChatAttachmentPreview/index.ts +8 -0
  97. package/src/shared/views/CometChatAttachmentViewer/CometChatAttachmentViewer.tsx +305 -0
  98. package/src/shared/views/CometChatAttachmentViewer/index.ts +2 -0
  99. package/src/shared/views/CometChatAudioBubble/CometChatAudioBubble.tsx +71 -74
  100. package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +587 -0
  101. package/src/shared/views/CometChatAudiosBubble/index.ts +2 -0
  102. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +31 -20
  103. package/src/shared/views/CometChatCaptionText/CometChatCaptionText.tsx +182 -0
  104. package/src/shared/views/CometChatCaptionText/index.ts +2 -0
  105. package/src/shared/views/CometChatComposerErrorBanner.tsx +83 -0
  106. package/src/shared/views/CometChatConversationStarter/CometChatConversationStarter.tsx +141 -0
  107. package/src/shared/views/CometChatConversationStarter/index.ts +2 -0
  108. package/src/shared/views/CometChatConversationSummary/CometChatConversationSummary.tsx +155 -0
  109. package/src/shared/views/CometChatConversationSummary/index.ts +2 -0
  110. package/src/shared/views/CometChatFileBubble/style.ts +6 -4
  111. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +316 -0
  112. package/src/shared/views/CometChatFilesBubble/index.ts +2 -0
  113. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +323 -0
  114. package/src/shared/views/CometChatImagesBubble/index.ts +2 -0
  115. package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +425 -0
  116. package/src/shared/views/CometChatMediaViewer/index.ts +2 -0
  117. package/src/shared/views/CometChatMediaViewer/mediaViewerUtils.ts +30 -0
  118. package/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx +14 -4
  119. package/src/shared/views/CometChatSendButtonView/CometChatSendButtonView.tsx +1 -0
  120. package/src/shared/views/CometChatSmartReplies/CometChatSmartReplies.tsx +172 -0
  121. package/src/shared/views/CometChatSmartReplies/index.ts +2 -0
  122. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +4 -3
  123. package/src/shared/views/CometChatVideoBubble/style.ts +3 -3
  124. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +441 -0
  125. package/src/shared/views/CometChatVideosBubble/index.ts +2 -0
  126. package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +78 -0
  127. package/src/shared/views/CometChatVoiceNoteBubble/index.ts +2 -0
  128. package/src/shared/views/index.ts +37 -1
  129. package/src/theme/CometChatThemeHelper.ts +8 -0
  130. package/src/theme/default/color/dark.ts +9 -0
  131. package/src/theme/default/color/light.ts +10 -0
  132. package/src/theme/type.ts +73 -0
@@ -0,0 +1,110 @@
1
+ import React from 'react';
2
+ import { FlatList, View } from 'react-native';
3
+ import { SelectedAttachment } from '../../modals/SelectedAttachment';
4
+ import { CometChatAttachmentTile } from './CometChatAttachmentTile';
5
+ import { useTheme } from '../../../theme';
6
+ import { useCompTheme } from '../../../theme/hook';
7
+ import { CometChatTheme } from '../../../theme/type';
8
+ import { deepMerge } from '../../helper/helperFunctions';
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // Design doc §5.0 — the composer's pre-send staging tray. Its per-tile layout
12
+ // (media thumbnails, file cards, per-file progress + retry) mirrors the
13
+ // PER-TYPE receive bubbles the batch fans out into — Images/Videos (media grid),
14
+ // Files (card list), Audios / Voice note — NOT a single combined gallery bubble
15
+ // (that model is retired, §8.0). On send the staged tiles fan out (§7) into one
16
+ // message per kind, each rendered by its matching per-type bubble.
17
+ // ---------------------------------------------------------------------------
18
+
19
+ export interface CometChatAttachmentTrayProps {
20
+ attachments: SelectedAttachment[];
21
+ onRemove: (fileId: string) => void;
22
+ onRetry: (fileId: string) => void;
23
+ /** Called when the user taps a media tile thumbnail to preview it. */
24
+ onPressTile?: (fileId: string) => void;
25
+ /** Structured style overrides (containerStyle / progressTrackStyle / progressFillStyle), deep-merged over theme + component theme. */
26
+ style?: CometChatTheme["attachmentTrayStyles"];
27
+ }
28
+
29
+ function useAggregatePercent(attachments: SelectedAttachment[]): number {
30
+ const totalBytes = attachments.reduce((s, a) => s + (a.file.size || 0), 0);
31
+ if (totalBytes === 0) return 0;
32
+ const loadedBytes = attachments.reduce(
33
+ (s, a) => s + ((a.uploadProgress / 100) * (a.file.size || 0)),
34
+ 0
35
+ );
36
+ return Math.min(100, Math.round((loadedBytes / totalBytes) * 100));
37
+ }
38
+
39
+ export const CometChatAttachmentTray = ({
40
+ attachments,
41
+ onRemove,
42
+ onRetry,
43
+ onPressTile,
44
+ style,
45
+ }: CometChatAttachmentTrayProps) => {
46
+ const theme = useTheme();
47
+ const compTheme = useCompTheme();
48
+ const s = deepMerge(
49
+ theme.attachmentTrayStyles ?? {},
50
+ compTheme.attachmentTrayStyles ?? {},
51
+ style ?? {}
52
+ );
53
+ const aggregatePercent = useAggregatePercent(attachments);
54
+ const allDone = attachments.every(
55
+ a => a.uploadState === 'COMPLETED' || a.uploadState === 'FAILED' || a.uploadState === 'REJECTED'
56
+ );
57
+
58
+ if (attachments.length === 0) {
59
+ return null;
60
+ }
61
+
62
+ return (
63
+ <View style={s.containerStyle}>
64
+ <FlatList
65
+ horizontal
66
+ data={attachments}
67
+ keyExtractor={(item) => item.fileId}
68
+ renderItem={({ item, index }) => (
69
+ <CometChatAttachmentTile
70
+ testID={`AttachmentTile-${index}`}
71
+ attachment={item}
72
+ onRemove={onRemove}
73
+ onRetry={onRetry}
74
+ onPress={onPressTile}
75
+ />
76
+ )}
77
+ showsHorizontalScrollIndicator={false}
78
+ // paddingTop gives the ✕ corner badge (which sits at top:-s2 on each tile) room inside the
79
+ // horizontal scroll view — without it the badge overflows the FlatList's top edge and is clipped.
80
+ contentContainerStyle={{ paddingHorizontal: theme.spacing.padding.p2, paddingTop: theme.spacing.padding.p2 }}
81
+ />
82
+ {/* §5.4 — byte-weighted aggregate bar; hidden once all files resolve */}
83
+ {!allDone && (
84
+ <View
85
+ style={[{
86
+ height: theme.spacing.spacing.s0_5,
87
+ marginHorizontal: theme.spacing.margin.m2,
88
+ marginBottom: theme.spacing.margin.m1,
89
+ borderRadius: theme.spacing.radius.r1,
90
+ backgroundColor: theme.color.neutral200,
91
+ overflow: 'hidden',
92
+ }, s.progressTrackStyle]}
93
+ >
94
+ <View
95
+ style={[{
96
+ height: theme.spacing.spacing.s0_5,
97
+ width: `${aggregatePercent}%`,
98
+ backgroundColor: theme.color.primary,
99
+ borderRadius: theme.spacing.radius.r1,
100
+ }, s.progressFillStyle]}
101
+ />
102
+ </View>
103
+ )}
104
+ </View>
105
+ );
106
+ };
107
+
108
+ // Backward-compat alias so existing imports keep working without breakage
109
+ export const CometChatAttachmentPreview = CometChatAttachmentTray;
110
+ export type CometChatAttachmentPreviewProps = CometChatAttachmentTrayProps;
@@ -0,0 +1,53 @@
1
+ import React from 'react';
2
+ import { StyleSheet, View } from 'react-native';
3
+ import Video from 'react-native-video';
4
+ import { SelectedAttachment } from '../../modals/SelectedAttachment';
5
+
6
+ interface StagedVideoDurationProbeProps {
7
+ attachments: SelectedAttachment[];
8
+ /** Called once per video with its duration in whole seconds (0 if it couldn't be read). */
9
+ onDuration: (fileId: string, durationSeconds: number) => void;
10
+ }
11
+
12
+ /**
13
+ * Off-screen probe that reads each staged VIDEO's duration ONCE (via react-native-video's `onLoad`)
14
+ * and reports it back, so it can be stored on the model and written into the message metadata at
15
+ * send time (the receiver's bubble then shows the duration chip without downloading the video).
16
+ *
17
+ * It mounts a hidden, muted, paused `<Video>` ONLY for videos that don't have a duration yet, and
18
+ * self-unmounts the moment a duration (or 0 on failure) is recorded — so there's no playback, no
19
+ * audio, no visual output, and nothing left mounted during list scroll. This keeps duration reading
20
+ * a one-time staging concern, never a render-time one.
21
+ */
22
+ export function StagedVideoDurationProbe({ attachments, onDuration }: StagedVideoDurationProbeProps) {
23
+ // Video AND audio: react-native-video reads both (mp3/aac included) via onLoad, one independent
24
+ // player per file — unlike the shared native SoundPlayer, so several audios don't race to 00:00.
25
+ const pending = attachments.filter(
26
+ a => (a.file.type.startsWith('video/') || a.file.type.startsWith('audio/')) && a.durationSeconds == null
27
+ );
28
+ if (pending.length === 0) return null;
29
+
30
+ return (
31
+ <View style={styles.hidden} pointerEvents="none">
32
+ {pending.map(a => (
33
+ <Video
34
+ key={a.fileId}
35
+ source={{ uri: a.file.uri }}
36
+ paused
37
+ muted
38
+ // onLoad → real duration; onError → 0 so we don't re-probe forever (chip just omits).
39
+ onLoad={(data: { duration?: number }) =>
40
+ onDuration(a.fileId, Math.max(0, Math.round(data?.duration ?? 0)))
41
+ }
42
+ onError={() => onDuration(a.fileId, 0)}
43
+ style={styles.hiddenVideo}
44
+ />
45
+ ))}
46
+ </View>
47
+ );
48
+ }
49
+
50
+ const styles = StyleSheet.create({
51
+ hidden: { width: 0, height: 0, overflow: 'hidden' },
52
+ hiddenVideo: { width: 0, height: 0 },
53
+ });
@@ -0,0 +1,8 @@
1
+ // Canonical names (§5.0)
2
+ export { CometChatAttachmentTray, CometChatAttachmentPreview } from './CometChatAttachmentTray';
3
+ export type { CometChatAttachmentTrayProps, CometChatAttachmentPreviewProps } from './CometChatAttachmentTray';
4
+
5
+ export { CometChatAttachmentTile, CometChatAttachmentPreviewItem } from './CometChatAttachmentTile';
6
+ export type { CometChatAttachmentTileProps, CometChatAttachmentPreviewItemProps } from './CometChatAttachmentTile';
7
+
8
+ export { getAttachmentPreviewStyle } from './CometChatAttachmentPreview.style';
@@ -0,0 +1,305 @@
1
+ import React, { useRef, useState } from 'react';
2
+ import {
3
+ ActivityIndicator,
4
+ Image,
5
+ Modal,
6
+ NativeModules,
7
+ PanResponder,
8
+ Share,
9
+ StyleSheet,
10
+ Text,
11
+ TouchableOpacity,
12
+ View,
13
+ } from 'react-native';
14
+ import { CometChat } from '@cometchat/chat-sdk-react-native';
15
+ import { Icon } from '../../icons/Icon';
16
+
17
+ export interface CometChatAttachmentViewerProps {
18
+ attachments: CometChat.Attachment[];
19
+ initialIndex: number;
20
+ message: CometChat.BaseMessage;
21
+ onClose: () => void;
22
+ /** Controls Modal visibility. Defaults to true for backward compatibility. */
23
+ visible?: boolean;
24
+ }
25
+
26
+ type DownloadState = 'IDLE' | 'DOWNLOADING' | 'DONE' | 'FAILED';
27
+
28
+ const { FileManager } = NativeModules;
29
+
30
+ function formatFileSize(bytes: number): string {
31
+ if (!(bytes > 0)) return ''; // undefined / 0 / NaN → show nothing (not "undefined B")
32
+ if (bytes >= 1_048_576) return `${(bytes / 1_048_576).toFixed(1)} MB`;
33
+ if (bytes >= 1_024) return `${(bytes / 1_024).toFixed(0)} KB`;
34
+ return `${bytes} B`;
35
+ }
36
+
37
+ function formatSentAt(sentAt: number): string {
38
+ const d = new Date(sentAt * 1000);
39
+ const h = d.getHours();
40
+ const m = d.getMinutes().toString().padStart(2, '0');
41
+ const ampm = h >= 12 ? 'PM' : 'AM';
42
+ return `${h % 12 || 12}:${m} ${ampm}`;
43
+ }
44
+
45
+ export const CometChatAttachmentViewer = ({
46
+ attachments,
47
+ initialIndex,
48
+ message,
49
+ onClose,
50
+ visible = true,
51
+ }: CometChatAttachmentViewerProps) => {
52
+ const [currentIndex, setCurrentIndex] = useState(initialIndex);
53
+ const [imageLoaded, setImageLoaded] = useState(false);
54
+ const [downloadState, setDownloadState] = useState<DownloadState>('IDLE');
55
+
56
+ const current = attachments[currentIndex];
57
+ const senderName = message.getSender?.()?.getName?.() ?? '';
58
+ const sentAtStr = message.getSentAt ? formatSentAt(message.getSentAt()) : '';
59
+
60
+ const panResponder = useRef(
61
+ PanResponder.create({
62
+ onMoveShouldSetPanResponder: (_, gs) =>
63
+ Math.abs(gs.dx) > 10 && Math.abs(gs.dx) > Math.abs(gs.dy),
64
+ onPanResponderRelease: (_, gs) => {
65
+ if (gs.dx < -40) {
66
+ setCurrentIndex(prev => Math.min(prev + 1, attachments.length - 1));
67
+ setImageLoaded(false);
68
+ setDownloadState('IDLE');
69
+ } else if (gs.dx > 40) {
70
+ setCurrentIndex(prev => Math.max(prev - 1, 0));
71
+ setImageLoaded(false);
72
+ setDownloadState('IDLE');
73
+ }
74
+ },
75
+ })
76
+ ).current;
77
+
78
+ const handleDownload = () => {
79
+ if (downloadState === 'DOWNLOADING' || downloadState === 'DONE') return;
80
+ setDownloadState('DOWNLOADING');
81
+ const url = current.getUrl();
82
+ const name = current.getName();
83
+ FileManager?.checkAndDownload(url, name, (result: string) => {
84
+ try {
85
+ const parsed = JSON.parse(result);
86
+ if (parsed.success) {
87
+ setDownloadState('DONE');
88
+ } else {
89
+ setDownloadState('FAILED');
90
+ }
91
+ } catch {
92
+ setDownloadState('FAILED');
93
+ }
94
+ });
95
+ };
96
+
97
+ const handleShare = async () => {
98
+ try {
99
+ await Share.share({ url: current.getUrl(), message: current.getName() });
100
+ } catch {
101
+ // share cancelled
102
+ }
103
+ };
104
+
105
+ const shortName =
106
+ current.getName().length > 20
107
+ ? `${current.getName().substring(0, 17)}...`
108
+ : current.getName();
109
+
110
+ return (
111
+ <Modal
112
+ animationType="slide"
113
+ transparent={false}
114
+ visible={visible}
115
+ onRequestClose={onClose}
116
+ statusBarTranslucent
117
+ >
118
+ <View style={styles.root}>
119
+ {/* Header */}
120
+ <View style={styles.header}>
121
+ <TouchableOpacity
122
+ onPress={onClose}
123
+ style={styles.closeButton}
124
+ accessibilityRole="button"
125
+ accessibilityLabel="Close viewer"
126
+ >
127
+ <Icon name="arrow-back-fill" color="#fff" height={22} width={22} />
128
+ </TouchableOpacity>
129
+
130
+ <View style={styles.headerMeta}>
131
+ <Text style={styles.headerTitle} numberOfLines={1}>
132
+ {shortName}
133
+ </Text>
134
+ <Text style={styles.headerSubtitle}>
135
+ {formatFileSize(current.getSize())}
136
+ </Text>
137
+ </View>
138
+
139
+ <View style={styles.headerActions}>
140
+ <TouchableOpacity
141
+ onPress={handleShare}
142
+ style={styles.actionButton}
143
+ accessibilityRole="button"
144
+ accessibilityLabel="Share"
145
+ >
146
+ <Icon name="share-fill" color="#fff" height={20} width={20} />
147
+ </TouchableOpacity>
148
+ <TouchableOpacity
149
+ onPress={handleDownload}
150
+ style={styles.actionButton}
151
+ accessibilityRole="button"
152
+ accessibilityLabel="Download"
153
+ disabled={downloadState === 'DOWNLOADING'}
154
+ >
155
+ {downloadState === 'DOWNLOADING' && (
156
+ <ActivityIndicator color="#fff" size="small" />
157
+ )}
158
+ {downloadState === 'DONE' && (
159
+ <Text style={styles.checkmark}>{'✓'}</Text>
160
+ )}
161
+ {downloadState !== 'DOWNLOADING' && downloadState !== 'DONE' && (
162
+ <Icon name="download-fill" color="#fff" height={20} width={20} />
163
+ )}
164
+ </TouchableOpacity>
165
+ </View>
166
+ </View>
167
+
168
+ {/* Media area */}
169
+ <View style={styles.mediaArea} {...panResponder.panHandlers}>
170
+ {!imageLoaded && (
171
+ <ActivityIndicator
172
+ color="#fff"
173
+ size="large"
174
+ style={StyleSheet.absoluteFill}
175
+ />
176
+ )}
177
+ <Image
178
+ source={{ uri: current.getUrl() }}
179
+ style={styles.image}
180
+ resizeMode="contain"
181
+ onLoad={() => setImageLoaded(true)}
182
+ />
183
+ </View>
184
+
185
+ {/* Footer: page dots + sender + timestamp */}
186
+ <View style={styles.footer}>
187
+ {attachments.length > 1 && (
188
+ <View style={styles.dotsRow}>
189
+ {attachments.map((a, i) => (
190
+ <View
191
+ key={a.getUrl()}
192
+ style={[
193
+ styles.dot,
194
+ i === currentIndex ? styles.dotActive : undefined,
195
+ ]}
196
+ />
197
+ ))}
198
+ </View>
199
+ )}
200
+ {Boolean(senderName || sentAtStr) && (
201
+ <Text style={styles.senderLine}>
202
+ {senderName ? `Sent by ${senderName}` : ''}
203
+ {senderName && sentAtStr ? ' • ' : ''}
204
+ {sentAtStr}
205
+ </Text>
206
+ )}
207
+ </View>
208
+ </View>
209
+ </Modal>
210
+ );
211
+ };
212
+
213
+ const styles = StyleSheet.create({
214
+ root: {
215
+ flex: 1,
216
+ backgroundColor: '#000',
217
+ },
218
+ header: {
219
+ position: 'absolute',
220
+ top: 0,
221
+ left: 0,
222
+ right: 0,
223
+ zIndex: 10,
224
+ flexDirection: 'row',
225
+ alignItems: 'center',
226
+ paddingTop: 48,
227
+ paddingHorizontal: 12,
228
+ paddingBottom: 12,
229
+ backgroundColor: 'rgba(0,0,0,0.4)',
230
+ },
231
+ closeButton: {
232
+ width: 40,
233
+ height: 40,
234
+ justifyContent: 'center',
235
+ alignItems: 'center',
236
+ },
237
+ headerMeta: {
238
+ flex: 1,
239
+ marginHorizontal: 8,
240
+ },
241
+ headerTitle: {
242
+ color: '#fff',
243
+ fontSize: 15,
244
+ fontWeight: '600',
245
+ },
246
+ headerSubtitle: {
247
+ color: 'rgba(255,255,255,0.7)',
248
+ fontSize: 12,
249
+ marginTop: 1,
250
+ },
251
+ headerActions: {
252
+ flexDirection: 'row',
253
+ gap: 8,
254
+ },
255
+ actionButton: {
256
+ width: 40,
257
+ height: 40,
258
+ justifyContent: 'center',
259
+ alignItems: 'center',
260
+ },
261
+ mediaArea: {
262
+ flex: 1,
263
+ justifyContent: 'center',
264
+ alignItems: 'center',
265
+ marginTop: 100,
266
+ marginBottom: 80,
267
+ },
268
+ image: {
269
+ width: '100%',
270
+ height: '100%',
271
+ },
272
+ footer: {
273
+ position: 'absolute',
274
+ bottom: 0,
275
+ left: 0,
276
+ right: 0,
277
+ paddingBottom: 32,
278
+ paddingHorizontal: 16,
279
+ backgroundColor: 'rgba(0,0,0,0.4)',
280
+ alignItems: 'center',
281
+ gap: 6,
282
+ },
283
+ dotsRow: {
284
+ flexDirection: 'row',
285
+ gap: 6,
286
+ paddingVertical: 8,
287
+ },
288
+ dot: {
289
+ width: 6,
290
+ height: 6,
291
+ borderRadius: 3,
292
+ backgroundColor: 'rgba(255,255,255,0.4)',
293
+ },
294
+ dotActive: {
295
+ backgroundColor: '#fff',
296
+ },
297
+ senderLine: {
298
+ color: 'rgba(255,255,255,0.8)',
299
+ fontSize: 13,
300
+ },
301
+ checkmark: {
302
+ color: '#fff',
303
+ fontSize: 16,
304
+ },
305
+ });
@@ -0,0 +1,2 @@
1
+ export { CometChatAttachmentViewer } from './CometChatAttachmentViewer';
2
+ export type { CometChatAttachmentViewerProps } from './CometChatAttachmentViewer';
@@ -14,11 +14,10 @@ import {
14
14
  } from "react-native";
15
15
  import { Icon } from "../../icons/Icon";
16
16
  import { AnimatedAudioWaves } from "./AnimatedAudioWaves";
17
+ import { audioPlaybackCoordinator } from "../../utils/audioPlaybackCoordinator";
17
18
 
18
19
  const { SoundPlayer } = NativeModules;
19
20
  const eventEmitter = new NativeEventEmitter(SoundPlayer);
20
- let listener: EmitterSubscription;
21
- let interval: ReturnType<typeof setTimeout>;;
22
21
 
23
22
  export interface CometChatAudioBubbleInterface {
24
23
  /**
@@ -61,6 +60,42 @@ export const CometChatAudioBubble = ({
61
60
  const [status, setStatus] = useState<"playing" | "paused" | "loading" | "">("");
62
61
  const [duration, setDuration] = useState(0);
63
62
  const [currentTime, setCurrentTime] = useState(0);
63
+ // Per-instance (the module-level interval/listener were shared across every voice-note bubble).
64
+ const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
65
+ const subRef = useRef<ReturnType<typeof eventEmitter.addListener> | null>(null);
66
+ const statusRef = useRef(status); statusRef.current = status;
67
+ const currentTimeRef = useRef(currentTime); currentTimeRef.current = currentTime;
68
+ // True when this clip was paused because another audio started (native player moved away).
69
+ const wasInterruptedRef = useRef(false);
70
+
71
+ const clearPoll = () => {
72
+ if (intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; }
73
+ };
74
+ const startPoll = () => {
75
+ clearPoll();
76
+ intervalRef.current = setInterval(() => {
77
+ SoundPlayer.getPosition((info: string) => {
78
+ try { if (info) setCurrentTime(JSON.parse(info).position); } catch (e) {}
79
+ });
80
+ }, 500);
81
+ };
82
+ // (Re)play from `fromSeconds`. Announces first so any other playing clip pauses in place.
83
+ const play = (fromSeconds = 0) => {
84
+ audioPlaybackCoordinator.announcePlay(audioUrl);
85
+ wasInterruptedRef.current = false;
86
+ setStatus("loading");
87
+ SoundPlayer.play(audioUrl, (s: string) => {
88
+ try {
89
+ if (JSON.parse(s)?.success) {
90
+ setStatus("playing");
91
+ if (fromSeconds > 0) SoundPlayer.playAt(Math.floor(fromSeconds), () => {});
92
+ startPoll();
93
+ } else {
94
+ setStatus("");
95
+ }
96
+ } catch (ex) { console.log(ex); }
97
+ });
98
+ };
64
99
 
65
100
  useEffect(() => {
66
101
  if (audioUrl) {
@@ -76,20 +111,33 @@ export const CometChatAudioBubble = ({
76
111
  };
77
112
  }, [audioUrl]);
78
113
 
114
+ // WhatsApp coordination: another audio (recorded or shared) starting pauses THIS one in place,
115
+ // keeping its position so it can resume from where it left off.
79
116
  useEffect(() => {
80
- listener = eventEmitter.addListener("soundPlayStatus", (data) => {
81
- if (audioUrl === data.url) {
82
- setStatus("");
83
-
84
- clearInterval(interval);
85
-
86
- setCurrentTime(0);
117
+ const unsub = audioPlaybackCoordinator.subscribe((activeUrl) => {
118
+ if (activeUrl === audioUrl) return;
119
+ if (statusRef.current === "playing" || statusRef.current === "paused") {
120
+ wasInterruptedRef.current = true;
121
+ clearPoll();
122
+ setStatus("paused"); // keep currentTime — position preserved
87
123
  }
88
124
  });
125
+ return unsub;
126
+ }, [audioUrl]);
89
127
 
128
+ // Native fires soundPlayStatus on natural completion AND when a new play() replaces this clip.
129
+ // Interrupt echo (we were interrupted) → ignore; genuine finish → reset to idle.
130
+ useEffect(() => {
131
+ subRef.current = eventEmitter.addListener("soundPlayStatus", (data) => {
132
+ if (audioUrl !== data.url) return;
133
+ if (wasInterruptedRef.current) return;
134
+ setStatus("");
135
+ clearPoll();
136
+ setCurrentTime(0);
137
+ });
90
138
  return () => {
91
- listener.remove();
92
- clearInterval(interval);
139
+ subRef.current?.remove();
140
+ clearPoll();
93
141
  };
94
142
  }, [audioUrl]);
95
143
 
@@ -98,82 +146,31 @@ export const CometChatAudioBubble = ({
98
146
  onPress(audioUrl);
99
147
  return;
100
148
  }
101
-
102
149
  if (status === "playing") {
150
+ // User pause — native player is still ours; a plain resume works later.
151
+ wasInterruptedRef.current = false;
103
152
  SoundPlayer.pause((s: string) => {
104
153
  try {
105
- const json = JSON.parse(s);
106
- if (json["success"] === true) {
154
+ if (JSON.parse(s)?.success) {
107
155
  setStatus("paused");
108
- clearInterval(interval);
156
+ clearPoll();
109
157
  }
110
- } catch (ex) {
111
- console.log(ex);
112
- }
158
+ } catch (ex) { console.log(ex); }
113
159
  });
114
160
  return;
115
161
  }
116
162
  if (status === "paused") {
117
- SoundPlayer.resume();
118
- if (Platform.OS == "ios") {
163
+ if (wasInterruptedRef.current) {
164
+ play(currentTimeRef.current); // player moved away — re-play from where we paused
165
+ } else {
166
+ audioPlaybackCoordinator.announcePlay(audioUrl); // resuming still stops any other clip
167
+ SoundPlayer.resume();
119
168
  setStatus("playing");
169
+ startPoll();
120
170
  }
121
- // Get total duration when audio starts playing
122
- SoundPlayer.getPosition((info: string) => {
123
- try {
124
- if (info) {
125
- if (Platform.OS == "android") {
126
- setStatus("playing");
127
- }
128
- setCurrentTime(JSON.parse(info).position);
129
- }
130
- } catch (e) {}
131
- });
132
-
133
- // Start tracking the current time
134
- interval = setInterval(() => {
135
- SoundPlayer.getPosition((info: string) => {
136
- try {
137
- if (info) {
138
- setCurrentTime(JSON.parse(info).position);
139
- }
140
- } catch (e) {}
141
- });
142
- }, 500);
143
171
  return;
144
172
  }
145
- if (audioUrl) {
146
- setStatus("loading");
147
- SoundPlayer.play(audioUrl, (s: string) => {
148
- try {
149
- const json = JSON.parse(s);
150
- if (json["success"] == true) {
151
- setStatus("playing");
152
- // Get total duration when audio starts playing
153
- SoundPlayer.getPosition((info: string) => {
154
- try {
155
- if (info) {
156
- setCurrentTime(JSON.parse(info).position);
157
- }
158
- } catch (e) {}
159
- });
160
-
161
- // Start tracking the current time
162
- interval = setInterval(() => {
163
- SoundPlayer.getPosition((info: string) => {
164
- try {
165
- if (info) {
166
- setCurrentTime(JSON.parse(info).position);
167
- }
168
- } catch (e) {}
169
- });
170
- }, 500);
171
- }
172
- } catch (ex) {
173
- console.log(ex);
174
- }
175
- });
176
- }
173
+ if (audioUrl) play(currentTimeRef.current || 0);
177
174
  };
178
175
 
179
176
  const pressTime = useRef<number | null>(0);