@cometchat/chat-uikit-react-native 5.2.11 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/android/build.gradle +3 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/CometchatUiKitPackage.java +4 -1
  3. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +909 -10
  4. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorPackage.kt +24 -0
  5. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +5382 -0
  6. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorViewManager.kt +452 -0
  7. package/ios/FileManager.m +430 -3
  8. package/ios/RichTextEditorView.swift +5504 -0
  9. package/ios/RichTextEditorViewManager.m +66 -0
  10. package/ios/RichTextEditorViewManager.swift +291 -0
  11. package/ios/ToolbarIcons.swift +736 -0
  12. package/package.json +1 -1
  13. package/react-native-cometchat-ui-kit.podspec +1 -1
  14. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +4557 -0
  15. package/src/CometChatCompactMessageComposer/SingleLineTextComposerConfiguration.tsx +568 -0
  16. package/src/CometChatCompactMessageComposer/heightUtils.ts +204 -0
  17. package/src/CometChatCompactMessageComposer/index.ts +56 -0
  18. package/src/CometChatCompactMessageComposer/resources/index.ts +5 -0
  19. package/src/CometChatCompactMessageComposer/styles.ts +291 -0
  20. package/src/CometChatConversations/CometChatConversations.tsx +139 -10
  21. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +1 -20
  22. package/src/CometChatMessageComposer/styles.tsx +0 -1
  23. package/src/CometChatMessageList/CometChatMessageList.tsx +6 -1
  24. package/src/CometChatRichTextEditor/RichTextEditorViewNativeComponent.ts +105 -0
  25. package/src/CometChatRichTextEditor/index.tsx +385 -0
  26. package/src/CometChatRichTextEditor/types.ts +162 -0
  27. package/src/CometChatSearch/CometChatSearch.tsx +8 -3
  28. package/src/index.ts +48 -1
  29. package/src/shared/constants/UIKitConstants.ts +12 -1
  30. package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +5 -5
  31. package/src/shared/formatters/CometChatRichTextFormatter/index.tsx +768 -0
  32. package/src/shared/formatters/index.ts +3 -0
  33. package/src/shared/framework/MessageDataSource.tsx +93 -2
  34. package/src/shared/helper/composerHelpers.ts +553 -0
  35. package/src/shared/helper/useKeyboard.tsx +7 -17
  36. package/src/shared/icons/components/code-blocks.tsx +13 -0
  37. package/src/shared/icons/components/code.tsx +11 -0
  38. package/src/shared/icons/components/format-bold.tsx +11 -0
  39. package/src/shared/icons/components/format-italic.tsx +11 -0
  40. package/src/shared/icons/components/format-list-bulleted.tsx +11 -0
  41. package/src/shared/icons/components/format-list-numbered.tsx +11 -0
  42. package/src/shared/icons/components/format-quote.tsx +13 -0
  43. package/src/shared/icons/components/format-strikethrough.tsx +13 -0
  44. package/src/shared/icons/components/format-underlined.tsx +11 -0
  45. package/src/shared/icons/components/smileys-&-people.tsx +1 -1
  46. package/src/shared/icons/icon-mapping.tsx +18 -0
  47. package/src/shared/index.ts +54 -2
  48. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +37 -32
  49. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +5 -0
  50. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +17 -12
  51. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +505 -500
  52. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +18 -13
  53. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +17 -12
  54. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +504 -499
  55. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +504 -499
  56. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +504 -499
  57. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +18 -13
  58. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +17 -12
  59. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +505 -500
  60. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +17 -12
  61. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +17 -12
  62. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +18 -13
  63. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +505 -500
  64. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +17 -12
  65. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +18 -13
  66. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +132 -11
  67. package/src/shared/utils/CometChatMessagePreview/style.ts +1 -3
  68. package/src/shared/utils/MarkdownUtils.ts +143 -0
  69. package/src/shared/utils/MentionUtils.ts +37 -0
  70. package/src/shared/utils/index.ts +5 -0
  71. package/src/shared/views/CometChatInlineAudioRecorder/AudioWaveformVisualizer.tsx +417 -0
  72. package/src/shared/views/CometChatInlineAudioRecorder/CometChatInlineAudioRecorder.tsx +537 -0
  73. package/src/shared/views/CometChatInlineAudioRecorder/index.ts +34 -0
  74. package/src/shared/views/CometChatInlineAudioRecorder/style.ts +155 -0
  75. package/src/shared/views/CometChatInlineAudioRecorder/types.ts +303 -0
  76. package/src/shared/views/CometChatInlineAudioRecorder/useAudioRecorder.ts +1336 -0
  77. package/src/shared/views/CometChatLinkConfirmPopup/CometChatLinkConfirmPopup.tsx +183 -0
  78. package/src/shared/views/CometChatLinkConfirmPopup/index.ts +13 -0
  79. package/src/shared/views/CometChatLinkConfirmPopup/style.ts +128 -0
  80. package/src/shared/views/CometChatSendButtonView/CometChatSendButtonView.tsx +32 -29
  81. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +64 -16
  82. package/src/shared/views/index.ts +39 -0
