Matthias Nott
2026-03-15 32ede5388bb6c66c5d5679c2d73fd6ec6b2342bf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import React, { useCallback, useEffect, useState } from "react";
import { ActionSheetIOS, Alert, Image, Platform, Pressable, Text, View } from "react-native";
import * as Clipboard from "expo-clipboard";
import { Message } from "../../types";
import { playSingle, stopPlayback, onPlayingChange } from "../../services/audio";
import { ImageViewer } from "./ImageViewer";
import { useTheme } from "../../contexts/ThemeContext";
interface MessageBubbleProps {
  message: Message;
  onDelete?: (id: string) => void;
  onPlayVoice?: (id: string) => void;
}
function formatDuration(ms?: number): string | null {
  if (!ms || ms <= 0) return null;
  const totalSeconds = Math.floor(ms / 1000);
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  return `${minutes}:${seconds.toString().padStart(2, "0")}`;
}
function formatTime(timestamp: number): string {
  const d = new Date(timestamp);
  return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}
export function MessageBubble({ message, onDelete, onPlayVoice }: MessageBubbleProps) {
  const [isPlaying, setIsPlaying] = useState(false);
  const [showViewer, setShowViewer] = useState(false);
  const { colors, isDark } = useTheme();
  const handleLongPress = useCallback(() => {
    const hasText = !!message.content;
    if (Platform.OS === "ios") {
      const options = ["Cancel"];
      if (hasText) options.push("Copy");
      if (onDelete) options.push("Delete Message");
      const destructiveIndex = onDelete ? options.indexOf("Delete Message") : undefined;
      ActionSheetIOS.showActionSheetWithOptions(
        {
          options,
          destructiveButtonIndex: destructiveIndex,
          cancelButtonIndex: 0,
        },
        (index) => {
          const selected = options[index];
          if (selected === "Copy") Clipboard.setStringAsync(message.content ?? "");
          else if (selected === "Delete Message") onDelete?.(message.id);
        },
      );
    } else {
      const buttons: any[] = [{ text: "Cancel", style: "cancel" }];
      if (hasText) buttons.push({ text: "Copy", onPress: () => Clipboard.setStringAsync(message.content ?? "") });
      if (onDelete) buttons.push({ text: "Delete", style: "destructive", onPress: () => onDelete(message.id) });
      Alert.alert("Message", undefined, buttons);
    }
  }, [onDelete, message.id, message.content]);
  // Track whether THIS bubble's audio is playing via the singleton URI
  useEffect(() => {
    return onPlayingChange((uri) => {
      setIsPlaying(uri !== null && uri === message.audioUri);
    });
  }, [message.audioUri]);
  const isUser = message.role === "user";
  const isSystem = message.role === "system";
  const handleVoicePress = useCallback(async () => {
    if (!message.audioUri) return;
    if (isPlaying) {
      await stopPlayback();
    } else if (onPlayVoice) {
      // Let parent handle chain playback (plays this + subsequent chunks)
      onPlayVoice(message.id);
    } else {
      await playSingle(message.audioUri, () => {});
    }
  }, [isPlaying, message.audioUri, onPlayVoice, message.id]);
  if (isSystem) {
    return (
      <View style={{ alignItems: "center", marginVertical: 4, paddingHorizontal: 16 }}>
        <Text style={{ color: colors.textMuted, fontSize: 12 }}>{message.content}</Text>
      </View>
    );
  }
  const bubbleBg = isUser
    ? colors.accent
    : isDark ? "#252538" : colors.bgSecondary;
  const bubbleRadius = isUser
    ? { borderTopRightRadius: 4 }
    : { borderTopLeftRadius: 4 };
  return (
    <Pressable
      onLongPress={handleLongPress}
      delayLongPress={500}
      style={{
        flexDirection: "row",
        marginVertical: 4,
        paddingHorizontal: 12,
        justifyContent: isUser ? "flex-end" : "flex-start",
      }}
    >
      <View
        style={{
          maxWidth: "78%",
          borderRadius: 16,
          paddingHorizontal: 16,
          paddingVertical: 12,
          backgroundColor: bubbleBg,
          ...bubbleRadius,
        }}
      >
        {message.type === "image" && message.imageBase64 ? (
          <View>
            <Pressable onPress={() => setShowViewer(true)}>
              <Image
                source={{ uri: `data:image/png;base64,${message.imageBase64}` }}
                style={{
                  width: 260,
                  height: 180,
                  borderRadius: 10,
                  backgroundColor: colors.bgTertiary,
                }}
                resizeMode="contain"
              />
            </Pressable>
            {message.content ? (
              <Text
                style={{
                  color: isUser ? "#FFF" : colors.textSecondary,
                  fontSize: 12,
                  marginTop: 4,
                }}
              >
                {message.content}
              </Text>
            ) : null}
            <ImageViewer
              visible={showViewer}
              imageBase64={message.imageBase64}
              onClose={() => setShowViewer(false)}
            />
          </View>
        ) : message.type === "voice" ? (
          <View>
            <Pressable
              onPress={handleVoicePress}
              style={{ flexDirection: "row", alignItems: "center", gap: 12 }}
            >
              <View
                style={{
                  width: 36,
                  height: 36,
                  borderRadius: 18,
                  alignItems: "center",
                  justifyContent: "center",
                  backgroundColor: isPlaying
                    ? "#FF9F43"
                    : isUser
                    ? "rgba(255,255,255,0.2)"
                    : colors.border,
                }}
              >
                <Text style={{ fontSize: 14, color: isUser ? "#FFF" : colors.text }}>
                  {isPlaying ? "\u23F8" : "\u25B6"}
                </Text>
              </View>
              <View style={{ flex: 1, flexDirection: "row", alignItems: "center", gap: 1, height: 32 }}>
                {Array.from({ length: 20 }).map((_, i) => (
                  <View
                    key={i}
                    style={{
                      flex: 1,
                      borderRadius: 2,
                      backgroundColor: isPlaying && i < 10
                        ? "#FF9F43"
                        : isUser
                        ? "rgba(255,255,255,0.5)"
                        : colors.textMuted,
                      height: `${20 + Math.sin(i * 0.8) * 60}%`,
                    }}
                  />
                ))}
              </View>
              {formatDuration(message.duration) && (
                <Text
                  style={{
                    fontSize: 11,
                    color: isUser ? "rgba(255,255,255,0.8)" : colors.textSecondary,
                  }}
                >
                  {formatDuration(message.duration)}
                </Text>
              )}
            </Pressable>
            {message.content ? (
              <Text
                style={{
                  fontSize: 14,
                  lineHeight: 20,
                  marginTop: 8,
                  color: isUser ? "rgba(255,255,255,0.9)" : colors.textSecondary,
                }}
              >
                {message.content}
              </Text>
            ) : null}
          </View>
        ) : (
          <Text
            style={{
              fontSize: 16,
              lineHeight: 24,
              color: isUser ? "#FFF" : colors.text,
            }}
          >
            {message.content}
          </Text>
        )}
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            marginTop: 4,
            gap: 4,
            justifyContent: isUser ? "flex-end" : "flex-start",
          }}
        >
          <Text
            style={{
              fontSize: 10,
              color: isUser ? "rgba(255,255,255,0.6)" : colors.textMuted,
            }}
          >
            {formatTime(message.timestamp)}
          </Text>
          {isUser && message.status === "error" && (
            <Text style={{ fontSize: 10, color: colors.danger }}> !</Text>
          )}
        </View>
      </View>
    </Pressable>
  );
}