@robono/messaging-react-native 0.13.0 → 0.15.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 (42) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/README.md +26 -0
  3. package/SBOM.spdx.json +638 -230
  4. package/dist/attachment-preview.d.ts +18 -0
  5. package/dist/attachment-preview.js +27 -0
  6. package/dist/composer-input.d.ts +5 -0
  7. package/dist/composer-input.js +13 -0
  8. package/dist/contact-directory.d.ts +26 -0
  9. package/dist/contact-directory.js +16 -0
  10. package/dist/conversation-selector.d.ts +9 -0
  11. package/dist/conversation-selector.js +19 -0
  12. package/dist/expo-document.d.ts +7 -0
  13. package/dist/expo-document.js +50 -0
  14. package/dist/expo-media.js +5 -1
  15. package/dist/expo-messenger.d.ts +4 -1
  16. package/dist/expo-messenger.js +1 -1
  17. package/dist/expo-screen.d.ts +5 -1
  18. package/dist/expo-screen.js +67 -31
  19. package/dist/expo-thumbnails.d.ts +3 -1
  20. package/dist/expo-thumbnails.js +3 -1
  21. package/dist/expo.d.ts +1 -0
  22. package/dist/inbox-search.d.ts +2 -1
  23. package/dist/inbox-search.js +2 -2
  24. package/dist/inbox.d.ts +3 -2
  25. package/dist/inbox.js +52 -3
  26. package/dist/index.d.ts +23 -4
  27. package/dist/index.js +88 -41
  28. package/dist/keyboard-container.d.ts +10 -0
  29. package/dist/keyboard-container.js +18 -0
  30. package/dist/media-controller.d.ts +1 -0
  31. package/dist/media-controller.js +3 -2
  32. package/dist/media-ui.d.ts +4 -1
  33. package/dist/media-ui.js +5 -5
  34. package/dist/pdf-preview.d.ts +2 -0
  35. package/dist/pdf-preview.js +7 -0
  36. package/dist/pdf-renderer.generated.d.ts +1 -0
  37. package/dist/pdf-renderer.generated.js +2 -0
  38. package/dist/preview-cache.d.ts +1 -0
  39. package/dist/preview-cache.js +2 -0
  40. package/dist/translation-settings.js +5 -3
  41. package/licenses/pdfjs-LICENSE +177 -0
  42. package/package.json +3 -3
package/dist/inbox.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { directoryWithoutChats, MessagingDirectoryRow } from './contact-directory.js';
2
3
  import { createInboxViewMemory, useInboxScroll } from './inbox-view.js';
3
4
  import { MessagingTypography } from './typography.js';
4
5
  import { Text, TextInput } from './typography.js';
@@ -11,7 +12,7 @@ import { AppState, FlatList, Image, Platform, Pressable, ScrollView, View } from
11
12
  import { defaultMessagingSettings } from '@robono/messaging';
12
13
  import { MessagingPopup, MessagingMenuSurface, MessagingPopupHeaderBoundary, messagingPopupColors, messagingPopupBackdrop } from './popup.js';
13
14
  /** Compact Messenger chat rows: avatar, name, last message, time and unread badge. */