@@ -0,0 +1,4557 @@
1
+ import React, { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo } from 'react';
2
+ import {
3
+ Animated,
4
+ View,
5
+ TextInput,
6
+ TouchableOpacity,
7
+ StyleProp,
8
+ ViewStyle,
9
+ TextStyle,
10
+ KeyboardAvoidingViewProps,
11
+ KeyboardAvoidingView,
12
+ Modal,
13
+ Platform,
14
+ NativeModules,
15
+ Text,
16
+ Image,
17
+ Dimensions,
18
+ ImageSourcePropType,
19
+ ImageStyle,
20
+ InteractionManager,
21
+ Keyboard,
22
+ ColorValue,
23
+ TouchableWithoutFeedbackProps,
24
+ ScrollView,
25
+ StyleSheet,
26
+ } from 'react-native';
27
+ import { JSX } from 'react';
28
+ import RichTextEditor, {
29
+ type RichTextEditorRef,
30
+ type ContentChangeEvent,
31
+ type ActiveStylesState,
32
+ } from '../CometChatRichTextEditor';
33
+
34
+ /**
35
+ * Link tap event data emitted by the native editor when a user taps an existing link.
36
+ * Matches the LinkTapEventData interface from the rich text editor bridge source.
37
+ */
38
+ interface LinkTapEventData {
39
+ url: string;
40
+ text: string;
41
+ location: number;
42
+ length: number;
43
+ }
44
+ import { Style } from './styles';
45
+ import {
46
+ calculateInputHeight,
47
+ resolveEffectiveMaxHeight,
48
+ getIconAlignment,
49
+ DEFAULT_MIN_HEIGHT,
50
+ DEFAULT_LINE_HEIGHT,
51
+ DEFAULT_PADDING_VERTICAL,
52
+ } from './heightUtils';
53
+ //@ts-ignore
54
+ import { CometChat } from '@cometchat/chat-sdk-react-native';
55
+ import { startStreamingForRunId, stopStreamingForRunId, streamingState$ } from '../shared/services/stream-message.service';
56
+ import {
57
+ CometChatSoundManager,
58
+ CometChatMentionsFormatter,
59
+ CometChatUrlsFormatter,
60
+ CometChatTextFormatter,
61
+ ChatConfigurator,
62
+ CometChatUIKit,
63
+ CometChatBottomSheet,
64
+ CometChatActionSheet,
65
+ CometChatMediaRecorder,
66
+ CometChatMessagePreview,
67
+ CometChatSuggestionList,
68
+ SuggestionItem,
69
+ useCometChatTranslation,
70
+ CometChatUIEvents,
71
+ CometChatInlineAudioRecorder,
72
+ } from '../shared';
73
+ import { useTheme } from '../theme';
74
+ import { CometChatTheme } from '../theme/type';
75
+ import { deepMerge } from '../shared/helper/helperFunctions';
76
+ import { CometChatMessageComposerAction, DeepPartial } from '../shared/helper/types';
77
+ import {
78
+ isAgenticUser as checkIsAgenticUser,
79
+ setQuotedMessageSafe,
80
+ deriveHideButton,
81
+ deriveDisableFeature,
82
+ ReplyMessageState,
83
+ parseMentionKey,
84
+ calcDeletionRange,
85
+ collectOverlappingMentions,
86
+ shiftRemainingMentionKeys,
87
+ MentionOverlap,
88
+ } from '../shared/helper/composerHelpers';
89
+ import { Icon } from '../shared/icons/Icon';
90
+ import { CometChatSendButtonView } from '../shared/views/CometChatSendButtonView/CometChatSendButtonView';
91
+ import { CometChatLinkConfirmPopup } from '../shared/views/CometChatLinkConfirmPopup';
92
+ import {
93
+ getUnixTimestampInMilliseconds,
94
+ messageStatus,
95
+ } from '../shared/utils/CometChatMessageHelper';
96
+ import { MessageTypeConstants, ReceiverTypeConstants, ConversationOptionConstants, MentionsVisibility, MentionsTargetElement, ViewAlignment, EnterKeyBehavior } from '../shared/constants/UIKitConstants';
97
+ import { MessageEvents } from '../shared/events';
98
+ import { CometChatUIEventHandler } from '../shared/events/CometChatUIEventHandler/CometChatUIEventHandler';
99
+ import { CometChatMessageEvents } from '../shared/events/CometChatMessageEvents';
100
+ import { ICONS } from './resources';
101
+ import { CommonUtils } from '../shared/utils/CommonUtils';
102
+ import { isCursorWithinMentionRange, getMentionRangeAtCursor } from '../shared/utils/MentionUtils';
103
+ import { stripMarkdown } from '../shared/utils/MarkdownUtils';
104
+ import { commonVars } from '../shared/base/vars';
105
+ import { permissionUtil } from '../shared/utils/PermissionUtil';
106
+ import { CheckPropertyExists } from '../shared/helper/functions';
107
+ import { CometChatStickerKeyboard } from '../extensions/Stickers/CometChatStickerKeyboard';
108
+ import { ExtensionTypeConstants } from '../extensions/ExtensionConstants';
109
+
110
+ const { FileManager, CommonUtil } = NativeModules;
111
+
112
+ // Listener IDs at module scope (v5 pattern)
113
+ const editMessageListenerID = "editMessageListener_" + new Date().getTime();
114
+ const replyMessageListenerID = "replyMessageListener_" + new Date().getTime();
115
+ const uiEventListenerID = "uiEventListener_" + new Date().getTime();
116
+ const uiEventListenerShowID = "uiEventListenerShow_" + new Date().getTime();
117
+ const uiEventListenerHideID = "uiEventListenerHide_" + new Date().getTime();
118
+
119
+ // Mic/sticker animation constants (hoisted to module level)
120
+ const MIC_ANIM_DURATION = 150;
121
+ const MIC_SLIDE_DISTANCE = 40;
122
+
123
+ // URL detection regex for paste-over-selection link creation (hoisted to module level)
124
+ // Note: paste-URL-over-selection is handled natively in iOS/Android editors
125
+
126
+ /**
127
+ * Styles for the custom rich text formatting toolbar.
128
+ * Note: theme-dependent values (colors) are applied inline at render time.
129
+ * Layout values use static constants since they don't vary by theme.
130
+ */
131
+ const richTextToolbarStyles = StyleSheet.create({
132
+ btn: {
133
+ width: 36,
134
+ height: 36,
135
+ borderRadius: 6,
136
+ justifyContent: 'center',
137
+ alignItems: 'center',
138
+ },
139
+ separator: {
140
+ width: 1,
141
+ height: 20,
142
+ marginHorizontal: 4,
143
+ },
144
+ });
145
+
146
+ /**
147
+ * Toolbar item configuration for the rich text formatting toolbar.
148
+ * Items with type 'separator' render a vertical divider.
149
+ * Items with type 'button' render a tappable icon.
150
+ */
151
+ type ToolbarSeparator = { type: 'separator' };
152
+ type ToolbarButton = {
153
+ type: 'button';
154
+ key: string;
155
+ icon: any;
156
+ iconName?: string;
157
+ isActive?: (styles: ActiveStylesState) => boolean;
158
+ onPress: (
159
+ inputRef: React.RefObject<any>,
160
+ selectionPosition: { start: number; end: number },
161
+ inputTextRef: React.RefObject<string>,
162
+ setLinkText: (t: string) => void,
163
+ setLinkUrl: (u: string) => void,
164
+ setShowLinkModal: (v: boolean) => void,
165
+ ) => void;
166
+ };
167
+ type ToolbarItem = ToolbarSeparator | ToolbarButton;
168
+
169
+ const richTextToolbarItems: ToolbarItem[] = [
170
+ { type: 'button', key: 'bold', icon: null, iconName: 'format-bold', isActive: (s) => s.bold, onPress: (ref) => ref.current?.toggleBold() },
171
+ { type: 'button', key: 'italic', icon: null, iconName: 'format-italic', isActive: (s) => s.italic, onPress: (ref) => ref.current?.toggleItalic() },
172
+ { type: 'button', key: 'underline', icon: null, iconName: 'format-underlined', isActive: (s) => s.underline, onPress: (ref) => ref.current?.toggleUnderline() },
173
+ { type: 'button', key: 'strikethrough', icon: null, iconName: 'format-strikethrough', isActive: (s) => s.strikethrough, onPress: (ref) => ref.current?.toggleStrikethrough() },
174
+ { type: 'separator' },
175
+ {
176
+ type: 'button', key: 'link', icon: null, iconName: 'link',
177
+ onPress: (_ref, selectionPosition, inputTextRef, setLinkText, setLinkUrl, setShowLinkModal) => {
178
+ const { start, end } = selectionPosition;
179
+ const currentText = inputTextRef.current || '';
180
+ const selectedText = start !== end ? currentText.substring(start, end) : '';
181
+ setLinkText(selectedText);
182
+ setLinkUrl('');
183
+ setShowLinkModal(true);
184
+ },
185
+ },
186
+ { type: 'button', key: 'ordered-list', icon: null, iconName: 'format-list-numbered', isActive: (s) => s.blockType === 'numbered' || s.blockType === 'quoteNumbered', onPress: (ref) => ref.current?.setNumberedList() },
187
+ { type: 'button', key: 'unordered-list', icon: null, iconName: 'format-list-bulleted', isActive: (s) => s.blockType === 'bullet' || s.blockType === 'quoteBullet', onPress: (ref) => ref.current?.setBulletList() },
188
+ { type: 'separator' },
189
+ { type: 'button', key: 'blockquote', icon: null, iconName: 'format-quote', isActive: (s) => s.blockType === 'quote' || s.blockType === 'quoteBullet' || s.blockType === 'quoteNumbered', onPress: (ref) => ref.current?.setQuote() },
190
+ { type: 'button', key: 'inline-code', icon: null, iconName: 'code', isActive: (s) => s.code, onPress: (ref) => ref.current?.toggleCode() },
191
+ { type: 'button', key: 'code-block', icon: null, iconName: 'code-blocks', onPress: (ref) => ref.current?.toggleCodeBlock() },
192
+ ];
193
+
194
+ /**
195
+ * ActionSheetBoard component for displaying attachment options (v5 pattern)
196
+ */
197
+ const ActionSheetBoard = (props: any) => {
198
+ const { shouldShow = false, onClose = () => {}, options = [], sheetRef, style } = props;
199
+ return (
200
+ <CometChatBottomSheet
201
+ style={{ maxHeight: Dimensions.get("window").height * 0.49 }}
202
+ ref={sheetRef}
203
+ onClose={onClose}
204
+ isOpen={shouldShow}
205
+ >
206
+ <CometChatActionSheet actions={options} style={style} />
207
+ </CometChatBottomSheet>
208
+ );
209
+ };
210
+
211
+ /**
212
+ * RecordAudio component for voice recording (v5 pattern)
213
+ */
214
+ const RecordAudio = (props: any) => {
215
+ const {
216
+ shouldShow = false,
217
+ onClose = () => {},
218
+ cometChatBottomSheetStyle = {},
219
+ sheetRef,
220
+ onPause = () => {},
221
+ onPlay = () => {},
222
+ onSend = (_recordedFile: string) => {},
223
+ onStop = (_recordedFile: string) => {},
224
+ onStart = () => {},
225
+ mediaRecorderStyle,
226
+ } = props;
227
+ return (
228
+ <CometChatBottomSheet
229
+ ref={sheetRef}
230
+ onClose={onClose}
231
+ style={cometChatBottomSheetStyle}
232
+ isOpen={shouldShow}
233
+ >
234
+ <CometChatMediaRecorder
235
+ onClose={onClose}
236
+ onPause={onPause}
237
+ onPlay={onPlay}
238
+ onSend={onSend}
239
+ onStop={onStop}
240
+ onStart={onStart}
241
+ style={mediaRecorderStyle}
242
+ />
243
+ </CometChatBottomSheet>
244
+ );
245
+ };
246
+
247
+ /**
248
+ * MessagePreviewTray component for displaying edit/reply message preview (v5 pattern)
249
+ */
250
+ const MessagePreviewTray = (props: any) => {
251
+ const { shouldShow = false, text = '', onClose = () => {}, title = '' } = props;
252
+ if (!shouldShow) return null;
253
+ return (
254
+ <CometChatMessagePreview
255
+ messagePreviewTitle={title}
256
+ messagePreviewSubtitle={stripMarkdown(text)}
257
+ onCloseClick={onClose}
258
+ />
259
+ );
260
+ };
261
+
262
+ /**
263
+ * AttachIconButton component for attachment button (v5 pattern)
264
+ */
265
+ const AttachIconButton = (props: {
266
+ onPress: TouchableWithoutFeedbackProps["onPress"];
267
+ icon: ImageSourcePropType | JSX.Element;
268
+ iconStyle: ImageStyle;
269
+ }) => {
270
+ return (
271
+ <TouchableOpacity onPress={props.onPress}>
272
+ <Icon
273
+ name='add-circle'
274
+ icon={props.icon}
275
+ color={props.iconStyle.tintColor}
276
+ height={props.iconStyle.height}
277
+ width={props.iconStyle.width}
278
+ imageStyle={props.iconStyle}
279
+ />
280
+ </TouchableOpacity>
281
+ );
282
+ };
283
+
284
+ /**
285
+ * EmojiButton component for SingleLineTextComposer.
286
+ * A custom emoji/sticker button with proper styling (no extra padding).
287
+ * Opens the sticker keyboard panel when pressed.
288
+ */
289
+ interface EmojiButtonProps {
290
+ user?: CometChat.User;
291
+ group?: CometChat.Group;
292
+ composerIdMap: Map<string, any>;
293
+ replyToMessage?: CometChat.BaseMessage;
294
+ closeReplyPreview?: () => void;
295
+ editorRef?: React.RefObject<RichTextEditorRef | null>;
296
+ }
297
+
298
+ const EmojiButton = ({ user, group, composerIdMap, replyToMessage, closeReplyPreview, editorRef }: EmojiButtonProps) => {
299
+ const [isPanelOpen, setIsPanelOpen] = React.useState(false);
300
+ const [keyboardOpen, setKeyboardOpen] = React.useState(false);
301
+ const theme = useTheme();
302
+ const loggedInUser = React.useRef<CometChat.User | null>(null);
303
+ const uiListenerIdRef = React.useRef<string>(`emoji_button_${Date.now()}`);
304
+
305
+ // Use refs to store reply message info to avoid stale closures
306
+ const replyToMessageRef = React.useRef(replyToMessage);
307
+ const closeReplyPreviewRef = React.useRef(closeReplyPreview);
308
+
309
+ // Update refs when props change
310
+ React.useEffect(() => {
311
+ replyToMessageRef.current = replyToMessage;
312
+ closeReplyPreviewRef.current = closeReplyPreview;
313
+ }, [replyToMessage, closeReplyPreview]);
314
+
315
+ // Fetch logged-in user
316
+ React.useEffect(() => {
317
+ CometChat.getLoggedinUser().then((u: CometChat.User | null) => {
318
+ if (u) loggedInUser.current = u;
319
+ });
320
+ }, []);
321
+
322
+ // Keyboard event handling
323
+ const keyboardShowEvent = Platform.select({
324
+ ios: "keyboardWillShow",
325
+ android: "keyboardDidShow",
326
+ }) as any;
327
+
328
+ const keyboardHideEvent = Platform.select({
329
+ ios: "keyboardWillHide",
330
+ android: "keyboardDidHide",
331
+ }) as any;
332
+
333
+ React.useEffect(() => {
334
+ const keyboardDidShowListener = Keyboard.addListener(keyboardShowEvent, () => {
335
+ setKeyboardOpen(true);
336
+ if (isPanelOpen) {
337
+ closePanel();
338
+ }
339
+ });
340
+
341
+ const keyboardDidHideListener = Keyboard.addListener(keyboardHideEvent, () => {
342
+ setKeyboardOpen(false);
343
+ });
344
+
345
+ return () => {
346
+ keyboardDidShowListener.remove();
347
+ keyboardDidHideListener.remove();
348
+ };
349
+ }, [isPanelOpen, keyboardShowEvent, keyboardHideEvent]);
350
+
351
+ // Send sticker message
352
+ const sendCustomMessage = React.useCallback((sticker: any) => {
353
+ let receiverId = user?.getUid() || group?.getGuid();
354
+ let receiverType = user
355
+ ? CometChat.RECEIVER_TYPE.USER
356
+ : group
357
+ ? CometChat.RECEIVER_TYPE.GROUP
358
+ : undefined;
359
+
360
+ if (!receiverType) return;
361
+
362
+ let customType = ExtensionTypeConstants.sticker;
363
+ let parentId = composerIdMap?.get("parentMessageId") || undefined;
364
+ let customMessage = new CometChat.CustomMessage(
365
+ receiverId,
366
+ receiverType,
367
+ customType,
368
+ sticker
369
+ );
370
+
371
+ customMessage.setCategory(CometChat.CATEGORY_CUSTOM as CometChat.MessageCategory);
372
+ customMessage.setParentMessageId(parentId);
373
+ customMessage.setMuid(String(getUnixTimestampInMilliseconds()));
374
+ customMessage.setSender(loggedInUser.current!);
375
+ if (user || group) {
376
+ customMessage.setReceiver((user || group)!);
377
+ }
378
+ customMessage.shouldUpdateConversation(true);
379
+ customMessage.setMetadata({ incrementUnreadCount: true });
380
+
381
+ // Set quoted message if replying
382
+ const currentReplyMessage = replyToMessageRef.current;
383
+ if (currentReplyMessage) {
384
+ customMessage.setQuotedMessage(currentReplyMessage);
385
+ customMessage.setQuotedMessageId(currentReplyMessage.getId());
386
+ }
387
+
388
+ // Close reply preview
389
+ const currentClosePreview = closeReplyPreviewRef.current;
390
+ if (currentClosePreview) {
391
+ currentClosePreview();
392
+ }
393
+
394
+ CometChatUIKit.sendCustomMessage(customMessage)
395
+ .then((res: CometChat.BaseMessage) => {
396
+ if (currentReplyMessage) {
397
+ CometChatMessageEvents.emit(CometChatMessageEvents.ccReplyToMessage, {
398
+ message: res,
399
+ status: messageStatus.success,
400
+ });
401
+ }
402
+ })
403
+ .catch((err: any) => {
404
+ console.error("Failed to send sticker:", err);
405
+ });
406
+ }, [user, group, composerIdMap]);
407
+
408
+ const openPanel = React.useCallback(() => {
409
+ Keyboard.dismiss();
410
+ editorRef?.current?.blur();
411
+ setIsPanelOpen(true);
412
+ CometChatUIEventHandler.emitUIEvent(CometChatUIEvents.showPanel, {
413
+ alignment: ViewAlignment.composerBottom,
414
+ child: () => <CometChatStickerKeyboard onPress={sendCustomMessage} />,
415
+ panelId: "sticker",
416
+ });
417
+ }, [sendCustomMessage, editorRef]);
418
+
419
+ const closePanel = React.useCallback(() => {
420
+ CometChatUIEventHandler.emitUIEvent(CometChatUIEvents.hidePanel, {
421
+ alignment: ViewAlignment.composerBottom,
422
+ child: () => null,
423
+ panelId: "sticker",
424
+ });
425
+ setIsPanelOpen(false);
426
+ }, []);
427
+
428
+ const togglePanel = React.useCallback(() => {
429
+ if (isPanelOpen) {
430
+ closePanel();
431
+ } else {
432
+ if (keyboardOpen) {
433
+ Keyboard.dismiss();
434
+ setTimeout(() => {
435
+ openPanel();
436
+ }, 200);
437
+ } else {
438
+ openPanel();
439
+ }
440
+ }
441
+ }, [isPanelOpen, keyboardOpen, openPanel, closePanel]);
442
+
443
+ // Listen to global UI events
444
+ React.useEffect(() => {
445
+ const id = uiListenerIdRef.current;
446
+ CometChatUIEventHandler.addUIListener(id, {
447
+ hidePanel: (payload: any) => {
448
+ if (isPanelOpen) {
449
+ if (!payload || payload?.panelId === "sticker" || payload?.alignment === ViewAlignment.composerBottom) {
450
+ setIsPanelOpen(false);
451
+ }
452
+ }
453
+ },
454
+ showPanel: (payload: any) => {
455
+ if (payload?.panelId === "sticker") {
456
+ setIsPanelOpen(true);
457
+ }
458
+ },
459
+ });
460
+ return () => {
461
+ CometChatUIEventHandler.removeUIListener(id);
462
+ };
463
+ }, [isPanelOpen]);
464
+
465
+ return (
466
+ <TouchableOpacity
467
+ onPress={togglePanel}
468
+ style={Style.iconButton}
469
+ accessibilityHint='Opens the sticker panel'
470
+ >
471
+ <Icon
472
+ name={isPanelOpen ? "sticker-fill" : "sticker"}
473
+ width={24}
474
+ height={24}
475
+ color={isPanelOpen ? theme.color.primary : theme.color.iconSecondary}
476
+ />
477
+ </TouchableOpacity>
478
+ );
479
+ };
480
+
481
+ /**
482
+ * Style interface for CometChatSingleLineMessageComposer.
483
+ * This is a type alias for backward compatibility with v4 patterns.
484
+ * In v5, styles are defined using DeepPartial<CometChatTheme["messageComposerStyles"]>.
485
+ */
486
+ export type SingleLineMessageComposerStyleInterface = DeepPartial<CometChatTheme["messageComposerStyles"]>;
487
+
488
+ /**
489
+ * Props interface for the CometChatSingleLineMessageComposer component (v5 pattern)
490
+ *
491
+ * This interface matches CometChatMessageComposerInterface for full API compatibility.
492
+ */
493
+ export interface CometChatCompactMessageComposerInterface {
494
+ /**
495
+ * Message composer identifier.
496
+ * @type {string | number}
497
+ */
498
+ id?: string | number;
499
+
500
+ /**
501
+ * CometChat SDK's user object.
502
+ * @type {CometChat.User}
503
+ */
504
+ user?: CometChat.User;
505
+
506
+ /**
507
+ * CometChat SDK's group object.
508
+ * @type {CometChat.Group}
509
+ */
510
+ group?: CometChat.Group;
511
+
512
+ /**
513
+ * Initial text value for the input.
514
+ * @type {string}
515
+ */
516
+ text?: string;
517
+
518
+ /**
519
+ * Placeholder text for the input.
520
+ * @type {string}
521
+ */
522
+ placeHolderText?: string;
523
+
524
+ /**
525
+ * Callback triggered when the input text changes.
526
+ * @param {string} text - The updated text.
527
+ */
528
+ onChangeText?: (text: string) => void;
529
+
530
+ /**
531
+ * Flag to turn off sound for outgoing messages.
532
+ * @type {boolean}
533
+ */
534
+ disableSoundForOutgoingMessages?: boolean;
535
+
536
+ /**
537
+ * Flag to turn off sound for messages (alias for disableSoundForOutgoingMessages).
538
+ * @type {boolean}
539
+ */
540
+ disableSoundForMessages?: boolean;
541
+
542
+ /**
543
+ * Custom audio sound to be played while sending messages.
544
+ * @type {*}
545
+ */
546
+ customSoundForOutgoingMessage?: any;
547
+
548
+ /**
549
+ * Custom audio sound for messages (alias for customSoundForOutgoingMessage).
550
+ * @type {*}
551
+ */
552
+ customSoundForMessage?: any;
553
+
554
+ /**
555
+ * Flag to disable typing events.
556
+ * @type {boolean}
557
+ */
558
+ disableTypingEvents?: boolean;
559
+
560
+ /**
561
+ * Initial text to be displayed in the composer.
562
+ * @type {string}
563
+ */
564
+ initialComposertext?: string;
565
+
566
+ /**
567
+ * Renders a preview section at the top of the composer.
568
+ */
569
+ HeaderView?: ({ user, group }: { user?: CometChat.User; group?: CometChat.Group }) => JSX.Element;
570
+
571
+ /**
572
+ * Renders a footer section at the bottom of the composer.
573
+ */
574
+ FooterView?: ({ user, group }: { user?: CometChat.User; group?: CometChat.Group }) => JSX.Element;
575
+
576
+ /**
577
+ * Callback triggered when the input text changes (alias for onChangeText).
578
+ * @param {string} text - The updated text.
579
+ */
580
+ onTextChange?: (text: string) => void;
581
+
582
+ /**
583
+ * Returns the attachment options for the composer.
584
+ */
585
+ attachmentOptions?: ({
586
+ user,
587
+ group,
588
+ composerId,
589
+ }: {
590
+ user?: CometChat.User;
591
+ group?: CometChat.Group;
592
+ composerId: Map<any, any>;
593
+ }) => CometChatMessageComposerAction[];
594
+
595
+ /**
596
+ * Replaces the default Auxiliary Button.
597
+ */
598
+ AuxiliaryButtonView?: ({
599
+ user,
600
+ group,
601
+ composerId,
602
+ }: {
603
+ user?: CometChat.User;
604
+ group?: CometChat.Group;
605
+ composerId: string | number;
606
+ }) => JSX.Element;
607
+
608
+ /**
609
+ * Replaces the default Secondary Button (attachment button).
610
+ */
611
+ SecondaryButtonView?: ({
612
+ user,
613
+ group,
614
+ composerId,
615
+ }: {
616
+ user?: CometChat.User;
617
+ group?: CometChat.Group;
618
+ composerId: string | number;
619
+ }) => JSX.Element;
620
+
621
+ /**
622
+ * Replaces the default Send Button.
623
+ */
624
+ SendButtonView?: ({
625
+ user,
626
+ group,
627
+ composerId,
628
+ }: {
629
+ user?: CometChat.User;
630
+ group?: CometChat.Group;
631
+ composerId: string | number;
632
+ }) => JSX.Element;
633
+
634
+ /**
635
+ * Message id required for threaded messages.
636
+ * @type {string | number}
637
+ */
638
+ parentMessageId?: string | number;
639
+
640
+ /**
641
+ * Custom styles for the message composer component.
642
+ */
643
+ style?: DeepPartial<CometChatTheme["messageComposerStyles"]>;
644
+
645
+ /**
646
+ * Custom styles for the message composer (alias for style).
647
+ */
648
+ messageComposerStyle?: DeepPartial<CometChatTheme["messageComposerStyles"]>;
649
+
650
+ /**
651
+ * Custom styles for the input field.
652
+ */
653
+ inputStyle?: StyleProp<TextStyle>;
654
+
655
+ /**
656
+ * Custom styles for the send button.
657
+ */
658
+ sendButtonStyle?: StyleProp<ViewStyle>;
659
+
660
+ /**
661
+ * Custom icon for the send button.
662
+ */
663
+ sendButtonIcon?: ImageSourcePropType;
664
+
665
+ /**
666
+ * Flag to hide the voice recording button.
667
+ * @type {boolean}
668
+ */
669
+ hideVoiceRecordingButton?: boolean;
670
+
671
+ /**
672
+ * Flag to hide voice recording (alias for hideVoiceRecordingButton).
673
+ * @type {boolean}
674
+ */
675
+ hideVoiceRecording?: boolean;
676
+
677
+ /**
678
+ * Custom icon URL for voice recording.
679
+ */
680
+ voiceRecordingIconURL?: ImageSourcePropType;
681
+
682
+ /**
683
+ * Custom styles for the media recorder.
684
+ */
685
+ mediaRecorderStyle?: any;
686
+
687
+ /**
688
+ * Custom pause icon URL for media recorder.
689
+ */
690
+ pauseIconUrl?: ImageSourcePropType;
691
+
692
+ /**
693
+ * Custom play icon URL for media recorder.
694
+ */
695
+ playIconUrl?: ImageSourcePropType;
696
+
697
+ /**
698
+ * Custom record icon URL for media recorder.
699
+ */
700
+ recordIconUrl?: ImageSourcePropType;
701
+
702
+ /**
703
+ * Custom delete icon URL for media recorder.
704
+ */
705
+ deleteIconUrl?: ImageSourcePropType;
706
+
707
+ /**
708
+ * Custom stop icon URL for media recorder.
709
+ */
710
+ stopIconUrl?: ImageSourcePropType;
711
+
712
+ /**
713
+ * Custom submit icon URL for media recorder.
714
+ */
715
+ submitIconUrl?: ImageSourcePropType;
716
+
717
+ /**
718
+ * Callback triggered when voice recording starts.
719
+ */
720
+ onVoiceRecordingStart?: () => void;
721
+
722
+ /**
723
+ * Callback triggered when voice recording ends.
724
+ * @param {string} recordedFile - The path to the recorded file.
725
+ */
726
+ onVoiceRecordingEnd?: (recordedFile: string) => void;
727
+
728
+ /**
729
+ * Callback triggered when the send button is pressed.
730
+ * @param {CometChat.BaseMessage} message - The base message object.
731
+ */
732
+ onSendButtonPress?: (message: CometChat.BaseMessage) => void;
733
+
734
+ /**
735
+ * Callback triggered when an error occurs.
736
+ * @param {CometChat.CometChatException} error - The error object.
737
+ */
738
+ onError?: (error: CometChat.CometChatException) => void;
739
+
740
+ /**
741
+ * Override properties for the KeyboardAvoidingView.
742
+ */
743
+ keyboardAvoidingViewProps?: KeyboardAvoidingViewProps;
744
+
745
+ /**
746
+ * Collection of text formatter classes to apply custom formatting.
747
+ */
748
+ textFormatters?: Array<
749
+ CometChatMentionsFormatter | CometChatUrlsFormatter | CometChatTextFormatter
750
+ >;
751
+
752
+ /**
753
+ * Flag to disable mention functionality.
754
+ */
755
+ disableMentions?: boolean;
756
+
757
+ /**
758
+ * Flag to disable the special group mention (@all / @channel etc.).
759
+ * @default false
760
+ */
761
+ disableMentionAll?: boolean;
762
+
763
+ /**
764
+ * Custom alias label for the group-wide mention.
765
+ * @default "all"
766
+ */
767
+ mentionAllLabel?: string;
768
+
769
+ /**
770
+ * Controls image quality when taking pictures from the camera.
771
+ * @default 20
772
+ */
773
+ imageQuality?: number;
774
+
775
+ /**
776
+ * If true, hides the camera option from the attachment options.
777
+ */
778
+ hideCameraOption?: boolean;
779
+
780
+ /**
781
+ * If true, hides the image attachment option from the attachment options.
782
+ */
783
+ hideImageAttachmentOption?: boolean;
784
+
785
+ /**
786
+ * If true, hides the video attachment option from the attachment options.
787
+ */
788
+ hideVideoAttachmentOption?: boolean;
789
+
790
+ /**
791
+ * If true, hides the audio attachment option from the attachment options.
792
+ */
793
+ hideAudioAttachmentOption?: boolean;
794
+
795
+ /**
796
+ * If true, hides the file/document attachment option from the attachment options.
797
+ */
798
+ hideFileAttachmentOption?: boolean;
799
+
800
+ /**
801
+ * If true, hides the polls option from the attachment options.
802
+ */
803
+ hidePollsAttachmentOption?: boolean;
804
+
805
+ /**
806
+ * If true, hides the collaborative document option.
807
+ */
808
+ hideCollaborativeDocumentOption?: boolean;
809
+
810
+ /**
811
+ * If true, hides the collaborative whiteboard option.
812
+ */
813
+ hideCollaborativeWhiteboardOption?: boolean;
814
+
815
+ /**
816
+ * If true, hides the entire attachment button from the composer.
817
+ */
818
+ hideAttachmentButton?: boolean;
819
+
820
+ /**
821
+ * Custom icon for the attachment button.
822
+ */
823
+ attachmentIcon?: ImageSourcePropType;
824
+
825
+ /**
826
+ * Callback triggered when the attachment button is clicked.
827
+ */
828
+ onAttachmentClick?: () => void;
829
+
830
+ /**
831
+ * If true, hides the stickers button from the composer.
832
+ */
833
+ hideStickersButton?: boolean;
834
+
835
+ /**
836
+ * If true, hides the send button from the composer.
837
+ */
838
+ hideSendButton?: boolean;
839
+
840
+ /**
841
+ * If true, hides all auxiliary buttons.
842
+ */
843
+ hideAuxiliaryButtons?: boolean;
844
+
845
+ /**
846
+ * If true, hides the auxiliary button (alias for hideAuxiliaryButtons).
847
+ */
848
+ hideAuxiliaryButton?: boolean;
849
+
850
+ /**
851
+ * Additional attachment options to append to defaults.
852
+ */
853
+ addAttachmentOptions?: ({
854
+ user,
855
+ group,
856
+ composerId,
857
+ }: {
858
+ user?: CometChat.User;
859
+ group?: CometChat.Group;
860
+ composerId: Map<any, any>;
861
+ }) => CometChatMessageComposerAction[];
862
+
863
+ /**
864
+ * Determines the alignment of auxiliary buttons.
865
+ * @default "left"
866
+ */
867
+ auxiliaryButtonsAlignment?: "left" | "right";
868
+
869
+ /**
870
+ * Determines the alignment of auxiliary buttons (deprecated alias).
871
+ * @default "right"
872
+ */
873
+ auxiliaryButtonAlignment?: "left" | "right";
874
+
875
+ /**
876
+ * Custom send button view for AI agents (only applies to @agentic users)
877
+ */
878
+ AgentSendButtonView?: React.ComponentType<{
879
+ isButtonDisabled: boolean;
880
+ composerRef: any;
881
+ }>;
882
+
883
+ // ============================================
884
+ // Auto-Expand Configuration Props (SingleLineTextComposer specific)
885
+ // ============================================
886
+
887
+ /**
888
+ * Maximum number of lines before scrolling is enabled.
889
+ * @default 5
890
+ */
891
+ maxLines?: number;
892
+
893
+ /**
894
+ * Enable rich text formatting toolbar (bold, italic, underline, strikethrough, code).
895
+ * When true, an inline toolbar is shown above the text input.
896
+ * When false, the editor behaves like a plain TextInput.
897
+ * @default true
898
+ */
899
+ enableRichTextEditor?: boolean;
900
+
901
+ /**
902
+ * Hides all rich text formatting options.
903
+ * When true, the toolbar is always visible by default (no toggle needed).
904
+ * @default false
905
+ */
906
+ hideRichTextFormattingOptions?: boolean;
907
+
908
+ /**
909
+ * Behavior when Enter key is pressed (Android only — iOS always inserts new line).
910
+ * @default EnterKeyBehavior.NewLine
911
+ * @platform Android
912
+ */
913
+ enterKeyBehavior?: EnterKeyBehavior;
914
+
915
+ /**
916
+ * Show Bold/Italic/Underline/Strikethrough in the text selection context menu.
917
+ * When true, formatting options appear in the native text selection popup.
918
+ * @default true
919
+ */
920
+ showTextSelectionMenuItems?: boolean;
921
+
922
+ /**
923
+ * Maximum number of mentions allowed per message.
924
+ * @default 10
925
+ */
926
+ maxMentionLimit?: number;
927
+
928
+ /**
929
+ * Callback triggered when mention limit is reached.
930
+ */
931
+ onMentionLimitReached?: () => void;
932
+
933
+ /**
934
+ * Minimum height for the input in pixels.
935
+ * @default 40
936
+ */
937
+ minInputHeight?: number;
938
+
939
+ /**
940
+ * Maximum height for the input in pixels.
941
+ */
942
+ maxInputHeight?: number;
943
+ }
944
+
945
+ /**
946
+ * Helper component for icon buttons (v5 pattern)
947
+ */
948
+ const IconButton = (props: {
949
+ icon?: ImageSourcePropType | JSX.Element;
950
+ name?: string;
951
+ onClick: () => void;
952
+ buttonStyle?: StyleProp<ViewStyle>;
953
+ iconStyle?: ImageStyle;
954
+ disable?: boolean;
955
+ tintColor?: ColorValue;
956
+ testID?: string;
957
+ }) => {
958
+ const { icon, name, onClick, buttonStyle, iconStyle, disable, tintColor, testID } = props;
959
+ return (
960
+ <TouchableOpacity
961
+ testID={testID}
962
+ activeOpacity={disable ? 1 : 0.7}
963
+ onPress={disable ? undefined : onClick}
964
+ style={[Style.imageButtonBase, buttonStyle]}
965
+ >
966
+ <Icon
967
+ name={name as any}
968
+ icon={icon}
969
+ color={tintColor}
970
+ height={iconStyle?.height || 24}
971
+ width={iconStyle?.width || 24}
972
+ imageStyle={iconStyle}
973
+ />
974
+ </TouchableOpacity>
975
+ );
976
+ };
977
+
978
+ /**
979
+ * CometChatSingleLineMessageComposer - A compact, single-line text input component
980
+ * for composing and sending text messages.
981
+ *
982
+ * This component is API-compatible with CometChatMessageComposer, allowing
983
+ * developers to easily swap between the two based on their UI requirements.
984
+ *
985
+ * Key differences from CometChatMessageComposer:
986
+ * - Single-line input (no multiline support)
987
+ * - Text-only messaging (no attachments, voice recording, etc.)
988
+ * - Compact UI suitable for inline messaging scenarios
989
+ *
990
+ * @example
991
+ * // Basic usage
992
+ * <CometChatSingleLineMessageComposer user={user} />
993
+ *
994
+ * @example
995
+ * // With custom auxiliary buttons
996
+ * <CometChatSingleLineMessageComposer
997
+ * user={user}
998
+ * AuxiliaryButtonView={() => <MyCustomButtons />}
999
+ * auxiliaryButtonsAlignment="right"
1000
+ * />
1001
+ */
1002
+ export const CometChatCompactMessageComposer = React.forwardRef(
1003
+ (props: CometChatCompactMessageComposerInterface, ref) => {
1004
+ const theme = useTheme();
1005
+ const { t } = useCometChatTranslation();
1006
+
1007
+ const {
1008
+ id,
1009
+ user,
1010
+ group,
1011
+ text,
1012
+ placeHolderText,
1013
+ onChangeText,
1014
+ style,
1015
+ messageComposerStyle, // API compatibility
1016
+ inputStyle,
1017
+ sendButtonStyle,
1018
+ sendButtonIcon,
1019
+ SendButtonView,
1020
+ onSendButtonPress,
1021
+ AuxiliaryButtonView,
1022
+ SecondaryButtonView,
1023
+ auxiliaryButtonsAlignment,
1024
+ auxiliaryButtonAlignment, // deprecated alias
1025
+ hideAuxiliaryButton,
1026
+ hideAuxiliaryButtons,
1027
+ hideAttachmentButton: propHideAttachmentButton,
1028
+ hideStickersButton: propHideStickersButton,
1029
+ hideSendButton,
1030
+ HeaderView,
1031
+ FooterView,
1032
+ parentMessageId,
1033
+ disableTypingEvents: propDisableTypingEvents,
1034
+ disableMentions: propDisableMentions,
1035
+ disableSoundForMessages = true,
1036
+ customSoundForMessage,
1037
+ textFormatters,
1038
+ onError,
1039
+ keyboardAvoidingViewProps,
1040
+ // Attachment props
1041
+ attachmentIcon,
1042
+ attachmentOptions,
1043
+ onAttachmentClick,
1044
+ imageQuality = 20,
1045
+ // Additional attachment options
1046
+ addAttachmentOptions,
1047
+ // Individual hide options for attachments
1048
+ hideCameraOption,
1049
+ hideImageAttachmentOption,
1050
+ hideVideoAttachmentOption,
1051
+ hideAudioAttachmentOption,
1052
+ hideFileAttachmentOption,
1053
+ hidePollsAttachmentOption,
1054
+ hideCollaborativeDocumentOption,
1055
+ hideCollaborativeWhiteboardOption,
1056
+ // Voice recording props
1057
+ hideVoiceRecording: propHideVoiceRecording,
1058
+ voiceRecordingIconURL,
1059
+ mediaRecorderStyle,
1060
+ pauseIconUrl,
1061
+ playIconUrl,
1062
+ recordIconUrl,
1063
+ deleteIconUrl,
1064
+ stopIconUrl,
1065
+ submitIconUrl,
1066
+ onVoiceRecordingStart,
1067
+ onVoiceRecordingEnd,
1068
+ // Auto-expand configuration props
1069
+ maxLines,
1070
+ minInputHeight,
1071
+ maxInputHeight,
1072
+ // Rich text formatting prop
1073
+ enableRichTextEditor = true,
1074
+ hideRichTextFormattingOptions = false,
1075
+ enterKeyBehavior = EnterKeyBehavior.NewLine,
1076
+ showTextSelectionMenuItems = true,
1077
+ maxMentionLimit = 10,
1078
+ onMentionLimitReached,
1079
+ // Agentic user props
1080
+ AgentSendButtonView,
1081
+ // Initial text prop
1082
+ initialComposertext,
1083
+ // Mention configuration props
1084
+ disableMentionAll = false,
1085
+ mentionAllLabel = "all",
1086
+ } = props;
1087
+
1088
+ // Auto-expand is always enabled (internal behavior)
1089
+ const autoExpand = true;
1090
+
1091
+ // ============================================
1092
+ // Agentic User Support
1093
+ // ============================================
1094
+
1095
+ /**
1096
+ * Helper function to check if the current user is an agentic user.
1097
+ * Agentic users have the role '@agentic' and require special handling:
1098
+ * - Auto-hide certain buttons (attachment, stickers, voice recording)
1099
+ * - Disable typing events and mentions
1100
+ * - Apply send button delay
1101
+ * - Track parent message ID for threaded conversations
1102
+ *
1103
+ * @returns {boolean} True if user has role '@agentic'
1104
+ */
1105
+ const isAgenticUser = useCallback((): boolean => {
1106
+ return checkIsAgenticUser(user);
1107
+ }, [user]);
1108
+
1109
+ /**
1110
+ * Derived state variables for automatic button hiding for agentic users.
1111
+ * When user is agentic, these buttons are automatically hidden regardless of prop values.
1112
+ * Uses shared helper function for consistency with CometChatMessageComposer.
1113
+ */
1114
+ const isAgentic = isAgenticUser();
1115
+ const hideAttachmentButton = deriveHideButton(isAgentic, propHideAttachmentButton);
1116
+ const hideStickersButton = deriveHideButton(isAgentic, propHideStickersButton);
1117
+ const hideVoiceRecordingButton = deriveHideButton(isAgentic, propHideVoiceRecording);
1118
+
1119
+ /**
1120
+ * Derived state variables for disabling typing events and mentions for agentic users.
1121
+ * When user is agentic, these features are automatically disabled.
1122
+ * Uses shared helper function for consistency with CometChatMessageComposer.
1123
+ */
1124
+ const disableTypingEvents = deriveDisableFeature(isAgentic, propDisableTypingEvents);
1125
+ const disableMentions = deriveDisableFeature(isAgentic, propDisableMentions);
1126
+
1127
+ // Resolve alignment (support both prop names)
1128
+ const resolvedAlignment = auxiliaryButtonsAlignment || auxiliaryButtonAlignment || 'right';
1129
+
1130
+ // Merge styles using deepMerge (support both style and messageComposerStyle)
1131
+ // For agentic users, hide the divider line
1132
+ const mergedComposerStyle = useMemo(() => {
1133
+ const propStyle = style || messageComposerStyle || {};
1134
+ const mergedStyle = deepMerge(theme.messageComposerStyles || {}, propStyle);
1135
+
1136
+ // Hide divider for agentic users (matching CometChatMessageComposer behavior)
1137
+ if (isAgentic) {
1138
+ return {
1139
+ ...mergedStyle,
1140
+ messageInputStyles: {
1141
+ ...mergedStyle.messageInputStyles,
1142
+ dividerStyle: {
1143
+ display: 'none' as const
1144
+ }
1145
+ }
1146
+ };
1147
+ }
1148
+ return mergedStyle;
1149
+ }, [theme.messageComposerStyles, style, messageComposerStyle, isAgentic]);
1150
+
1151
+ // Use merged style throughout the component
1152
+ const resolvedStyle = mergedComposerStyle;
1153
+
1154
+ /**
1155
+ * inputTextRef: holds the current text value without triggering re-renders.
1156
+ * Updated on every keystroke from onContentChange.
1157
+ * inputText state is only updated for programmatic changes (mentions, clear, edit)
1158
+ * to push text to native via the text prop.
1159
+ */
1160
+ const inputTextRef = React.useRef(initialComposertext ?? text ?? '');
1161
+ const [inputText, setInputText] = React.useState(initialComposertext ?? text ?? '');
1162
+
1163
+ /**
1164
+ * Flag to skip the next onContentChange after a programmatic text update.
1165
+ * Prevents handleTextChange from processing the echo of our own setText.
1166
+ */
1167
+ const skipNextContentChange = React.useRef(false);
1168
+
1169
+ /**
1170
+ * Timestamp until which onSelectionChange events should be ignored.
1171
+ * After programmatic setText (e.g. mention insertion), the native side
1172
+ * fires multiple selection change events that reset cursor to 0.
1173
+ * We ignore all selection events for a short window after setText.
1174
+ */
1175
+ const ignoreSelectionUntil = React.useRef(0);
1176
+
1177
+ /**
1178
+ * Stores the latest blocks from the RichTextEditor's onContentChange.
1179
+ * Used to convert structured formatting data to markdown when sending.
1180
+ */
1181
+ const blocksRef = React.useRef<any[]>([]);
1182
+
1183
+ /**
1184
+ * Structured blocks to load into the native editor when entering edit mode.
1185
+ * Parsed from the original message's markdown via markdownToBlocks.
1186
+ * Passed as the `initialContent` prop so the editor displays WYSIWYG formatting.
1187
+ * Reset to undefined when edit mode is exited or input is cleared.
1188
+ */
1189
+ const [editContentBlocks, setEditContentBlocks] = React.useState<any[] | undefined>(undefined);
1190
+
1191
+ const [isVisible, setIsVisible] = React.useState(false);
1192
+ const [CustomView, setCustomView] = React.useState<React.ReactNode>(null);
1193
+ const [CustomViewHeader, setCustomViewHeader] = React.useState<React.FC | React.ReactNode>(null);
1194
+ const [CustomViewFooter, setCustomViewFooter] = React.useState<React.FC | React.ReactNode>(null);
1195
+ const [kbOffset, setKbOffset] = React.useState(59);
1196
+ const [showActionSheet, setShowActionSheet] = React.useState(false);
1197
+ const [actionSheetItems, setActionSheetItems] = React.useState<CometChatMessageComposerAction[]>([]);
1198
+ const [showInlineRecorder, setShowInlineRecorder] = React.useState(false);
1199
+
1200
+ // Mic/sticker animation: single Animated.Value drives mic slide + fade
1201
+ // 0 = idle (mic visible), 1 = typing (mic hidden)
1202
+ const micAnimValue = React.useRef(new Animated.Value(0)).current;
1203
+ const [messagePreview, setMessagePreview] = React.useState<{ message: any; mode: string } | null>(null);
1204
+ const [showMentionList, setShowMentionList] = React.useState(false);
1205
+ const [mentionsSearchData, setMentionsSearchData] = React.useState<Array<SuggestionItem>>([]);
1206
+ const [suggestionListLoader, setSuggestionListLoader] = React.useState(false);
1207
+ const [selectionPosition, setSelectionPosition] = React.useState<{ start: number; end: number }>({ start: 0, end: 0 });
1208
+
1209
+ // Active formatting styles state — tracks which styles are active at the cursor position
1210
+ const [activeStyles, setActiveStyles] = React.useState<ActiveStylesState>({
1211
+ bold: false,
1212
+ italic: false,
1213
+ underline: false,
1214
+ strikethrough: false,
1215
+ code: false,
1216
+ codeBlock: false,
1217
+ highlight: false,
1218
+ blockType: 'paragraph',
1219
+ alignment: 'left',
1220
+ });
1221
+ // Ref mirror of activeStyles — always current (no render-cycle delay).
1222
+ // Used by shouldOpenList so the mention popup isn't blocked by stale state
1223
+ // after exiting a code block.
1224
+ const activeStylesRef = React.useRef<ActiveStylesState>(activeStyles);
1225
+
1226
+ // Link modal state (Slack-style: prefills selected text)
1227
+ const [showLinkModal, setShowLinkModal] = React.useState(false);
1228
+ const [linkText, setLinkText] = React.useState('');
1229
+ const [linkUrl, setLinkUrl] = React.useState('');
1230
+
1231
+ // Link tap dialog state (edit/remove existing links)
1232
+ const [linkTapData, setLinkTapData] = React.useState<{
1233
+ url: string; text: string; location: number; length: number;
1234
+ } | null>(null);
1235
+ const [linkEditMode, setLinkEditMode] = React.useState(false);
1236
+ const [editLinkUrl, setEditLinkUrl] = React.useState('');
1237
+ const [editLinkText, setEditLinkText] = React.useState('');
1238
+
1239
+ // Track which code button is active (inline code vs code block)
1240
+ const [codeBlockActive, setCodeBlockActive] = React.useState(false);
1241
+
1242
+ // Focus tracking for floating toolbar visibility
1243
+ const [isFocused, setIsFocused] = React.useState(false);
1244
+
1245
+
1246
+ /**
1247
+ * Tracks links inserted via the JS modal.
1248
+ * Maps link display text to URL. Used at send time to wrap
1249
+ * matching text with [text](url) markdown as a fallback
1250
+ * in case the native editor's blocks data is stale.
1251
+ */
1252
+ const pendingLinksRef = React.useRef<Map<string, string>>(new Map());
1253
+
1254
+ /**
1255
+ * Handles link tap events from the native editor.
1256
+ * Opens the link tap dialog with the tapped link's metadata.
1257
+ */
1258
+ const onLinkTap = useCallback((data: LinkTapEventData) => {
1259
+ setLinkTapData(data);
1260
+ setLinkEditMode(false);
1261
+ setEditLinkUrl(data.url);
1262
+ setEditLinkText(data.text);
1263
+ }, []);
1264
+
1265
+ /**
1266
+ * Sets input text programmatically — used for mentions, clear, edit message.
1267
+ * Updates React state (for UI like send button) and pushes to native
1268
+ * via imperative setText command (force=true bypasses typing guard).
1269
+ * The text prop is NOT used (removed from JSX to prevent cursor jumping).
1270
+ */
1271
+ const setInputTextProgrammatic = React.useCallback((newText: string) => {
1272
+ inputTextRef.current = newText;
1273
+ skipNextContentChange.current = true;
1274
+ setInputText(newText);
1275
+ inputRef.current?.setText?.(newText);
1276
+ }, []);
1277
+
1278
+ // ============================================
1279
+ // Warning Message Support
1280
+ // ============================================
1281
+
1282
+ /**
1283
+ * State for tracking warning message (e.g., mention limit reached).
1284
+ * When set, displays a warning in the CustomViewHeader area.
1285
+ */
1286
+ const [warningMessage, setWarningMessage] = React.useState<string>('');
1287
+
1288
+ // ============================================
1289
+ // Reply Message Support
1290
+ // ============================================
1291
+
1292
+ /**
1293
+ * State for tracking reply message.
1294
+ * When set, displays a reply preview and attaches the quoted message to sent messages.
1295
+ */
1296
+ const [replyMessage, setReplyMessage] = React.useState<ReplyMessageState | null>(null);
1297
+
1298
+ /**
1299
+ * Ref to hold current replyMessage value to avoid stale closures in callbacks.
1300
+ * This is necessary because attachment handlers and other callbacks may capture
1301
+ * stale state values.
1302
+ */
1303
+ const replyMessageRef = React.useRef(replyMessage);
1304
+
1305
+ /**
1306
+ * Callback to close the reply preview.
1307
+ * Clears the reply message state and hides the preview.
1308
+ */
1309
+ const closeReplyPreview = useCallback(() => {
1310
+ setReplyMessage(null);
1311
+ }, []);
1312
+
1313
+ // ============================================
1314
+ // Agentic User State Management
1315
+ // ============================================
1316
+
1317
+ /**
1318
+ * State for tracking send button delay for agentic users.
1319
+ * When true, the send button is disabled for 1 second after sending.
1320
+ */
1321
+ const [isSendButtonDisabledForDelay, setIsSendButtonDisabledForDelay] = React.useState(false);
1322
+
1323
+ /**
1324
+ * State for tracking streaming status for agentic users.
1325
+ * Used to show/hide the stop button during AI response streaming.
1326
+ */
1327
+ const [isStreaming, setIsStreaming] = React.useState(false);
1328
+ const [showStopButton, setShowStopButton] = React.useState(false);
1329
+
1330
+ // ============================================
1331
+ // Auto-Expand Height State Management
1332
+ // ============================================
1333
+
1334
+ /**
1335
+ * Resolve the effective min and max heights for auto-expand mode.
1336
+ * Uses props, style overrides, or defaults in that order of precedence.
1337
+ */
1338
+ const resolvedMinHeight = minInputHeight ?? DEFAULT_MIN_HEIGHT;
1339
+ const resolvedLineHeight = DEFAULT_LINE_HEIGHT;
1340
+ const resolvedMaxHeight = resolveEffectiveMaxHeight({
1341
+ maxLines,
1342
+ maxHeight: maxInputHeight,
1343
+ lineHeight: resolvedLineHeight,
1344
+ paddingVertical: DEFAULT_PADDING_VERTICAL,
1345
+ });
1346
+
1347
+ /**
1348
+ * State for tracking the current input height.
1349
+ * Initialized to minHeight (single-line height).
1350
+ * Only used when autoExpand is true.
1351
+ *
1352
+ */
1353
+ const [inputHeight, setInputHeight] = React.useState<number>(resolvedMinHeight);
1354
+
1355
+ /**
1356
+ * State for tracking whether the input is expanded beyond single-line height.
1357
+ * Used for icon alignment and other UI adjustments.
1358
+ *
1359
+ */
1360
+ const [isExpanded, setIsExpanded] = React.useState<boolean>(false);
1361
+
1362
+ // ============================================
1363
+ // Debouncing for Height Updates
1364
+ // ============================================
1365
+
1366
+ /**
1367
+ * Debounce delay in milliseconds.
1368
+ * 16ms corresponds to one frame at 60fps, ensuring smooth updates
1369
+ * while preventing excessive re-renders during rapid typing.
1370
+ *
1371
+ */
1372
+ const DEBOUNCE_DELAY_MS = 16;
1373
+
1374
+ /**
1375
+ * Ref to track pending height update timeout.
1376
+ * Used to debounce rapid content size changes and prevent flickering.
1377
+ *
1378
+ */
1379
+ const pendingHeightUpdateRef = React.useRef<NodeJS.Timeout | null>(null);
1380
+
1381
+ /**
1382
+ * Ref to store the latest pending height value.
1383
+ * This ensures that only the final height value within the debounce
1384
+ * window is applied to state (debounce idempotence).
1385
+ *
1386
+ */
1387
+ const pendingHeightValueRef = React.useRef<number | null>(null);
1388
+
1389
+ /**
1390
+ * Cleanup pending height update timeout on unmount.
1391
+ * Prevents memory leaks and state updates on unmounted component.
1392
+ *
1393
+ */
1394
+ useEffect(() => {
1395
+ return () => {
1396
+ if (pendingHeightUpdateRef.current) {
1397
+ clearTimeout(pendingHeightUpdateRef.current);
1398
+ pendingHeightUpdateRef.current = null;
1399
+ }
1400
+ };
1401
+ }, []);
1402
+
1403
+ /**
1404
+ * Apply the debounced height update to state.
1405
+ * Only updates if the new height differs from current height.
1406
+ *
1407
+ * @param newHeight - The new height value to apply
1408
+ *
1409
+ */
1410
+ const applyHeightUpdate = useCallback((newHeight: number) => {
1411
+ // Only update state if height has changed
1412
+ if (newHeight !== inputHeight) {
1413
+ setInputHeight(newHeight);
1414
+
1415
+ // Update expanded state based on whether height exceeds minHeight
1416
+ const newIsExpanded = newHeight > resolvedMinHeight;
1417
+ if (newIsExpanded !== isExpanded) {
1418
+ setIsExpanded(newIsExpanded);
1419
+ }
1420
+ }
1421
+ }, [inputHeight, isExpanded, resolvedMinHeight]);
1422
+
1423
+ /**
1424
+ * Handle content size changes from the TextInput.
1425
+ * Uses debouncing to prevent flickering during rapid content changes.
1426
+ * Calculates the new height using utility functions and updates state
1427
+ * only when the height actually changes.
1428
+ *
1429
+ * This handler supports both expansion (when text is added) and contraction
1430
+ * (when text is deleted). When text is deleted and content height decreases,
1431
+ * the input height shrinks accordingly, returning to minHeight when the
1432
+ * content fits within a single line.
1433
+ *
1434
+ * @param event - The content size change event from TextInput
1435
+ *
1436
+ */
1437
+ const handleContentSizeChange = useCallback((event: { nativeEvent: { contentSize: { width: number; height: number } } }) => {
1438
+ if (!autoExpand) {
1439
+ return;
1440
+ }
1441
+
1442
+ const { height: contentHeight } = event.nativeEvent.contentSize;
1443
+
1444
+ // Calculate the new height using the utility function
1445
+ const newHeight = calculateInputHeight(contentHeight, resolvedMinHeight, resolvedMaxHeight);
1446
+
1447
+ // Store the latest pending height value
1448
+ pendingHeightValueRef.current = newHeight;
1449
+
1450
+ // Clear any existing pending update
1451
+ if (pendingHeightUpdateRef.current) {
1452
+ clearTimeout(pendingHeightUpdateRef.current);
1453
+ }
1454
+
1455
+ // Schedule debounced height update
1456
+ pendingHeightUpdateRef.current = setTimeout(() => {
1457
+ // Apply the latest pending height value
1458
+ if (pendingHeightValueRef.current !== null) {
1459
+ applyHeightUpdate(pendingHeightValueRef.current);
1460
+ pendingHeightValueRef.current = null;
1461
+ }
1462
+ pendingHeightUpdateRef.current = null;
1463
+ }, DEBOUNCE_DELAY_MS);
1464
+ }, [autoExpand, resolvedMinHeight, resolvedMaxHeight, applyHeightUpdate]);
1465
+
1466
+ // Refs (v5 pattern: use React.useRef)
1467
+ const loggedInUser = React.useRef<CometChat.User | null>(null);
1468
+ const chatWith = React.useRef<string>('');
1469
+ const chatWithId = React.useRef<string>('');
1470
+ const inputRef = React.useRef<RichTextEditorRef>(null);
1471
+ const isTyping = React.useRef<NodeJS.Timeout | null>(null);
1472
+ const allFormatters = React.useRef<Map<string, CometChatTextFormatter | CometChatMentionsFormatter>>(new Map());
1473
+ const bottomSheetRef = React.useRef<any>(null);
1474
+ const mentionMap = React.useRef<Map<string, SuggestionItem>>(new Map());
1475
+ const trackingCharacters = React.useRef<string[]>([]);
1476
+ const activeCharacter = React.useRef<string>('');
1477
+ const searchStringRef = React.useRef<string>('');
1478
+ // Initialize plainTextInputRef with initialComposertext if provided
1479
+ const plainTextInputRef = React.useRef<string>(initialComposertext ?? '');
1480
+
1481
+ /**
1482
+ * Syncs mention ranges from mentionMap to the native editor for visual styling.
1483
+ * Converts mentionMap keys ("start_end") into [{start, end}] and dispatches
1484
+ * the setMentionRanges command so the native side can apply bold purple + background.
1485
+ */
1486
+ const syncMentionRanges = React.useCallback(() => {
1487
+ const ranges: Array<{ start: number; end: number }> = [];
1488
+ mentionMap.current.forEach((_value, key) => {
1489
+ const parts = key.split('_');
1490
+ const start = parseInt(parts[0], 10);
1491
+ const end = parseInt(parts[1], 10);
1492
+ if (!isNaN(start) && !isNaN(end)) {
1493
+ ranges.push({ start, end });
1494
+ }
1495
+ });
1496
+ inputRef.current?.setMentionRanges?.(ranges);
1497
+ }, []);
1498
+
1499
+ /**
1500
+ * Ref for tracking send button delay timer for agentic users.
1501
+ * Used to clear the timer on unmount to prevent memory leaks.
1502
+ */
1503
+ const sendButtonDelayTimer = React.useRef<NodeJS.Timeout | null>(null);
1504
+
1505
+ /**
1506
+ * Ref for tracking parent message ID for agentic users.
1507
+ * After first message sent to agentic user without parentMessageId prop,
1508
+ * stores the message ID for subsequent messages.
1509
+ */
1510
+ const parentMessageIdRef = React.useRef<number | null>(null);
1511
+
1512
+ // Handle platform-specific keyboard offset (iOS safe area insets)
1513
+ useLayoutEffect(() => {
1514
+ if (Platform.OS === 'ios') {
1515
+ if (Number.isInteger(commonVars.safeAreaInsets.top)) {
1516
+ setKbOffset(commonVars.safeAreaInsets.top ?? 59);
1517
+ return;
1518
+ }
1519
+ CommonUtil?.getSafeAreaInsets?.().then((res: { top: number; bottom: number }) => {
1520
+ if (Number.isInteger(res.top)) {
1521
+ commonVars.safeAreaInsets.top = res.top;
1522
+ commonVars.safeAreaInsets.bottom = res.bottom;
1523
+ setKbOffset(res.top);
1524
+ }
1525
+ }).catch(() => {
1526
+ // Fallback to default offset if native module fails
1527
+ });
1528
+ }
1529
+ }, []);
1530
+
1531
+ // Get logged in user
1532
+ useEffect(() => {
1533
+ CometChat.getLoggedinUser()
1534
+ .then((u: CometChat.User | null) => {
1535
+ if (u) {
1536
+ loggedInUser.current = u;
1537
+ }
1538
+ })
1539
+ .catch((error: CometChat.CometChatException) => {
1540
+ onError?.(error);
1541
+ });
1542
+ }, []);
1543
+
1544
+ /**
1545
+ * Subscribe to streaming state observable for agentic users.
1546
+ * Updates isStreaming state when streaming status changes.
1547
+ * Hides stop button when streaming ends.
1548
+ */
1549
+ useEffect(() => {
1550
+ const sub = streamingState$.subscribe((streaming) => {
1551
+ setIsStreaming(streaming);
1552
+ if (!streaming) setShowStopButton(false);
1553
+ });
1554
+ return () => sub.unsubscribe();
1555
+ }, []);
1556
+
1557
+ /**
1558
+ * Cleanup effect for send button delay timer.
1559
+ * Clears the timer on unmount to prevent memory leaks.
1560
+ */
1561
+ useEffect(() => {
1562
+ return () => {
1563
+ if (sendButtonDelayTimer.current) {
1564
+ clearTimeout(sendButtonDelayTimer.current);
1565
+ sendButtonDelayTimer.current = null;
1566
+ }
1567
+ };
1568
+ }, []);
1569
+
1570
+ /**
1571
+ * Keep replyMessageRef in sync with replyMessage state.
1572
+ * This ensures callbacks always have access to the current reply message value.
1573
+ */
1574
+ useEffect(() => {
1575
+ replyMessageRef.current = replyMessage;
1576
+ }, [replyMessage]);
1577
+
1578
+ // Configure receiver from user prop
1579
+ useEffect(() => {
1580
+ if (user) {
1581
+ chatWith.current = ReceiverTypeConstants.user;
1582
+ chatWithId.current = user.getUid();
1583
+ }
1584
+ }, [user]);
1585
+
1586
+ // Configure receiver from group prop
1587
+ useEffect(() => {
1588
+ if (group) {
1589
+ chatWith.current = ReceiverTypeConstants.group;
1590
+ chatWithId.current = group.getGuid();
1591
+ }
1592
+ }, [group]);
1593
+
1594
+ // Initialize text formatters
1595
+ useEffect(() => {
1596
+ let _formatter = [...(textFormatters || [])];
1597
+
1598
+ // Add default mentions formatter if not disabled
1599
+ if (!disableMentions) {
1600
+ const mentionsFormatter = ChatConfigurator.getDataSource().getMentionsFormatter();
1601
+ if (CometChatUIKit.loggedInUser) {
1602
+ mentionsFormatter.setLoggedInUser(CometChatUIKit.loggedInUser);
1603
+ }
1604
+ mentionsFormatter.setContext?.("composer");
1605
+ if (resolvedStyle?.mentionsStyle) {
1606
+ mentionsFormatter.setMentionsStyle(
1607
+ resolvedStyle.mentionsStyle as CometChatTheme["mentionsStyle"]
1608
+ );
1609
+ }
1610
+ // Set target element for mentions (matching MessageComposer pattern)
1611
+ mentionsFormatter.setTargetElement?.(MentionsTargetElement.textinput);
1612
+
1613
+ // Configure mention all settings
1614
+ if (mentionAllLabel) {
1615
+ mentionsFormatter.setMentionAllLabel(mentionAllLabel);
1616
+ }
1617
+ mentionsFormatter.setDisableMentionAll(disableMentionAll);
1618
+
1619
+ if (user) {
1620
+ mentionsFormatter.setUser(user);
1621
+ }
1622
+ if (group) {
1623
+ mentionsFormatter.setGroup(group);
1624
+ }
1625
+ _formatter.unshift(mentionsFormatter);
1626
+ }
1627
+
1628
+ _formatter.forEach((formatter) => {
1629
+ if (id !== undefined) {
1630
+ formatter.setComposerId(id);
1631
+ }
1632
+ if (user) {
1633
+ formatter.setUser(user);
1634
+ }
1635
+ if (group) {
1636
+ formatter.setGroup(group);
1637
+ }
1638
+
1639
+ // Get tracking character for this formatter
1640
+ const trackingChar = formatter.getTrackingCharacter?.();
1641
+
1642
+ // Clone and store formatter using tracking character as key (matching MessageComposer pattern)
1643
+ const newFormatter = CommonUtils.clone(formatter);
1644
+ if (trackingChar) {
1645
+ allFormatters.current.set(trackingChar, newFormatter);
1646
+
1647
+ // Set up tracking characters for mention detection
1648
+ if (!trackingCharacters.current.includes(trackingChar)) {
1649
+ trackingCharacters.current.push(trackingChar);
1650
+ }
1651
+ }
1652
+ });
1653
+ }, []);
1654
+
1655
+ // Initialize input with text prop
1656
+ useEffect(() => {
1657
+ if (text !== undefined) {
1658
+ setInputTextProgrammatic(text);
1659
+ }
1660
+ }, [text]);
1661
+
1662
+ // Create composerId map for attachment options
1663
+ const composerIdMap = new Map().set('parentMessageId', parentMessageId);
1664
+
1665
+ /**
1666
+ * Handle custom view click for attachment options
1667
+ */
1668
+ const handleOnClick = (CustomViewFn: any) => {
1669
+ const view = CustomViewFn(
1670
+ user,
1671
+ group,
1672
+ {
1673
+ uid: user?.getUid(),
1674
+ guid: group?.getGuid(),
1675
+ parentMessageId: parentMessageId,
1676
+ },
1677
+ {
1678
+ onClose: () => setIsVisible(false),
1679
+ }
1680
+ );
1681
+ bottomSheetRef.current?.togglePanel();
1682
+ setTimeout(() => {
1683
+ setCustomView(() => view);
1684
+ setIsVisible(true);
1685
+ }, 200);
1686
+ };
1687
+
1688
+ // Initialize attachment options
1689
+ useEffect(() => {
1690
+ const defaultAttachmentOptions =
1691
+ ChatConfigurator.dataSource.getAttachmentOptions(
1692
+ theme,
1693
+ user,
1694
+ group,
1695
+ composerIdMap,
1696
+ {
1697
+ // Individual hide options
1698
+ hideCameraOption,
1699
+ hideImageAttachmentOption,
1700
+ hideVideoAttachmentOption,
1701
+ hideAudioAttachmentOption,
1702
+ hideFileAttachmentOption,
1703
+ hidePollsAttachmentOption,
1704
+ hideCollaborativeDocumentOption,
1705
+ hideCollaborativeWhiteboardOption,
1706
+ // Reply context
1707
+ replyToMessage: replyMessage?.message,
1708
+ closeReplyPreview,
1709
+ }
1710
+ );
1711
+
1712
+ setActionSheetItems(() =>
1713
+ attachmentOptions && typeof attachmentOptions === 'function'
1714
+ ? attachmentOptions({ user, group, composerId: composerIdMap })?.map((item) => {
1715
+ if (typeof item.CustomView === 'function')
1716
+ return {
1717
+ ...item,
1718
+ onPress: () => handleOnClick(item.CustomView),
1719
+ };
1720
+ if (typeof item.onPress === 'function')
1721
+ return {
1722
+ ...item,
1723
+ onPress: () => {
1724
+ setShowActionSheet(false);
1725
+ item.onPress?.(user, group);
1726
+ },
1727
+ };
1728
+ return {
1729
+ ...item,
1730
+ onPress: () => fileInputHandler(item.id ?? ''),
1731
+ };
1732
+ })
1733
+ : [
1734
+ // Default attachment options
1735
+ ...defaultAttachmentOptions.map((item) => {
1736
+ if (typeof item.CustomView === 'function')
1737
+ return {
1738
+ ...item,
1739
+ onPress: () => handleOnClick(item.CustomView),
1740
+ };
1741
+ if (typeof item.onPress === 'function')
1742
+ return {
1743
+ ...item,
1744
+ onPress: () => {
1745
+ setShowActionSheet(false);
1746
+ item.onPress(user, group);
1747
+ },
1748
+ };
1749
+ return {
1750
+ ...item,
1751
+ onPress: () => fileInputHandler(item.id),
1752
+ };
1753
+ }),
1754
+ // Additional attachment options
1755
+ ...(addAttachmentOptions && typeof addAttachmentOptions === 'function'
1756
+ ? addAttachmentOptions({ user, group, composerId: composerIdMap })?.map((item) => {
1757
+ if (typeof item.CustomView === 'function')
1758
+ return {
1759
+ ...item,
1760
+ onPress: () => handleOnClick(item.CustomView),
1761
+ };
1762
+ if (typeof item.onPress === 'function')
1763
+ return {
1764
+ ...item,
1765
+ onPress: () => {
1766
+ setShowActionSheet(false);
1767
+ item.onPress?.(user, group);
1768
+ },
1769
+ };
1770
+ return {
1771
+ ...item,
1772
+ onPress: () => fileInputHandler(item.id ?? ''),
1773
+ };
1774
+ })
1775
+ : []),
1776
+ ]
1777
+ );
1778
+ }, [
1779
+ user,
1780
+ group,
1781
+ id,
1782
+ parentMessageId,
1783
+ hideCameraOption,
1784
+ hideImageAttachmentOption,
1785
+ hideVideoAttachmentOption,
1786
+ hideAudioAttachmentOption,
1787
+ hideFileAttachmentOption,
1788
+ hidePollsAttachmentOption,
1789
+ hideCollaborativeDocumentOption,
1790
+ hideCollaborativeWhiteboardOption,
1791
+ addAttachmentOptions,
1792
+ replyMessage,
1793
+ closeReplyPreview,
1794
+ ]);
1795
+
1796
+ /**
1797
+ * Handle panel show/hide events
1798
+ * Updates CustomViewHeader and CustomViewFooter based on alignment
1799
+ *
1800
+ */
1801
+ const handlePanel = useCallback((item: { child?: React.FC | React.ReactNode; alignment?: string }) => {
1802
+ if (item.child) {
1803
+ if (item.alignment === ViewAlignment.composerTop) {
1804
+ // Handle both FC and ReactNode types
1805
+ const childContent = typeof item.child === 'function'
1806
+ ? React.createElement(item.child as React.FC)
1807
+ : item.child;
1808
+ setCustomViewHeader(childContent);
1809
+ } else if (item.alignment === ViewAlignment.composerBottom) {
1810
+ const childContent = typeof item.child === 'function'
1811
+ ? React.createElement(item.child as React.FC)
1812
+ : item.child;
1813
+ setCustomViewFooter(childContent);
1814
+ }
1815
+ } else {
1816
+ if (item.alignment === ViewAlignment.composerTop) {
1817
+ setCustomViewHeader(null);
1818
+ } else if (item.alignment === ViewAlignment.composerBottom) {
1819
+ setCustomViewFooter(null);
1820
+ }
1821
+ }
1822
+ }, []);
1823
+
1824
+ // Add edit message event listener
1825
+ useEffect(() => {
1826
+ CometChatUIEventHandler.addMessageListener(editMessageListenerID, {
1827
+ ccMessageEdited: (item: { message: any; status: string }) => previewMessage(item),
1828
+ });
1829
+
1830
+ return () => {
1831
+ CometChatUIEventHandler.removeMessageListener(editMessageListenerID);
1832
+ };
1833
+ }, []);
1834
+
1835
+ /**
1836
+ * Add reply message event listener.
1837
+ * Subscribes to ccReplyToMessage events to display reply preview.
1838
+ */
1839
+ useEffect(() => {
1840
+ CometChatMessageEvents.addListener(
1841
+ CometChatMessageEvents.ccReplyToMessage,
1842
+ replyMessageListenerID,
1843
+ (data: any) => {
1844
+ if (data.status === messageStatus.inprogress) {
1845
+ previewReplyMessage(data.message);
1846
+ }
1847
+ }
1848
+ );
1849
+
1850
+ return () => {
1851
+ CometChatMessageEvents.removeListener(
1852
+ CometChatMessageEvents.ccReplyToMessage,
1853
+ replyMessageListenerID
1854
+ );
1855
+ };
1856
+ }, []);
1857
+
1858
+ // Add UI event listener for suggestion data, bottom sheet toggle, and compose message
1859
+ useEffect(() => {
1860
+ CometChatUIEventHandler.addUIListener(uiEventListenerID, {
1861
+ // Handle suggestion data for mentions
1862
+ ccSuggestionData(item: { id: string | number; data: Array<SuggestionItem> }) {
1863
+ if (activeCharacter.current && id === item?.id) {
1864
+ // Check if mention limit warning should be shown (matching MessageComposer pattern)
1865
+ const warningView = getMentionLimitView();
1866
+ if (warningView) {
1867
+ return;
1868
+ }
1869
+ setMentionsSearchData(item?.data);
1870
+ setSuggestionListLoader(false);
1871
+ }
1872
+ },
1873
+ // Handle bottom sheet toggle events (for custom views)
1874
+ ccToggleBottomSheet: (item: { botView?: boolean; child?: React.FC | React.ReactNode }) => {
1875
+ if (item?.botView) {
1876
+ // Handle botView for custom views - convert FC to ReactNode if needed
1877
+ const childContent = typeof item.child === 'function'
1878
+ ? React.createElement(item.child as React.FC)
1879
+ : (item.child || null);
1880
+ setCustomView(childContent);
1881
+ return;
1882
+ }
1883
+ // Toggle bottom sheet visibility
1884
+ setIsVisible(false);
1885
+ bottomSheetRef.current?.togglePanel();
1886
+ },
1887
+ // Handle compose message events (for AI smart replies, etc.)
1888
+ ccComposeMessage: (textData: { text?: string }) => {
1889
+ setIsVisible(false);
1890
+ bottomSheetRef.current?.togglePanel();
1891
+
1892
+ // Update input with received text
1893
+ if (textData?.text !== undefined) {
1894
+ plainTextInputRef.current = textData.text;
1895
+ setInputTextProgrammatic(textData.text);
1896
+ onChangeText?.(textData.text);
1897
+ }
1898
+ },
1899
+ });
1900
+
1901
+ return () => {
1902
+ CometChatUIEventHandler.removeUIListener(uiEventListenerID);
1903
+ };
1904
+ }, [id]);
1905
+
1906
+ // Handle panel hide events — always clear the content to avoid
1907
+ // a stale separator line when hidePanel passes child: () => null
1908
+ // (a truthy function that renders nothing).
1909
+ const handleHidePanel = useCallback((item: { child?: React.FC | React.ReactNode; alignment?: string }) => {
1910
+ if (item.alignment === ViewAlignment.composerTop) {
1911
+ setCustomViewHeader(null);
1912
+ } else if (item.alignment === ViewAlignment.composerBottom) {
1913
+ setCustomViewFooter(null);
1914
+ }
1915
+ }, []);
1916
+
1917
+ // Add panel show/hide listeners
1918
+ useEffect(() => {
1919
+ CometChatUIEventHandler.addUIListener(uiEventListenerShowID, {
1920
+ showPanel: (item: { child?: React.FC; alignment?: string }) => handlePanel(item),
1921
+ });
1922
+ CometChatUIEventHandler.addUIListener(uiEventListenerHideID, {
1923
+ hidePanel: (item: { child?: React.FC; alignment?: string }) => handleHidePanel(item),
1924
+ });
1925
+
1926
+ return () => {
1927
+ CometChatUIEventHandler.removeUIListener(uiEventListenerShowID);
1928
+ CometChatUIEventHandler.removeUIListener(uiEventListenerHideID);
1929
+ };
1930
+ }, []);
1931
+
1932
+ /**
1933
+ * Camera callback handler for processing captured images
1934
+ */
1935
+ const cameraCallback = async (cameraImage: any) => {
1936
+ if (CheckPropertyExists(cameraImage, 'error')) {
1937
+ return;
1938
+ }
1939
+ const { name, uri, type } = cameraImage;
1940
+ const file = {
1941
+ name,
1942
+ type,
1943
+ uri,
1944
+ };
1945
+ sendMediaMessage(
1946
+ chatWithId.current,
1947
+ file,
1948
+ MessageTypeConstants.image,
1949
+ chatWith.current
1950
+ );
1951
+ };
1952
+
1953
+ /**
1954
+ * File input handler for different file types
1955
+ * Handles image, video, audio, file, and takePhoto options
1956
+ */
1957
+ const fileInputHandler = async (fileType: string) => {
1958
+ if (fileType === MessageTypeConstants.takePhoto) {
1959
+ if (!(await permissionUtil.startResourceBasedTask(['camera']))) {
1960
+ return;
1961
+ }
1962
+ let quality = imageQuality;
1963
+ if (isNaN(imageQuality) || imageQuality < 1 || imageQuality > 100) {
1964
+ quality = 20;
1965
+ }
1966
+ if (Platform.OS === 'android') {
1967
+ FileManager.openCamera(
1968
+ fileType,
1969
+ Math.round(quality),
1970
+ cameraCallback
1971
+ );
1972
+ } else {
1973
+ FileManager.openCamera(
1974
+ fileType,
1975
+ cameraCallback
1976
+ );
1977
+ }
1978
+ } else if (Platform.OS === 'ios' && fileType === MessageTypeConstants.video) {
1979
+ NativeModules.VideoPickerModule.pickVideo((file: any) => {
1980
+ if (file.uri) {
1981
+ sendMediaMessage(
1982
+ chatWithId.current,
1983
+ file,
1984
+ MessageTypeConstants.video,
1985
+ chatWith.current
1986
+ );
1987
+ }
1988
+ });
1989
+ } else {
1990
+ FileManager.openFileChooser(fileType, async (fileInfo: any) => {
1991
+ if (CheckPropertyExists(fileInfo, 'error')) {
1992
+ return;
1993
+ }
1994
+ const { name, uri, type } = fileInfo;
1995
+ const file = {
1996
+ name,
1997
+ type,
1998
+ uri,
1999
+ };
2000
+ sendMediaMessage(
2001
+ chatWithId.current,
2002
+ file,
2003
+ fileType,
2004
+ chatWith.current
2005
+ );
2006
+ });
2007
+ }
2008
+ };
2009
+
2010
+ /**
2011
+ * Send media message (image, video, audio, file)
2012
+ * Includes reply message support for quoted messages.
2013
+ */
2014
+ const sendMediaMessage = (
2015
+ receiverId: string,
2016
+ messageInput: { name: string; type: string; uri: string },
2017
+ messageType: string,
2018
+ receiverType: string
2019
+ ) => {
2020
+ setShowActionSheet(false);
2021
+
2022
+ // Capture current reply message using ref to avoid stale closures
2023
+ const currentReplyMessage = replyMessageRef.current;
2024
+ const replyMessageId = currentReplyMessage?.message?.getId?.() ?? null;
2025
+
2026
+ const mediaMessage = new CometChat.MediaMessage(
2027
+ receiverId,
2028
+ messageInput,
2029
+ messageType,
2030
+ receiverType
2031
+ );
2032
+
2033
+ mediaMessage.setSender(loggedInUser.current!);
2034
+ mediaMessage.setReceiver((user || group)!);
2035
+ mediaMessage.setType(messageType);
2036
+ mediaMessage.setMuid(String(getUnixTimestampInMilliseconds()));
2037
+ mediaMessage.setData({
2038
+ type: messageType,
2039
+ category: CometChat.CATEGORY_MESSAGE,
2040
+ name: messageInput.name,
2041
+ file: messageInput,
2042
+ url: messageInput.uri,
2043
+ sender: loggedInUser.current,
2044
+ });
2045
+
2046
+ if (parentMessageId) {
2047
+ mediaMessage.setParentMessageId(parentMessageId as number);
2048
+ }
2049
+
2050
+ /**
2051
+ * Handle reply message - set quoted message for media replies.
2052
+ * Uses shared helper for consistency with CometChatMessageComposer.
2053
+ */
2054
+ if (replyMessageId && currentReplyMessage?.message) {
2055
+ setQuotedMessageSafe(mediaMessage, currentReplyMessage.message, replyMessageId);
2056
+ }
2057
+
2058
+ // Create local message for immediate UI feedback
2059
+ const localMessage = new CometChat.MediaMessage(
2060
+ receiverId,
2061
+ messageInput,
2062
+ messageType,
2063
+ receiverType
2064
+ );
2065
+
2066
+ localMessage.setSender(loggedInUser.current!);
2067
+ localMessage.setReceiver((user || group)!);
2068
+ localMessage.setType(messageType);
2069
+ localMessage.setMuid(String(getUnixTimestampInMilliseconds()));
2070
+ localMessage.setData({
2071
+ type: messageType,
2072
+ category: CometChat.CATEGORY_MESSAGE,
2073
+ name: messageInput.name,
2074
+ file: messageInput,
2075
+ url: messageInput.uri,
2076
+ sender: loggedInUser.current,
2077
+ attachments: [messageInput],
2078
+ });
2079
+
2080
+ if (parentMessageId) {
2081
+ localMessage.setParentMessageId(parentMessageId as number);
2082
+ }
2083
+
2084
+ // Set quoted message on local message for UI feedback
2085
+ if (replyMessageId && currentReplyMessage?.message) {
2086
+ setQuotedMessageSafe(localMessage, currentReplyMessage.message, replyMessageId);
2087
+ (localMessage as any).quotedMessage = currentReplyMessage.message;
2088
+ }
2089
+
2090
+ // Clear reply preview after preparing message
2091
+ setReplyMessage(null);
2092
+
2093
+ // Emit in-progress event
2094
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageSent, {
2095
+ message: localMessage,
2096
+ status: messageStatus.inprogress,
2097
+ });
2098
+
2099
+ // Play sound if enabled
2100
+ if (!disableSoundForMessages) {
2101
+ playAudio();
2102
+ }
2103
+
2104
+ // Send message via SDK
2105
+ CometChat.sendMediaMessage(mediaMessage)
2106
+ .then((message: CometChat.BaseMessage) => {
2107
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageSent, {
2108
+ message: message,
2109
+ status: messageStatus.success,
2110
+ });
2111
+ })
2112
+ .catch((error: CometChat.CometChatException) => {
2113
+ onError?.(error);
2114
+ (localMessage as any).data.metaData = { error: true };
2115
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageSent, {
2116
+ message: localMessage,
2117
+ status: messageStatus.error,
2118
+ });
2119
+ });
2120
+ };
2121
+
2122
+ /**
2123
+ * Play outgoing message sound
2124
+ */
2125
+ const playAudio = () => {
2126
+ if (customSoundForMessage) {
2127
+ CometChatSoundManager.play(
2128
+ CometChatSoundManager.SoundOutput.outgoingMessage,
2129
+ customSoundForMessage
2130
+ );
2131
+ } else {
2132
+ CometChatSoundManager.play(
2133
+ CometChatSoundManager.SoundOutput.outgoingMessage
2134
+ );
2135
+ }
2136
+ };
2137
+
2138
+ /**
2139
+ * Send recorded audio as a media message
2140
+ * Called when voice recording is completed and submitted
2141
+ */
2142
+ const _sendRecordedAudio = (recordedFile: string) => {
2143
+ // Invoke the onVoiceRecordingEnd callback if provided
2144
+ onVoiceRecordingEnd?.(recordedFile);
2145
+
2146
+ const fileObj = {
2147
+ name: 'audio-recording' + recordedFile.split('/audio-recording')[1],
2148
+ type: 'audio/mp4',
2149
+ uri: recordedFile,
2150
+ };
2151
+
2152
+ sendMediaMessage(
2153
+ chatWithId.current,
2154
+ fileObj,
2155
+ MessageTypeConstants.audio,
2156
+ chatWith.current
2157
+ );
2158
+ };
2159
+
2160
+ /**
2161
+ * Handle inline audio recorder submit.
2162
+ * Sends the recorded audio file and hides the inline recorder.
2163
+ */
2164
+ const handleInlineRecorderSubmit = useCallback((recordedFile: string) => {
2165
+ const fileObj = {
2166
+ name: 'audio-recording' + recordedFile.split('/audio-recording')[1],
2167
+ type: 'audio/mp4',
2168
+ uri: recordedFile,
2169
+ };
2170
+ sendMediaMessage(chatWithId.current, fileObj, MessageTypeConstants.audio, chatWith.current);
2171
+ setShowInlineRecorder(false);
2172
+ }, []);
2173
+
2174
+ /**
2175
+ * Handle inline audio recorder cancel.
2176
+ * Hides the inline recorder without sending.
2177
+ */
2178
+ const handleInlineRecorderCancel = useCallback(() => {
2179
+ setShowInlineRecorder(false);
2180
+ }, []);
2181
+
2182
+ /**
2183
+ * Handle voice recording start
2184
+ * Called when recording begins
2185
+ */
2186
+ const handleVoiceRecordingStart = () => {
2187
+ onVoiceRecordingStart?.();
2188
+ };
2189
+
2190
+ /**
2191
+ * Clear the input field.
2192
+ * When autoExpand is enabled, also resets the height to minHeight.
2193
+ * This ensures the input returns to its collapsed state when cleared.
2194
+ *
2195
+ */
2196
+ const clearInputBox = useCallback(() => {
2197
+ setInputTextProgrammatic('');
2198
+ plainTextInputRef.current = '';
2199
+ blocksRef.current = [];
2200
+ pendingLinksRef.current.clear();
2201
+ setEditContentBlocks(undefined);
2202
+ // Clear the RichTextEditor content
2203
+ inputRef.current?.clear();
2204
+
2205
+ // When autoExpand is enabled, reset height to minHeight
2206
+ // This handles the edge case of clearing all text
2207
+ if (autoExpand) {
2208
+ setInputHeight(resolvedMinHeight);
2209
+ setIsExpanded(false);
2210
+ }
2211
+ }, [autoExpand, resolvedMinHeight]);
2212
+
2213
+ /**
2214
+ * Start typing indicator
2215
+ */
2216
+ const startTyping = useCallback(() => {
2217
+ if (disableTypingEvents) {
2218
+ return;
2219
+ }
2220
+
2221
+ // Check if user is blocked
2222
+ if (user && (user.getBlockedByMe() || user.getHasBlockedMe())) {
2223
+ return;
2224
+ }
2225
+
2226
+ if (isTyping.current) {
2227
+ clearTimeout(isTyping.current);
2228
+ isTyping.current = null;
2229
+ } else {
2230
+ const typingNotification = new CometChat.TypingIndicator(
2231
+ chatWithId.current,
2232
+ chatWith.current
2233
+ );
2234
+ CometChat.startTyping(typingNotification);
2235
+ }
2236
+
2237
+ isTyping.current = setTimeout(() => {
2238
+ // End typing inline to avoid circular dependency
2239
+ if (disableTypingEvents) {
2240
+ return;
2241
+ }
2242
+ if (isTyping.current) {
2243
+ clearTimeout(isTyping.current);
2244
+ isTyping.current = null;
2245
+ }
2246
+ const typingNotification = new CometChat.TypingIndicator(
2247
+ chatWithId.current,
2248
+ chatWith.current
2249
+ );
2250
+ CometChat.endTyping(typingNotification);
2251
+ }, 500);
2252
+ }, [disableTypingEvents, user]);
2253
+
2254
+ /**
2255
+ * End typing indicator
2256
+ */
2257
+ const endTyping = useCallback(() => {
2258
+ if (disableTypingEvents) {
2259
+ return;
2260
+ }
2261
+
2262
+ if (isTyping.current) {
2263
+ clearTimeout(isTyping.current);
2264
+ isTyping.current = null;
2265
+ }
2266
+
2267
+ const typingNotification = new CometChat.TypingIndicator(
2268
+ chatWithId.current,
2269
+ chatWith.current
2270
+ );
2271
+ CometChat.endTyping(typingNotification);
2272
+ }, [disableTypingEvents]);
2273
+
2274
+ /**
2275
+ * Check if cursor is within a mention range
2276
+ */
2277
+ /**
2278
+ * Escape special regex characters
2279
+ */
2280
+ const escapeRegExp = (string: string): string => {
2281
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2282
+ };
2283
+
2284
+ /**
2285
+ * Extract text from cursor position to find search string
2286
+ */
2287
+ const extractTextFromCursor = (inputText: string, cursorPosition: number): string => {
2288
+ const leftText = inputText.substring(0, cursorPosition);
2289
+ const escapedPrefixes = trackingCharacters.current.map(escapeRegExp).join('|');
2290
+ const pattern = new RegExp(`(${escapedPrefixes})([\\w\\s]*)$`);
2291
+ const match = leftText.match(pattern);
2292
+
2293
+ if (match) {
2294
+ return match[2] || '';
2295
+ }
2296
+ return '';
2297
+ };
2298
+
2299
+ /**
2300
+ * Check if mention list should be opened.
2301
+ * Suppressed when cursor is inside a code block or inline code span
2302
+ * (Req 12.1, 12.2, 12.3).
2303
+ */
2304
+ const shouldOpenList = (
2305
+ selection: { start: number; end: number },
2306
+ searchString: string,
2307
+ tracker: string
2308
+ ): boolean => {
2309
+ if (disableMentions) return false;
2310
+ // Suppress mention picker inside code or code block contexts.
2311
+ // Read from ref to avoid stale closure after code block exit.
2312
+ const styles = activeStylesRef.current;
2313
+ if (styles.code || styles.codeBlock) return false;
2314
+
2315
+ return (
2316
+ selection.start === selection.end &&
2317
+ !isCursorWithinMentionRange(mentionMap.current, selection.start - searchString.length) &&
2318
+ trackingCharacters.current.includes(tracker) &&
2319
+ (searchString === ''
2320
+ ? (plainTextInputRef.current[selection.start - 2]?.length === 1 &&
2321
+ plainTextInputRef.current[selection.start - 2]?.trim()?.length === 0) ||
2322
+ plainTextInputRef.current[selection.start - 2] === undefined
2323
+ : true) &&
2324
+ (plainTextInputRef.current[selection.start - 1]?.length === 1 &&
2325
+ plainTextInputRef.current[selection.start - 1]?.trim()?.length === 0
2326
+ ? searchString.length > 0
2327
+ : true)
2328
+ );
2329
+ };
2330
+
2331
+ /**
2332
+ * Open mention list based on cursor position
2333
+ */
2334
+ let openListTimeoutId: NodeJS.Timeout | null = null;
2335
+ const openList = (selection: { start: number; end: number }) => {
2336
+ if (disableMentions) return;
2337
+
2338
+ if (openListTimeoutId) {
2339
+ clearTimeout(openListTimeoutId);
2340
+ }
2341
+
2342
+ openListTimeoutId = setTimeout(() => {
2343
+ const searchString = extractTextFromCursor(plainTextInputRef.current, selection.start);
2344
+ const tracker = searchString
2345
+ ? plainTextInputRef.current[selection.start - (searchString.length + 1)]
2346
+ : plainTextInputRef.current[selection.start - 1];
2347
+
2348
+ if (shouldOpenList(selection, searchString, tracker)) {
2349
+ activeCharacter.current = tracker;
2350
+ searchStringRef.current = searchString;
2351
+ setShowMentionList(true);
2352
+ setSuggestionListLoader(true);
2353
+
2354
+ const formatter = allFormatters.current.get(tracker);
2355
+ if (formatter instanceof CometChatMentionsFormatter) {
2356
+ const shouldShowMentionList =
2357
+ formatter.getVisibleIn() === MentionsVisibility.both ||
2358
+ (formatter.getVisibleIn() === MentionsVisibility.usersConversationOnly && user) ||
2359
+ (formatter.getVisibleIn() === MentionsVisibility.groupsConversationOnly && group);
2360
+ if (shouldShowMentionList) {
2361
+ formatter.search(searchString);
2362
+ }
2363
+ } else if (formatter) {
2364
+ formatter.search(searchString);
2365
+ }
2366
+ } else {
2367
+ activeCharacter.current = '';
2368
+ searchStringRef.current = '';
2369
+ setShowMentionList(false);
2370
+ setMentionsSearchData([]);
2371
+ }
2372
+ }, 100);
2373
+ };
2374
+
2375
+ /**
2376
+ * Remove overlapping mentions from text and map.
2377
+ * Tracks total shift for position adjustment and updates formatter suggestion items.
2378
+ * Clears warning message if below mention limit.
2379
+ *
2380
+ * @param text - The original text
2381
+ * @param overlaps - Array of overlapping mentions to remove
2382
+ * @param map - The mention map to update
2383
+ * @returns Object with newText and totalShift
2384
+ */
2385
+ const removeMentionsFromTextAndMap = (
2386
+ text: string,
2387
+ overlaps: MentionOverlap[],
2388
+ map: Map<string, SuggestionItem>
2389
+ ): { newText: string; totalShift: number } => {
2390
+ let adjustment = 0;
2391
+ let newText = text;
2392
+
2393
+ overlaps.forEach(({ key, value, start, end }) => {
2394
+ const adjStart = start + adjustment;
2395
+ const adjEnd = end + adjustment;
2396
+
2397
+ newText = newText.slice(0, adjStart) + newText.slice(adjEnd);
2398
+ map.delete(key);
2399
+ adjustment -= adjEnd - adjStart;
2400
+
2401
+ // Keep formatter in sync
2402
+ if (value.id && !ifIdExists(value.id, map)) {
2403
+ const trackingChar = value.trackingCharacter;
2404
+ if (trackingChar) {
2405
+ const fmt = allFormatters.current.get(trackingChar);
2406
+ if (fmt instanceof CometChatMentionsFormatter) {
2407
+ const users = fmt.getSuggestionItems().filter((u: SuggestionItem) => u.id !== value.id);
2408
+ fmt.setSuggestionItems(users);
2409
+ if (!getMentionLimitView(fmt)) setWarningMessage('');
2410
+ }
2411
+ }
2412
+ }
2413
+ });
2414
+
2415
+ return { newText, totalShift: adjustment };
2416
+ };
2417
+
2418
+ /**
2419
+ * Main helper to handle mention deletion.
2420
+ * Orchestrates mention deletion using helper functions.
2421
+ * Returns true if mentions were deleted, false otherwise.
2422
+ * Updates cursor position after deletion.
2423
+ *
2424
+ * @param oldText - The text before deletion
2425
+ * @param newText - The text after deletion (from TextInput)
2426
+ * @returns True if mentions were deleted and handled, false otherwise
2427
+ */
2428
+ const deleteMentionHelper = (oldText: string, newText: string): boolean => {
2429
+ const deletionLen = oldText.length - newText.length;
2430
+ const range = calcDeletionRange(selectionPosition, deletionLen);
2431
+
2432
+ // Verify the deletion actually happened at the calculated range.
2433
+ // Block-type toggles (list/blockquote) remove prefixes at line starts,
2434
+ // not at the cursor position. If the calculated range doesn't match
2435
+ // the actual deletion, skip mention deletion to avoid false positives.
2436
+ const expectedAfterDeletion = oldText.substring(0, range.start) + oldText.substring(range.end);
2437
+ if (expectedAfterDeletion !== newText) return false;
2438
+
2439
+ const deletionMentionMap = new Map(mentionMap.current);
2440
+ const overlaps = collectOverlappingMentions(range, deletionMentionMap);
2441
+
2442
+ if (overlaps.length === 0) return false;
2443
+
2444
+ const { newText: finalText, totalShift } = removeMentionsFromTextAndMap(
2445
+ oldText,
2446
+ overlaps,
2447
+ deletionMentionMap
2448
+ );
2449
+
2450
+ shiftRemainingMentionKeys(deletionMentionMap, range.start, totalShift);
2451
+
2452
+ plainTextInputRef.current = finalText;
2453
+ setInputTextProgrammatic(finalText);
2454
+ onChangeText?.(finalText);
2455
+ mentionMap.current = deletionMentionMap;
2456
+
2457
+ // Update cursor position to the start of the first deleted mention
2458
+ const firstStart = overlaps[0].start;
2459
+ ignoreSelectionUntil.current = Date.now() + 500;
2460
+ InteractionManager.runAfterInteractions(() => {
2461
+ inputRef.current?.setSelection?.(firstStart);
2462
+ setSelectionPosition({ start: firstStart, end: firstStart });
2463
+ syncMentionRanges();
2464
+ });
2465
+
2466
+ return true;
2467
+ };
2468
+
2469
+ /**
2470
+ * Handle text input change
2471
+ * Tracks cursor position and updates mention map positions.
2472
+ * Checks for deletion and calls deleteMentionHelper before normal processing.
2473
+ */
2474
+ const handleTextChange = (newText: string) => {
2475
+ const oldText = plainTextInputRef.current;
2476
+
2477
+ // Check if this is a deletion - call deleteMentionHelper before normal processing
2478
+ if (oldText.length > newText.length) {
2479
+ const handled = deleteMentionHelper(oldText, newText);
2480
+ if (handled) {
2481
+ // Mention deletion was handled, skip normal processing
2482
+ startTyping();
2483
+ return;
2484
+ }
2485
+ }
2486
+
2487
+ const removing = plainTextInputRef.current.length > newText.length;
2488
+ const adding = plainTextInputRef.current.length < newText.length;
2489
+ const textDiff = newText.length - plainTextInputRef.current.length;
2490
+ const notAtLast = (selectionPosition.start + textDiff) < newText.length;
2491
+
2492
+ // Update plain text input ref
2493
+ plainTextInputRef.current = newText;
2494
+
2495
+ inputTextRef.current = newText;
2496
+ setInputText(newText);
2497
+ onChangeText?.(newText);
2498
+ startTyping();
2499
+
2500
+ // Update mention map positions based on text changes
2501
+ let decr = 0;
2502
+ const newMentionMap = new Map(mentionMap.current);
2503
+
2504
+ mentionMap.current.forEach((value, key) => {
2505
+ const position = {
2506
+ start: parseInt(key.split('_')[0]),
2507
+ end: parseInt(key.split('_')[1]),
2508
+ };
2509
+
2510
+ // Runs when cursor before the mention and before the last position
2511
+ if (
2512
+ notAtLast &&
2513
+ (selectionPosition.start - 1 <= position.start ||
2514
+ selectionPosition.start - textDiff <= position.start)
2515
+ ) {
2516
+ if (removing) {
2517
+ decr = selectionPosition.end - selectionPosition.start - textDiff;
2518
+ position.start = position.start - decr;
2519
+ position.end = position.end - decr;
2520
+ } else if (adding) {
2521
+ decr = selectionPosition.end - selectionPosition.start + textDiff;
2522
+ position.start = position.start + decr;
2523
+ position.end = position.end + decr;
2524
+ }
2525
+ if (removing || adding) {
2526
+ const newKey = `${position.start}_${position.end}`;
2527
+ if (position.start >= 0) {
2528
+ newMentionMap.set(newKey, value);
2529
+ }
2530
+ newMentionMap.delete(key);
2531
+ }
2532
+ }
2533
+
2534
+ // Code to delete mention from hashmap if it's been modified
2535
+ const expectedMentionPos = plainTextInputRef.current.substring(position.start, position.end);
2536
+
2537
+ if (expectedMentionPos !== value.promptText) {
2538
+ const newKey = `${position.start}_${position.end}`;
2539
+ newMentionMap.delete(newKey);
2540
+
2541
+ // Try to recover the mention by searching for its promptText in the new text.
2542
+ // This handles block-type toggles (list/blockquote) where prefixes
2543
+ // shift text positions but the mention text is still present.
2544
+ const promptText = value.promptText || '';
2545
+ let recovered = false;
2546
+ if (promptText) {
2547
+ // Search near the expected position first, then fall back to full text
2548
+ const searchFrom = Math.max(0, position.start - 20);
2549
+ let localIdx = plainTextInputRef.current.indexOf(promptText, searchFrom);
2550
+ // Fallback: if not found near expected position, search from beginning
2551
+ if (localIdx === -1 && searchFrom > 0) {
2552
+ localIdx = plainTextInputRef.current.indexOf(promptText, 0);
2553
+ }
2554
+ while (localIdx !== -1) {
2555
+ const recoveredKey = `${localIdx}_${localIdx + promptText.length}`;
2556
+ if (!newMentionMap.has(recoveredKey)) {
2557
+ newMentionMap.set(recoveredKey, value);
2558
+ recovered = true;
2559
+ break;
2560
+ }
2561
+ localIdx = plainTextInputRef.current.indexOf(promptText, localIdx + 1);
2562
+ }
2563
+ }
2564
+
2565
+ // Mention text truly gone — remove from formatters
2566
+ if (!recovered && value.id && !ifIdExists(value.id, newMentionMap)) {
2567
+ const trackingChar = value.trackingCharacter;
2568
+ if (trackingChar) {
2569
+ const targetedFormatter = allFormatters.current.get(trackingChar);
2570
+ if (targetedFormatter) {
2571
+ const existingCCUsers = [...targetedFormatter.getSuggestionItems()];
2572
+ const userPosition = existingCCUsers.findIndex(
2573
+ (item: SuggestionItem) => item.id === value.id
2574
+ );
2575
+ if (userPosition !== -1) {
2576
+ existingCCUsers.splice(userPosition, 1);
2577
+ (targetedFormatter as CometChatMentionsFormatter).setSuggestionItems(existingCCUsers);
2578
+ if (!getMentionLimitView(targetedFormatter as CometChatMentionsFormatter)) {
2579
+ setWarningMessage('');
2580
+ }
2581
+ }
2582
+ }
2583
+ }
2584
+ }
2585
+ }
2586
+ });
2587
+
2588
+ mentionMap.current = newMentionMap;
2589
+ // Sync mention visual styling after text change shifts mention positions
2590
+ syncMentionRanges();
2591
+ };
2592
+
2593
+ /**
2594
+ * Handle selection change for mention tracking
2595
+ */
2596
+ const handleSelectionChange = (event: { nativeEvent: { selection: { start: number; end: number } } }) => {
2597
+ const { selection } = event.nativeEvent;
2598
+
2599
+ if (Date.now() < ignoreSelectionUntil.current) {
2600
+ return;
2601
+ }
2602
+
2603
+ const cursorPos = selection.start;
2604
+ const mentionRange = getMentionRangeAtCursor(mentionMap.current, cursorPos);
2605
+
2606
+ if (mentionRange) {
2607
+ const distanceToStart = cursorPos - mentionRange.start;
2608
+ const distanceToEnd = mentionRange.end - cursorPos;
2609
+ let targetPosition: number;
2610
+ if (distanceToStart <= distanceToEnd) {
2611
+ targetPosition = mentionRange.start;
2612
+ } else {
2613
+ targetPosition = mentionRange.end;
2614
+ }
2615
+ if (targetPosition !== cursorPos) {
2616
+ InteractionManager.runAfterInteractions(() => {
2617
+ inputRef.current?.setSelection?.(targetPosition);
2618
+ setSelectionPosition({ start: targetPosition, end: targetPosition });
2619
+ });
2620
+ return;
2621
+ }
2622
+ }
2623
+
2624
+ setSelectionPosition(selection);
2625
+ openList(selection);
2626
+ };
2627
+
2628
+ /**
2629
+ * Insert mention at specific position in the mention map
2630
+ */
2631
+ const insertMentionAt = (
2632
+ map: Map<string, SuggestionItem>,
2633
+ insertAt: number,
2634
+ key: string,
2635
+ value: SuggestionItem
2636
+ ): Map<string, SuggestionItem> => {
2637
+ const mentionsArray = Array.from(map);
2638
+ mentionsArray.splice(insertAt, 0, [key, value]);
2639
+ return new Map(mentionsArray);
2640
+ };
2641
+
2642
+ /**
2643
+ * Check if an ID exists in the mention map
2644
+ */
2645
+ const ifIdExists = (id: string, hashmap: Map<string, SuggestionItem>): boolean => {
2646
+ for (const [, value] of hashmap) {
2647
+ if (value.id === id) {
2648
+ return true;
2649
+ }
2650
+ }
2651
+ return false;
2652
+ };
2653
+
2654
+ /**
2655
+ * Handle mention selection from suggestion list
2656
+ */
2657
+ const onMentionPress = (item: SuggestionItem) => {
2658
+ // Enforce maxMentionLimit — prevent inserting if limit reached
2659
+ if (mentionMap.current.size >= maxMentionLimit) {
2660
+ onMentionLimitReached?.();
2661
+ setShowMentionList(false);
2662
+ setMentionsSearchData([]);
2663
+ return;
2664
+ }
2665
+
2666
+ setShowMentionList(false);
2667
+ setMentionsSearchData([]);
2668
+
2669
+ const promptText = item.promptText || '';
2670
+ const notAtLast = selectionPosition.start < plainTextInputRef.current.length;
2671
+ const textDiff =
2672
+ plainTextInputRef.current.length +
2673
+ promptText.length -
2674
+ searchStringRef.current.length -
2675
+ plainTextInputRef.current.length;
2676
+
2677
+ let incr = 0;
2678
+ let mentionPos = 0;
2679
+
2680
+ const newMentionMap = new Map(mentionMap.current);
2681
+
2682
+ const targetedFormatter = allFormatters.current.get(activeCharacter.current);
2683
+
2684
+ if (targetedFormatter) {
2685
+ const existingCCUsers = [...targetedFormatter.getSuggestionItems()];
2686
+ const userAlreadyExists = existingCCUsers.find(
2687
+ (existingUser: SuggestionItem) => existingUser.id === item.id
2688
+ );
2689
+ if (!userAlreadyExists) {
2690
+ const cometchatUIUserArray: Array<SuggestionItem> = [...existingCCUsers];
2691
+ cometchatUIUserArray.push(item);
2692
+ (targetedFormatter as CometChatMentionsFormatter).setSuggestionItems(cometchatUIUserArray);
2693
+ }
2694
+ }
2695
+
2696
+ mentionMap.current.forEach((value, key) => {
2697
+ const position = {
2698
+ start: parseInt(key.split('_')[0]),
2699
+ end: parseInt(key.split('_')[1]),
2700
+ };
2701
+
2702
+ if (!(selectionPosition.start <= position.start)) {
2703
+ mentionPos += 1;
2704
+ }
2705
+
2706
+ // Delete mention from hashmap if cursor is within it
2707
+ if (
2708
+ position.end === selectionPosition.end ||
2709
+ (selectionPosition.start > position.start && selectionPosition.end <= position.end)
2710
+ ) {
2711
+ const newKey = `${position.start}_${position.end}`;
2712
+ newMentionMap.delete(newKey);
2713
+ mentionPos -= 1;
2714
+ }
2715
+
2716
+ if (notAtLast && selectionPosition.start - 1 <= position.start) {
2717
+ incr = selectionPosition.end - selectionPosition.start + textDiff;
2718
+ const newKey = `${position.start + incr}_${position.end + incr}`;
2719
+ newMentionMap.set(newKey, value);
2720
+ newMentionMap.delete(key);
2721
+ }
2722
+ });
2723
+ mentionMap.current = newMentionMap;
2724
+
2725
+ // Update the input text with the mention
2726
+ const updatedPlainTextInput = `${plainTextInputRef.current.substring(
2727
+ 0,
2728
+ selectionPosition.start - (1 + searchStringRef.current.length)
2729
+ )}${promptText + ' '}${plainTextInputRef.current.substring(
2730
+ selectionPosition.end,
2731
+ plainTextInputRef.current.length
2732
+ )}`;
2733
+ plainTextInputRef.current = updatedPlainTextInput;
2734
+
2735
+ const key =
2736
+ selectionPosition.start -
2737
+ (1 + searchStringRef.current.length) +
2738
+ '_' +
2739
+ (selectionPosition.start - (searchStringRef.current.length + 1) + promptText.length);
2740
+
2741
+ const updatedMap = insertMentionAt(mentionMap.current, mentionPos, key, {
2742
+ ...item,
2743
+ trackingCharacter: activeCharacter.current,
2744
+ });
2745
+ mentionMap.current = updatedMap;
2746
+
2747
+ // Calculate cursor position after the mention + space
2748
+ const newCursorPosition =
2749
+ selectionPosition.start -
2750
+ (searchStringRef.current.length + 1) +
2751
+ (promptText.length) +
2752
+ 1; // +1 for the space after mention
2753
+
2754
+ // Update the input text state — ignore native selection events for 500ms
2755
+ ignoreSelectionUntil.current = Date.now() + 500;
2756
+ setInputTextProgrammatic(updatedPlainTextInput);
2757
+
2758
+ // Set cursor position and sync mention styling to native editor
2759
+ setTimeout(() => {
2760
+ inputRef.current?.setSelection?.(newCursorPosition);
2761
+ // Update our tracking state without triggering a re-render to native
2762
+ setSelectionPosition({ start: newCursorPosition, end: newCursorPosition });
2763
+ // Apply mention visual styling (bold purple + background pill) in native editor
2764
+ syncMentionRanges();
2765
+ }, 100);
2766
+ };
2767
+
2768
+ /**
2769
+ * Handle end reached for suggestion list pagination
2770
+ */
2771
+ const onSuggestionListEndReached = () => {
2772
+ // Pagination can be implemented here if needed
2773
+ };
2774
+
2775
+ /**
2776
+ * Get mention limit warning view
2777
+ * Displays a warning when the mention limit is reached.
2778
+ * Also sets the warningMessage state for display in CustomViewHeader.
2779
+ *
2780
+ * @param targettedFormatterParam - Optional formatter to check (defaults to active formatter)
2781
+ * @returns boolean - true if warning should be shown, false otherwise
2782
+ */
2783
+ const getMentionLimitView = (targettedFormatterParam?: CometChatMentionsFormatter): boolean => {
2784
+ const targetedFormatter = allFormatters.current.get(activeCharacter.current) ?? targettedFormatterParam;
2785
+
2786
+ if (!(targetedFormatter instanceof CometChatMentionsFormatter)) {
2787
+ return false;
2788
+ }
2789
+
2790
+ let shouldWarn = false;
2791
+ let limit: number | undefined;
2792
+
2793
+ // Check if formatter has limit capabilities
2794
+ if (targetedFormatter.getLimit && targetedFormatter.getLimit()) {
2795
+ limit = targetedFormatter.getLimit();
2796
+ if (targetedFormatter.getUniqueUsersList && targetedFormatter.getUniqueUsersList()?.size >= limit) {
2797
+ shouldWarn = true;
2798
+ }
2799
+ }
2800
+
2801
+ if (!shouldWarn) {
2802
+ setWarningMessage('');
2803
+ return false;
2804
+ }
2805
+
2806
+ const errorString = targetedFormatter.getErrorString
2807
+ ? targetedFormatter.getErrorString()
2808
+ : `${t('MENTION_UPTO')} ${limit} ${limit === 1 ? t('TIME') : t('TIMES')} ${t('AT_A_TIME')}.`;
2809
+
2810
+ setWarningMessage(errorString);
2811
+ return true;
2812
+ };
2813
+
2814
+ /**
2815
+ * Render mention limit warning view in suggestion list
2816
+ * Uses the warningMessage state set by getMentionLimitView
2817
+ */
2818
+ const renderMentionLimitWarning = () => {
2819
+ if (!warningMessage) return null;
2820
+
2821
+ return (
2822
+ <View
2823
+ style={{
2824
+ flexDirection: 'row',
2825
+ alignItems: 'center',
2826
+ paddingTop: 5,
2827
+ paddingLeft: 5,
2828
+ borderTopWidth: 1,
2829
+ borderTopColor: theme.color.borderDefault,
2830
+ }}
2831
+ >
2832
+ <Icon
2833
+ name="info-fill"
2834
+ color={theme.color.error}
2835
+ height={20}
2836
+ width={20}
2837
+ />
2838
+ <Text
2839
+ style={{
2840
+ marginLeft: 5,
2841
+ color: theme.color.textSecondary,
2842
+ ...theme.typography.caption1.regular,
2843
+ }}
2844
+ >
2845
+ {warningMessage}
2846
+ </Text>
2847
+ </View>
2848
+ );
2849
+ };
2850
+
2851
+ /**
2852
+ * Convert mentions to underlying text format for sending
2853
+ * Iterates through mentionMap and replaces prompt text with underlying text
2854
+ */
2855
+ const getRegexString = (str: string): string => {
2856
+ // Get an array of the entries in the map using the spread operator
2857
+ const entries = [...mentionMap.current.entries()].reverse();
2858
+
2859
+ let uidInput = str;
2860
+
2861
+ // Iterate over the array in reverse order
2862
+ entries.forEach(([key, value]) => {
2863
+ const [start, end] = key.split('_').map(Number);
2864
+
2865
+ const pre = uidInput.substring(0, start);
2866
+ const post = uidInput.substring(end);
2867
+
2868
+ uidInput = pre + value.underlyingText + post;
2869
+ });
2870
+
2871
+ return uidInput;
2872
+ };
2873
+
2874
+ /**
2875
+ * Replace mention display names with underlying tokens in the given text.
2876
+ * Uses name-based indexOf (not position-based splicing) because markdown
2877
+ * syntax added by blocksToMarkdown shifts character positions.
2878
+ * Entries are sorted left-to-right so indexOf finds the correct occurrence
2879
+ * when the same display name appears multiple times.
2880
+ */
2881
+ const replaceMentionsWithTokens = (text: string): string => {
2882
+ if (mentionMap.current.size === 0) return text;
2883
+ const entries = [...mentionMap.current.entries()].sort((a, b) => {
2884
+ return parseInt(a[0].split('_')[0]) - parseInt(b[0].split('_')[0]);
2885
+ });
2886
+ let result = text;
2887
+ let offset = 0;
2888
+ for (const [, value] of entries) {
2889
+ const displayName = value.promptText || '';
2890
+ const underlying = value.underlyingText || '';
2891
+ if (!displayName || !underlying) continue;
2892
+ const idx = result.indexOf(displayName, offset);
2893
+ if (idx === -1) continue;
2894
+ result = result.substring(0, idx) + underlying + result.substring(idx + displayName.length);
2895
+ offset = idx + underlying.length;
2896
+ }
2897
+ return result;
2898
+ };
2899
+
2900
+ /**
2901
+ * Preview message for edit mode
2902
+ * Called when an edit message event is received
2903
+ * Populates the input with the original message text
2904
+ */
2905
+ const previewMessage = ({ message, status }: { message: any; status: string }) => {
2906
+ if (status === messageStatus.inprogress) {
2907
+ // Populate formatter SuggestionItems from the message's mentioned users.
2908
+ // Only handleComposerPreview is needed — getFormattedText returns JSX
2909
+ // which is unused here since we feed plain text to markdownToBlocks.
2910
+ allFormatters.current.forEach((formatter: CometChatTextFormatter | CometChatMentionsFormatter) => {
2911
+ formatter.handleComposerPreview?.(message);
2912
+ });
2913
+
2914
+ // Resolve mention tokens (<@uid:...>, <@all:...>) to display names
2915
+ // and build mentionMap so the native editor can apply mention styling.
2916
+ const rawText = message?.text ?? '';
2917
+ const mentionFormatter = allFormatters.current.get('@');
2918
+ let resolvedText = rawText;
2919
+ const newMentionMap = new Map<string, SuggestionItem>();
2920
+
2921
+ if (mentionFormatter instanceof CometChatMentionsFormatter) {
2922
+ const suggestionItems = mentionFormatter.getSuggestionItems();
2923
+ const itemLookup = new Map<string, SuggestionItem>();
2924
+ for (const item of suggestionItems) {
2925
+ itemLookup.set(item.id, item);
2926
+ }
2927
+
2928
+ // Single-pass: collect matches, build resolved text via array join
2929
+ const mentionRegex = /<@(?:uid|all):(.*?)>/g;
2930
+ let match: RegExpExecArray | null;
2931
+ const segments: string[] = [];
2932
+ let lastIndex = 0;
2933
+ const mentionPositions: Array<{ start: number; length: number; item: SuggestionItem }> = [];
2934
+ let resolvedLength = 0;
2935
+
2936
+ while ((match = mentionRegex.exec(rawText)) !== null) {
2937
+ // Append text before this match
2938
+ const before = rawText.substring(lastIndex, match.index);
2939
+ segments.push(before);
2940
+ resolvedLength += before.length;
2941
+
2942
+ const item = itemLookup.get(match[1]);
2943
+ const displayText = item?.promptText ?? `@${match[1]}`;
2944
+ segments.push(displayText);
2945
+
2946
+ if (item) {
2947
+ mentionPositions.push({ start: resolvedLength, length: displayText.length, item });
2948
+ }
2949
+ resolvedLength += displayText.length;
2950
+ lastIndex = match.index + match[0].length;
2951
+ }
2952
+ // Append trailing text
2953
+ segments.push(rawText.substring(lastIndex));
2954
+ resolvedText = segments.join('');
2955
+
2956
+ // Build mentionMap from collected positions
2957
+ for (const mp of mentionPositions) {
2958
+ const key = `${mp.start}_${mp.start + mp.length}`;
2959
+ newMentionMap.set(key, new SuggestionItem({
2960
+ ...mp.item,
2961
+ trackingCharacter: '@',
2962
+ }));
2963
+ }
2964
+ }
2965
+
2966
+ mentionMap.current = newMentionMap;
2967
+
2968
+ // Set the message preview state with resolved text (display names, not tokens)
2969
+ setMessagePreview({
2970
+ message: { ...message, text: resolvedText },
2971
+ mode: ConversationOptionConstants.edit,
2972
+ });
2973
+
2974
+ // Parse markdown into structured blocks and load into the native editor
2975
+ const blocks = markdownToBlocks(resolvedText);
2976
+ inputTextRef.current = resolvedText;
2977
+ plainTextInputRef.current = resolvedText;
2978
+ blocksRef.current = blocks;
2979
+
2980
+ // Do NOT call setInputText here — that would push text via the React
2981
+ // text prop, which races with setContent and can strip formatting or
2982
+ // trigger handleTextChange that corrupts mentionMap. Instead, update
2983
+ // only the refs and the inputText state silently after setContent loads.
2984
+
2985
+ // Load structured blocks into the native editor.
2986
+ setTimeout(() => {
2987
+ inputRef.current?.setContent?.(blocks);
2988
+ inputRef.current?.focus();
2989
+ // Update inputText state AFTER setContent so the text prop doesn't
2990
+ // race with attributed text. The native editor already has the content.
2991
+ setInputText(resolvedText);
2992
+ // Apply mention styling after native editor finishes processing setContent
2993
+ setTimeout(syncMentionRanges, 100);
2994
+ }, 100);
2995
+ }
2996
+ };
2997
+
2998
+ /**
2999
+ * Preview message for reply mode.
3000
+ * Called when a ccReplyToMessage event is received.
3001
+ * Clears any active edit preview before showing the reply preview.
3002
+ */
3003
+ const previewReplyMessage = (message: any) => {
3004
+ // Clear edit preview if it exists
3005
+ if (messagePreview) {
3006
+ setMessagePreview(null);
3007
+ mentionMap.current = new Map();
3008
+ plainTextInputRef.current = '';
3009
+ syncMentionRanges();
3010
+ }
3011
+
3012
+ // Set the reply message state
3013
+ setReplyMessage({
3014
+ message: message,
3015
+ mode: ConversationOptionConstants.reply,
3016
+ });
3017
+
3018
+ // Focus input after setting preview
3019
+ try {
3020
+ inputRef.current?.focus();
3021
+ } catch (error) {
3022
+ // Ignore focus errors
3023
+ }
3024
+ };
3025
+
3026
+ /**
3027
+ * Expose ref methods for programmatic control.
3028
+ * Allows parent components to:
3029
+ * - Trigger edit mode programmatically
3030
+ * - Send text messages
3031
+ * - Get current input text
3032
+ * - Clear the input field
3033
+ * - Reset streaming state
3034
+ */
3035
+ useImperativeHandle(ref, () => ({
3036
+ previewMessageForEdit: previewMessage,
3037
+ sendTextMessage,
3038
+ getText: () => plainTextInputRef.current,
3039
+ clear: () => {
3040
+ clearInputBox();
3041
+ inputRef.current?.clear();
3042
+ },
3043
+ // Rich text formatting methods — exposed so developers can build custom toolbars.
3044
+ // These call the same native methods as the built-in inline toolbar.
3045
+ // Use these when enableRichTextEditor={false} and you want to provide your own UI controls.
3046
+
3047
+ /** Toggles bold formatting on the current selection or at the cursor position. */
3048
+ toggleBold: () => inputRef.current?.toggleBold(),
3049
+ /** Toggles italic formatting on the current selection or at the cursor position. */
3050
+ toggleItalic: () => inputRef.current?.toggleItalic(),
3051
+ /** Toggles underline formatting on the current selection or at the cursor position. */
3052
+ toggleUnderline: () => inputRef.current?.toggleUnderline(),
3053
+ /** Toggles strikethrough formatting on the current selection or at the cursor position. */
3054
+ toggleStrikethrough: () => inputRef.current?.toggleStrikethrough(),
3055
+ /** Toggles inline code formatting on the current selection or at the cursor position. */
3056
+ toggleCode: () => inputRef.current?.toggleCode(),
3057
+ /** Toggles text highlight/background color on the current selection. Pass an optional hex color string. */
3058
+ toggleHighlight: (color?: string) => inputRef.current?.toggleHighlight(color),
3059
+ /** Converts the current line/block to a heading (toggles between heading and paragraph). */
3060
+ setHeading: () => inputRef.current?.setHeading(),
3061
+ /** Converts the current line/block to a bullet (unordered) list item. */
3062
+ setBulletList: () => inputRef.current?.setBulletList(),
3063
+ /** Converts the current line/block to a numbered (ordered) list item. */
3064
+ setNumberedList: () => inputRef.current?.setNumberedList(),
3065
+ /** Converts the current line/block to a blockquote. */
3066
+ setQuote: () => inputRef.current?.setQuote(),
3067
+ /** Converts the current line/block to a checklist item with a toggleable checkbox. */
3068
+ setChecklist: () => inputRef.current?.setChecklist(),
3069
+ /** Resets the current line/block back to a normal paragraph. */
3070
+ setParagraph: () => inputRef.current?.setParagraph(),
3071
+ /** Inserts a hyperlink at the current selection. Wraps selected text or inserts new link text. */
3072
+ insertLink: (url: string, text: string) => inputRef.current?.insertLink(url, text),
3073
+ /** Undoes the last editing action. */
3074
+ undo: () => inputRef.current?.undo(),
3075
+ /** Redoes the last undone editing action. */
3076
+ redo: () => inputRef.current?.redo(),
3077
+ /** Removes all inline formatting (bold, italic, underline, etc.) from the current selection. */
3078
+ clearFormatting: () => inputRef.current?.clearFormatting(),
3079
+ /** Increases the indentation level of the current line/block (for lists and quotes). */
3080
+ indent: () => inputRef.current?.indent(),
3081
+ /** Decreases the indentation level of the current line/block. */
3082
+ outdent: () => inputRef.current?.outdent(),
3083
+ /** Sets text alignment for the current line/block: 'left', 'center', or 'right'. */
3084
+ setAlignment: (alignment: 'left' | 'center' | 'right') => inputRef.current?.setAlignment(alignment),
3085
+ /** Programmatically focuses the editor (opens keyboard). */
3086
+ focus: () => inputRef.current?.focus(),
3087
+ /** Programmatically blurs the editor (dismisses keyboard). */
3088
+ blur: () => inputRef.current?.blur(),
3089
+ /**
3090
+ * Reset streaming state and stop any active streaming.
3091
+ * Resets showStopButton and isStreaming to false.
3092
+ * Calls stopStreamingForRunId() with error handling.
3093
+ */
3094
+ resetStreaming: () => {
3095
+ setShowStopButton(false);
3096
+ setIsStreaming(false);
3097
+ try {
3098
+ stopStreamingForRunId();
3099
+ } catch (error) {
3100
+ // Silently handle streaming stop errors
3101
+ // The UI state is already reset
3102
+ }
3103
+ },
3104
+ }));
3105
+
3106
+ /**
3107
+ * Update CustomViewHeader when warningMessage changes.
3108
+ * Displays an info icon and warning text when mention limit is reached.
3109
+ * Clears the header when warning is cleared.
3110
+ */
3111
+ useLayoutEffect(() => {
3112
+ if (warningMessage) {
3113
+ setCustomViewHeader(
3114
+ <View
3115
+ style={{
3116
+ flexDirection: 'row',
3117
+ alignItems: 'center',
3118
+ padding: theme.spacing?.padding?.p2 || 8,
3119
+ borderRadius: resolvedStyle?.containerStyle?.borderRadius as number || 8,
3120
+ backgroundColor: resolvedStyle?.containerStyle?.backgroundColor as string || theme.color.background1,
3121
+ borderColor: resolvedStyle?.containerStyle?.borderColor as string,
3122
+ borderWidth: resolvedStyle?.containerStyle?.borderWidth as number,
3123
+ marginBottom: 2,
3124
+ }}
3125
+ >
3126
+ <Icon name='info-fill' color={theme.color.error} height={16} width={16} />
3127
+ <Text
3128
+ style={{
3129
+ marginLeft: 5,
3130
+ color: theme.color.error,
3131
+ ...theme.typography.caption1.regular,
3132
+ }}
3133
+ >
3134
+ {warningMessage}
3135
+ </Text>
3136
+ </View>
3137
+ );
3138
+ return;
3139
+ }
3140
+ setCustomViewHeader(null);
3141
+ }, [warningMessage, theme, resolvedStyle]);
3142
+
3143
+ /**
3144
+ * Parse a markdown string into the block format expected by the native
3145
+ * editor's setContent(blocks:) / initialContentJson.
3146
+ *
3147
+ * This is the inverse of blocksToMarkdown. It handles:
3148
+ * - Code blocks (``` ... ```) → { type: "codeBlock", text, styles: [] }
3149
+ * - Blockquotes (> ...) → { type: "quote", text, styles: [] }
3150
+ * - Bullet lists (- ...) → { type: "bullet", text, styles }
3151
+ * - Numbered lists (1. ...) → { type: "numbered", text, styles }
3152
+ * - Inline styles (bold **, italic _, underline <u></u>, strikethrough ~~, code `)
3153
+ * → { type: "paragraph", text, styles: [{style, start, end}] }
3154
+ */
3155
+ const markdownToBlocks = (markdown: string): any[] => {
3156
+ if (!markdown) return [];
3157
+
3158
+ /**
3159
+ * Parse inline markdown styles from a line of text.
3160
+ * Returns the plain text and an array of style spans.
3161
+ * Supports nested styles (e.g. **<u>bold underline</u>**).
3162
+ */
3163
+ const parseInlineStyles = (line: string): { text: string; styles: any[] } => {
3164
+ const styles: any[] = [];
3165
+ let plain = '';
3166
+
3167
+ // Helper: recursively parse inner content and offset style positions
3168
+ const parseNested = (content: string, offset: number): string => {
3169
+ const inner = parseInlineStyles(content);
3170
+ for (const s of inner.styles) {
3171
+ styles.push({ style: s.style, start: s.start + offset, end: s.end + offset });
3172
+ }
3173
+ return inner.text;
3174
+ };
3175
+
3176
+ let i = 0;
3177
+ while (i < line.length) {
3178
+ // Markdown link: [text](url)
3179
+ if (line[i] === '[') {
3180
+ const closeBracket = line.indexOf('](', i + 1);
3181
+ if (closeBracket !== -1) {
3182
+ const closeParen = line.indexOf(')', closeBracket + 2);
3183
+ if (closeParen !== -1) {
3184
+ const start = plain.length;
3185
+ const linkText = line.substring(i + 1, closeBracket);
3186
+ const linkUrl = line.substring(closeBracket + 2, closeParen);
3187
+ plain += linkText;
3188
+ styles.push({ style: 'link', start, end: plain.length, url: linkUrl });
3189
+ i = closeParen + 1;
3190
+ continue;
3191
+ }
3192
+ }
3193
+ }
3194
+
3195
+ // Triple-backtick inline code block: ```...```
3196
+ if (line[i] === '`' && line[i + 1] === '`' && line[i + 2] === '`') {
3197
+ const closeIdx = line.indexOf('```', i + 3);
3198
+ if (closeIdx !== -1) {
3199
+ const start = plain.length;
3200
+ const content = line.substring(i + 3, closeIdx);
3201
+ plain += content;
3202
+ styles.push({ style: 'code', start, end: plain.length });
3203
+ i = closeIdx + 3;
3204
+ continue;
3205
+ }
3206
+ }
3207
+
3208
+ // Inline code: `...` (no nesting inside code)
3209
+ if (line[i] === '`') {
3210
+ const closeIdx = line.indexOf('`', i + 1);
3211
+ if (closeIdx !== -1) {
3212
+ const start = plain.length;
3213
+ const content = line.substring(i + 1, closeIdx);
3214
+ plain += content;
3215
+ styles.push({ style: 'code', start, end: plain.length });
3216
+ i = closeIdx + 1;
3217
+ continue;
3218
+ }
3219
+ }
3220
+
3221
+ // Bold: **...**
3222
+ if (line[i] === '*' && line[i + 1] === '*') {
3223
+ const closeIdx = line.indexOf('**', i + 2);
3224
+ if (closeIdx !== -1) {
3225
+ const start = plain.length;
3226
+ const content = line.substring(i + 2, closeIdx);
3227
+ const innerText = parseNested(content, start);
3228
+ plain += innerText;
3229
+ styles.push({ style: 'bold', start, end: plain.length });
3230
+ i = closeIdx + 2;
3231
+ continue;
3232
+ }
3233
+ }
3234
+
3235
+ // Strikethrough: ~~...~~
3236
+ if (line[i] === '~' && line[i + 1] === '~') {
3237
+ const closeIdx = line.indexOf('~~', i + 2);
3238
+ if (closeIdx !== -1) {
3239
+ const start = plain.length;
3240
+ const content = line.substring(i + 2, closeIdx);
3241
+ const innerText = parseNested(content, start);
3242
+ plain += innerText;
3243
+ styles.push({ style: 'strikethrough', start, end: plain.length });
3244
+ i = closeIdx + 2;
3245
+ continue;
3246
+ }
3247
+ }
3248
+
3249
+ // Underline: <u>text</u> (HTML tag, case-insensitive)
3250
+ if (line[i] === '<' && line.substring(i, i + 3).toLowerCase() === '<u>') {
3251
+ const closeIdx = line.toLowerCase().indexOf('</u>', i + 3);
3252
+ if (closeIdx !== -1) {
3253
+ const start = plain.length;
3254
+ const content = line.substring(i + 3, closeIdx);
3255
+ const innerText = parseNested(content, start);
3256
+ plain += innerText;
3257
+ styles.push({ style: 'underline', start, end: plain.length });
3258
+ i = closeIdx + 4;
3259
+ continue;
3260
+ }
3261
+ }
3262
+
3263
+ // Italic: _..._
3264
+ if (line[i] === '_') {
3265
+ const closeIdx = line.indexOf('_', i + 1);
3266
+ if (closeIdx !== -1) {
3267
+ const start = plain.length;
3268
+ const content = line.substring(i + 1, closeIdx);
3269
+ const innerText = parseNested(content, start);
3270
+ plain += innerText;
3271
+ styles.push({ style: 'italic', start, end: plain.length });
3272
+ i = closeIdx + 1;
3273
+ continue;
3274
+ }
3275
+ }
3276
+
3277
+ // Plain character
3278
+ plain += line[i];
3279
+ i++;
3280
+ }
3281
+
3282
+ return { text: plain, styles };
3283
+ };
3284
+
3285
+ const lines = markdown.split('\n');
3286
+ const blocks: any[] = [];
3287
+ let i = 0;
3288
+
3289
+ while (i < lines.length) {
3290
+ const line = lines[i];
3291
+
3292
+ // Code block fence: ```
3293
+ if (line.trimEnd() === '```' || line.startsWith('```')) {
3294
+ const afterOpen = line.substring(3);
3295
+ const firstClose = afterOpen.indexOf('```');
3296
+
3297
+ if (firstClose > 0) {
3298
+ // Has closing ``` on the same line
3299
+ const afterFirstBlock = afterOpen.substring(firstClose + 3).trim();
3300
+ if (afterFirstBlock.length === 0) {
3301
+ // Single ```content``` on this line — treat as one code block
3302
+ const content = afterOpen.substring(0, firstClose);
3303
+ blocks.push({ type: 'codeBlock', text: content, styles: [] });
3304
+ i++;
3305
+ continue;
3306
+ } else {
3307
+ // Multiple ```...``` or mixed content — treat as paragraph with inline code styles
3308
+ const { text, styles } = parseInlineStyles(line);
3309
+ blocks.push({ type: 'paragraph', text, styles });
3310
+ i++;
3311
+ continue;
3312
+ }
3313
+ }
3314
+
3315
+ // Standalone ``` or ```langId — multi-line fenced code block
3316
+ i++;
3317
+ const codeLines: string[] = [];
3318
+ while (i < lines.length && lines[i].trimEnd() !== '```') {
3319
+ codeLines.push(lines[i]);
3320
+ i++;
3321
+ }
3322
+ // Each code line becomes its own codeBlock block (matching native editor format)
3323
+ if (codeLines.length === 0) {
3324
+ blocks.push({ type: 'codeBlock', text: '', styles: [] });
3325
+ } else {
3326
+ for (const cl of codeLines) {
3327
+ blocks.push({ type: 'codeBlock', text: cl, styles: [] });
3328
+ }
3329
+ }
3330
+ // Skip closing fence
3331
+ if (i < lines.length) i++;
3332
+ continue;
3333
+ }
3334
+
3335
+ // Blockquote + bullet: > - ...
3336
+ if (line.startsWith('> - ')) {
3337
+ const content = line.substring(4);
3338
+ const { text, styles } = parseInlineStyles(content);
3339
+ blocks.push({ type: 'quoteBullet', text, styles });
3340
+ i++;
3341
+ continue;
3342
+ }
3343
+
3344
+ // Blockquote + numbered: > 1. ...
3345
+ if (/^> \d+\.\s/.test(line)) {
3346
+ const content = line.replace(/^> \d+\.\s/, '');
3347
+ const { text, styles } = parseInlineStyles(content);
3348
+ blocks.push({ type: 'quoteNumbered', text, styles });
3349
+ i++;
3350
+ continue;
3351
+ }
3352
+
3353
+ // Blockquote: > ...
3354
+ if (line.startsWith('> ')) {
3355
+ const content = line.substring(2);
3356
+ const { text, styles } = parseInlineStyles(content);
3357
+ blocks.push({ type: 'quote', text, styles });
3358
+ i++;
3359
+ continue;
3360
+ }
3361
+
3362
+ // Bullet list: - ...
3363
+ if (line.startsWith('- ')) {
3364
+ const content = line.substring(2);
3365
+ const { text, styles } = parseInlineStyles(content);
3366
+ blocks.push({ type: 'bullet', text, styles });
3367
+ i++;
3368
+ continue;
3369
+ }
3370
+
3371
+ // Numbered list: 1. ... (any digit prefix)
3372
+ if (/^\d+\.\s/.test(line)) {
3373
+ const content = line.replace(/^\d+\.\s/, '');
3374
+ const { text, styles } = parseInlineStyles(content);
3375
+ blocks.push({ type: 'numbered', text, styles });
3376
+ i++;
3377
+ continue;
3378
+ }
3379
+
3380
+ // Heading: # ...
3381
+ if (line.startsWith('# ')) {
3382
+ const content = line.substring(2);
3383
+ const { text, styles } = parseInlineStyles(content);
3384
+ blocks.push({ type: 'heading', text, styles });
3385
+ i++;
3386
+ continue;
3387
+ }
3388
+
3389
+ // Default: paragraph with inline styles
3390
+ const { text, styles } = parseInlineStyles(line);
3391
+ blocks.push({ type: 'paragraph', text, styles });
3392
+ i++;
3393
+ }
3394
+
3395
+ return blocks;
3396
+ };
3397
+
3398
+ /**
3399
+ * Convert RichTextEditor blocks to markdown string.
3400
+ * Handles overlapping style ranges (e.g. bold+italic+underline on same text).
3401
+ */
3402
+ const blocksToMarkdown = (blocks: any[]): string => {
3403
+ if (!blocks || blocks.length === 0) return '';
3404
+
3405
+ // Marker map for each style type — open/close pairs
3406
+ // Most markers are symmetric (same open and close), but underline uses HTML tags.
3407
+ const markerMap: Record<string, { open: string; close: string }> = {
3408
+ bold: { open: '**', close: '**' },
3409
+ italic: { open: '_', close: '_' },
3410
+ underline: { open: '<u>', close: '</u>' },
3411
+ strikethrough: { open: '~~', close: '~~' },
3412
+ code: { open: '`', close: '`' },
3413
+ };
3414
+
3415
+ // Order matters: outer markers wrap inner ones
3416
+ const styleOrder = ['bold', 'underline', 'strikethrough', 'italic', 'code'];
3417
+
3418
+ const applyInlineStyles = (text: string, styles: any[]): string => {
3419
+ if (!styles || styles.length === 0 || !text) return text;
3420
+
3421
+ // Collect all boundary positions where style sets change
3422
+ const boundaries = new Set<number>();
3423
+ boundaries.add(0);
3424
+ boundaries.add(text.length);
3425
+ for (const s of styles) {
3426
+ boundaries.add(Math.max(0, s.start));
3427
+ boundaries.add(Math.min(text.length, s.end));
3428
+ }
3429
+ const sorted = Array.from(boundaries).sort((a, b) => a - b);
3430
+
3431
+ // Build segments with their active style sets
3432
+ const segActiveStyles: string[][] = [];
3433
+ const segTexts: string[] = [];
3434
+ const segLinkUrls: string[] = [];
3435
+ for (let i = 0; i < sorted.length - 1; i++) {
3436
+ const segStart = sorted[i];
3437
+ const segEnd = sorted[i + 1];
3438
+ const segment = text.substring(segStart, segEnd);
3439
+ if (segment.length === 0) continue;
3440
+
3441
+ const active: string[] = [];
3442
+ let linkUrl = '';
3443
+ for (const s of styles) {
3444
+ const sStart = Math.max(0, s.start);
3445
+ const sEnd = Math.min(text.length, s.end);
3446
+ if (sStart <= segStart && sEnd >= segEnd) {
3447
+ if (s.style === 'link' && s.url) {
3448
+ linkUrl = s.url;
3449
+ } else if (markerMap[s.style] !== undefined && !active.includes(s.style)) {
3450
+ active.push(s.style);
3451
+ }
3452
+ }
3453
+ }
3454
+ segActiveStyles.push(active);
3455
+ segTexts.push(segment);
3456
+ segLinkUrls.push(linkUrl);
3457
+ }
3458
+
3459
+ if (segTexts.length === 0) return text;
3460
+
3461
+ // Build markdown with properly nested markers.
3462
+ // We maintain a stack of currently open styles. Between segments,
3463
+ // we close styles that are ending (popping from stack) and open
3464
+ // styles that are starting (pushing onto stack). This ensures
3465
+ // markers are always properly nested.
3466
+ let result = '';
3467
+ let openStack: string[] = []; // styles currently open, in nesting order
3468
+
3469
+ for (let i = 0; i < segTexts.length; i++) {
3470
+ const curr = segActiveStyles[i];
3471
+ // Determine which styles in styleOrder should be active
3472
+ const desired = styleOrder.filter(s => curr.includes(s));
3473
+
3474
+ // Close styles that are open but not desired (pop from top of stack)
3475
+ // We must close in reverse stack order (innermost first)
3476
+ const toClose: string[] = [];
3477
+ const toReopen: string[] = [];
3478
+ // Find styles to close: anything in openStack not in desired
3479
+ // But we may need to close styles above them too (and reopen)
3480
+ const newStack: string[] = [];
3481
+ for (const s of openStack) {
3482
+ if (desired.includes(s)) {
3483
+ newStack.push(s);
3484
+ }
3485
+ }
3486
+ // Close everything from top of stack down to what we need
3487
+ // Then reopen what should stay
3488
+ if (openStack.length > 0) {
3489
+ // Find the deepest style that needs to close
3490
+ let closeFrom = -1;
3491
+ for (let j = openStack.length - 1; j >= 0; j--) {
3492
+ if (!desired.includes(openStack[j])) {
3493
+ closeFrom = j;
3494
+ break;
3495
+ }
3496
+ }
3497
+ if (closeFrom >= 0) {
3498
+ // Close everything from top down to closeFrom
3499
+ for (let j = openStack.length - 1; j >= closeFrom; j--) {
3500
+ result += markerMap[openStack[j]].close;
3501
+ if (desired.includes(openStack[j])) {
3502
+ toReopen.push(openStack[j]);
3503
+ }
3504
+ }
3505
+ openStack = openStack.slice(0, closeFrom);
3506
+ // Reopen styles that should stay (in their original order)
3507
+ for (const s of toReopen.reverse()) {
3508
+ result += markerMap[s].open;
3509
+ openStack.push(s);
3510
+ }
3511
+ }
3512
+ }
3513
+
3514
+ // Open new styles that are desired but not yet open
3515
+ for (const s of desired) {
3516
+ if (!openStack.includes(s)) {
3517
+ result += markerMap[s].open;
3518
+ openStack.push(s);
3519
+ }
3520
+ }
3521
+
3522
+ // Add segment text (with link wrapping if needed)
3523
+ if (segLinkUrls[i]) {
3524
+ result += `[${segTexts[i]}](${segLinkUrls[i]})`;
3525
+ } else {
3526
+ result += segTexts[i];
3527
+ }
3528
+ }
3529
+
3530
+ // Close all remaining open styles (innermost first)
3531
+ for (let j = openStack.length - 1; j >= 0; j--) {
3532
+ result += markerMap[openStack[j]].close;
3533
+ }
3534
+
3535
+ return result;
3536
+ };
3537
+
3538
+ // Strip trailing empty list items (bullet/numbered) so "1. text\n2. " sends as "1. text"
3539
+ let blockCount = blocks.length;
3540
+ while (blockCount > 0) {
3541
+ const last = blocks[blockCount - 1];
3542
+ if ((last.type === 'bullet' || last.type === 'numbered' || last.type === 'quoteBullet' || last.type === 'quoteNumbered') && !(last.text || '').trim()) {
3543
+ blockCount--;
3544
+ } else {
3545
+ break;
3546
+ }
3547
+ }
3548
+
3549
+ const lines: string[] = [];
3550
+ let inCodeBlock = false;
3551
+ let orderedCounter = 0;
3552
+ for (let i = 0; i < blockCount; i++) {
3553
+ const block = blocks[i];
3554
+ const text = block.text || '';
3555
+ const styles: any[] = block.styles || [];
3556
+ const blockType = block.type || 'paragraph';
3557
+
3558
+ if (blockType === 'codeBlock') {
3559
+ if (!inCodeBlock) {
3560
+ // Check if this is a single-line code block (no consecutive codeBlock after it)
3561
+ const nextBlock = i + 1 < blocks.length ? blocks[i + 1] : null;
3562
+ if (!nextBlock || (nextBlock.type || 'paragraph') !== 'codeBlock') {
3563
+ // Single-line: emit ```content``` (no newlines)
3564
+ lines.push(`\`\`\`${text}\`\`\``);
3565
+ orderedCounter = 0;
3566
+ continue;
3567
+ }
3568
+ // Multi-line: use fenced format
3569
+ lines.push('```');
3570
+ inCodeBlock = true;
3571
+ }
3572
+ // Code block lines use raw text (no inline style markers)
3573
+ lines.push(text);
3574
+ } else {
3575
+ // Close code block fence if we were inside one
3576
+ if (inCodeBlock) {
3577
+ lines.push('```');
3578
+ inCodeBlock = false;
3579
+ }
3580
+
3581
+ const styledText = applyInlineStyles(text, styles);
3582
+
3583
+ switch (blockType) {
3584
+ case 'bullet':
3585
+ case 'quoteBullet':
3586
+ // Bullet lines don't reset the counter (Slack behavior)
3587
+ lines.push(blockType === 'quoteBullet' ? `> - ${styledText}` : `- ${styledText}`);
3588
+ break;
3589
+ case 'numbered':
3590
+ orderedCounter++;
3591
+ lines.push(`${orderedCounter}. ${styledText}`);
3592
+ break;
3593
+ case 'quoteNumbered':
3594
+ orderedCounter++;
3595
+ lines.push(`> ${orderedCounter}. ${styledText}`);
3596
+ break;
3597
+ case 'quote': lines.push(`> ${styledText}`); break;
3598
+ case 'heading': lines.push(`# ${styledText}`); break;
3599
+ default:
3600
+ orderedCounter = 0;
3601
+ lines.push(styledText);
3602
+ break;
3603
+ }
3604
+ }
3605
+ }
3606
+ // Close any trailing code block fence
3607
+ if (inCodeBlock) {
3608
+ lines.push('```');
3609
+ }
3610
+
3611
+ return lines.join('\n');
3612
+ };
3613
+
3614
+ /**
3615
+ * Send text message
3616
+ * Includes agentic user support for:
3617
+ * - Parent message ID tracking
3618
+ * - Send button delay
3619
+ * - Streaming start
3620
+ * - Reply message support
3621
+ */
3622
+ const sendTextMessage = () => {
3623
+ const trimmedText = inputText.trim();
3624
+
3625
+ if (trimmedText.length === 0) {
3626
+ return;
3627
+ }
3628
+
3629
+ // Check if in edit mode - call editMessage instead
3630
+ if (messagePreview !== null) {
3631
+ editMessage(messagePreview.message);
3632
+ return;
3633
+ }
3634
+
3635
+ // Capture current reply message before clearing (for quoted message)
3636
+ const currentReplyMessage = replyMessage;
3637
+ const replyMessageId = currentReplyMessage?.message?.getId?.() ?? null;
3638
+
3639
+ // Convert blocks to markdown if rich text is enabled, otherwise use plain text
3640
+ let textToSend = enableRichTextEditor && blocksRef.current.length > 0
3641
+ ? blocksToMarkdown(blocksRef.current)
3642
+ : trimmedText;
3643
+ // Apply pending links: replace link display text with [text](url) markdown
3644
+ if (pendingLinksRef.current.size > 0) {
3645
+ pendingLinksRef.current.forEach((url, displayText) => {
3646
+ // Only replace if the text isn't already wrapped in markdown link syntax
3647
+ const escaped = displayText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
3648
+ const alreadyLinked = new RegExp(`\\[${escaped}\\]\\(`);
3649
+ if (!alreadyLinked.test(textToSend)) {
3650
+ // Use a function replacement to avoid $ special patterns in replacement string
3651
+ textToSend = textToSend.replace(displayText, () => `[${displayText}](${url})`);
3652
+ }
3653
+ });
3654
+ pendingLinksRef.current.clear();
3655
+ }
3656
+
3657
+ // Process mentions to underlying text format before sending.
3658
+ // Mention map positions are based on plain text (plainTextInputRef),
3659
+ // but blocksToMarkdown adds markdown syntax (```, `, **, etc.) that
3660
+ // shifts character positions. So when mentions exist, do a name-based
3661
+ // find-and-replace on the markdown text instead of position-based splicing.
3662
+ let processedText: string;
3663
+ if (mentionMap.current.size > 0) {
3664
+ processedText = replaceMentionsWithTokens(textToSend);
3665
+ } else {
3666
+ processedText = getRegexString(textToSend);
3667
+ }
3668
+
3669
+ let textMessage = new CometChat.TextMessage(
3670
+ chatWithId.current,
3671
+ processedText,
3672
+ chatWith.current
3673
+ );
3674
+
3675
+ textMessage.setSender(loggedInUser.current!);
3676
+ textMessage.setReceiver((user || group)!);
3677
+ textMessage.setMuid(String(getUnixTimestampInMilliseconds()));
3678
+
3679
+ // Handle parent message ID for threaded messages
3680
+ // For agentic users, use tracked parent message ID if no prop provided
3681
+ if (parentMessageId) {
3682
+ textMessage.setParentMessageId(parentMessageId as number);
3683
+ } else if (isAgenticUser() && parentMessageIdRef.current) {
3684
+ textMessage.setParentMessageId(parentMessageIdRef.current);
3685
+ }
3686
+
3687
+ /**
3688
+ * Handle reply message - set quoted message for replies.
3689
+ * Uses shared helper for consistency with CometChatMessageComposer.
3690
+ */
3691
+ if (replyMessageId && currentReplyMessage?.message) {
3692
+ setQuotedMessageSafe(textMessage, currentReplyMessage.message, replyMessageId);
3693
+ }
3694
+
3695
+ // Process text through formatters
3696
+ allFormatters.current.forEach((formatter) => {
3697
+ textMessage = formatter.handlePreMessageSend(textMessage);
3698
+ });
3699
+
3700
+ clearInputBox();
3701
+ // Clear mention map after sending
3702
+ mentionMap.current = new Map();
3703
+ endTyping();
3704
+
3705
+ /**
3706
+ * Clear reply preview after preparing message.
3707
+ */
3708
+ setReplyMessage(null);
3709
+
3710
+ // If custom send handler is provided, use it
3711
+ if (onSendButtonPress) {
3712
+ onSendButtonPress(textMessage);
3713
+ return;
3714
+ }
3715
+
3716
+ // Emit in-progress event
3717
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageSent, {
3718
+ message: textMessage,
3719
+ status: messageStatus.inprogress,
3720
+ });
3721
+
3722
+ // Play sound if enabled
3723
+ if (!disableSoundForMessages) {
3724
+ playAudio();
3725
+ }
3726
+
3727
+ /**
3728
+ * Enable 1-second delay for agentic users after sending.
3729
+ * This prevents rapid-fire messages to AI agents.
3730
+ */
3731
+ if (isAgenticUser()) {
3732
+ setIsSendButtonDisabledForDelay(true);
3733
+ if (sendButtonDelayTimer.current) {
3734
+ clearTimeout(sendButtonDelayTimer.current);
3735
+ }
3736
+ sendButtonDelayTimer.current = setTimeout(() => {
3737
+ setIsSendButtonDisabledForDelay(false);
3738
+ }, 1000);
3739
+ }
3740
+
3741
+ // Send message via SDK
3742
+ CometChat.sendMessage(textMessage)
3743
+ .then((message: CometChat.BaseMessage) => {
3744
+ /**
3745
+ * For agentic users without parentMessageId prop:
3746
+ * - Store the message ID as parent for subsequent messages
3747
+ * - Start streaming for the message
3748
+ */
3749
+ if (isAgenticUser() && !parentMessageId && message?.getId) {
3750
+ const messageId = typeof message.getId() === 'string'
3751
+ ? Number(message.getId())
3752
+ : message.getId();
3753
+
3754
+ // Store parent message ID for subsequent messages
3755
+ if (!isNaN(messageId) && !parentMessageIdRef.current) {
3756
+ parentMessageIdRef.current = messageId;
3757
+ }
3758
+
3759
+ // Start streaming for agentic user messages
3760
+ if (messageId && !isNaN(messageId)) {
3761
+ startStreamingForRunId(String(messageId));
3762
+ }
3763
+ }
3764
+
3765
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageSent, {
3766
+ message: message,
3767
+ status: messageStatus.success,
3768
+ });
3769
+ })
3770
+ .catch((error: CometChat.CometChatException) => {
3771
+ onError?.(error);
3772
+ (textMessage as any).data.metaData = { error: true };
3773
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageSent, {
3774
+ message: textMessage,
3775
+ status: messageStatus.error,
3776
+ });
3777
+ });
3778
+ };
3779
+
3780
+ /**
3781
+ * Edit an existing message
3782
+ * Called when in edit mode and user submits the edited text
3783
+ */
3784
+ const editMessage = (originalMessage: any) => {
3785
+ endTyping();
3786
+
3787
+ // Convert blocks to markdown and replace mention display names with tokens
3788
+ const trimmedText = inputText.trim();
3789
+ let textToSend = enableRichTextEditor && blocksRef.current.length > 0
3790
+ ? blocksToMarkdown(blocksRef.current)
3791
+ : trimmedText;
3792
+ textToSend = replaceMentionsWithTokens(textToSend);
3793
+
3794
+ // Create new text message with edited content
3795
+ const textMessage = new CometChat.TextMessage(
3796
+ chatWithId.current,
3797
+ textToSend,
3798
+ chatWith.current
3799
+ );
3800
+
3801
+ // Set the message ID from the original message
3802
+ textMessage.setId(originalMessage.id);
3803
+
3804
+ if (parentMessageId) {
3805
+ textMessage.setParentMessageId(parentMessageId as number);
3806
+ }
3807
+
3808
+ // Clear input and preview
3809
+ clearInputBox();
3810
+ setMessagePreview(null);
3811
+
3812
+ // If custom send handler is provided, use it
3813
+ if (onSendButtonPress) {
3814
+ onSendButtonPress(textMessage);
3815
+ return;
3816
+ }
3817
+
3818
+ // Play sound if enabled
3819
+ if (!disableSoundForMessages) {
3820
+ playAudio();
3821
+ }
3822
+
3823
+ // Edit message via SDK
3824
+ CometChat.editMessage(textMessage)
3825
+ .then((editedMessage: CometChat.BaseMessage) => {
3826
+ CometChatUIEventHandler.emitMessageEvent(MessageEvents.ccMessageEdited, {
3827
+ message: editedMessage,
3828
+ status: messageStatus.success,
3829
+ });
3830
+ })
3831
+ .catch((error: CometChat.CometChatException) => {
3832
+ onError?.(error);
3833
+ });
3834
+ };
3835
+
3836
+ /**
3837
+ * Check if the text has actual user content beyond formatting markers.
3838
+ * When a user taps bullet, numbered list, blockquote, or applies inline
3839
+ * formatting without typing content, the editor inserts markers but no
3840
+ * real content — send should stay disabled.
3841
+ *
3842
+ * Handles: empty code block fences, empty inline format markers
3843
+ * (** **, _ _, <u></u>, ~~ ~~, ` `), nested empty formatting,
3844
+ * and block prefixes (• , N. , ▎ ).
3845
+ */
3846
+ const hasActualContent = (text: string): boolean => {
3847
+ let stripped = text;
3848
+ // Remove code block fences and keep only inner content
3849
+ stripped = stripped.replace(/```[\s\S]*?```/g, (m) => m.slice(3, -3));
3850
+ // Remove inline format markers (keep inner content)
3851
+ stripped = stripped.replace(/\*\*(.+?)\*\*/g, '$1');
3852
+ stripped = stripped.replace(/<u>(.+?)<\/u>/gi, '$1');
3853
+ stripped = stripped.replace(/~~(.+?)~~/g, '$1');
3854
+ stripped = stripped.replace(/`(.+?)`/g, '$1');
3855
+ stripped = stripped.replace(/(?<![a-zA-Z0-9])_(.+?)_(?![a-zA-Z0-9])/g, '$1');
3856
+ // Remove empty inline format markers (no content between delimiters)
3857
+ stripped = stripped.replace(/\*\*\s*\*\*/g, '');
3858
+ stripped = stripped.replace(/<u>\s*<\/u>/gi, '');
3859
+ stripped = stripped.replace(/~~\s*~~/g, '');
3860
+ stripped = stripped.replace(/`\s*`/g, '');
3861
+ stripped = stripped.replace(/(?<![a-zA-Z0-9])_\s*_(?![a-zA-Z0-9])/g, '');
3862
+ // Remove block prefixes (bullet, numbered list, blockquote, and combinations)
3863
+ stripped = stripped
3864
+ .split('\n')
3865
+ .map(line => line.replace(/^(>\s)?(-\s|•\s|‧\s|▎\s|\d+\.\s)+/, '').trim())
3866
+ .join('');
3867
+ return stripped.length > 0;
3868
+ };
3869
+
3870
+ /**
3871
+ * Mic button slide/fade animation effect.
3872
+ * Triggers forward animation (slide out + fade) when text appears,
3873
+ * and reverse animation (slide in + fade in) when text is cleared.
3874
+ * Rapid toggling is handled by Animated API cancellation — calling
3875
+ * .start() on a new animation cancels the previous one.
3876
+ */
3877
+ const hasContent = hasActualContent(inputText);
3878
+ useEffect(() => {
3879
+ if (hideVoiceRecordingButton) return;
3880
+
3881
+ Animated.timing(micAnimValue, {
3882
+ toValue: hasContent ? 1 : 0,
3883
+ duration: MIC_ANIM_DURATION,
3884
+ useNativeDriver: true,
3885
+ }).start();
3886
+ }, [hasContent, hideVoiceRecordingButton]);
3887
+
3888
+ /**
3889
+ * Check if send button should be disabled.
3890
+ * For agentic users, also considers:
3891
+ * - Streaming state (disabled while AI is responding)
3892
+ * - Send button delay (disabled for 1 second after sending)
3893
+ */
3894
+ const isSendDisabled = isStreaming || !hasActualContent(inputText) || isSendButtonDisabledForDelay;
3895
+
3896
+ /**
3897
+ * Get send button tint color based on state
3898
+ */
3899
+ const getSendButtonTint = () => {
3900
+ if (isSendDisabled) {
3901
+ return theme.color.iconSecondary;
3902
+ }
3903
+ return resolvedStyle?.sendIconStyle?.tintColor || theme.color.primary;
3904
+ };
3905
+
3906
+ /**
3907
+ * Get attachment icon tint color
3908
+ */
3909
+ const getAttachmentIconTint = () => {
3910
+ return resolvedStyle?.attachmentIconStyle?.tintColor || theme.color.iconSecondary;
3911
+ };
3912
+
3913
+ /**
3914
+ * Render secondary button (left side, for API compatibility)
3915
+ * By default, shows the attachment button (📎) which opens the attachment action sheet.
3916
+ * For agentic users, the attachment button is automatically hidden.
3917
+ */
3918
+ const renderSecondaryButton = () => {
3919
+ // Hide attachment button for agentic users
3920
+ if (hideAttachmentButton) {
3921
+ return null;
3922
+ }
3923
+
3924
+ if (SecondaryButtonView) {
3925
+ return (
3926
+ <SecondaryButtonView
3927
+ user={user}
3928
+ group={group}
3929
+ composerId={id || 'single-line-composer'}
3930
+ />
3931
+ );
3932
+ }
3933
+
3934
+ // Default attachment button - opens action sheet
3935
+ const handleAttachmentClick = () => {
3936
+ if (onAttachmentClick) {
3937
+ onAttachmentClick();
3938
+ }
3939
+ setShowActionSheet(true);
3940
+ };
3941
+
3942
+ // Always show attachment button by default (per requirements doc)
3943
+ // The button opens the attachment action sheet with default options from ChatConfigurator
3944
+ // Use SVG icon name for proper tintColor support
3945
+ return (
3946
+ <IconButton
3947
+ name={attachmentIcon ? undefined : 'add-circle'}
3948
+ icon={attachmentIcon}
3949
+ onClick={handleAttachmentClick}
3950
+ buttonStyle={Style.iconButton}
3951
+ iconStyle={Style.icon}
3952
+ tintColor={getAttachmentIconTint()}
3953
+ />
3954
+ );
3955
+ };
3956
+
3957
+ /**
3958
+ * Render auxiliary button
3959
+ * Uses custom EmojiButton component with proper styling (no extra padding).
3960
+ * For agentic users, auxiliary buttons are automatically hidden.
3961
+ * When placed on the right (next to mic), slides/fades with the same animation as the mic button.
3962
+ */
3963
+ const renderAuxiliaryButton = () => {
3964
+ // Hide auxiliary buttons if prop is set
3965
+ if (hideAuxiliaryButton || hideAuxiliaryButtons) {
3966
+ return null;
3967
+ }
3968
+
3969
+ // Hide stickers button if prop is set
3970
+ if (hideStickersButton) {
3971
+ return null;
3972
+ }
3973
+
3974
+ // For agentic users, hide default auxiliary buttons (but allow custom ones)
3975
+ if (isAgenticUser() && !AuxiliaryButtonView) {
3976
+ return null;
3977
+ }
3978
+
3979
+ let content: JSX.Element;
3980
+
3981
+ // If custom AuxiliaryButtonView is provided, use it
3982
+ if (AuxiliaryButtonView) {
3983
+ content = (
3984
+ <AuxiliaryButtonView
3985
+ user={user}
3986
+ group={group}
3987
+ composerId={id || 'single-line-composer'}
3988
+ />
3989
+ );
3990
+ } else {
3991
+ // Use custom EmojiButton with proper styling (no extra padding)
3992
+ content = (
3993
+ <EmojiButton
3994
+ user={user}
3995
+ group={group}
3996
+ composerIdMap={composerIdMap}
3997
+ replyToMessage={replyMessage?.message}
3998
+ closeReplyPreview={closeReplyPreview}
3999
+ editorRef={inputRef}
4000
+ />
4001
+ );
4002
+ }
4003
+
4004
+ // No animation needed for sticker — it naturally shifts via flexbox
4005
+ // when the mic button's layout collapses
4006
+ return content;
4007
+ };
4008
+
4009
+ /**
4010
+ * Default agent send button view component.
4011
+ * Uses CometChatSendButtonView for agentic users with streaming support.
4012
+ */
4013
+ const DefaultAgentSendButtonView = useCallback(
4014
+ ({ isButtonDisabled, composerRef }: { isButtonDisabled: boolean; composerRef: any }) => (
4015
+ <CometChatSendButtonView
4016
+ isButtonDisabled={isButtonDisabled}
4017
+ composerRef={composerRef}
4018
+ isStreaming={isStreaming}
4019
+ showStopButton={showStopButton}
4020
+ setShowStopButton={setShowStopButton}
4021
+ />
4022
+ ),
4023
+ [isStreaming, showStopButton]
4024
+ );
4025
+
4026
+ /**
4027
+ * Render send button
4028
+ * Always shows send button with disabled/enabled states based on input content.
4029
+ * When input is empty, send button is disabled with inactive tint color.
4030
+ * When input has text, send button is enabled with active tint color.
4031
+ * For agentic users, renders the agent send button with streaming support.
4032
+ */
4033
+ const renderSendButton = () => {
4034
+ if (hideSendButton) {
4035
+ return null;
4036
+ }
4037
+
4038
+ // For agentic users, use the agent send button view
4039
+ if (isAgenticUser()) {
4040
+ const disabled = isStreaming || inputText.trim().length === 0 || (messagePreview !== null) || isSendButtonDisabledForDelay;
4041
+ const SendButtonComponent = AgentSendButtonView || DefaultAgentSendButtonView;
4042
+
4043
+ // Create a ref-like object that matches what CometChatSendButtonView expects
4044
+ const composerRef = {
4045
+ current: {
4046
+ sendTextMessage: () => {
4047
+ if (!disabled) {
4048
+ sendTextMessage();
4049
+ }
4050
+ }
4051
+ }
4052
+ };
4053
+
4054
+ return <SendButtonComponent isButtonDisabled={disabled} composerRef={composerRef} />;
4055
+ }
4056
+
4057
+ if (SendButtonView) {
4058
+ return (
4059
+ <SendButtonView
4060
+ user={user}
4061
+ group={group}
4062
+ composerId={id || 'single-line-composer'}
4063
+ />
4064
+ );
4065
+ }
4066
+
4067
+ // Always show send button with disabled/enabled state based on input content
4068
+ // Figma spec: 32×32 circle, primary bg when active, background4 when disabled
4069
+ const sendIconSize = theme.spacing.spacing.s5;
4070
+ const sendIconColor = isSendDisabled
4071
+ ? (theme.color.iconSecondary as string)
4072
+ : (theme.color.primaryButtonIcon as string);
4073
+ return (
4074
+ <TouchableOpacity
4075
+ testID="send-button"
4076
+ onPress={sendTextMessage}
4077
+ disabled={isSendDisabled}
4078
+ style={[{
4079
+ width: theme.spacing.spacing.s8,
4080
+ height: theme.spacing.spacing.s8,
4081
+ borderRadius: theme.spacing.spacing.s15,
4082
+ padding: theme.spacing.padding.p1,
4083
+ justifyContent: 'center',
4084
+ alignItems: 'center',
4085
+ backgroundColor: isSendDisabled
4086
+ ? (theme.color.background4 as string)
4087
+ : (theme.color.primary as string),
4088
+ }, sendButtonStyle]}
4089
+ >
4090
+ {sendButtonIcon ? (
4091
+ <Icon
4092
+ icon={sendButtonIcon}
4093
+ width={sendIconSize}
4094
+ height={sendIconSize}
4095
+ color={sendIconColor}
4096
+ />
4097
+ ) : (
4098
+ <Icon
4099
+ name="send-fill"
4100
+ width={sendIconSize}
4101
+ height={sendIconSize}
4102
+ color={sendIconColor}
4103
+ />
4104
+ )}
4105
+ </TouchableOpacity>
4106
+ );
4107
+ };
4108
+
4109
+ /**
4110
+ * Render voice recording button with slide/fade animation.
4111
+ * Shows/hides based on hideVoiceRecordingButton (derived from prop or agentic user status).
4112
+ * For agentic users, voice recording is automatically hidden.
4113
+ * The button slides right (translateX 0→30) and fades out (opacity 1→0) when text is entered,
4114
+ * and reverses when text is cleared. Layout collapses to width:0 after animation completes.
4115
+ */
4116
+ const RecordAudioButtonView = () => {
4117
+ // Preserve guard: hideVoiceRecordingButton or agentic returns null before wrapper
4118
+ if (hideVoiceRecordingButton) {
4119
+ return null;
4120
+ }
4121
+ // Hide voice recording button when inline recorder is active
4122
+ if (showInlineRecorder) {
4123
+ return null;
4124
+ }
4125
+ // Animated wrapper: translateX slides right, opacity fades out
4126
+ return (
4127
+ <Animated.View
4128
+ pointerEvents={hasContent ? 'none' : 'auto'}
4129
+ style={{
4130
+ opacity: micAnimValue.interpolate({ inputRange: [0, 1], outputRange: [1, 0] }),
4131
+ transform: [{ translateX: micAnimValue.interpolate({ inputRange: [0, 1], outputRange: [0, MIC_SLIDE_DISTANCE] }) }],
4132
+ }}
4133
+ >
4134
+ <IconButton
4135
+ name={voiceRecordingIconURL ? undefined : 'mic'}
4136
+ icon={voiceRecordingIconURL}
4137
+ onClick={() => {
4138
+ // Show inline recorder
4139
+ setTimeout(() => setShowInlineRecorder(true), 50);
4140
+ }}
4141
+ buttonStyle={Style.iconButton}
4142
+ iconStyle={Style.icon}
4143
+ tintColor={getAttachmentIconTint()}
4144
+ />
4145
+ </Animated.View>
4146
+ );
4147
+ };
4148
+
4149
+ // Container styles - outer wrapper with padding (matches MessageComposer)
4150
+ const wrapperStyle: StyleProp<ViewStyle> = [
4151
+ Style.wrapper,
4152
+ {
4153
+ backgroundColor: resolvedStyle?.containerStyle?.backgroundColor || theme.color.background3,
4154
+ },
4155
+ ];
4156
+
4157
+ // Inner container styles with border (matches MessageComposer: messageInputStyles.containerStyle)
4158
+ const containerStyle: StyleProp<ViewStyle> = [
4159
+ Style.container,
4160
+ resolvedStyle?.containerStyle,
4161
+ {
4162
+ backgroundColor: resolvedStyle?.messageInputStyles?.containerStyle?.backgroundColor || theme.color.background1,
4163
+ borderColor: resolvedStyle?.messageInputStyles?.containerStyle?.borderColor || theme.color.borderDefault,
4164
+ },
4165
+ ];
4166
+
4167
+ // Input styles - use messageInputStyles from v5 theme
4168
+ const textInputStyle: StyleProp<TextStyle> = [
4169
+ Style.textInput,
4170
+ resolvedStyle?.messageInputStyles?.textStyle,
4171
+ {
4172
+ color: resolvedStyle?.messageInputStyles?.textStyle?.color || theme.color.textPrimary,
4173
+ // Apply dynamic height when autoExpand is enabled
4174
+ ...(autoExpand ? { height: inputHeight } : {}),
4175
+ },
4176
+ inputStyle,
4177
+ ];
4178
+
4179
+ // Separator style (matches Figma: Seprator)
4180
+ const separatorStyle: StyleProp<ViewStyle> = [
4181
+ Style.separator,
4182
+ resolvedStyle?.messageInputStyles?.dividerStyle,
4183
+ ];
4184
+
4185
+ return (
4186
+ <>
4187
+ {/* Modal for custom views */}
4188
+ <Modal
4189
+ animationType="slide"
4190
+ visible={isVisible}
4191
+ onRequestClose={() => {
4192
+ setIsVisible(false);
4193
+ }}
4194
+ presentationStyle="pageSheet"
4195
+ >
4196
+ {CustomView && CustomView}
4197
+ </Modal>
4198
+
4199
+ {/* KeyboardAvoidingView wrapper */}
4200
+ <KeyboardAvoidingView
4201
+ key={id}
4202
+ behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
4203
+ keyboardVerticalOffset={Platform.select({ ios: kbOffset })}
4204
+ {...keyboardAvoidingViewProps}
4205
+ >
4206
+ {/* Outer wrapper with padding (matches Figma: Message Composer) */}
4207
+ <View style={wrapperStyle}>
4208
+ {/* Inner container with border (matches Figma: Base_Message Composer) */}
4209
+ <View style={containerStyle}>
4210
+ {/* Action Sheet for attachments */}
4211
+ <ActionSheetBoard
4212
+ sheetRef={bottomSheetRef}
4213
+ options={actionSheetItems}
4214
+ shouldShow={showActionSheet}
4215
+ onClose={() => setShowActionSheet(false)}
4216
+ style={resolvedStyle?.attachmentOptionsStyles}
4217
+ />
4218
+
4219
+ {/* Voice Recording - removed bottom sheet, using inline recorder instead */}
4220
+
4221
+ {HeaderView ? (
4222
+ <HeaderView />
4223
+ ) : CustomViewHeader ? (
4224
+ typeof CustomViewHeader === 'function' ? (
4225
+ <CustomViewHeader />
4226
+ ) : (
4227
+ CustomViewHeader
4228
+ )
4229
+ ) : null}
4230
+
4231
+ {/* Mention Suggestion List */}
4232
+ {showMentionList && plainTextInputRef.current.length > 0 && mentionsSearchData.length > 0 && (
4233
+ <View
4234
+ style={[
4235
+ theme.mentionsListStyle.containerStyle,
4236
+ // Keep height stable to reduce flicker when list data loads/empties
4237
+ { maxHeight: Dimensions.get('window').height * (messagePreview ? 0.2 : (Platform.OS === 'ios' ? 0.15 : 0.22)) },
4238
+ ]}
4239
+ >
4240
+ <CometChatSuggestionList
4241
+ data={mentionsSearchData}
4242
+ listStyle={theme.mentionsListStyle}
4243
+ onPress={onMentionPress}
4244
+ onEndReached={onSuggestionListEndReached}
4245
+ loading={suggestionListLoader}
4246
+ />
4247
+ {renderMentionLimitWarning()}
4248
+ </View>
4249
+ )}
4250
+
4251
+ {/* Message Preview Tray for Edit Mode */}
4252
+ <MessagePreviewTray
4253
+ shouldShow={messagePreview !== null}
4254
+ text={typeof messagePreview?.message?.text === 'string' ? messagePreview.message.text : ''}
4255
+ title={t('EDIT_MESSAGE')}
4256
+ onClose={() => {
4257
+ setMessagePreview(null);
4258
+ clearInputBox();
4259
+ }}
4260
+ />
4261
+
4262
+ {replyMessage && replyMessage.message && (
4263
+ <CometChatMessagePreview
4264
+ message={replyMessage.message}
4265
+ showCloseIcon={true}
4266
+ closeIconURL={ICONS.CLOSE}
4267
+ onCloseClick={closeReplyPreview}
4268
+ titleStyle={{ color: theme.color.textHighlight as string }}
4269
+ style={{
4270
+ borderRadius: 8,
4271
+ borderLeftWidth: 3,
4272
+ borderLeftColor: theme.color.borderHighlight as string,
4273
+ margin: theme.spacing?.padding?.p1 || 4,
4274
+ }}
4275
+ />
4276
+ )}
4277
+
4278
+ {/* Conditional: Show inline recorder OR input row */}
4279
+ {showInlineRecorder ? (
4280
+ <CometChatInlineAudioRecorder
4281
+ onSubmit={handleInlineRecorderSubmit}
4282
+ onCancel={handleInlineRecorderCancel}
4283
+ style={(resolvedStyle as any)?.inlineAudioRecorderStyle}
4284
+ />
4285
+ ) : (
4286
+ <>
4287
+ {/* Top Field - Input row with icons (matches Figma: Top Field) */}
4288
+ <View
4289
+ style={[
4290
+ Style.inputRow,
4291
+ isExpanded && { alignItems: 'flex-end' as const },
4292
+ ]}
4293
+ >
4294
+ {/* Left icons container - dynamic alignment based on expansion state */}
4295
+ <View style={[
4296
+ Style.leftIconsContainer,
4297
+ isExpanded && { alignItems: 'flex-end' as const }
4298
+ ]}>
4299
+ {/* Secondary button (attachment) */}
4300
+ {renderSecondaryButton()}
4301
+ </View>
4302
+
4303
+ {/* Auxiliary button on left if alignment is 'left' */}
4304
+ {resolvedAlignment === 'left' && renderAuxiliaryButton()}
4305
+
4306
+ {/* Rich Text Editor - replaces TextInput with same styling */}
4307
+ <View
4308
+ style={{ flex: 1, maxHeight: resolvedMaxHeight, overflow: 'hidden' }}
4309
+ {...(Platform.OS === 'web' ? {
4310
+ onKeyDown: (e: any) => {
4311
+ // Tab key inserts indentation on web (Req 3.1); no-op on native (Req 3.2)
4312
+ if (e.key === 'Tab') {
4313
+ e.preventDefault();
4314
+ inputRef.current?.setText?.(inputText + '\t');
4315
+ }
4316
+ },
4317
+ } : {})}
4318
+ >
4319
+ <RichTextEditor
4320
+ ref={inputRef}
4321
+ testID="rich-text-editor"
4322
+ initialContent={editContentBlocks}
4323
+ style={{
4324
+ backgroundColor: 'transparent',
4325
+ }}
4326
+ onContentChange={(event: ContentChangeEvent) => {
4327
+ const newText = event.nativeEvent.text;
4328
+ // Store blocks for markdown conversion when sending.
4329
+ // The RichTextEditor wrapper already parses blocksJson into blocks,
4330
+ // so event.nativeEvent.blocks is always populated.
4331
+ if (event.nativeEvent.blocks && event.nativeEvent.blocks.length > 0) {
4332
+ blocksRef.current = event.nativeEvent.blocks;
4333
+ }
4334
+ if (skipNextContentChange.current) {
4335
+ skipNextContentChange.current = false;
4336
+ plainTextInputRef.current = newText;
4337
+ inputTextRef.current = newText;
4338
+ return;
4339
+ }
4340
+
4341
+ handleTextChange(newText);
4342
+ }}
4343
+ onSelectionChange={(event: any) => {
4344
+ const { start, end } = event.nativeEvent;
4345
+ handleSelectionChange({ nativeEvent: { selection: { start, end } } });
4346
+ }}
4347
+ onActiveStylesChange={(styles: ActiveStylesState) => {
4348
+ activeStylesRef.current = styles;
4349
+ setActiveStyles(styles);
4350
+ // Sync codeBlockActive from native codeBlock field
4351
+ setCodeBlockActive(!!styles.codeBlock);
4352
+ }}
4353
+ onSizeChange={(height: number) => {
4354
+ if (autoExpand) {
4355
+ // Snap to resolvedMinHeight when height is within 2px of it
4356
+ // to prevent sub-pixel layout drift between initial empty state
4357
+ // and post-clear empty state on iOS (UITextView.sizeThatFits
4358
+ // returns slightly different values for these two states)
4359
+ const snapped = Math.abs(height - resolvedMinHeight) <= 2 ? resolvedMinHeight : height;
4360
+ const clamped = Math.max(resolvedMinHeight, Math.min(snapped, resolvedMaxHeight));
4361
+ setInputHeight(clamped);
4362
+ const newIsExpanded = clamped > resolvedMinHeight;
4363
+ if (newIsExpanded !== isExpanded) {
4364
+ setIsExpanded(newIsExpanded);
4365
+ }
4366
+ }
4367
+ }}
4368
+ onFocus={() => {
4369
+ setIsFocused(true);
4370
+ startTyping();
4371
+ }}
4372
+ onBlur={() => {
4373
+ setIsFocused(false);
4374
+ endTyping();
4375
+ }}
4376
+ placeholder={placeHolderText || (isAgenticUser() ? t('ASK_ANYTHING') : t('ENTER_YOUR_MESSAGE_HERE'))}
4377
+ placeholderTextColor={resolvedStyle?.messageInputStyles?.placeHolderTextColor as string || theme.color.textTertiary as string}
4378
+ variant="plain"
4379
+ showToolbar={false}
4380
+ maxHeight={resolvedMaxHeight}
4381
+ numberOfLines={maxLines ?? 5}
4382
+ textStyle={{
4383
+ fontSize: (resolvedStyle?.messageInputStyles?.textStyle as any)?.fontSize ?? 14,
4384
+ color: (resolvedStyle?.messageInputStyles?.textStyle?.color || theme.color.textPrimary) as string,
4385
+ fontFamily: (resolvedStyle?.messageInputStyles?.textStyle as any)?.fontFamily,
4386
+ }}
4387
+ codeBackgroundColor={theme.color.neutral200 as string}
4388
+ codeBorderColor={theme.color.neutral300 as string}
4389
+ codeTextColor={(theme.mode === 'dark' ? theme.color.extendedPrimary900 : theme.color.primary) as string}
4390
+ codeFontSize={theme.typography.caption1.regular.fontSize as number}
4391
+ onLinkTap={onLinkTap}
4392
+ enterKeyBehavior={enterKeyBehavior as string}
4393
+ showTextSelectionMenuItems={showTextSelectionMenuItems}
4394
+ onSendRequest={() => {
4395
+ if (!isSendDisabled) {
4396
+ sendTextMessage();
4397
+ }
4398
+ }}
4399
+ />
4400
+ </View>
4401
+
4402
+ {/* Right icons container - dynamic alignment based on expansion state */}
4403
+ <View style={[
4404
+ Style.rightIconsContainer,
4405
+ isExpanded && { alignItems: 'flex-end' as const }
4406
+ ]}>
4407
+ {/* Auxiliary button (stickers/emoji) on right — slides right with mic */}
4408
+ {resolvedAlignment === 'right' && !hideVoiceRecordingButton && (
4409
+ <Animated.View style={{
4410
+ transform: [{ translateX: micAnimValue.interpolate({ inputRange: [0, 1], outputRange: [0, MIC_SLIDE_DISTANCE] }) }],
4411
+ }}>
4412
+ {renderAuxiliaryButton()}
4413
+ </Animated.View>
4414
+ )}
4415
+ {resolvedAlignment === 'right' && hideVoiceRecordingButton && renderAuxiliaryButton()}
4416
+
4417
+ {/* Voice recording button - matches Figma design */}
4418
+ {!hideVoiceRecordingButton && !isAgenticUser() && <RecordAudioButtonView />}
4419
+
4420
+ {/* Send button */}
4421
+ {renderSendButton()}
4422
+ </View>
4423
+ </View>
4424
+
4425
+ {/* Rich text toolbar — shown below input row */}
4426
+ {enableRichTextEditor && !hideRichTextFormattingOptions && (
4427
+ <View style={{
4428
+ flexDirection: 'row',
4429
+ alignItems: 'center',
4430
+ paddingHorizontal: theme.spacing.padding.p2,
4431
+ paddingVertical: 6,
4432
+ borderTopWidth: StyleSheet.hairlineWidth,
4433
+ borderTopColor: theme.color.borderLight as string,
4434
+ }}>
4435
+ <ScrollView
4436
+ testID="toolbar-scrollview"
4437
+ horizontal
4438
+ showsHorizontalScrollIndicator={false}
4439
+ contentContainerStyle={{ alignItems: 'center', gap: 2 }}
4440
+ >
4441
+ {richTextToolbarItems.map((item, index) => {
4442
+ if (item.type === 'separator') {
4443
+ return <View key={`sep-${index}`} style={[richTextToolbarStyles.separator, { backgroundColor: theme.color.borderLight as string }]} />;
4444
+ }
4445
+ // Slack-style: disable inline format buttons inside code blocks;
4446
+ // block-level buttons (lists, quote, code-block) stay enabled.
4447
+ const codeBlockAllowedKeys = ['ordered-list', 'unordered-list', 'blockquote', 'code-block'];
4448
+ const isDisabled = codeBlockActive && !codeBlockAllowedKeys.includes(item.key);
4449
+ let isActive = item.isActive?.(activeStyles) ?? false;
4450
+ // Distinguish inline code vs code block highlighting
4451
+ if (item.key === 'inline-code') {
4452
+ isActive = activeStyles.code && !codeBlockActive;
4453
+ } else if (item.key === 'code-block') {
4454
+ isActive = codeBlockActive;
4455
+ }
4456
+ const iconColor = isDisabled
4457
+ ? theme.color.iconSecondary
4458
+ : isActive ? theme.color.iconPrimary : theme.color.iconSecondary;
4459
+ return (
4460
+ <TouchableOpacity
4461
+ key={item.key}
4462
+ testID={`toolbar-${item.key}`}
4463
+ accessibilityValue={{ text: isActive ? 'on' : 'off' }}
4464
+ disabled={isDisabled}
4465
+ style={[richTextToolbarStyles.btn, isActive && { backgroundColor: theme.color.background4 as string }, isDisabled && { opacity: 0.3 }]}
4466
+ onPress={() => {
4467
+ if (item.key === 'inline-code') {
4468
+ setCodeBlockActive(false);
4469
+ }
4470
+ // Code-block active state is driven by native
4471
+ // onActiveStylesChange — don't eagerly set it here
4472
+ // since the button is a toggle.
4473
+ item.onPress(inputRef, selectionPosition, inputTextRef, setLinkText, setLinkUrl, setShowLinkModal);
4474
+ }}
4475
+ >
4476
+ <Icon
4477
+ name={item.iconName as any}
4478
+ width={theme.spacing.spacing.s6}
4479
+ height={theme.spacing.spacing.s6}
4480
+ color={iconColor}
4481
+ />
4482
+ </TouchableOpacity>
4483
+ );
4484
+ })}
4485
+ </ScrollView>
4486
+ </View>
4487
+ )}
4488
+ </>
4489
+ )}
4490
+
4491
+ {/* Separator line - only show when there's footer content (matches Figma: Seprator) */}
4492
+ {(FooterView || CustomViewFooter) && <View style={separatorStyle} />}
4493
+
4494
+ {FooterView ? (
4495
+ <FooterView />
4496
+ ) : CustomViewFooter ? (
4497
+ typeof CustomViewFooter === 'function' ? (
4498
+ <CustomViewFooter />
4499
+ ) : (
4500
+ CustomViewFooter
4501
+ )
4502
+ ) : null}
4503
+ </View>
4504
+ </View>
4505
+ </KeyboardAvoidingView>
4506
+
4507
+ {/* Link insertion popup (reuses CometChatLinkConfirmPopup in insert mode) */}
4508
+ <CometChatLinkConfirmPopup
4509
+ visible={showLinkModal}
4510
+ url=""
4511
+ initialEditText={linkText}
4512
+ initialEditUrl={linkUrl}
4513
+ insertMode
4514
+ onDismiss={() => setShowLinkModal(false)}
4515
+ onEdit={(newUrl, newText) => {
4516
+ inputRef.current?.insertLink(newUrl, newText);
4517
+ pendingLinksRef.current.set(newText, newUrl);
4518
+ setShowLinkModal(false);
4519
+ }}
4520
+ onRemove={() => setShowLinkModal(false)}
4521
+ />
4522
+
4523
+ {/* Link tap edit/remove dialog (shown when user taps an existing link) */}
4524
+ <CometChatLinkConfirmPopup
4525
+ visible={linkTapData !== null}
4526
+ url={linkTapData?.url ?? ''}
4527
+ initialEditUrl={editLinkUrl}
4528
+ initialEditText={editLinkText}
4529
+ onDismiss={() => {
4530
+ setLinkTapData(null);
4531
+ setLinkEditMode(false);
4532
+ inputRef.current?.focus();
4533
+ }}
4534
+ onEdit={(newUrl, newText) => {
4535
+ if (linkTapData) {
4536
+ (inputRef.current as any)?.updateLink(
4537
+ linkTapData.location,
4538
+ linkTapData.length,
4539
+ newUrl,
4540
+ newText,
4541
+ );
4542
+ }
4543
+ setLinkTapData(null);
4544
+ setLinkEditMode(false);
4545
+ }}
4546
+ onRemove={() => {
4547
+ if (linkTapData) {
4548
+ (inputRef.current as any)?.removeLink(linkTapData.location, linkTapData.length);
4549
+ }
4550
+ setLinkTapData(null);
4551
+ setLinkEditMode(false);
4552
+ }}
4553
+ />
4554
+ </>
4555
+ );
4556
+ }
4557
+ );