@figoailabs/figochat-react-native 0.0.0-stage → 1.0.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.
@@ -0,0 +1,650 @@
1
+ import React, { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
2
+ import {
3
+ ActivityIndicator,
4
+ Alert,
5
+ FlatList,
6
+ Image,
7
+ Keyboard,
8
+ KeyboardEvent,
9
+ LayoutAnimation,
10
+ Linking,
11
+ Platform,
12
+ Pressable,
13
+ StyleProp,
14
+ StyleSheet,
15
+ Text,
16
+ TextInput,
17
+ View,
18
+ ViewStyle,
19
+ } from 'react-native';
20
+ import * as DocumentPicker from 'expo-document-picker';
21
+ import {
22
+ AudioModule,
23
+ RecordingPresets,
24
+ setAudioModeAsync,
25
+ useAudioRecorder,
26
+ useAudioRecorderState,
27
+ } from 'expo-audio';
28
+
29
+ import { FigoChat } from './FigoChat';
30
+ import { FigoChatError } from './client';
31
+ import { FigoRealtimeSubscription } from './realtime';
32
+ import { contrastText } from './colors';
33
+ import { AttachIcon, MicIcon, SendIcon } from './icons';
34
+ import { friendlyMessage } from './messages';
35
+ import type { FigoAttachment, FigoChatMessage, FigoLocalFile } from './types';
36
+
37
+ export interface FigoChatViewProps {
38
+ /** Shows a close button in the header and calls this when it is pressed. */
39
+ onClose?: () => void;
40
+ /** Hide the header if the host app draws its own. Defaults to true. */
41
+ showHeader?: boolean;
42
+ /** Input placeholder. Defaults to "Type a message". */
43
+ placeholder?: string;
44
+ /** Turn voice notes off. Defaults to true. */
45
+ enableVoice?: boolean;
46
+ /** Turn file uploads off. Defaults to true. */
47
+ enableAttachments?: boolean;
48
+ /**
49
+ * Extra space added above the keyboard on iOS. Rarely needed: the view measures how much of it the
50
+ * keyboard covers, so it already works inside modals, under navigation headers and in safe areas.
51
+ */
52
+ keyboardVerticalOffset?: number;
53
+ /** Replace the built-in glyph icons with your own (e.g. from an icon library). */
54
+ icons?: Partial<Record<'send' | 'attach' | 'mic' | 'stop' | 'close' | 'newChat', React.ReactNode>>;
55
+ /** Called with every error the view shows, for logging. */
56
+ onError?: (error: FigoChatError) => void;
57
+ style?: StyleProp<ViewStyle>;
58
+ }
59
+
60
+ interface PendingFile {
61
+ id: string;
62
+ file: FigoLocalFile;
63
+ url?: string;
64
+ status: 'uploading' | 'done' | 'error';
65
+ }
66
+
67
+ let idCounter = 0;
68
+ const newId = () => `${Date.now().toString(36)}-${(idCounter++).toString(36)}`;
69
+ const IMAGE_EXT = /\.(png|jpe?g|gif|webp|bmp|heic|heif)(\?|$)/i;
70
+
71
+ export function FigoChatView({
72
+ onClose,
73
+ showHeader = true,
74
+ placeholder = 'Type a message',
75
+ enableVoice = true,
76
+ enableAttachments = true,
77
+ keyboardVerticalOffset = 0,
78
+ icons = {},
79
+ onError,
80
+ style,
81
+ }: FigoChatViewProps) {
82
+ const initialized = useSyncExternalStore(FigoChat.subscribe, FigoChat.isInitialized, FigoChat.isInitialized);
83
+ if (!initialized) {
84
+ return (
85
+ <View style={[styles.center, style]}>
86
+ <Text style={styles.muted}>FigoChat is not initialized. Call FigoChat.initialize(...) first.</Text>
87
+ </View>
88
+ );
89
+ }
90
+ return (
91
+ <ChatScreen
92
+ onClose={onClose}
93
+ showHeader={showHeader}
94
+ placeholder={placeholder}
95
+ enableVoice={enableVoice}
96
+ enableAttachments={enableAttachments}
97
+ keyboardVerticalOffset={keyboardVerticalOffset}
98
+ icons={icons}
99
+ onError={onError}
100
+ style={style}
101
+ />
102
+ );
103
+ }
104
+
105
+ function ChatScreen(props: Required<Omit<FigoChatViewProps, 'onClose' | 'onError' | 'style'>> & Pick<FigoChatViewProps, 'onClose' | 'onError' | 'style'>) {
106
+ const config = FigoChat.getConfig();
107
+ const client = FigoChat.getClient();
108
+ const primary = config.primaryColor;
109
+ const onPrimary = contrastText(primary);
110
+ const maxFiles = config.maxFiles ?? 5;
111
+ const maxBytes = (config.maxFileSizeMB ?? 10) * 1024 * 1024;
112
+
113
+ const welcome = useMemo<FigoChatMessage[]>(
114
+ () => (config.welcomeMessage ? [{ id: 'welcome', role: 'assistant', text: config.welcomeMessage, createdAt: new Date() }] : []),
115
+ [config.welcomeMessage],
116
+ );
117
+ const [messages, setMessages] = useState<FigoChatMessage[]>(welcome);
118
+ const [input, setInput] = useState('');
119
+ const [pending, setPending] = useState<PendingFile[]>([]);
120
+ const [waiting, setWaiting] = useState(false);
121
+ const [transcribing, setTranscribing] = useState(false);
122
+ const [threadId, setThreadId] = useState<string | undefined>(() => FigoChat.getThreadId());
123
+ const mounted = useRef(true);
124
+ // set back to true on every (re)run: React re-runs effects in Strict Mode and on Fast Refresh, and a flag
125
+ // left false would make the view ignore every reply and keyboard event from then on
126
+ useEffect(() => {
127
+ mounted.current = true;
128
+ return () => {
129
+ mounted.current = false;
130
+ };
131
+ }, []);
132
+
133
+ const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY);
134
+ const recorderState = useAudioRecorderState(recorder, 250);
135
+ const recording = recorderState.isRecording;
136
+
137
+ // kept in a ref so an inline onError prop doesn't re-create callbacks (and re-subscribe) on every render
138
+ const onErrorRef = useRef(props.onError);
139
+ onErrorRef.current = props.onError;
140
+ const reportError = useCallback((e: unknown) => {
141
+ const err = e instanceof FigoChatError ? e : new FigoChatError(String((e as Error)?.message ?? e), 'UNKNOWN');
142
+ onErrorRef.current?.(err);
143
+ return err;
144
+ }, []);
145
+
146
+ const addMessage = (m: FigoChatMessage) => setMessages((prev) => [...prev, m]);
147
+ const patchMessage = (id: string, patch: Partial<FigoChatMessage>) =>
148
+ setMessages((prev) => prev.map((m) => (m.id === id ? { ...m, ...patch } : m)));
149
+
150
+ // Live agent messages: subscribe to the Pusher channel named after the thread id and show what arrives
151
+ // on the left, like an assistant reply. Re-subscribes when the thread changes and stops on unmount.
152
+ useEffect(() => {
153
+ if (!threadId) return;
154
+ const subscription = new FigoRealtimeSubscription(
155
+ FigoChat.getRealtimeStore(),
156
+ threadId,
157
+ (text) => {
158
+ if (mounted.current) addMessage({ id: newId(), role: 'assistant', text, createdAt: new Date() });
159
+ },
160
+ (e) => reportError(e instanceof FigoChatError ? e : new FigoChatError('Live updates are unavailable.', 'REALTIME')),
161
+ );
162
+ subscription.start();
163
+ return () => subscription.stop();
164
+ }, [threadId, reportError]);
165
+
166
+ const ask = useCallback(
167
+ async (userMessage: FigoChatMessage) => {
168
+ setWaiting(true);
169
+ try {
170
+ const reply = await client.sendMessage(userMessage.text, (userMessage.attachments ?? []).map((a) => a.url));
171
+ if (!mounted.current) return;
172
+ patchMessage(userMessage.id, { status: 'sent' });
173
+ if (reply.threadId) setThreadId(reply.threadId);
174
+ // in live agent mode the API relays the message to the agent and answers with nothing;
175
+ // the agent's reply arrives on the thread channel instead
176
+ if (reply.answer) {
177
+ addMessage({ id: newId(), role: 'assistant', text: reply.answer, createdAt: new Date() });
178
+ } else if (reply.threadMode !== 'liveagent') {
179
+ addMessage({ id: newId(), role: 'assistant', text: '…', createdAt: new Date() });
180
+ }
181
+ } catch (e) {
182
+ if (!mounted.current) return;
183
+ const err = reportError(e);
184
+ patchMessage(userMessage.id, { status: 'error' });
185
+ addMessage({ id: newId(), role: 'system', text: friendlyMessage(err, 'chat'), createdAt: new Date() });
186
+ } finally {
187
+ if (mounted.current) setWaiting(false);
188
+ }
189
+ },
190
+ [client, reportError],
191
+ );
192
+
193
+ const send = useCallback(
194
+ (textOverride?: string) => {
195
+ const text = (textOverride ?? input).trim();
196
+ const ready = pending.filter((p) => p.status === 'done' && p.url);
197
+ if (waiting || (!text && ready.length === 0)) return;
198
+ if (pending.some((p) => p.status === 'uploading')) {
199
+ Alert.alert('Please wait', 'Your files are still uploading.');
200
+ return;
201
+ }
202
+
203
+ const attachments: FigoAttachment[] = ready.map((p) => ({
204
+ url: p.url!,
205
+ name: p.file.name,
206
+ mimeType: p.file.mimeType,
207
+ localUri: p.file.uri,
208
+ }));
209
+ const message: FigoChatMessage = {
210
+ id: newId(),
211
+ role: 'user',
212
+ text: text || (attachments.length > 1 ? 'Please review the attached files.' : 'Please review the attached file.'),
213
+ attachments,
214
+ createdAt: new Date(),
215
+ status: 'sending',
216
+ };
217
+ addMessage(message);
218
+ setInput('');
219
+ setPending([]);
220
+ ask(message);
221
+ },
222
+ [input, pending, waiting, ask],
223
+ );
224
+
225
+ const retry = (m: FigoChatMessage) => {
226
+ if (waiting) return;
227
+ patchMessage(m.id, { status: 'sending' });
228
+ ask(m);
229
+ };
230
+
231
+ // ---------- files ----------
232
+ const pickFiles = async () => {
233
+ const room = maxFiles - pending.length;
234
+ if (room <= 0) {
235
+ Alert.alert('Limit reached', `You can attach up to ${maxFiles} files per message.`);
236
+ return;
237
+ }
238
+ const result = await DocumentPicker.getDocumentAsync({ multiple: true, copyToCacheDirectory: true, type: '*/*' });
239
+ if (result.canceled || !result.assets?.length) return;
240
+
241
+ const tooBig = result.assets.filter((a) => (a.size ?? 0) > maxBytes);
242
+ if (tooBig.length) {
243
+ Alert.alert('File too large', `${tooBig.map((a) => a.name).join(', ')} is larger than ${config.maxFileSizeMB ?? 10} MB.`);
244
+ }
245
+ const accepted = result.assets.filter((a) => (a.size ?? 0) <= maxBytes).slice(0, room);
246
+ if (!accepted.length) return;
247
+
248
+ const items: PendingFile[] = accepted.map((a) => ({
249
+ id: newId(),
250
+ file: { uri: a.uri, name: a.name, mimeType: a.mimeType ?? undefined, size: a.size ?? undefined },
251
+ status: 'uploading',
252
+ }));
253
+ setPending((prev) => [...prev, ...items]);
254
+
255
+ // one request per file so a failure only marks that file
256
+ await Promise.all(
257
+ items.map(async (item) => {
258
+ try {
259
+ const [url] = await client.uploadFiles([item.file]);
260
+ if (mounted.current) setPending((prev) => prev.map((p) => (p.id === item.id ? { ...p, url, status: 'done' } : p)));
261
+ } catch (e) {
262
+ reportError(e);
263
+ if (mounted.current) setPending((prev) => prev.map((p) => (p.id === item.id ? { ...p, status: 'error' } : p)));
264
+ }
265
+ }),
266
+ );
267
+ };
268
+
269
+ const removePending = (id: string) => setPending((prev) => prev.filter((p) => p.id !== id));
270
+
271
+ // ---------- voice ----------
272
+ const startRecording = async () => {
273
+ try {
274
+ const permission = await AudioModule.requestRecordingPermissionsAsync();
275
+ if (!permission.granted) {
276
+ Alert.alert('Microphone access', 'Allow microphone access in Settings to send voice messages.');
277
+ return;
278
+ }
279
+ await setAudioModeAsync({ playsInSilentMode: true, allowsRecording: true });
280
+ await recorder.prepareToRecordAsync();
281
+ recorder.record();
282
+ } catch (e) {
283
+ const err = reportError(e);
284
+ Alert.alert('Recording failed', friendlyMessage(err, 'recording'));
285
+ }
286
+ };
287
+
288
+ const stopRecording = async (discard = false) => {
289
+ const durationMs = recorderState.durationMillis ?? 0; // read before stop(), which resets the state
290
+ try {
291
+ await recorder.stop();
292
+ await setAudioModeAsync({ playsInSilentMode: true, allowsRecording: false });
293
+ } catch (e) {
294
+ reportError(e);
295
+ }
296
+ const uri = recorder.uri;
297
+ if (discard || !uri) return;
298
+ if (durationMs < 600) return; // accidental tap
299
+
300
+ setTranscribing(true);
301
+ try {
302
+ const text = await client.transcribe({ uri, name: 'voice-note.m4a', mimeType: 'audio/mp4' });
303
+ if (!mounted.current) return;
304
+ if (!text) {
305
+ Alert.alert('Nothing heard', 'We could not hear anything in that recording. Please try again.');
306
+ } else if (config.autoSendVoice === false) {
307
+ setInput((prev) => (prev ? `${prev} ${text}` : text));
308
+ } else {
309
+ send(text);
310
+ }
311
+ } catch (e) {
312
+ const err = reportError(e);
313
+ if (mounted.current) Alert.alert('Voice message failed', friendlyMessage(err, 'voice'));
314
+ } finally {
315
+ if (mounted.current) setTranscribing(false);
316
+ }
317
+ };
318
+
319
+ const newConversation = () => {
320
+ if (waiting) return;
321
+ FigoChat.resetConversation();
322
+ setThreadId(undefined);
323
+ setMessages(welcome);
324
+ setPending([]);
325
+ setInput('');
326
+ };
327
+
328
+ // ---------- keyboard (iOS) ----------
329
+ // Pads the bottom by exactly the part of this view the keyboard covers, measured in the window.
330
+ // KeyboardAvoidingView guesses this from offsets and gets it wrong inside a Modal or safe-area padding.
331
+ // Android resizes the window itself (adjustResize), so nothing is needed there.
332
+ const rootRef = useRef<View>(null);
333
+ const [keyboardPad, setKeyboardPad] = useState(0);
334
+ const extraOffset = props.keyboardVerticalOffset;
335
+ useEffect(() => {
336
+ if (Platform.OS !== 'ios') return;
337
+ const animate = (e?: KeyboardEvent) =>
338
+ LayoutAnimation.configureNext(
339
+ LayoutAnimation.create(e?.duration || 250, LayoutAnimation.Types.keyboard, LayoutAnimation.Properties.opacity),
340
+ );
341
+ const onChange = (e: KeyboardEvent) => {
342
+ rootRef.current?.measureInWindow((_x, y, _w, h) => {
343
+ if (!mounted.current) return;
344
+ const overlap = Math.max(0, y + h - e.endCoordinates.screenY);
345
+ animate(e);
346
+ setKeyboardPad(overlap > 0 ? overlap + extraOffset : 0);
347
+ });
348
+ };
349
+ const onHide = (e: KeyboardEvent) => {
350
+ animate(e);
351
+ setKeyboardPad(0);
352
+ };
353
+ const change = Keyboard.addListener('keyboardWillChangeFrame', onChange);
354
+ const hide = Keyboard.addListener('keyboardWillHide', onHide);
355
+ return () => {
356
+ change.remove();
357
+ hide.remove();
358
+ };
359
+ }, [extraOffset]);
360
+
361
+ // ---------- render ----------
362
+ const canSend = !waiting && (input.trim().length > 0 || pending.some((p) => p.status === 'done'));
363
+ const showMic = props.enableVoice && !canSend && input.trim().length === 0;
364
+ const data = useMemo(() => [...messages].reverse(), [messages]);
365
+
366
+ return (
367
+ <View ref={rootRef} style={[styles.root, props.style, { paddingBottom: keyboardPad }]}>
368
+ {props.showHeader && (
369
+ <View style={[styles.header, { backgroundColor: primary }]}>
370
+ <Text style={[styles.headerTitle, { color: onPrimary }]} numberOfLines={1}>
371
+ {config.title ?? 'Chat'}
372
+ </Text>
373
+ <Pressable onPress={newConversation} hitSlop={10} style={styles.headerButton} accessibilityLabel="New conversation">
374
+ {props.icons.newChat ?? <Text style={[styles.headerIcon, { color: onPrimary }]}>↻</Text>}
375
+ </Pressable>
376
+ {props.onClose && (
377
+ <Pressable onPress={props.onClose} hitSlop={10} style={styles.headerButton} accessibilityLabel="Close chat">
378
+ {props.icons.close ?? <Text style={[styles.headerIcon, { color: onPrimary }]}>✕</Text>}
379
+ </Pressable>
380
+ )}
381
+ </View>
382
+ )}
383
+
384
+ <FlatList
385
+ style={styles.list}
386
+ contentContainerStyle={styles.listContent}
387
+ data={data}
388
+ inverted
389
+ keyExtractor={(m) => m.id}
390
+ keyboardShouldPersistTaps="handled"
391
+ ListHeaderComponent={waiting ? <TypingBubble /> : null}
392
+ renderItem={({ item }) => (
393
+ <MessageBubble message={item} primary={primary} onPrimary={onPrimary} onRetry={() => retry(item)} />
394
+ )}
395
+ />
396
+
397
+ {pending.length > 0 && (
398
+ <View style={styles.pendingRow}>
399
+ {pending.map((p) => (
400
+ <View key={p.id} style={[styles.pendingChip, p.status === 'error' && styles.pendingChipError]}>
401
+ {p.status === 'uploading' && <ActivityIndicator size="small" color={primary} style={{ marginRight: 6 }} />}
402
+ <Text style={styles.pendingName} numberOfLines={1}>
403
+ {p.status === 'error' ? `Failed: ${p.file.name}` : p.file.name}
404
+ </Text>
405
+ <Pressable onPress={() => removePending(p.id)} hitSlop={8} accessibilityLabel={`Remove ${p.file.name}`}>
406
+ <Text style={styles.pendingRemove}>×</Text>
407
+ </Pressable>
408
+ </View>
409
+ ))}
410
+ </View>
411
+ )}
412
+
413
+ {recording || transcribing ? (
414
+ <View style={styles.inputRow}>
415
+ <View style={styles.recordingInfo}>
416
+ {transcribing ? (
417
+ <>
418
+ <ActivityIndicator size="small" color={primary} />
419
+ <Text style={styles.recordingText}>Processing your voice message…</Text>
420
+ </>
421
+ ) : (
422
+ <>
423
+ <View style={styles.recordingDot} />
424
+ <Text style={styles.recordingText}>Recording {formatDuration(recorderState.durationMillis ?? 0)}</Text>
425
+ <Pressable onPress={() => stopRecording(true)} hitSlop={8} style={{ marginLeft: 'auto' }}>
426
+ <Text style={styles.cancelText}>Cancel</Text>
427
+ </Pressable>
428
+ </>
429
+ )}
430
+ </View>
431
+ {!transcribing && (
432
+ <Pressable
433
+ onPress={() => stopRecording(false)}
434
+ style={[styles.roundButton, { backgroundColor: primary }]}
435
+ accessibilityLabel="Stop recording and send"
436
+ >
437
+ {props.icons.stop ?? <View style={[styles.stopSquare, { backgroundColor: onPrimary }]} />}
438
+ </Pressable>
439
+ )}
440
+ </View>
441
+ ) : (
442
+ <View style={styles.inputRow}>
443
+ {props.enableAttachments && (
444
+ <Pressable onPress={pickFiles} style={styles.iconButton} disabled={waiting} accessibilityLabel="Attach files">
445
+ {props.icons.attach ?? <AttachIcon color="#6B7280" />}
446
+ </Pressable>
447
+ )}
448
+ <TextInput
449
+ style={styles.input}
450
+ value={input}
451
+ onChangeText={setInput}
452
+ placeholder={props.placeholder}
453
+ placeholderTextColor="#8A8F98"
454
+ multiline
455
+ maxLength={4000}
456
+ />
457
+ {showMic ? (
458
+ <Pressable
459
+ onPress={startRecording}
460
+ style={[styles.roundButton, { backgroundColor: primary }]}
461
+ disabled={waiting}
462
+ accessibilityLabel="Record a voice message"
463
+ >
464
+ {props.icons.mic ?? <MicIcon color={onPrimary} />}
465
+ </Pressable>
466
+ ) : (
467
+ <Pressable
468
+ onPress={() => send()}
469
+ disabled={!canSend}
470
+ style={[styles.roundButton, { backgroundColor: primary, opacity: canSend ? 1 : 0.4 }]}
471
+ accessibilityLabel="Send message"
472
+ >
473
+ {props.icons.send ?? <SendIcon color={onPrimary} />}
474
+ </Pressable>
475
+ )}
476
+ </View>
477
+ )}
478
+ </View>
479
+ );
480
+ }
481
+
482
+ function MessageBubble({
483
+ message,
484
+ primary,
485
+ onPrimary,
486
+ onRetry,
487
+ }: {
488
+ message: FigoChatMessage;
489
+ primary: string;
490
+ onPrimary: string;
491
+ onRetry: () => void;
492
+ }) {
493
+ if (message.role === 'system') {
494
+ return (
495
+ <View style={styles.systemRow}>
496
+ <Text style={styles.systemText}>{message.text}</Text>
497
+ </View>
498
+ );
499
+ }
500
+ const mine = message.role === 'user';
501
+ const textColor = mine ? onPrimary : '#1F2328';
502
+ return (
503
+ <View style={[styles.bubbleRow, mine ? styles.bubbleRowMine : styles.bubbleRowTheirs]}>
504
+ <View style={[styles.bubble, mine ? { backgroundColor: primary, borderBottomRightRadius: 4 } : styles.bubbleTheirs]}>
505
+ {message.attachments?.map((a) => (
506
+ <AttachmentView key={a.url} attachment={a} color={textColor} />
507
+ ))}
508
+ <RichText text={message.text} color={textColor} linkColor={mine ? onPrimary : primary} />
509
+ </View>
510
+ {mine && message.status === 'sending' && <Text style={styles.status}>Sending…</Text>}
511
+ {mine && message.status === 'error' && (
512
+ <Pressable onPress={onRetry} hitSlop={6}>
513
+ <Text style={[styles.status, styles.statusError]}>Not sent. Tap to retry</Text>
514
+ </Pressable>
515
+ )}
516
+ </View>
517
+ );
518
+ }
519
+
520
+ function AttachmentView({ attachment, color }: { attachment: FigoAttachment; color: string }) {
521
+ const isImage = attachment.mimeType?.startsWith('image/') || IMAGE_EXT.test(attachment.name) || IMAGE_EXT.test(attachment.url);
522
+ const open = () => Linking.openURL(attachment.url).catch(() => undefined);
523
+ if (isImage) {
524
+ return (
525
+ <Pressable onPress={open}>
526
+ <Image source={{ uri: attachment.localUri ?? attachment.url }} style={styles.imageAttachment} resizeMode="cover" />
527
+ </Pressable>
528
+ );
529
+ }
530
+ return (
531
+ <Pressable onPress={open} style={[styles.fileAttachment, { borderColor: color }]}>
532
+ <Text style={[styles.fileAttachmentText, { color }]} numberOfLines={1}>
533
+ {attachment.name}
534
+ </Text>
535
+ </Pressable>
536
+ );
537
+ }
538
+
539
+ /** Renders **bold** and tappable urls; everything else is plain text. */
540
+ function RichText({ text, color, linkColor }: { text: string; color: string; linkColor: string }) {
541
+ const parts = useMemo(() => {
542
+ const tokens: { t: string; bold?: boolean; url?: string }[] = [];
543
+ const re = /(\*\*[^*]+\*\*)|(https?:\/\/[^\s)]+)/g;
544
+ let last = 0;
545
+ let m: RegExpExecArray | null;
546
+ while ((m = re.exec(text))) {
547
+ if (m.index > last) tokens.push({ t: text.slice(last, m.index) });
548
+ if (m[1]) tokens.push({ t: m[1].slice(2, -2), bold: true });
549
+ else tokens.push({ t: m[2], url: m[2] });
550
+ last = m.index + m[0].length;
551
+ }
552
+ if (last < text.length) tokens.push({ t: text.slice(last) });
553
+ return tokens;
554
+ }, [text]);
555
+
556
+ return (
557
+ <Text style={[styles.messageText, { color }]} selectable>
558
+ {parts.map((p, i) =>
559
+ p.url ? (
560
+ <Text key={i} style={{ color: linkColor, textDecorationLine: 'underline' }} onPress={() => Linking.openURL(p.url!).catch(() => undefined)}>
561
+ {p.t}
562
+ </Text>
563
+ ) : (
564
+ <Text key={i} style={p.bold ? { fontWeight: '700' } : undefined}>
565
+ {p.t}
566
+ </Text>
567
+ ),
568
+ )}
569
+ </Text>
570
+ );
571
+ }
572
+
573
+ function TypingBubble() {
574
+ const [dots, setDots] = useState(1);
575
+ useEffect(() => {
576
+ const t = setInterval(() => setDots((d) => (d % 3) + 1), 400);
577
+ return () => clearInterval(t);
578
+ }, []);
579
+ return (
580
+ <View style={[styles.bubbleRow, styles.bubbleRowTheirs]}>
581
+ <View style={[styles.bubble, styles.bubbleTheirs]}>
582
+ <Text style={[styles.messageText, { color: '#6B7280', width: 24 }]}>{'•'.repeat(dots)}</Text>
583
+ </View>
584
+ </View>
585
+ );
586
+ }
587
+
588
+ function formatDuration(ms: number) {
589
+ const s = Math.floor(ms / 1000);
590
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
591
+ }
592
+
593
+ const styles = StyleSheet.create({
594
+ root: { flex: 1, backgroundColor: '#FFFFFF' },
595
+ center: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 24 },
596
+ muted: { color: '#6B7280', textAlign: 'center' },
597
+ header: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, paddingVertical: 14 },
598
+ headerTitle: { flex: 1, fontSize: 17, fontWeight: '600' },
599
+ headerButton: { marginLeft: 16 },
600
+ headerIcon: { fontSize: 18, fontWeight: '600' },
601
+ list: { flex: 1 },
602
+ listContent: { paddingHorizontal: 12, paddingVertical: 12 },
603
+ bubbleRow: { marginVertical: 4, maxWidth: '85%' },
604
+ bubbleRowMine: { alignSelf: 'flex-end', alignItems: 'flex-end' },
605
+ bubbleRowTheirs: { alignSelf: 'flex-start', alignItems: 'flex-start' },
606
+ bubble: { borderRadius: 18, paddingHorizontal: 14, paddingVertical: 10 },
607
+ bubbleTheirs: { backgroundColor: '#F1F3F5', borderBottomLeftRadius: 4 },
608
+ messageText: { fontSize: 15, lineHeight: 21 },
609
+ status: { fontSize: 11, color: '#8A8F98', marginTop: 3 },
610
+ statusError: { color: '#D93025' },
611
+ systemRow: { alignSelf: 'center', marginVertical: 6, paddingHorizontal: 12, paddingVertical: 6, borderRadius: 10, backgroundColor: '#FDECEA' },
612
+ systemText: { fontSize: 12, color: '#B3261E', textAlign: 'center' },
613
+ imageAttachment: { width: 200, height: 150, borderRadius: 12, marginBottom: 6, backgroundColor: '#00000010' },
614
+ fileAttachment: { borderWidth: StyleSheet.hairlineWidth, borderRadius: 10, paddingHorizontal: 10, paddingVertical: 8, marginBottom: 6, maxWidth: 240 },
615
+ fileAttachmentText: { fontSize: 13 },
616
+ pendingRow: { flexDirection: 'row', flexWrap: 'wrap', paddingHorizontal: 12, paddingTop: 8, gap: 6 },
617
+ pendingChip: { flexDirection: 'row', alignItems: 'center', backgroundColor: '#F1F3F5', borderRadius: 14, paddingHorizontal: 10, paddingVertical: 6, maxWidth: 220 },
618
+ pendingChipError: { backgroundColor: '#FDECEA' },
619
+ pendingName: { fontSize: 12, color: '#1F2328', flexShrink: 1 },
620
+ pendingRemove: { fontSize: 16, color: '#6B7280', marginLeft: 6 },
621
+ inputRow: {
622
+ flexDirection: 'row',
623
+ alignItems: 'flex-end',
624
+ paddingHorizontal: 10,
625
+ paddingVertical: 8,
626
+ borderTopWidth: StyleSheet.hairlineWidth,
627
+ borderTopColor: '#E5E7EB',
628
+ gap: 8,
629
+ },
630
+ iconButton: { width: 40, height: 40, alignItems: 'center', justifyContent: 'center' },
631
+ input: {
632
+ flex: 1,
633
+ minHeight: 40,
634
+ maxHeight: 120,
635
+ borderRadius: 20,
636
+ backgroundColor: '#F1F3F5',
637
+ paddingHorizontal: 14,
638
+ paddingTop: Platform.OS === 'ios' ? 10 : 8,
639
+ paddingBottom: Platform.OS === 'ios' ? 10 : 8,
640
+ fontSize: 15,
641
+ color: '#1F2328',
642
+ },
643
+ roundButton: { width: 40, height: 40, borderRadius: 20, alignItems: 'center', justifyContent: 'center' },
644
+ glyph: { fontSize: 18 },
645
+ stopSquare: { width: 14, height: 14, borderRadius: 2 },
646
+ recordingInfo: { flex: 1, flexDirection: 'row', alignItems: 'center', height: 40, paddingHorizontal: 6, gap: 8 },
647
+ recordingDot: { width: 10, height: 10, borderRadius: 5, backgroundColor: '#D93025' },
648
+ recordingText: { fontSize: 15, color: '#1F2328' },
649
+ cancelText: { fontSize: 15, color: '#6B7280' },
650
+ });