14
- export function MessagingInbox({ client, userId, contacts = {}, appearance, active = true, onSelect, onDeleted, companyName, headerActions, searchText, selectedId, query: controlledQuery, onSearchChange, viewMemory }) {
15
+ export function MessagingInbox({ client, userId, contacts = {}, appearance, active = true, onSelect, onDeleted, companyName, headerActions, searchText, selectedId, query: controlledQuery, onSearchChange, viewMemory, directory = [], onOpenDirectoryContact }) {
15
16
  const { text: uiText, locale: uiLocale, number: uiNumber, count: uiCount } = useRobonoLocale();
16
17
  const state = useSyncExternalStore(client.subscribe, client.getSnapshot, client.getSnapshot), design = appearance ?? state.appearance ?? defaultMessagingSettings().appearance, c = design.colors;
17
18
  useEffect(() => { const update = (value) => { if (active && (value === null || value === 'active'))
@@ -25,6 +26,51 @@ export function MessagingInbox({ client, userId, contacts = {}, appearance, acti
25
26
  const scroll = useInboxScroll(memory, 'chats:' + query.trim(), state.conversations.length > 0 && !state.loading, !state.hasMore);
26
27
  const [selected, setSelected] = useState(null), [confirm, setConfirm] = useState(false), [busy, setBusy] = useState(false), [error, setError] = useState('');
27
28
  const title = (row) => row.contactId === userId ? uiText('Notes to self') : row.kind === 'group' ? row.name ?? 'Group' : contacts[row.contactId ?? '']?.name ?? row.contactId ?? 'Chat';
29
+ const [directorySelection, setDirectorySelection] = useState(null), [directoryBusy, setDirectoryBusy] = useState(false), [directoryError, setDirectoryError] = useState('');
30
+ const directoryRequest = useRef(null), directoryRef = useRef(directory);
31
+ directoryRef.current = directory;
32
+ const cancelDirectory = () => { directoryRequest.current?.abort(); directoryRequest.current = null; setDirectoryBusy(false); setDirectorySelection(null); setDirectoryError(''); };
33
+ useEffect(() => { cancelDirectory(); return () => directoryRequest.current?.abort(); }, [client, userId]);
34
+ useEffect(() => { const sub = AppState.addEventListener('change', state => { if (state !== 'active')
35
+ cancelDirectory(); }); return () => sub.remove(); }, []);
36
+ useEffect(() => { if (!active)
37
+ cancelDirectory(); }, [active]);
38
+ useEffect(() => { if (directorySelection) {
39
+ const current = directory.find(c => c.id === directorySelection.id);
40
+ if (!current || current.available !== directorySelection.available || current.contactId !== directorySelection.contactId)
41
+ cancelDirectory();
42
+ } }, [directory, directorySelection]);
43
+ async function openDirectory(entry) {
44
+ directoryRequest.current?.abort();
45
+ setDirectorySelection(entry);
46
+ setDirectoryError('');
47
+ setDirectoryBusy(false);
48
+ if (!entry.available || !onOpenDirectoryContact)
49
+ return;
50
+ const control = new AbortController();
51
+ directoryRequest.current = control;
52
+ setDirectoryBusy(true);
53
+ try {
54
+ const row = await onOpenDirectoryContact(entry, control.signal);
55
+ const current = directoryRef.current.find(c => c.id === entry.id);
56
+ if (control.signal.aborted || !current?.available || current.contactId !== entry.contactId)
57
+ return;
58
+ setDirectorySelection(null);
59
+ onSelect(row);
60
+ }
61
+ catch (e) {
62
+ if (!control.signal.aborted)
63
+ setDirectoryError(e instanceof Error ? e.message : uiText('This conversation is unavailable.'));
64
+ }
65
+ finally {
66
+ if (directoryRequest.current === control) {
67
+ directoryRequest.current = null;
68
+ setDirectoryBusy(false);
69
+ }
70
+ }
71
+ }
72
+ const directoryRows = directoryWithoutChats(directory, state.conversations, query);
73
+ const inboxRows = [...state.conversations.filter(row => !query.trim() || [title(row), row.lastMessage?.text ?? '', searchText?.(row) ?? ''].join(' ').toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())).map(chat => ({ kind: 'chat', chat })), ...directoryRows.map(entry => ({ kind: 'directory', entry }))];
28
74
  const rows = useRef(new Map()), pending = useRef(null);
29
75
  const [menuVisible, setMenuVisible] = useState(false), [confirmVisible, setConfirmVisible] = useState(false), [anchor, setAnchor] = useState({ x: 12, y: 88 });
30
76
  const openOptions = (row) => { if (!state.inboxActionsAvailable)
@@ -61,7 +107,10 @@ export function MessagingInbox({ client, userId, contacts = {}, appearance, acti
61
107
  } }
62
108
  const preview = (row) => { const m = row.lastMessage; if (!m)
63
109
  return 'No messages yet'; const text = m.kind === 'text' ? m.text ?? '' : ({ voice: 'Voice message', image: 'Photo', video: 'Video', document: 'Document', poll: 'Poll' }[m.kind] ?? 'Message'); return (m.senderId === userId ? 'You: ' : '') + text; };
64
- return _jsx(MessagingTypography, { appearance: design, children: _jsxs(View, { style: { flex: 1, minHeight: 0, backgroundColor: c.background }, children: [_jsx(MessagingPopupHeaderBoundary, { children: _jsxs(View, { testID: "messaging-inbox-header", style: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', minHeight: 64, paddingHorizontal: 16, paddingVertical: 8, gap: 8 }, children: [_jsx(Text, { accessibilityRole: "header", numberOfLines: 1, style: { flex: 1, color: c.foreground, fontSize: 20, fontWeight: '700' }, children: companyName ?? design.name }), headerActions] }) }), _jsxs(View, { style: { margin: 12, marginTop: 8, flexDirection: 'row', alignItems: 'center', gap: 8, borderRadius: 10, paddingHorizontal: 10, backgroundColor: c.foreground + '0b' }, children: [_jsx(MessageIcon, { name: "search", size: 20, color: c.secondary }), _jsx(TextInput, { accessibilityLabel: uiText("Search chats"), placeholder: state.globalSearchAvailable ? uiText("Search chats and messages") : uiText("Search chats"), placeholderTextColor: c.secondary, value: query, onChangeText: setQuery, maxLength: 200, autoCapitalize: "none", autoCorrect: false, style: { flex: 1, minHeight: 44, color: c.foreground, fontSize: 16 } }), !!query && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Clear chat search"), onPress: () => setQuery(''), style: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "close", size: 20, color: c.secondary }) })] }), state.error && _jsxs(View, { style: { padding: 12 }, children: [_jsx(Text, { accessibilityRole: "alert", style: { color: c.foreground }, children: state.error }), _jsx(Pressable, { accessibilityRole: "button", onPress: () => void client.refresh().catch(() => { }), children: _jsx(Text, { style: { color: c.accent, paddingVertical: 8 }, children: uiText("Try again") }) })] }), query.trim() && state.globalSearchAvailable ? _jsx(InboxMessageSearch, { viewMemory: memory, client: client, query: query.trim(), appearance: design, name: title, chats: state.conversations.filter(row => title(row).toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())), onSelect: onSelect }, userId) : _jsx(FlatList, { ...scroll, testID: "messaging-inbox-list", data: state.conversations.filter(row => !query.trim() || [title(row), row.lastMessage?.text ?? '', searchText?.(row) ?? ''].join(' ').toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())), keyExtractor: row => row.id, contentContainerStyle: { flexGrow: 1 }, ItemSeparatorComponent: () => _jsx(View, { style: { height: 1, backgroundColor: c.foreground + '12', marginLeft: 64 } }), ListEmptyComponent: _jsx(Text, { style: { padding: 20, textAlign: 'center', color: c.secondary }, children: state.loading ? uiText("Loading chats…") : state.error ? '' : query ? uiText("No matching chats.") : uiText("No chats yet") }), ListFooterComponent: state.hasMore ? _jsx(Pressable, { accessibilityRole: "button", disabled: state.loading, onPress: () => void client.loadMore().catch(() => { }), children: _jsx(Text, { style: { padding: 12, textAlign: 'center', color: c.accent }, children: state.loading ? uiText("Loading…") : uiText("More chats") }) }) : null, renderItem: ({ item }) => {
110
+ return _jsx(MessagingTypography, { appearance: design, children: _jsxs(View, { style: { flex: 1, minHeight: 0, backgroundColor: c.background }, children: [_jsx(MessagingPopupHeaderBoundary, { children: _jsxs(View, { testID: "messaging-inbox-header", style: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', minHeight: 64, paddingHorizontal: 16, paddingVertical: 8, gap: 8 }, children: [_jsx(Text, { accessibilityRole: "header", numberOfLines: 1, style: { flex: 1, color: c.foreground, fontSize: 20, fontWeight: '700' }, children: companyName ?? design.name }), headerActions] }) }), _jsxs(View, { style: { margin: 12, marginTop: 8, flexDirection: 'row', alignItems: 'center', gap: 8, borderRadius: 10, paddingHorizontal: 10, backgroundColor: c.foreground + '0b' }, children: [_jsx(MessageIcon, { name: "search", size: 20, color: c.secondary }), _jsx(TextInput, { accessibilityLabel: uiText("Search chats"), placeholder: state.globalSearchAvailable ? uiText("Search chats and messages") : uiText("Search chats"), placeholderTextColor: c.secondary, value: query, onChangeText: setQuery, maxLength: 200, autoCapitalize: "none", autoCorrect: false, style: { flex: 1, minHeight: 44, color: c.foreground, fontSize: 16 } }), !!query && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Clear chat search"), onPress: () => setQuery(''), style: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "close", size: 20, color: c.secondary }) })] }), state.error && _jsxs(View, { style: { padding: 12 }, children: [_jsx(Text, { accessibilityRole: "alert", style: { color: c.foreground }, children: state.error }), _jsx(Pressable, { accessibilityRole: "button", onPress: () => void client.refresh().catch(() => { }), children: _jsx(Text, { style: { color: c.accent, paddingVertical: 8 }, children: uiText("Try again") }) })] }), query.trim() && state.globalSearchAvailable ? _jsx(InboxMessageSearch, { viewMemory: memory, client: client, query: query.trim(), appearance: design, name: title, chats: state.conversations.filter(row => title(row).toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())), onSelect: onSelect, directoryHeader: directoryRows.map(entry => _jsx(MessagingDirectoryRow, { contact: entry, appearance: design, onPress: () => void openDirectory(entry) }, entry.id)) }, userId) : _jsx(FlatList, { ...scroll, testID: "messaging-inbox-list", data: inboxRows, keyExtractor: row => row.kind === 'chat' ? 'chat:' + row.chat.id : 'directory:' + row.entry.id, contentContainerStyle: { flexGrow: 1 }, ItemSeparatorComponent: () => _jsx(View, { style: { height: 1, backgroundColor: c.foreground + '12', marginLeft: 64 } }), ListEmptyComponent: _jsx(Text, { style: { padding: 20, textAlign: 'center', color: c.secondary }, children: state.loading ? uiText("Loading chats…") : state.error ? '' : query ? uiText("No matching chats.") : uiText("No chats yet") }), ListFooterComponent: state.hasMore ? _jsx(Pressable, { accessibilityRole: "button", disabled: state.loading, onPress: () => void client.loadMore().catch(() => { }), children: _jsx(Text, { style: { padding: 12, textAlign: 'center', color: c.accent }, children: state.loading ? uiText("Loading…") : uiText("More chats") }) }) : null, renderItem: ({ item: row }) => {
111
+ if (row.kind === 'directory')
112
+ return _jsx(MessagingDirectoryRow, { contact: row.entry, appearance: design, onPress: () => void openDirectory(row.entry) });
113
+ const item = row.chat;
65
114
  const person = item.contactId ? contacts[item.contactId] : undefined, title = item.contactId === userId ? uiText('Notes to self') : item.kind === 'group' ? item.name ?? 'Group' : person?.name ?? item.contactId ?? 'Chat';
66
115
  const date = item.lastMessage ? new Date(item.lastMessage.createdAt) : null;
67
116
  return _jsxs(Pressable, { ref: node => { if (node)
@@ -69,7 +118,7 @@ export function MessagingInbox({ client, userId, contacts = {}, appearance, acti
69
118
  else
70
119
  rows.current.delete(item.id); }, accessibilityRole: "button", accessibilityState: { selected: item.id === selectedId }, accessibilityLabel: item.unreadCount ? uiText('{name}, {count} unread', { name: title, count: uiNumber(item.unreadCount) }) : title, onPress: () => onSelect(item), onLongPress: () => openOptions(item), accessibilityActions: state.inboxActionsAvailable ? [{ name: 'showOptions', label: uiText("Chat options") }] : [], onAccessibilityAction: e => { if (e.nativeEvent.actionName === 'showOptions')
71
120
  openOptions(item); }, ...(Platform.OS === 'web' ? { onContextMenu: (e) => { e.preventDefault(); openOptions(item); } } : {}), style: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 12, paddingVertical: 10, minHeight: 68, backgroundColor: item.id === selectedId ? c.accent + '15' : undefined }, children: [person?.avatarUrl ? _jsx(Image, { source: { uri: person.avatarUrl }, style: { width: 40, height: 40, borderRadius: 20 } }) : _jsx(View, { style: { width: 40, height: 40, borderRadius: 20, backgroundColor: c.accent + '20', alignItems: 'center', justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.accent, fontSize: 18, fontWeight: '700' }, children: title.slice(0, 1).toUpperCase() }) }), _jsxs(View, { style: { flex: 1, minWidth: 0 }, children: [_jsxs(Text, { numberOfLines: 1, style: { color: c.foreground, fontSize: 16, fontWeight: '700' }, children: [title, item.muted ? uiText(" · Muted") : ''] }), _jsx(Text, { numberOfLines: 1, style: { color: c.secondary, marginTop: 3, fontSize: 14 }, children: preview(item) })] }), _jsxs(View, { style: { alignItems: 'flex-end', gap: 4 }, children: [_jsx(Text, { style: { color: item.unreadCount ? c.accent : c.secondary, fontSize: 12 }, children: date ? date.toDateString() === new Date().toDateString() ? date.toLocaleTimeString(uiLocale, { hour: 'numeric', minute: '2-digit' }) : date.toLocaleDateString(uiLocale, { month: 'short', day: 'numeric' }) : '' }), item.unreadCount > 0 && _jsx(View, { style: { minWidth: 20, height: 20, borderRadius: 10, borderWidth: 1.5, borderColor: c.accent, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 5 }, children: _jsx(Text, { style: { color: c.accent, fontSize: 10, fontWeight: '900' }, children: item.unreadCount > 99 ? '99+' : item.unreadCount }) })] })] });
72
- } }), selected && _jsxs(_Fragment, { children: [_jsx(MessagingMenuSurface, { visible: menuVisible, onDismiss: dismissed, onClose: () => { if (!busy)
121
+ } }), directorySelection && _jsxs(MessagingPopup, { compact: true, title: directorySelection.name, background: c.background, foreground: c.foreground, onClose: cancelDirectory, children: [_jsx(Text, { accessibilityRole: directoryError ? 'alert' : undefined, style: { color: messagingPopupColors.foreground, fontSize: 16, lineHeight: 23, paddingVertical: 12 }, children: directoryBusy ? uiText('Opening chat…') : directoryError || directorySelection.detail }), !!directoryError && directorySelection.available && _jsx(Pressable, { accessibilityRole: "button", onPress: () => void openDirectory(directorySelection), style: { minHeight: 44, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.accent }, children: uiText('Try again') }) })] }), selected && _jsxs(_Fragment, { children: [_jsx(MessagingMenuSurface, { visible: menuVisible, onDismiss: dismissed, onClose: () => { if (!busy)
73
122
  setSelected(null); }, children: rect => {
74
123
  const width = Math.min(218, rect.width - 24), top = Math.max(12, Math.min(anchor.y - rect.top, rect.height - 124));
75
124
  return _jsxs(View, { style: { flex: 1 }, children: [_jsx(Pressable, { accessibilityLabel: uiText("Close chat options"), onPress: () => { if (!busy)
package/dist/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { type MessagingHeaderOptions } from './conversation-selector.js';
2
+ export type { MessagingHeaderOptions, MessagingConversationChoice } from './conversation-selector.js';
3
+ import { type AttachmentPreviewLoader } from './attachment-preview.js';
1
4
  export { MessagingConnectionState, type MessagingConnectionStateProps, MessagingSignIn, MessagingPhoneInput, MessagingChoicePicker, type MessagingSignInProps, type MessagingPhoneInputProps, type MessagingChoice, type MessagingChoicePickerProps } from './sign-in.js';
2
5
  import type { MessagingCustomization } from './customization.js';
3
6
  export { RobonoLocaleProvider, useRobonoLocale } from './localization.js';
@@ -61,6 +64,24 @@ export interface AttachmentChoice {
61
64
  durationMs?: number;
62
65
  }
63
66
  export interface MessagingScreenProps {
67
+ /** Standard header configuration; no replacement Header component required. */
68
+ header?: MessagingHeaderOptions;
69
+ conversationMode?: "messenger" | "walkie-talkie";
70
+ /** The host owns safe-area insets. Set enabled:false if a parent already avoids the keyboard. */
71
+ keyboard?: {
72
+ enabled?: boolean;
73
+ behavior?: 'height' | 'position' | 'padding';
74
+ verticalOffset?: number;
75
+ bottomInset?: number;
76
+ };
77
+ /** Effective host permission. The transform request must still authorize on the server. */
78
+ languageTools?: {
79
+ translation?: boolean;
80
+ transcription?: boolean;
81
+ voiceOutput?: boolean;
82
+ preferredLanguage?: string;
83
+ revision?: string | number;
84
+ };
64
85
  /** Disabled links render as plain text. Callbacks replace system navigation;
65
86
  * providing openUrl also disables embedded social browsing. */
66
87
  linkHandling?: {
@@ -136,10 +157,7 @@ export interface MessagingScreenProps {
136
157
  prepareAttachment?: (kind: Exclude<MessageKind, 'text' | 'poll'>, media: MessageMedia) => Promise<MessageMedia>;
137
158
  retainDraftAttachments?: boolean;
138
159
  /** Resolve an authorized thumbnail and/or normalized waveform. Never put signed URLs in message data. */
139
- attachmentPreview?: (message: MessagingMessage) => Promise<{
140
- uri?: string;
141
- waveform?: number[];
142
- }>;
160
+ attachmentPreview?: AttachmentPreviewLoader;
143
161
  /** Authorize the asset and open it using your app's media player/viewer. */
144
162
  openAttachment?: (message: MessagingMessage) => Promise<void>;
145
163
  openSavedAttachment?: (record: SavedMessage) => Promise<void>;
@@ -196,3 +214,4 @@ export declare function MessagingScreen(props: MessagingScreenProps): React.JSX.
196
214
  export { MessagingInbox, type MessagingInboxProps } from './inbox.js';
197
215
  export type { PlaybackProps } from './media-ui.js';
198
216
  export type { InboxViewMemory } from './inbox-view.js';
217
+ export type { MessagingDirectoryContact, MessagingDirectoryOptions } from './contact-directory.js';
package/dist/index.js CHANGED
@@ -1,9 +1,14 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { ComposerInput } from './composer-input.js';
3
+ import { MessagingKeyboardContainer } from './keyboard-container.js';
4
+ import { conversationMessages } from '@robono/messaging';
5
+ import { ConversationSelector } from './conversation-selector.js';
6
+ import { useAttachmentPreview } from './attachment-preview.js';
2
7
  import { MessagingRoomModeration, MessagingRoomRemoval } from './room-moderation.js';
3
8
  export { MessagingConnectionState, MessagingSignIn, MessagingPhoneInput, MessagingChoicePicker } from './sign-in.js';
4
9
  import { CustomMessage } from './custom-message.js';
5
10
  import { MessagingTypography } from './typography.js';
6
- import { Text, TextInput } from './typography.js';
11
+ import { Text } from './typography.js';
7
12
  import { useRobonoLocale, RobonoLocaleProvider, localizeMessagingAppearance } from './localization.js';
8
13
  export { RobonoLocaleProvider, useRobonoLocale } from './localization.js';
9
14
  import { MessagingMenuSurface } from './popup.js';
@@ -33,7 +38,7 @@ export { MessagingSafety } from './safety.js';
33
38
  import { PollMessage, PollComposer } from "./polls.js";
34
39
  export { PollMessage, PollComposer } from "./polls.js";
35
40
  import { createContext, useContext, useEffect, useRef, useState, useSyncExternalStore, } from "react";
36
- import { Animated, ActivityIndicator, AppState, BackHandler, FlatList, Image, KeyboardAvoidingView, Keyboard, Linking, Platform, Pressable, ScrollView, View, useWindowDimensions, } from "react-native";
41
+ import { Animated, ActivityIndicator, AppState, BackHandler, FlatList, Image, Keyboard, Linking, Platform, Pressable, ScrollView, View, useWindowDimensions, } from "react-native";
37
42
  import { useQuoteGesture, messageInfoRevealWidth, messageReplyRevealWidth } from "./use-quote-gesture.js";
38
43
  import { MessageIcon, duration, fileSize, chatSurface, composerSurface } from "./icons.js";
39
44
  import { VoiceMessageComposer } from "./voice-composer.js";
@@ -78,6 +83,18 @@ function MessagingProviderContent({ children, ...props }) {
78
83
  const subscription = AppState.addEventListener('change', update);
79
84
  return () => { subscription.remove(); props.client.setPresenceActive(false); };
80
85
  }, [props.client, props.active]);
86
+ useEffect(() => {
87
+ const sync = (value) => { if (props.active !== false && !state.loading && state.conversationId && (value === null || value === 'active'))
88
+ props.client.start();
89
+ else
90
+ props.client.stop(); };
91
+ sync(AppState.currentState);
92
+ const sub = AppState.addEventListener('change', sync);
93
+ return () => { sub.remove(); props.client.stop(); };
94
+ }, [props.client, props.active, state.conversationId, state.loading]);
95
+ const conversationMode = props.conversationMode ?? props.appearance?.conversationMode ?? state.settings?.appearance.conversationMode ?? 'messenger';
96
+ useEffect(() => { props.client.setViewMode(conversationMode); }, [props.client, conversationMode]);
97
+ const visibleState = { ...state, messages: conversationMessages(state, conversationMode) };
81
98
  const [forwarding, setForwarding] = useState([]), [deleting, setDeleting] = useState([]);
82
99
  const [selection, setSelection] = useState([]);
83
100
  const [saved, setSaved] = useState([]), [savedOpen, setSavedOpen] = useState(false), [saving, setSaving] = useState(false), [savedError, setSavedError] = useState('');
@@ -108,7 +125,7 @@ function MessagingProviderContent({ children, ...props }) {
108
125
  savingRef.current = false;
109
126
  setSaving(false);
110
127
  } }
111
- const selected = selection.map(old => state.messages.find(m => m.id === old.id) ?? old).filter(m => !m.deleted && m.conversationId === state.conversationId);
128
+ const selected = selection.map(old => visibleState.messages.find(m => m.id === old.id) ?? old).filter(m => !m.deleted && m.conversationId === state.conversationId);
112
129
  useEffect(() => { setSelection([]); }, [state.conversationId, state.settings?.enabled, state.historyWindow, state.focus?.sequence]);
113
130
  useEffect(() => { if (!selection.length)
114
131
  return; const sub = BackHandler.addEventListener('hardwareBackPress', () => { setSelection([]); return true; }); return () => sub.remove(); }, [selection.length]);
@@ -138,13 +155,16 @@ function MessagingProviderContent({ children, ...props }) {
138
155
  setForwarding([m]);
139
156
  else
140
157
  setDeleting([m]); }, [props.requestedMessageAction]);
158
+ const effectiveAppearance = props.appearance ?? state.settings?.appearance ?? defaultMessagingSettings().appearance;
141
159
  const value = {
142
160
  ...props,
161
+ linkHandling: { ...props.linkHandling, webLinks: props.linkHandling?.webLinks !== false && effectiveAppearance.linkHandling?.webLinks !== false, addresses: props.linkHandling?.addresses !== false && effectiveAppearance.linkHandling?.addresses !== false },
162
+ languageTools: { ...props.languageTools, voiceOutput: props.languageTools?.voiceOutput !== false && effectiveAppearance.spokenTranslations !== false },
143
163
  openDiscussion: (threadRoot) => setDiscussion({ threadRoot }),
144
- state,
164
+ state: visibleState,
145
165
  extrasState: extrasState?.conversationId === state.conversationId && state.settings?.enabled && !state.offline ? extrasState : null,
146
166
  reply: reply?.conversationId === state.conversationId
147
- ? (state.messages.find(m => m.id === reply.id && !m.deleted) ? { ...state.messages.find(m => m.id === reply.id), ...(reply.threadRoot ? { threadRoot: reply.threadRoot } : {}) } : null)
167
+ ? (visibleState.messages.find(m => m.id === reply.id && !m.deleted) ? { ...visibleState.messages.find(m => m.id === reply.id), ...(reply.threadRoot ? { threadRoot: reply.threadRoot } : {}) } : null)
148
168
  : null,
149
169
  setReply,
150
170
  editing: state.messageActionsAvailable && editing?.conversationId === state.conversationId && state.settings?.enabled && state.conversation?.canSend !== false && state.messages.some(m => m.id === editing.id && !m.deleted) ? editing : null,
@@ -251,22 +271,23 @@ function MessagingActivity({ ink }) {
251
271
  }
252
272
  export function MessagingHeader({ children } = {}) {
253
273
  const { text: uiText, locale: uiLocale, number: uiNumber, count: uiCount } = useRobonoLocale();
254
- const { contact, design, state, client, openDiscussion, userId, participants, onBack, onContactOptions, selection, setSelection, language, components, callActions, attachmentPreview, openAttachment } = useMessagingUI();
274
+ const { contact, design, state, client, openDiscussion, userId, participants, onBack, onContactOptions, selection, setSelection, language, components, callActions, attachmentPreview, openAttachment, header: headerOptions, languageTools } = useMessagingUI();
255
275
  const [scheduledOpen, setScheduledOpen] = useState(false);
256
276
  const [safetyOpen, setSafetyOpen] = useState(false), [searchOpen, setSearchOpen] = useState(false), [detailsOpen, setDetailsOpen] = useState(false), [groupOpen, setGroupOpen] = useState(false), [moderationOpen, setModerationOpen] = useState(false);
257
277
  useEffect(() => { setDetailsOpen(false); setGroupOpen(false); setModerationOpen(false); setScheduledOpen(false); }, [state.conversationId]);
258
278
  const menuButton = useRef(null), viewport = useWindowDimensions(), [menuAnchor, setMenuAnchor] = useState({ x: 12, y: 12 });
259
279
  const openContactMenu = () => menuButton.current?.measureInWindow((x, y, width, height) => { setMenuAnchor({ x: Math.max(12, Math.min(x + width - 240, viewport.width - 252)), y: y + height + 4 }); setSafetyOpen(true); });
260
- const translationAvailable = !!state.settings?.enabled && !!state.settings.features.translation && client.hasLanguageTools();
280
+ const translationAvailable = languageTools?.translation !== false && !!state.settings?.enabled && !!state.settings.features.translation && client.hasLanguageTools();
261
281
  const c = design.colors, header = messagingHeaderColors(design, state.conversation?.kind === 'group');
262
282
  return (_jsxs(_Fragment, { children: [_jsxs(View, { testID: "messaging-chat-header", style: {
263
283
  flexDirection: "row",
264
284
  alignItems: "center",
265
285
  paddingHorizontal: 12,
266
286
  paddingVertical: 4,
287
+ paddingTop: headerOptions?.paddingTop ?? 4, paddingBottom: headerOptions?.paddingBottom ?? 4, paddingStart: headerOptions?.paddingStart ?? 12, paddingEnd: headerOptions?.paddingEnd ?? 12,
267
288
  backgroundColor: header.background,
268
289
  gap: 4,
269
- }, children: [(onBack || selection.length > 0) && (_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: selection.length ? uiText("Clear message selection") : uiText("Back"), onPress: () => selection.length ? setSelection([]) : onBack?.(), style: { width: 44, flexShrink: 0, alignSelf: "stretch", marginStart: -12, marginEnd: -4, marginVertical: -4, alignItems: "center", justifyContent: "center" }, children: _jsx(MessageIcon, { name: "back", color: header.foreground, size: 32 }) })), _jsxs(View, { testID: "messaging-chat-identity", style: { flex: 1, minWidth: 0, flexDirection: "row", alignItems: "center", gap: 8 }, children: [design.showAvatars && (contact.avatarUrl
290
+ }, children: [(onBack || selection.length > 0) && (_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: selection.length ? uiText("Clear message selection") : uiText("Back"), onPress: () => selection.length ? setSelection([]) : onBack?.(), style: { width: 44, flexShrink: 0, alignSelf: "stretch", marginStart: -12, marginEnd: -4, marginVertical: -4, alignItems: "center", justifyContent: "center" }, children: _jsx(MessageIcon, { name: "back", color: header.foreground, size: 32 }) })), _jsxs(Pressable, { onPress: headerOptions?.onProfile, disabled: !headerOptions?.onProfile, accessibilityRole: headerOptions?.onProfile ? "button" : undefined, accessibilityLabel: headerOptions?.onProfile ? uiText("View profile") : undefined, testID: "messaging-chat-identity", style: { flex: 1, minWidth: 0, flexDirection: "row", alignItems: "center", gap: 8 }, children: [design.showAvatars && (contact.avatarUrl
270
291
  ? (_jsx(Image, { source: { uri: contact.avatarUrl }, style: { width: 38, height: 38, borderRadius: 19, borderWidth: 1, borderColor: "#ffffff" } }))
271
292
  : (_jsx(View, { style: {
272
293
  width: 38,
@@ -277,7 +298,7 @@ export function MessagingHeader({ children } = {}) {
277
298
  backgroundColor: c.incoming,
278
299
  alignItems: "center",
279
300
  justifyContent: "center",
280
- }, children: _jsx(Text, { style: { color: c.incomingText }, children: state.conversation?.kind === 'group' ? (state.conversation.name ?? 'Group').slice(0, 1) : contact.name.slice(0, 1) }) }))), _jsxs(View, { style: { flex: 1, minWidth: 0 }, children: [_jsx(Text, { numberOfLines: 1, style: { color: header.foreground, fontSize: 18, fontWeight: "800" }, children: state.conversation?.kind === 'group' ? state.conversation.name : contact.name }), _jsx(MessagingActivity, { ink: header.foreground })] })] }), design.logoUrl && (_jsx(Image, { source: { uri: design.logoUrl }, accessibilityLabel: design.name, style: { width: 32, height: 32 } })), children, components?.HeaderActions && _jsx(components.HeaderActions, { conversationId: state.conversationId, contact: contact, appearance: design }), state.conversation?.canSend !== false && _jsx(MessagingHeaderCalls, { actions: callActions, name: state.conversation?.kind === 'group' ? (state.conversation.name ?? 'Group') : contact.name, group: state.conversation?.kind === 'group', color: header.foreground }, state.conversationId), _jsx(PrivacyControl, { color: header.foreground }), (onContactOptions || state.conversation?.safety || state.searchAvailable || state.scheduledMessagesAvailable || translationAvailable) && (_jsx(Pressable, { accessibilityRole: "button", testID: "messaging-contact-options", accessibilityLabel: uiText("Contact options"), ref: menuButton, accessibilityState: { expanded: safetyOpen }, onPress: onContactOptions ?? openContactMenu, style: { width: 42, height: 42, alignItems: "center", justifyContent: "center" }, children: _jsx(MessageIcon, { name: "more", color: header.foreground, size: 25 }) })), safetyOpen && _jsx(MessagingSafety, { onScheduled: state.scheduledMessagesAvailable ? () => { setSafetyOpen(false); setScheduledOpen(true); } : undefined, onDetails: state.settings?.enabled && (state.sharedMediaAvailable || state.conversation?.kind === 'group') ? () => { setSafetyOpen(false); setDetailsOpen(true); } : undefined, onPins: state.discussionAvailable ? () => { setSafetyOpen(false); openDiscussion(); } : undefined, menuAnchor: menuAnchor, client: client, state: state, appearance: design, name: state.conversation?.kind === 'group' ? (state.conversation.name ?? 'Conversation') : contact.name, onSearch: state.searchAvailable && state.settings?.enabled ? () => { setSafetyOpen(false); setSearchOpen(true); } : undefined, onClose: () => setSafetyOpen(false), children: translationAvailable && _jsx(TranslationSettings, { client: client, appearance: design, preference: state.translationPreference, language: language, sourceLanguage: contact.language, voiceAvailable: !!components?.TranslationVoice, onSaved: () => setSafetyOpen(false) }, state.conversationId) })] }), scheduledOpen && _jsx(ScheduledMessages, { client: client, accent: c.accent, onClose: () => setScheduledOpen(false) }, state.conversationId), groupOpen && _jsx(MessagingGroupEditor, { client: client, userId: userId, contacts: participants ?? {}, conversation: state.conversation, groups: state.settings?.groups, accent: c.accent, onClose: () => setGroupOpen(false), onSaved: () => setGroupOpen(false) }), moderationOpen && _jsx(MessagingRoomModeration, { client: client, userId: userId, participants: participants, accent: c.accent, onClose: () => setModerationOpen(false) }), detailsOpen && _jsx(ConversationDetails, { onModerate: () => setModerationOpen(true), onEditGroup: () => setGroupOpen(true), onLeft: onBack, client: client, state: state, userId: userId, contact: contact, participants: participants, accent: c.accent, onClose: () => setDetailsOpen(false), attachmentPreview: attachmentPreview, openAttachment: openAttachment }), searchOpen && state.searchAvailable && state.settings?.enabled && _jsx(MessagingSearch, { client: client, appearance: design, onClose: () => setSearchOpen(false), resolveName: id => id === userId ? 'You' : participants?.[id]?.name ?? (state.conversation?.kind === 'direct' ? contact.name : 'Chat member') }, state.conversationId)] }));
301
+ }, children: _jsx(Text, { style: { color: c.incomingText }, children: state.conversation?.kind === 'group' ? (state.conversation.name ?? 'Group').slice(0, 1) : contact.name.slice(0, 1) }) }))), _jsxs(View, { style: { flex: 1, minWidth: 0 }, children: [_jsx(Text, { numberOfLines: 1, style: { color: header.foreground, fontSize: 18, fontWeight: "800" }, children: state.conversation?.kind === 'group' ? state.conversation.name : contact.name }), _jsx(MessagingActivity, { ink: header.foreground })] })] }), _jsx(ConversationSelector, { options: headerOptions, selectedId: state.conversationId, color: header.foreground, background: header.background }), headerOptions?.onClose && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Close conversation"), onPress: headerOptions.onClose, style: { width: 44, height: 44, alignItems: "center", justifyContent: "center" }, children: _jsx(MessageIcon, { name: "close", color: header.foreground, size: 24 }) }), design.logoUrl && (_jsx(Image, { source: { uri: design.logoUrl }, accessibilityLabel: design.name, style: { width: 32, height: 32 } })), children, components?.HeaderActions && _jsx(components.HeaderActions, { conversationId: state.conversationId, contact: contact, appearance: design }), state.conversation?.canSend !== false && _jsx(MessagingHeaderCalls, { actions: callActions, name: state.conversation?.kind === 'group' ? (state.conversation.name ?? 'Group') : contact.name, group: state.conversation?.kind === 'group', color: header.foreground }, state.conversationId), _jsx(PrivacyControl, { color: header.foreground }), (onContactOptions || state.conversation?.safety || state.searchAvailable || state.scheduledMessagesAvailable || translationAvailable) && (_jsx(Pressable, { accessibilityRole: "button", testID: "messaging-contact-options", accessibilityLabel: uiText("Contact options"), ref: menuButton, accessibilityState: { expanded: safetyOpen }, onPress: onContactOptions ?? openContactMenu, style: { width: 42, height: 42, alignItems: "center", justifyContent: "center" }, children: _jsx(MessageIcon, { name: "more", color: header.foreground, size: 25 }) })), safetyOpen && _jsx(MessagingSafety, { onScheduled: state.scheduledMessagesAvailable ? () => { setSafetyOpen(false); setScheduledOpen(true); } : undefined, onDetails: state.settings?.enabled && (state.sharedMediaAvailable || state.conversation?.kind === 'group') ? () => { setSafetyOpen(false); setDetailsOpen(true); } : undefined, onPins: state.discussionAvailable ? () => { setSafetyOpen(false); openDiscussion(); } : undefined, menuAnchor: menuAnchor, client: client, state: state, appearance: design, name: state.conversation?.kind === 'group' ? (state.conversation.name ?? 'Conversation') : contact.name, onSearch: state.searchAvailable && state.settings?.enabled ? () => { setSafetyOpen(false); setSearchOpen(true); } : undefined, onClose: () => setSafetyOpen(false), children: translationAvailable && _jsx(TranslationSettings, { client: client, appearance: design, preference: state.translationPreference, language: languageTools?.preferredLanguage ?? language, sourceLanguage: contact.language, voiceAvailable: languageTools?.voiceOutput !== false && !!components?.TranslationVoice, onSaved: () => setSafetyOpen(false) }, state.conversationId) })] }), scheduledOpen && _jsx(ScheduledMessages, { client: client, accent: c.accent, onClose: () => setScheduledOpen(false) }, state.conversationId), groupOpen && _jsx(MessagingGroupEditor, { client: client, userId: userId, contacts: participants ?? {}, conversation: state.conversation, groups: state.settings?.groups, accent: c.accent, onClose: () => setGroupOpen(false), onSaved: () => setGroupOpen(false) }), moderationOpen && _jsx(MessagingRoomModeration, { client: client, userId: userId, participants: participants, accent: c.accent, onClose: () => setModerationOpen(false) }), detailsOpen && _jsx(ConversationDetails, { onModerate: () => setModerationOpen(true), onEditGroup: () => setGroupOpen(true), onLeft: onBack, client: client, state: state, userId: userId, contact: contact, participants: participants, accent: c.accent, onClose: () => setDetailsOpen(false), attachmentPreview: attachmentPreview, openAttachment: openAttachment }), searchOpen && state.searchAvailable && state.settings?.enabled && _jsx(MessagingSearch, { client: client, appearance: design, onClose: () => setSearchOpen(false), resolveName: id => id === userId ? 'You' : participants?.[id]?.name ?? (state.conversation?.kind === 'direct' ? contact.name : 'Chat member') }, state.conversationId)] }));
281
302
  }
282
303
  function PrivacyControl({ color }) {
283
304
  const { text: uiText, locale: uiLocale, number: uiNumber, count: uiCount } = useRobonoLocale();
@@ -324,21 +345,13 @@ function MediaContent({ message, ink, footer, onOpen, onLongPress }) {
324
345
  } if (rows.has(voiceKey))
325
346
  return; rows.add(voiceKey); if (rows.size > 2048)
326
347
  rows.delete(rows.values().next().value); updateHeard(n => n + 1); };
327
- const [preview, setPreview] = useState({});
328
- useEffect(() => {
329
- let current = true;
330
- setPreview({});
331
- if (attachmentPreview)
332
- void attachmentPreview(message).then(value => { if (current)
333
- setPreview(value); }).catch(() => { });
334
- return () => { current = false; };
335
- }, [message.id, message.conversationId, message.media?.assetId, attachmentPreview]);
348
+ const { preview, failed, retry, onImageError } = useAttachmentPreview(message, attachmentPreview, useMessagingUI().active !== false);
336
349
  if (message.kind === 'voice') {
337
350
  const Voice = components?.VoiceMessage;
338
- return Voice ? _jsx(Voice, { mine: message.senderId === userId, heard: heard, onPlayed: onPlayed, background: message.senderId === userId ? design.colors.outgoing : undefined, message: message, ink: ink, accent: design.colors.accent, waveform: preview.waveform ?? message.media?.waveform, showWaveform: design.showWaveform !== false, footer: footer, onOpen: onOpen, onLongPress: onLongPress }) : _jsx(VoicePlayback, { mine: message.senderId === userId, heard: heard, onPlayed: onPlayed, background: message.senderId === userId ? design.colors.outgoing : undefined, ink: ink, accent: design.colors.accent, waveform: preview.waveform ?? message.media?.waveform, showWaveform: design.showWaveform !== false, durationMs: message.media?.durationMs, footer: footer, onToggle: onOpen, onLongPress: onLongPress });
351
+ return Voice ? _jsx(Voice, { mine: message.senderId === userId, heard: heard, onPlayed: onPlayed, background: message.senderId === userId ? design.colors.outgoing : design.colors.incoming, message: message, ink: ink, accent: design.colors.accent, waveform: preview.waveform ?? message.media?.waveform, showWaveform: design.showWaveform !== false, footer: footer, onOpen: onOpen, onLongPress: onLongPress }) : _jsx(VoicePlayback, { mine: message.senderId === userId, heard: heard, onPlayed: onPlayed, background: message.senderId === userId ? design.colors.outgoing : design.colors.incoming, ink: ink, accent: design.colors.accent, waveform: preview.waveform ?? message.media?.waveform, showWaveform: design.showWaveform !== false, durationMs: message.media?.durationMs, footer: footer, onToggle: onOpen, onLongPress: onLongPress });
339
352
  }
340
353
  if (message.kind === 'image' || message.kind === 'video')
341
- return _jsx(View, { style: { width: 220, maxWidth: '100%', gap: 0 }, children: _jsxs(View, { style: { height: 155, borderRadius: 10, overflow: 'hidden', alignItems: 'center', justifyContent: 'center', backgroundColor: '#00000012' }, children: [preview.uri ? _jsx(Image, { source: { uri: preview.uri }, accessibilityLabel: message.media?.fileName ?? uiText(mediaNames[message.kind]), resizeMode: "cover", onError: () => setPreview(value => ({ ...value, uri: undefined })), style: { width: '100%', height: '100%' } }) : _jsx(MessageIcon, { name: message.kind, color: ink, size: 36 }), message.kind === 'video' && _jsxs(_Fragment, { children: [_jsx(View, { style: { position: 'absolute', borderRadius: 24, padding: 10, backgroundColor: '#00000099' }, children: _jsx(MessageIcon, { name: "play", color: "#ffffff" }) }), _jsx(Text, { style: { position: 'absolute', left: 8, bottom: 8, color: '#ffffff', backgroundColor: '#000000aa', borderRadius: 4, paddingHorizontal: 5, fontSize: 12 }, children: duration(message.media?.durationMs) })] })] }) });
354
+ return _jsx(View, { style: { width: 220, maxWidth: '100%', gap: 0 }, children: _jsxs(View, { style: { height: 155, borderRadius: 10, overflow: 'hidden', alignItems: 'center', justifyContent: 'center', backgroundColor: '#00000012' }, children: [preview.uri ? _jsx(Image, { source: { uri: preview.uri }, accessibilityLabel: message.media?.fileName ?? uiText(mediaNames[message.kind]), resizeMode: "cover", onError: onImageError, style: { width: '100%', height: '100%' } }) : _jsx(MessageIcon, { name: message.kind, color: ink, size: 36 }), failed && !preview.uri && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText('Retry preview'), onPress: event => { event.stopPropagation(); retry(); }, style: { position: 'absolute', bottom: 6, right: 6, minHeight: 44, paddingHorizontal: 12, justifyContent: 'center', backgroundColor: design.colors.incoming, borderRadius: 18 }, children: _jsx(Text, { style: { color: design.colors.accent }, children: uiText('Retry preview') }) }), message.kind === 'video' && _jsxs(_Fragment, { children: [_jsx(View, { style: { position: 'absolute', borderRadius: 24, padding: 10, backgroundColor: '#00000099' }, children: _jsx(MessageIcon, { name: "play", color: "#ffffff" }) }), _jsx(Text, { style: { position: 'absolute', left: 8, bottom: 8, color: '#ffffff', backgroundColor: '#000000aa', borderRadius: 4, paddingHorizontal: 5, fontSize: 12 }, children: duration(message.media?.durationMs) })] })] }) });
342
355
  return _jsxs(View, { style: { flexDirection: 'row', alignItems: 'center', gap: 12, width: 220, minHeight: 56, padding: 8, borderRadius: 6, backgroundColor: ink + '09' }, children: [_jsx(MessageIcon, { name: "document", color: design.colors.accent, size: 30 }), _jsxs(View, { style: { flex: 1, gap: 4 }, children: [_jsx(Text, { numberOfLines: 2, style: { color: ink, fontSize: 14, fontWeight: '600' }, children: message.media?.fileName ?? uiText("File") }), _jsxs(Text, { style: { color: ink, fontSize: 12, opacity: 0.75 }, children: [message.media?.fileName?.split('.').pop()?.toUpperCase(), " \u00B7 ", fileSize(message.media?.byteSize)] })] })] });
343
356
  }
344
357
  function messageTimeLabel(message, locale, text) { return (message.editedAt && !message.deleted ? text('edited') + ' · ' : '') + new Date(message.createdAt).toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' }); }
@@ -350,7 +363,7 @@ function MessageMetadata({ mine, ink, pendingStatus }) {
350
363
  }
351
364
  export function MessagingBubble({ message, pendingStatus, previousMessage, nextMessage }) {
352
365
  const { text: uiText, locale: uiLocale, number: uiNumber, count: uiCount } = useRobonoLocale();
353
- const { userId, design, state, client, participants, openDiscussion, discussionPreview, discussionRoot, setReply, setEditing, setForwarding, setDeleting, selection, setSelection, saved, saving, toggleSaved, onMessageOptions, openAttachment, language, contact, copyText, components, extras, extrasState, onCallHistory, linkHandling } = useMessagingUI();
366
+ const { userId, design, state, client, participants, openDiscussion, discussionPreview, discussionRoot, setReply, setEditing, setForwarding, setDeleting, selection, setSelection, saved, saving, toggleSaved, onMessageOptions, openAttachment, language, contact, copyText, components, extras, extrasState, onCallHistory, linkHandling, languageTools } = useMessagingUI();
354
367
  const deliveryStatus = pendingStatus ?? (message.senderId === userId && message.delivery?.state === 'pending' ? 'sending' : message.senderId === userId && message.delivery?.state === 'failed' ? 'failed' : undefined);
355
368
  const candidateExtra = !message.custom && !pendingStatus && !message.deleted ? extrasState?.messages[message.id] : undefined;
356
369
  const extra = candidateExtra?.address && (linkHandling?.addresses === false || linkHandling?.openAddress) ? undefined : candidateExtra;
@@ -381,30 +394,30 @@ export function MessagingBubble({ message, pendingStatus, previousMessage, nextM
381
394
  });
382
395
  const [transformed, setTransformed] = useState(null), [transforming, setTransforming] = useState(false), [showOriginal, setShowOriginal] = useState(false), [translationAutoPlay, setTranslationAutoPlay] = useState(false);
383
396
  const TranslationVoice = components?.TranslationVoice;
384
- const canTranscript = !pendingStatus && voice && !!state.settings?.features.transcription && client.hasLanguageTools() && !message.deleted;
397
+ const canTranscript = languageTools?.transcription !== false && !pendingStatus && voice && !!state.settings?.features.transcription && client.hasLanguageTools() && !message.deleted;
385
398
  const translation = state.translationPreference;
386
- const translationLanguage = translation?.language ?? language;
399
+ const translationLanguage = translation?.language ?? languageTools?.preferredLanguage ?? language;
387
400
  const sourceLanguage = participants?.[message.senderId]?.language ?? (state.conversation?.kind === 'direct' ? contact.language : undefined) ?? translation?.sourceLanguage;
388
- const canTranslate = !mine && !extra?.weather && !extra?.call && !pendingStatus && ['text', 'voice'].includes(message.kind) && !!state.settings?.enabled && !!state.settings.features.translation && client.hasLanguageTools() && !message.deleted && translation?.mode !== undefined && translation.mode !== 'off' && needsMessageTranslation(sourceLanguage, translationLanguage) && (translation.mode !== 'voice' || !!TranslationVoice);
389
- const transformGeneration = useRef(0);
390
- useEffect(() => { transformGeneration.current++; setTransformed(null); setTransforming(false); setShowOriginal(false); setTranslationAutoPlay(false); return () => { transformGeneration.current++; }; }, [message.id, message.deleted, message.text, message.media?.assetId, translationLanguage, translation?.mode, sourceLanguage, state.settings?.enabled, state.settings?.features.transcription, state.settings?.features.translation]);
401
+ const canTranslate = languageTools?.translation !== false && !mine && !extra?.weather && !extra?.call && !pendingStatus && ['text', 'voice'].includes(message.kind) && !!state.settings?.enabled && !!state.settings.features.translation && client.hasLanguageTools() && !message.deleted && translation?.mode !== undefined && translation.mode !== 'off' && needsMessageTranslation(sourceLanguage, translationLanguage) && (translation.mode !== 'voice' || languageTools?.voiceOutput === false || !!TranslationVoice);
402
+ const transformGeneration = useRef(0), transformAbort = useRef(null);
403
+ useEffect(() => { transformAbort.current?.abort(); transformGeneration.current++; setTransformed(null); setTransforming(false); setShowOriginal(false); setTranslationAutoPlay(false); return () => { transformAbort.current?.abort(); transformGeneration.current++; }; }, [message.id, message.deleted, message.text, message.media?.assetId, translationLanguage, translation?.mode, sourceLanguage, state.settings?.enabled, state.settings?.features.transcription, state.settings?.features.translation, languageTools?.translation, languageTools?.transcription, languageTools?.voiceOutput, languageTools?.revision]);
391
404
  useEffect(() => { if (!transformed?.audio)
392
405
  return; const timer = setTimeout(() => setTransformed(null), Math.max(0, Date.parse(transformed.audio.expiresAt) - Date.now())); return () => clearTimeout(timer); }, [transformed]);
393
406
  async function transform(kind, output = 'text') { setShowOriginal(false); setTranslationAutoPlay(false); if (transformed?.kind === kind && !!transformed.audio === (output === 'voice')) {
394
407
  setShowOriginal(false);
395
408
  return;
396
409
  } if (transforming)
397
- return; const generation = ++transformGeneration.current; setTransforming(true); setActions(false); setError(''); try {
398
- const result = await client.transform(message.id, kind, translationLanguage ?? Intl.DateTimeFormat().resolvedOptions().locale, output);
410
+ return; const generation = ++transformGeneration.current, controller = transformAbort.current = new AbortController(); setTransforming(true); setActions(false); setError(''); try {
411
+ const result = await client.transform(message.id, kind, translationLanguage ?? Intl.DateTimeFormat().resolvedOptions().locale, output, { signal: controller.signal });
399
412
  if (generation === transformGeneration.current) {
400
413
  setTransformed(result);
401
414
  setShowOriginal(false);
402
415
  setTranslationAutoPlay(output === 'voice');
403
416
  }
404
417
  }
405
- catch {
406
- if (generation === transformGeneration.current)
407
- setError(uiText("This message could not be converted. Try again."));
418
+ catch (e) {
419
+ if (generation === transformGeneration.current && !controller.signal.aborted)
420
+ setError(e instanceof MessagingError && e.status === 402 ? uiText("There are not enough credits for this language tool.") : e instanceof MessagingError && [401, 403].includes(e.status) ? uiText("This language tool is no longer allowed.") : uiText("This message could not be converted. Try again."));
408
421
  }
409
422
  finally {
410
423
  if (generation === transformGeneration.current)
@@ -456,7 +469,7 @@ export function MessagingBubble({ message, pendingStatus, previousMessage, nextM
456
469
  const footer = _jsx(MessageMetadata, { message: message, mine: mine, ink: visual ? '#ffffff' : ink, pendingStatus: deliveryStatus });
457
470
  const bigEmoji = message.kind === 'text' && !message.replyTo && !extra && !canTranslate && !transformed && isBigEmojiText(message.text);
458
471
  const showingTransform = !!transformed && !showOriginal && (transformed.kind === 'transcript' || canTranslate);
459
- const languageActions = (canTranscript || canTranslate || transformed) && _jsxs(View, { testID: "message-language-actions", style: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: voice && !showingTransform ? 'flex-end' : 'flex-start', columnGap: 8, rowGap: 0 }, children: [transformed && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: showOriginal ? (transformed.kind === 'transcript' ? 'Show transcript' : 'Show translation') : uiText("Show original"), onPress: () => { setTranslationAutoPlay(false); setShowOriginal(v => !v); }, hitSlop: 8, style: { minHeight: 17, paddingVertical: 1, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.accent, fontSize: 11, lineHeight: 15 }, children: showOriginal ? (transformed.kind === 'transcript' ? 'Show transcript' : 'Show translation') : uiText("Show original") }) }), canTranscript && !transformed && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Read voice message"), disabled: transforming, onPress: () => void transform('transcript'), hitSlop: 8, style: { minHeight: 17, paddingVertical: 1, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.accent, fontSize: 11, lineHeight: 15 }, children: transforming ? uiText("Transcribing…") : uiText("Transcript") }) }), canTranslate && transformed?.kind !== 'translation' && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: translation.mode === 'voice' ? uiText("Play translation") : uiText("Translate message"), disabled: transforming, onPress: () => void transform('translation', translation.mode === 'voice' ? 'voice' : 'text'), hitSlop: 8, style: { minHeight: 17, paddingVertical: 1, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.accent, fontSize: 11, lineHeight: 15 }, children: translation.mode === 'voice' ? uiText("Play Translation") : uiText("Translate") }) })] });
472
+ const languageActions = (canTranscript || canTranslate || transformed) && _jsxs(View, { testID: "message-language-actions", style: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: voice && !showingTransform ? 'flex-end' : 'flex-start', columnGap: 8, rowGap: 0 }, children: [transformed && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: showOriginal ? (transformed.kind === 'transcript' ? 'Show transcript' : 'Show translation') : uiText("Show original"), onPress: () => { setTranslationAutoPlay(false); setShowOriginal(v => !v); }, hitSlop: 8, style: { minHeight: 17, paddingVertical: 1, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.accent, fontSize: 11, lineHeight: 15 }, children: showOriginal ? (transformed.kind === 'transcript' ? 'Show transcript' : 'Show translation') : uiText("Show original") }) }), canTranscript && !transformed && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Read voice message"), disabled: transforming, onPress: () => void transform('transcript'), hitSlop: 8, style: { minHeight: 17, paddingVertical: 1, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.accent, fontSize: 11, lineHeight: 15 }, children: transforming ? uiText("Transcribing…") : uiText("Transcript") }) }), canTranslate && transformed?.kind !== 'translation' && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: translation.mode === 'voice' && languageTools?.voiceOutput !== false ? uiText("Play translation") : uiText("Translate message"), disabled: transforming, onPress: () => void transform('translation', translation.mode === 'voice' && languageTools?.voiceOutput !== false ? 'voice' : 'text'), hitSlop: 8, style: { minHeight: 17, paddingVertical: 1, justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.accent, fontSize: 11, lineHeight: 15 }, children: translation.mode === 'voice' && languageTools?.voiceOutput !== false ? uiText("Play Translation") : uiText("Translate") }) })] });
460
473
  const fallbackContent = _jsx(View, { testID: "message-original-text", children: _jsx(Text, { selectable: true, style: { color: ink, fontSize: 16, lineHeight: 22 }, children: renderText(message.text ?? '') }) });
461
474
  const originalContent = message.custom && !message.deleted ? _jsxs(Pressable, { onLongPress: menu, children: [_jsx(CustomMessage, { message: message, mine: mine, appearance: design, pendingStatus: pendingStatus, components: components, enabled: canInteract, children: fallbackContent }), pendingStatus && footer] }) : extra?.weather || extra?.call ? extraCard : message.kind === 'poll' ? _jsx(PollMessage, { onLongPress: menu, message: message, userId: userId, ink: ink, accent: c.accent, background: c.background, foreground: c.foreground, resolveVoterName: id => id === userId ? 'You' : participants?.[id]?.name ?? (state.conversation?.kind === 'direct' ? contextContactName : 'Chat member'), enabled: canInteract && !!state.settings?.features.poll, onVote: options => client.vote(message.id, options), onClose: () => client.closePoll(message.id) }) : message.kind === 'text' ? _jsxs(View, { testID: "message-original-text", children: [_jsx(Text, { selectable: true, style: { color: ink, fontSize: bigEmoji ? 48 : 16, lineHeight: bigEmoji ? 58 : 22 }, children: renderText(message.text ?? '') }), pendingStatus && footer] }) : _jsx(MediaContent, { message: message, ink: ink, accent: c.accent, footer: voice ? languageActions : undefined, onOpen: () => void open(), onLongPress: menu });
462
475
  const content = showingTransform ? _jsxs(View, { children: [_jsx(Text, { style: { color: ink, fontSize: 11, opacity: .65, marginBottom: 2 }, children: transformed.kind === 'transcript' ? uiText("Transcript") : 'Translated · ' + supportedLanguageLabel(translationLanguage) }), transformed.audio && TranslationVoice ? _jsx(View, { testID: "message-translated-voice", children: _jsx(TranslationVoice, { transform: transformed, ink: ink, accent: c.accent, showWaveform: design.showWaveform !== false, autoPlay: translationAutoPlay }) }) : _jsx(Text, { testID: "message-language-result", selectable: true, style: { color: ink, fontSize: 16, lineHeight: 22 }, children: transformed.text }), !voice && footer] }) : originalContent;
@@ -502,6 +515,7 @@ function MessageSelection() {
502
515
  const forward = enabled && ordered.every(m => client.canForward(m)), remove = enabled && state.messageActionsAvailable && ordered.every(m => m.senderId === userId && !m.readAt && !m.deleted);
503
516
  return _jsxs(View, { accessibilityLabel: uiText("Selected message actions"), style: { flexDirection: 'row', alignItems: 'center', minHeight: 48, paddingHorizontal: 4, gap: 0, backgroundColor: c.background, borderTopWidth: 1, borderTopColor: c.secondary + '25' }, children: [_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Clear message selection"), onPress: () => setSelection([]), style: { minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "close", color: c.foreground }) }), _jsx(Text, { accessibilityLiveRegion: "polite", accessibilityLabel: uiText('{count} selected', { count: selection.length }), style: { flex: 1, color: c.foreground, fontSize: 15 }, children: selection.length }), selection.length === 1 && !!ordered[0].text && (copyText || Platform.OS === 'web') && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Copy selected message text"), onPress: () => { void (copyText ? copyText(ordered[0].text) : navigator.clipboard.writeText(ordered[0].text)).then(() => setSelection([])).catch(() => setError(uiText("The text could not be copied."))); }, style: { minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "copy", color: c.accent }) }), selection.length === 1 && client.hasSavedMessages() && ordered[0].kind !== 'poll' && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: saved.some(r => r.key === savedMessageKey(ordered[0])) ? uiText("Remove selected message from Saved") : uiText("Save selected message"), disabled: saving, onPress: () => void toggleSaved(ordered[0]), style: { minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "bookmark", color: c.accent }) }), forward && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Forward selected messages"), onPress: () => { setForwarding(ordered); setSelection([]); }, style: { minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "forward", color: c.accent }) }), remove && selection.length === 1 && ordered[0].kind !== 'poll' && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Edit selected message"), onPress: () => { setEditing(ordered[0]); setSelection([]); }, style: { minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "edit", color: c.accent }) }), remove && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Delete selected messages"), onPress: () => { setDeleting(ordered); setSelection([]); }, style: { minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "trash", color: c.accent }) }), !!error && _jsxs(MessagingPopup, { compact: true, contentWidth: 640, title: uiText("Message"), foreground: c.foreground, background: c.background, onClose: () => setError(''), children: [_jsx(Text, { accessibilityRole: "alert", style: { color: messagingPopupColors.foreground }, children: error }), _jsx(Pressable, { accessibilityRole: "button", onPress: () => setError(''), style: { minHeight: 44, alignSelf: 'flex-end', justifyContent: 'center' }, children: _jsx(Text, { style: { color: c.accent }, children: uiText("OK") }) })] })] });
504
517
  }
518
+ const conversationReadingPositions = new WeakMap();
505
519
  export function MessagingList() {
506
520
  const { text: uiText, locale: uiLocale, number: uiNumber, count: uiCount } = useRobonoLocale();
507
521
  const context = useMessagingUI();
@@ -553,6 +567,25 @@ export function MessagingList() {
553
567
  const timer = setTimeout(() => { setHighlight(null); scrollTarget.current = null; }, 2500);
554
568
  return () => { cancelAnimationFrame(frame); settling.forEach(clearTimeout); clearTimeout(timer); };
555
569
  }, [state.focus]);
570
+ const readingKey = state.conversationId + ':' + (context.conversationMode ?? design.conversationMode ?? 'messenger');
571
+ const restoredReading = useRef('');
572
+ useEffect(() => {
573
+ if (state.loading || !state.settings)
574
+ return;
575
+ if (!state.settings.enabled) {
576
+ conversationReadingPositions.get(client)?.delete(readingKey);
577
+ return;
578
+ }
579
+ if (restoredReading.current === readingKey)
580
+ return;
581
+ restoredReading.current = readingKey;
582
+ const anchor = conversationReadingPositions.get(client)?.get(readingKey);
583
+ if (anchor) {
584
+ nearLatest.current = false;
585
+ setAway(true);
586
+ void client.focusMessage(anchor).catch(() => { conversationReadingPositions.get(client)?.delete(readingKey); });
587
+ }
588
+ }, [client, readingKey, state.loading, state.settings?.enabled]);
556
589
  const newest = items[0]?.clientMessageId ?? '', outgoing = state.pending.at(-1)?.clientMessageId ?? '';
557
590
  useEffect(() => {
558
591
  if (newest && newest !== lastNewest.current) {
@@ -570,10 +603,27 @@ export function MessagingList() {
570
603
  const pending = useRef("");
571
604
  const onVisible = useRef(({ viewableItems }) => {
572
605
  const ui = current.current;
606
+ if (ui.active !== false && !ui.state.loading && ui.state.settings?.enabled) {
607
+ let memory = conversationReadingPositions.get(ui.client);
608
+ if (!memory) {
609
+ memory = new Map();
610
+ conversationReadingPositions.set(ui.client, memory);
611
+ }
612
+ const key = ui.state.conversationId + ':' + (ui.conversationMode ?? ui.design.conversationMode ?? 'messenger');
613
+ const anchor = viewableItems.find(v => v.isViewable && v.item.conversationId === ui.state.conversationId && /^\d+$/.test(v.item.id));
614
+ if (nearLatest.current)
615
+ memory.delete(key);
616
+ else if (anchor) {
617
+ memory.delete(key);
618
+ memory.set(key, anchor.item.id);
619
+ while (memory.size > 30)
620
+ memory.delete(memory.keys().next().value);
621
+ }
622
+ }
573
623
  if (ui.active === false || AppState.currentState !== "active" ||
574
624
  !ui.state.inboxAvailable && !ui.state.settings?.features.readReceipts)
575
625
  return;
576
- const visible = viewableItems.filter((v) => v.isViewable && v.item.senderId !== ui.userId).map((v) => v.item).sort((a, b) => BigInt(a.id) > BigInt(b.id) ? -1 : 1);
626
+ const visible = viewableItems.filter((v) => v.isViewable && v.item.conversationId === ui.state.conversationId && /^\d+$/.test(v.item.id) && v.item.senderId !== ui.userId).map((v) => v.item).sort((a, b) => BigInt(a.id) > BigInt(b.id) ? -1 : 1);
577
627
  const last = visible[0];
578
628
  if (!last)
579
629
  return;
@@ -608,7 +658,7 @@ export function MessagingList() {
608
658
  if (state.hasMore && !state.loading && !state.historyError) {
609
659
  void client.loadOlder().catch(() => { });
610
660
  }
611
- }, onEndReachedThreshold: 0.2, ListHeaderComponent: state.historyWindow && state.hasNewer ? _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Load newer messages"), disabled: state.loading, onPress: () => void client.loadNewer().catch(() => { }), style: { padding: 10, minHeight: 44, alignItems: 'center' }, children: _jsx(Text, { style: { color: design.colors.accent }, children: uiText("Load newer messages") }) }) : null, ListFooterComponent: _jsxs(_Fragment, { children: [state.messages.length > 0 && (state.loading || state.historyError || state.hasMore) ? _jsx(View, { style: { padding: 10, alignItems: 'center' }, children: state.loading ? _jsx(ActivityIndicator, { accessibilityLabel: uiText("Loading earlier messages"), color: design.colors.accent }) : _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: state.historyError ? uiText("Retry earlier messages") : uiText("Load earlier messages"), onPress: () => void client.loadOlder().catch(() => { }), style: { minHeight: 44, justifyContent: 'center' }, children: _jsx(Text, { style: { color: design.colors.accent }, children: state.historyError ? uiText("Earlier messages could not load. Retry") : uiText("Load earlier messages") }) }) }) : null, context.extrasState?.privacyLens && _jsx(View, { testID: "privacy-history-spacer", style: { height: Math.max(0, historyHeight - privacyReadingStripHeight) } })] }), ListEmptyComponent: _jsx(Text, { style: { color: design.colors.secondary }, children: state.loading ? uiText("Loading messages…") : design.labels.empty }) }, context.extrasState?.privacyLens ? "privacy-reading" : "regular-history") }), (away || state.historyWindow) && _jsx(Animated.View, { testID: "latest-message-control", pointerEvents: showLatest ? 'auto' : 'none', accessibilityElementsHidden: !showLatest, importantForAccessibility: showLatest ? 'auto' : 'no-hide-descendants', ...(Platform.OS === 'web' ? { 'aria-hidden': !showLatest } : {}), style: { position: 'absolute', left: '50%', marginLeft: -22, bottom: 8, opacity: Platform.OS === 'web' ? (showLatest ? 1 : 0) : latestOpacity, ...(Platform.OS === 'web' ? { transitionProperty: 'opacity', transitionDuration: '200ms' } : {}) }, children: _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: newMessages ? uiText("New messages. Go to latest") : uiText("Go to latest message"), disabled: !showLatest, onPress: () => jumpToLatest(), style: { width: 44, height: 44, borderRadius: 22, borderWidth: 1.5, borderColor: design.colors.accent, backgroundColor: chatSurface(design.colors.background), justifyContent: 'center', alignItems: 'center' }, children: _jsx(MessageIcon, { name: "arrow-down", color: design.colors.accent, size: 26 }) }) }), _jsx(MessageSelection, {})] }));
661
+ }, onEndReachedThreshold: 0.2, ListHeaderComponent: state.historyWindow && state.hasNewer ? _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Load newer messages"), disabled: state.loading, onPress: () => void client.loadNewer().catch(() => { }), style: { padding: 10, minHeight: 44, alignItems: 'center' }, children: _jsx(Text, { style: { color: design.colors.accent }, children: uiText("Load newer messages") }) }) : null, ListFooterComponent: _jsxs(_Fragment, { children: [state.messages.length > 0 && (state.loading || state.historyError || state.hasMore) ? _jsx(View, { style: { padding: 10, alignItems: 'center' }, children: state.loading ? _jsx(ActivityIndicator, { accessibilityLabel: uiText("Loading earlier messages"), color: design.colors.accent }) : _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: state.historyError ? uiText("Retry earlier messages") : uiText("Load earlier messages"), onPress: () => void client.loadOlder().catch(() => { }), style: { minHeight: 44, justifyContent: 'center' }, children: _jsx(Text, { style: { color: design.colors.accent }, children: state.historyError ? uiText("Earlier messages could not load. Retry") : uiText("Load earlier messages") }) }) }) : null, context.extrasState?.privacyLens && _jsx(View, { testID: "privacy-history-spacer", style: { height: Math.max(0, historyHeight - privacyReadingStripHeight) } })] }), ListEmptyComponent: _jsx(Text, { style: { color: design.colors.secondary }, children: state.loading ? uiText("Loading messages…") : design.labels.empty }) }, state.conversationId + (context.extrasState?.privacyLens ? "privacy-reading" : "regular-history")) }), (away || state.historyWindow) && _jsx(Animated.View, { testID: "latest-message-control", pointerEvents: showLatest ? 'auto' : 'none', accessibilityElementsHidden: !showLatest, importantForAccessibility: showLatest ? 'auto' : 'no-hide-descendants', ...(Platform.OS === 'web' ? { 'aria-hidden': !showLatest } : {}), style: { position: 'absolute', left: '50%', marginLeft: -22, bottom: 8, opacity: Platform.OS === 'web' ? (showLatest ? 1 : 0) : latestOpacity, ...(Platform.OS === 'web' ? { transitionProperty: 'opacity', transitionDuration: '200ms' } : {}) }, children: _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: newMessages ? uiText("New messages. Go to latest") : uiText("Go to latest message"), disabled: !showLatest, onPress: () => jumpToLatest(), style: { width: 44, height: 44, borderRadius: 22, borderWidth: 1.5, borderColor: design.colors.accent, backgroundColor: chatSurface(design.colors.background), justifyContent: 'center', alignItems: 'center' }, children: _jsx(MessageIcon, { name: "arrow-down", color: design.colors.accent, size: 26 }) }) }), _jsx(MessageSelection, {})] }));
612
662
  }
613
663
  /** One horizontal media row on phones and in the browser preview. */
614
664
  function AttachmentStrip({ children, label, height, recent = false }) {
@@ -723,9 +773,6 @@ export function MessagingComposer() {
723
773
  useEffect(() => setPollOpen(false), [state.conversationId]);
724
774
  const [attachmentsOpen, setAttachmentsOpen] = useState(false);
725
775
  const attachmentButton = useRef(null);
726
- const [inputHeight, setInputHeight] = useState(44);
727
- useEffect(() => { if (!draft)
728
- setInputHeight(42); }, [draft]);
729
776
  const inFlight = useRef(false);
730
777
  const voiceInFlight = useRef(false);
731
778
  const [voicePending, setVoicePending] = useState(false);
@@ -946,11 +993,11 @@ export function MessagingComposer() {
946
993
  }
947
994
  else {
948
995
  setAttachmentsOpen(true);
949
- } }, style: { width: 42, height: 44, flexShrink: 0, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: attachmentsOpen ? "keyboard" : "plus", color: c.accent, size: 25 }) }), features?.text && _jsx(TextInput, { ref: input, accessibilityLabel: design.labels.compose, placeholder: design.labels.compose, placeholderTextColor: c.secondary, value: draft, editable: !blocked, onChangeText: setDraft, onContentSizeChange: e => setInputHeight(Math.max(44, Math.min(120, e.nativeEvent.contentSize.height))), multiline: true, numberOfLines: 1, maxLength: 10000, ...(Platform.OS === 'web' ? { onKeyPress: (event) => { const native = event.nativeEvent; if (native.key === 'Enter' && !native.shiftKey && !native.isComposing && native.keyCode !== 229) {
996
+ } }, style: { width: 42, height: 44, flexShrink: 0, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: attachmentsOpen ? "keyboard" : "plus", color: c.accent, size: 25 }) }), features?.text && _jsx(ComposerInput, { ref: input, accessibilityLabel: design.labels.compose, placeholder: design.labels.compose, placeholderTextColor: c.secondary, value: draft, editable: !blocked, onChangeText: setDraft, maxLength: 10000, ...(Platform.OS === 'web' ? { onKeyPress: (event) => { const native = event.nativeEvent; if (native.key === 'Enter' && !native.shiftKey && !native.isComposing && native.keyCode !== 229) {
950
997
  event.preventDefault();
951
998
  if (!blocked)
952
999
  void send();
953
- } } } : {}), onFocus: () => setAttachmentsOpen(false), style: { ...(Platform.OS === 'web' ? { outlineStyle: 'none' } : {}), writingDirection: draft ? 'auto' : uiDirection, textAlign: uiDirection === 'rtl' ? 'right' : 'left', flex: 1, minWidth: 0, minHeight: 44, height: inputHeight, maxHeight: 120, color: c.foreground, fontSize: 16, lineHeight: 22, paddingHorizontal: 4, paddingVertical: 8, backgroundColor: 'transparent' } }), !features?.text && _jsx(View, { style: { flex: 1 } }), features?.voice && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Voice message"), disabled: voicePending || busy || blocked, onPress: () => void pick('voice'), style: { width: 42, height: 44, flexShrink: 0, alignItems: 'center', justifyContent: 'center', opacity: voicePending || busy || blocked ? 0.5 : 1 }, children: _jsx(MessageIcon, { name: "mic", color: c.accent, size: 23 }) })] }), (features?.text || selected.length > 0) && _jsx(QuickSendButton, { choice: state.quickMessage, empty: !draft.trim() && !selected.length && !voice.hasVoice && !voice.sendVoice, enabled: !!features?.text, disabled: blocked, editing: !!editing, sendAvailable: !!draft.trim() || !!voice.sendVoice || selected.length > 0, appearance: design, onSchedule: state.scheduledMessagesAvailable && !editing && (!!draft.trim() || selected.length > 0) && !voice.hasVoice && !voice.sendVoice ? () => { setScheduleError(''); setScheduleOpen(true); } : undefined, onChoose: emoji => { void client.setQuickMessage(emoji).catch(() => setError(uiText("This quick message could not be saved on this device."))); }, onSend: () => { if (voice.sendVoice)
1000
+ } } } : {}), onFocus: () => setAttachmentsOpen(false), style: { ...(Platform.OS === 'web' ? { outlineStyle: 'none' } : {}), writingDirection: draft ? 'auto' : uiDirection, textAlign: uiDirection === 'rtl' ? 'right' : 'left', flex: 1, minWidth: 0, minHeight: 44, maxHeight: 120, color: c.foreground, fontSize: 16, lineHeight: 22, paddingHorizontal: 4, paddingVertical: 8, backgroundColor: 'transparent' } }), !features?.text && _jsx(View, { style: { flex: 1 } }), features?.voice && _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Voice message"), disabled: voicePending || busy || blocked, onPress: () => void pick('voice'), style: { width: 42, height: 44, flexShrink: 0, alignItems: 'center', justifyContent: 'center', opacity: voicePending || busy || blocked ? 0.5 : 1 }, children: _jsx(MessageIcon, { name: "mic", color: c.accent, size: 23 }) })] }), (features?.text || selected.length > 0) && _jsx(QuickSendButton, { choice: state.quickMessage, empty: !draft.trim() && !selected.length && !voice.hasVoice && !voice.sendVoice, enabled: !!features?.text, disabled: blocked, editing: !!editing, sendAvailable: !!draft.trim() || !!voice.sendVoice || selected.length > 0, appearance: design, onSchedule: state.scheduledMessagesAvailable && !editing && (!!draft.trim() || selected.length > 0) && !voice.hasVoice && !voice.sendVoice ? () => { setScheduleError(''); setScheduleOpen(true); } : undefined, onChoose: emoji => { void client.setQuickMessage(emoji).catch(() => setError(uiText("This quick message could not be saved on this device."))); }, onSend: () => { if (voice.sendVoice)
954
1001
  voice.sendVoice();
955
1002
  else
956
1003
  void send(); }, onQuickSend: emoji => { void submit({ kind: 'text', text: emoji }).catch(() => { }); } }, state.conversationId)] });
@@ -1002,9 +1049,9 @@ function MessagingWaitingChanges() {
1002
1049
  }
1003
1050
  export function MessagingConversation() {
1004
1051
  const { text: uiText } = useRobonoLocale();
1005
- const { state, client, components, design, style } = useMessagingUI();
1052
+ const { state, client, components, design, style, keyboard } = useMessagingUI();
1006
1053
  const Header = components?.Header ?? MessagingHeader, List = components?.List ?? MessagingList, Composer = components?.Composer ?? MessagingComposer;
1007
- return (_jsxs(KeyboardAvoidingView, { behavior: Platform.OS === "ios" ? "padding" : undefined, style: [{ flex: 1, backgroundColor: design.colors.background }, style], children: [_jsx(MessagingPopupHeaderBoundary, { children: _jsx(Header, {}) }), _jsx(List, {}), state.error && (_jsx(Text, { accessibilityRole: "alert", style: { padding: 12, color: design.colors.foreground }, children: uiText(state.error) })), _jsx(MessagingWaitingChanges, {}), _jsx(Composer, {}, state.conversationId)] }));
1054
+ return (_jsxs(MessagingKeyboardContainer, { options: keyboard, style: [{ backgroundColor: design.colors.background }, style], children: [_jsx(MessagingPopupHeaderBoundary, { children: _jsx(Header, {}) }), _jsx(List, {}), state.error && (_jsx(Text, { accessibilityRole: "alert", style: { padding: 12, color: design.colors.foreground }, children: uiText(state.error) })), _jsx(MessagingWaitingChanges, {}), _jsx(View, { style: { paddingBottom: Math.max(0, keyboard?.bottomInset ?? 0) }, children: _jsx(Composer, {}, state.conversationId) })] }));
1008
1055
  }
1009
1056
  /** Embed inside your app's safe area and navigation. No engine, push or global audio side effects. */
1010
1057
  export function MessagingScreen(props) {
@@ -0,0 +1,10 @@
1
+ import React from 'react';
2
+ import { type StyleProp, type ViewStyle } from 'react-native';
3
+ import type { MessagingKeyboardOptions } from '@robono/messaging';
4
+ /** Measure the supplied screen's origin so hosts do not need to duplicate
5
+ * header/safe-area calculations. A host-owned keyboard container can opt out. */
6
+ export declare function MessagingKeyboardContainer({ options, style, children }: {
7
+ options?: MessagingKeyboardOptions;
8
+ style?: StyleProp<ViewStyle>;
9
+ children: React.ReactNode;
10
+ }): React.JSX.Element;
@@ -0,0 +1,18 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useCallback, useEffect, useRef, useState } from 'react';
3
+ import { KeyboardAvoidingView, Platform, StatusBar, View, useWindowDimensions } from 'react-native';
4
+ /** Measure the supplied screen's origin so hosts do not need to duplicate
5
+ * header/safe-area calculations. A host-owned keyboard container can opt out. */
6
+ export function MessagingKeyboardContainer({ options, style, children }) {
7
+ const parent = useRef(null), [offset, setOffset] = useState(0), window = useWindowDimensions();
8
+ const measure = useCallback(() => {
9
+ parent.current?.measureInWindow((_x, y) => {
10
+ // Android's measureInWindow subtracts the status bar, while keyboard screenY
11
+ // is a screen coordinate. iOS already reports the full window coordinate.
12
+ const next = Math.max(0, y + (Platform.OS === 'android' ? (StatusBar.currentHeight ?? 0) : 0));
13
+ setOffset(old => Math.abs(old - next) < .5 ? old : next);
14
+ });
15
+ }, []);
16
+ useEffect(() => { const frame = requestAnimationFrame(measure); return () => cancelAnimationFrame(frame); }, [measure, window.width, window.height]);
17
+ return _jsx(View, { ref: parent, onLayout: measure, style: { flex: 1, minHeight: 0 }, children: _jsx(KeyboardAvoidingView, { enabled: options?.enabled !== false, keyboardVerticalOffset: options?.verticalOffset ?? offset, behavior: options?.behavior ?? (Platform.OS === 'ios' ? 'padding' : Platform.OS === 'android' ? 'height' : undefined), style: [{ flex: 1 }, style], children: children }) });
18
+ }
@@ -116,6 +116,7 @@ export declare class MessagingMediaController {
116
116
  signal: AbortSignal;
117
117
  }) => Promise<T>, options?: {
118
118
  reauthorize?: boolean;
119
+ requireLocalFile?: boolean;
119
120
  }): Promise<T>;
120
121
  /** Recover a failed/expired native stream once through fresh authorized download. */
121
122
  fallbackStream(uri: string, positionMs: number, autoPlay: boolean): Promise<void>;
@@ -320,11 +320,12 @@ export class MessagingMediaController {
320
320
  const signal = this.abort?.signal;
321
321
  if (!signal)
322
322
  throw Error('The attachment is unavailable.');
323
- if (!file.stream && !options.reauthorize)
323
+ if (options.requireLocalFile === false || !file.stream && !options.reauthorize)
324
324
  return save(file, { message, signal });
325
325
  if (!message || !this.abort)
326
326
  throw Error('The attachment is unavailable.');
327
- const copy = await this.options.storage.download(options.reauthorize ? { ...message, attachmentDownload: undefined } : message, { signal: this.abort.signal, onProgress: () => { } });
327
+ const copy = await this.options.storage.download(options.reauthorize ? { ...message, attachmentDownload: undefined } : message, { signal: this.abort.signal, onProgress: value => { if (this.isCurrent(generation))
328
+ this.update({ progress: Math.max(0, Math.min(1, value)) }); } });
328
329
  try {
329
330
  if (!this.isCurrent(generation) || this.options.getConversationId() !== conversationId)
330
331
  throw Error('The media viewer is closed.');