@robono/messaging-react-native 0.21.0 → 0.22.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.
package/app.plugin.cjs CHANGED
@@ -1,5 +1,11 @@
1
- const {withDangerousMod,createRunOncePlugin} = require('expo/config-plugins');
2
- module.exports=createRunOncePlugin(config=>withDangerousMod(config,['ios',async value=>{
1
+ const {withDangerousMod,withInfoPlist,createRunOncePlugin} = require('expo/config-plugins');
2
+ module.exports=createRunOncePlugin(config=>{
3
+ config=withInfoPlist(config,value=>{
4
+ value.modResults.UIBackgroundModes=[...new Set([...(value.modResults.UIBackgroundModes??[]),'remote-notification'])];
5
+ return value;
6
+ });
7
+ return withDangerousMod(config,['ios',async value=>{
3
8
  require('./plugin/preserve-call-audio.cjs').install(value.modRequest.projectRoot);
4
9
  return value;
5
- }]),'@robono/messaging-react-native',require('./package.json').version);
10
+ }]);
11
+ },'@robono/messaging-react-native',require('./package.json').version);
@@ -0,0 +1,12 @@
1
+ import type { MessagingAppearance, MessagingMessage } from '@robono/messaging';
2
+ export declare function bubbleCorners(appearance: MessagingAppearance, mine: boolean, caption?: boolean): {
3
+ borderTopLeftRadius: number;
4
+ borderTopRightRadius: number;
5
+ borderBottomLeftRadius: number;
6
+ borderBottomRightRadius: number;
7
+ };
8
+ export declare function bubbleDelivery(message: MessagingMessage, pending: 'sending' | 'queued' | 'failed' | undefined, receipts: boolean, appearance: MessagingAppearance): {
9
+ readonly phase: "failed" | "sent" | "consumed" | "delivered";
10
+ readonly color: string;
11
+ readonly style: "circle" | "bar";
12
+ };
@@ -0,0 +1,11 @@
1
+ export function bubbleCorners(appearance, mine, caption = false) {
2
+ const radius = appearance.presentation?.bubbleShape === 'square' ? 0 : appearance.presentation?.bubbleShape === 'rounded' ? 16 : 8;
3
+ const emphasized = appearance.presentation?.bubbleStyle === 'rounded-corner' ? Math.max(28, radius) : radius;
4
+ return { borderTopLeftRadius: radius, borderTopRightRadius: radius, borderBottomLeftRadius: caption ? 0 : mine ? radius : emphasized, borderBottomRightRadius: caption ? 0 : mine ? emphasized : radius };
5
+ }
6
+ export function bubbleDelivery(message, pending, receipts, appearance) {
7
+ const phase = pending === 'failed' || message.delivery?.state === 'failed' ? 'failed' : pending || message.delivery?.state === 'pending' ? 'sent' : receipts && !!message.readAt ? 'consumed' : 'delivered';
8
+ const colors = appearance.messageStatus;
9
+ const color = phase === 'failed' ? '#c94040' : phase === 'sent' ? colors?.sent ?? '#929292' : phase === 'delivered' ? colors?.delivered ?? '#ffffff' : colors?.consumed ?? appearance.colors.accent;
10
+ return { phase, color, style: colors?.style ?? 'bar' };
11
+ }
@@ -2,12 +2,13 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Text } from './typography.js';
3
3
  import { useRobonoLocale } from './localization.js';
4
4
  import { useEffect, useRef, useState } from 'react';
5
- import { Pressable, View } from 'react-native';
5
+ import { Pressable, View, ActivityIndicator } from 'react-native';
6
+ import { MessageIcon } from './icons.js';
6
7
  import { useMessagingUI } from './index.js';
7
8
  /** A new, reviewed message after no answer. Never records or sends a call automatically. */
8
9
  export function UnansweredCallMessage({ callId, onDismiss }) {
9
10
  const { text: uiText, locale: uiLocale, number: uiNumber, count: uiCount } = useRobonoLocale();
10
- const { client, design, state, pickAttachment, releaseAttachment, components } = useMessagingUI();
11
+ const { client, design, state, userId, pickAttachment, releaseAttachment, prepareAttachment, openAttachment, components } = useMessagingUI();
11
12
  const [option, setOption] = useState(null);
12
13
  const [draft, setDraft] = useState(null);
13
14
  const [busy, setBusy] = useState(false), [error, setError] = useState(''), [attempt, setAttempt] = useState(0);
@@ -84,6 +85,7 @@ export function UnansweredCallMessage({ callId, onDismiss }) {
84
85
  setBusy(true);
85
86
  setError('');
86
87
  const id = generation.current;
88
+ let transferred = false;
87
89
  try {
88
90
  const current = await client.unansweredCall(callId);
89
91
  if (id !== generation.current)
@@ -93,16 +95,29 @@ export function UnansweredCallMessage({ callId, onDismiss }) {
93
95
  setOption(current);
94
96
  return;
95
97
  }
96
- // The client now owns the stable retry identity. Unmounting only releases
97
- // local preview resources, never the uploaded asset needed by a retry.
98
- const work = client.send({ kind: draft.kind, media: draft.media, unansweredCallId: callId });
99
- clearDraft();
98
+ const content = { kind: draft.kind, media: draft.media, unansweredCallId: callId };
99
+ const media = draft.media, kind = draft.kind;
100
+ const previous = new Set(client.getSnapshot().pending.map(item => item.clientMessageId));
101
+ const work = client.send(content, prepareAttachment ? async () => ({ ...content, media: await prepareAttachment(kind, media) }) : undefined);
102
+ const queued = client.getSnapshot().pending.find(item => !previous.has(item.clientMessageId));
103
+ if (!queued) {
104
+ await work;
105
+ return;
106
+ }
107
+ // Transfer the draft to the outgoing message. Failed uploads retain the
108
+ // local file for the standard retry; unmount must not remove it.
109
+ transferred = true;
110
+ prepared.current = null;
111
+ setDraft(null);
100
112
  onDismiss();
101
113
  await work;
114
+ const result = client.getSnapshot();
115
+ if (result.messages.some(message => message.clientMessageId === queued.clientMessageId))
116
+ await release.current?.(media);
102
117
  }
103
118
  catch {
104
119
  if (id === generation.current)
105
- setError(uiText("The message could not be sent. Check the conversation for a retry."));
120
+ setError(uiText(transferred ? "The message could not be sent. Check the conversation for a retry." : "Your recording was kept. Please try sending again."));
106
121
  }
107
122
  finally {
108
123
  inFlight.current = false;
@@ -110,9 +125,24 @@ export function UnansweredCallMessage({ callId, onDismiss }) {
110
125
  setBusy(false);
111
126
  }
112
127
  }
128
+ async function preview() {
129
+ if (!draft || !openAttachment || busy)
130
+ return;
131
+ const id = generation.current;
132
+ setError('');
133
+ const message = { id: 'call-draft-' + draft.media.assetId, clientMessageId: 'call-draft-' + draft.media.assetId, conversationId: state.conversationId, senderId: userId, createdAt: new Date().toISOString(), readAt: null, kind: draft.kind, media: draft.media };
134
+ try {
135
+ await openAttachment(message);
136
+ }
137
+ catch {
138
+ if (id === generation.current)
139
+ setError(uiText('This recording could not be opened.'));
140
+ }
141
+ }
113
142
  if (!pickAttachment || !state.settings?.enabled || state.conversation?.canSend === false || (!option && !error))
114
143
  return null;
115
144
  const c = design.colors, VoiceAttachment = components?.VoiceAttachment;
116
- const action = (label, onPress) => _jsx(Pressable, { accessibilityRole: "button", disabled: busy, onPress: onPress, style: { paddingVertical: 12, paddingHorizontal: 4, minHeight: 44 }, children: _jsx(Text, { style: { color: c.incomingText, fontWeight: '600' }, children: label }) });
117
- return _jsxs(View, { style: { backgroundColor: c.incoming, padding: 16, borderTopWidth: 1, borderTopColor: c.secondary + '30', gap: 6 }, children: [_jsx(Text, { style: { color: c.incomingText, fontSize: 16, fontWeight: '600' }, children: uiText("No answer") }), option && _jsx(Text, { style: { color: c.incomingText, fontSize: 14 }, children: draft ? uiText("Review your message, then send it.") : uiText("Leave a {value1} message in this chat.", { value1: option.kind === 'voice' ? 'voice' : 'video' }) }), draft && _jsx(View, { children: draft.kind === 'voice' && VoiceAttachment ? _jsx(VoiceAttachment, { media: draft.media, appearance: design, disabled: busy, onRemove: clearDraft }) : _jsx(Text, { style: { color: c.incomingText }, children: draft.kind === 'voice' ? uiText('Voice message ready') : uiText('Video message ready') }) }), _jsxs(View, { style: { flexDirection: 'row', gap: 16, flexWrap: 'wrap' }, children: [option && (draft ? action('Send message', () => void send()) : action(`Record ${option.kind === 'voice' ? 'voice' : 'video'} message`, () => void record())), !option && error && action('Try again', () => setAttempt(value => value + 1)), action('Not now', () => { clearDraft(); onDismiss(); })] }), !!error && _jsx(Text, { accessibilityRole: "alert", style: { color: c.incomingText }, children: error })] });
145
+ const accentInk = parseInt(c.accent.slice(1, 3), 16) * .299 + parseInt(c.accent.slice(3, 5), 16) * .587 + parseInt(c.accent.slice(5, 7), 16) * .114 > 150 ? '#111111' : '#ffffff';
146
+ const action = (label, onPress, primary = false) => _jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText(label), disabled: busy, onPress: onPress, style: { paddingVertical: 10, paddingHorizontal: 14, minHeight: 44, borderRadius: 22, backgroundColor: primary ? c.accent : 'transparent', borderWidth: primary ? 0 : 1, borderColor: c.secondary + '55', alignItems: 'center', justifyContent: 'center', flexDirection: 'row', gap: 8, opacity: busy ? .6 : 1 }, children: [primary && busy ? _jsx(ActivityIndicator, { size: "small", color: accentInk }) : primary && _jsx(MessageIcon, { name: draft ? 'send' : option?.kind === 'video' ? 'video' : 'mic', color: accentInk, size: 18 }), _jsx(Text, { style: { color: primary ? accentInk : c.incomingText, fontWeight: '600', fontSize: 14 }, children: uiText(label) })] });
147
+ return _jsxs(View, { testID: "unanswered-call-message", style: { backgroundColor: c.incoming, padding: 12, borderTopWidth: 1, borderTopColor: c.secondary + '30', gap: 10 }, children: [_jsxs(View, { style: { flexDirection: 'row', alignItems: 'center', gap: 10 }, children: [_jsx(View, { style: { width: 36, height: 36, borderRadius: 18, backgroundColor: c.accent + '20', alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: option?.kind === 'video' ? 'video' : 'mic', color: c.accent, size: 20 }) }), _jsxs(View, { style: { flex: 1, gap: 2 }, children: [_jsx(Text, { style: { color: c.incomingText, fontSize: 16, fontWeight: '700' }, children: uiText("Leave a message") }), _jsx(Text, { style: { color: c.incomingText, opacity: .75, fontSize: 13 }, children: draft ? uiText("Review before sending.") : uiText("No answer. Send a recording instead.") })] })] }), draft && _jsx(View, { testID: "call-message-review", style: { borderWidth: 1, borderColor: c.secondary + '40', borderRadius: 12, padding: 8 }, children: draft.kind === 'voice' && VoiceAttachment ? _jsx(VoiceAttachment, { media: draft.media, appearance: design, disabled: busy, onRemove: clearDraft }) : _jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText(draft.kind === 'video' ? 'Play video' : 'Play recording'), disabled: busy, onPress: () => void preview(), style: { minHeight: 60, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 8 }, children: [_jsx(View, { style: { width: 40, height: 40, borderRadius: 20, backgroundColor: c.accent, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "play", size: 20, color: accentInk }) }), _jsxs(View, { children: [_jsx(Text, { style: { color: c.incomingText, fontSize: 15, fontWeight: '600' }, children: uiText(draft.kind === 'video' ? 'Play video' : 'Play recording') }), _jsxs(Text, { style: { color: c.incomingText, opacity: .65, fontSize: 12 }, children: [Math.floor((draft.media.durationMs ?? 0) / 60000), ":", String(Math.floor((draft.media.durationMs ?? 0) / 1000) % 60).padStart(2, '0')] })] })] }) }), _jsxs(View, { style: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 8, flexWrap: 'wrap' }, children: [action(draft ? 'Cancel' : 'Not now', () => { clearDraft(); onDismiss(); }), _jsxs(View, { style: { flexDirection: 'row', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-end', flex: 1 }, children: [draft && action('Record again', () => void record()), option && action(draft ? 'Send message' : `Record ${option.kind === 'voice' ? 'voice' : 'video'} message`, () => void (draft ? send() : record()), true), !option && error && action('Try again', () => setAttempt(value => value + 1), true)] })] }), !!error && _jsx(Text, { accessibilityRole: "alert", style: { color: c.incomingText, fontSize: 13 }, children: error })] });
118
148
  }
@@ -0,0 +1,7 @@
1
+ import React from 'react';
2
+ /** A two-pixel inside edge, narrowing to a point at both bubble corners. */
3
+ export declare function DeliveryBar({ color, topRadius, bottomRadius }: {
4
+ color: string;
5
+ topRadius: number;
6
+ bottomRadius: number;
7
+ }): React.JSX.Element;
@@ -0,0 +1,19 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useState } from 'react';
3
+ import { View } from 'react-native';
4
+ import Svg, { Path, G } from 'react-native-svg';
5
+ /** A two-pixel inside edge, narrowing to a point at both bubble corners. */
6
+ export function DeliveryBar({ color, topRadius, bottomRadius }) {
7
+ const [height, setHeight] = useState(0);
8
+ const scale = height ? Math.min(1, height / Math.max(1, topRadius + bottomRadius)) : 1;
9
+ const top = topRadius * scale, bottom = bottomRadius * scale;
10
+ const capHeight = (radius) => radius > 0 ? radius : Math.min(8, height ? height / 2 : 8);
11
+ const cap = (radius, bottom = false) => {
12
+ const width = Math.max(2, radius), height = capHeight(radius);
13
+ const path = radius > 0
14
+ ? `M 0 0 C ${radius * .5523} 0 ${radius} ${radius * .4477} ${radius} ${radius} L ${Math.max(0, radius - 2)} ${radius} C ${Math.max(0, radius - 2)} ${radius * .4477} ${radius * .5523} 1 0 0 Z`
15
+ : `M 2 0 L 2 ${height} L 0 ${height} Z`;
16
+ return _jsx(Svg, { width: width, height: height, viewBox: `0 0 ${width} ${height}`, style: { position: 'absolute', right: 0, ...(bottom ? { bottom: 0 } : { top: 0 }) }, accessible: false, children: _jsx(G, { transform: bottom ? `translate(0 ${height}) scale(1 -1)` : undefined, children: _jsx(Path, { d: path, fill: color }) }) });
17
+ };
18
+ return _jsxs(View, { pointerEvents: "none", onLayout: e => setHeight(e.nativeEvent.layout.height), style: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }, children: [_jsx(View, { style: { position: 'absolute', top: capHeight(top), bottom: capHeight(bottom), right: 0, width: 2, backgroundColor: color } }), cap(top), cap(bottom, true)] });
19
+ }
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import { type ExpoMessagingScreenProps } from './expo.js';
2
+ import { type ExpoMessagingScreenProps } from './expo-screen.js';
3
3
  import { type MessagingCallingScreenProps } from './calling.js';
4
4
  export type ExpoMessagingCallingScreenProps = Omit<ExpoMessagingScreenProps, 'renderConversation'> & Pick<MessagingCallingScreenProps, 'onCall' | 'callLabel' | 'onVideoCall' | 'videoCallLabel' | 'unansweredCallId' | 'onDismissCallMessage'>;
5
5
  /** Optional composition of the shared conversation, calling entry and native recording/review tools. */
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { ExpoMessagingScreen } from './expo.js';
2
+ import { ExpoMessagingScreen } from './expo-screen.js';
3
3
  import { MessagingCallingScreen } from './calling.js';
4
4
  /** Optional composition of the shared conversation, calling entry and native recording/review tools. */
5
5
  export function ExpoMessagingCallingScreen({ onCall, callLabel, onVideoCall, videoCallLabel, unansweredCallId, onDismissCallMessage, ...props }) {
@@ -55,6 +55,11 @@ export function createExpoMessenger(options) {
55
55
  });
56
56
  const calling = options.calling === false ? undefined : createExpoMessengerCalling({ ...options, inbox });
57
57
  const audioSession = options.audioSession ?? createExpoMessagingAudioSession({ isCallActive: () => isNativeCallAudioActive() || calling?.isActive() === true || options.isCallActive?.() === true });
58
+ let notificationRevision;
59
+ const stopNotificationSync = inbox.subscribe(() => { const next = inbox.getSnapshot().inboxCursor; if (next && next !== notificationRevision) {
60
+ notificationRevision = next;
61
+ void connection?.reconcile().catch(() => { });
62
+ } });
58
63
  let connection = null, pending = null, closed = false;
59
64
  let openNotification;
60
65
  const notifications = options.notifications === false ? undefined : {
@@ -97,10 +102,10 @@ export function createExpoMessenger(options) {
97
102
  };
98
103
  return { client, inbox, storage, audioSession, notifications, calling, availability, maps: mapConnection?.workspace, ...(connectedExtras ? { extras: connectedExtras.extras, components: { TrackingMap: connectedExtras.TrackingMap } } : {}),
99
104
  async signOut() { if (closed)
100
- return; closed = true; activitySubscription?.remove(); const extraCleanup = connectedExtras?.signOut(); inbox.dispose(); const results = await Promise.allSettled([availability?.signOut(), extraCleanup, calling?.dispose(), mapConnection?.signOut(), client.signOut(), (async () => { await pending?.catch(() => { }); await connection?.signOut(); })()]); const failed = results.find(r => r.status === 'rejected'); if (failed?.status === 'rejected')
105
+ return; closed = true; stopNotificationSync(); activitySubscription?.remove(); const extraCleanup = connectedExtras?.signOut(); inbox.dispose(); const results = await Promise.allSettled([availability?.signOut(), extraCleanup, calling?.dispose(), mapConnection?.signOut(), client.signOut(), (async () => { await pending?.catch(() => { }); await connection?.signOut(); })()]); const failed = results.find(r => r.status === 'rejected'); if (failed?.status === 'rejected')
101
106
  throw failed.reason; },
102
107
  dispose() { if (closed)
103
- return; closed = true; activitySubscription?.remove(); availability?.dispose(); void calling?.dispose().catch(() => { }); mapConnection?.dispose(); void connectedExtras?.dispose().catch(() => { }); connection?.dispose(); inbox.dispose(); client.dispose(); },
108
+ return; closed = true; stopNotificationSync(); activitySubscription?.remove(); availability?.dispose(); void calling?.dispose().catch(() => { }); mapConnection?.dispose(); void connectedExtras?.dispose().catch(() => { }); connection?.dispose(); inbox.dispose(); client.dispose(); },
104
109
  };
105
110
  }
106
111
  export async function createHostedExpoMessenger(options) {
@@ -161,6 +166,10 @@ function ExpoMessengerContent({ inbox, contacts = emptyContacts, initialConversa
161
166
  const subscription = AppState.addEventListener('change', sync);
162
167
  return () => { subscription.remove(); props.client.stop(); };
163
168
  }, [selected?.id, props.client, props.active]);
169
+ useEffect(() => { const sync = (state) => { if (props.active !== false && (state === null || state === 'active'))
170
+ inbox.start();
171
+ else
172
+ inbox.stop(); }; sync(AppState.currentState); const sub = AppState.addEventListener('change', sync); return () => { sub.remove(); inbox.stop(); }; }, [inbox, props.active]);
164
173
  const autoCalls = calling && selected && selected.contactId !== props.userId && groupAllowed ? { ...(callState.features.voice ? { voice: () => calling.call(selected.id, 'voice', selected.kind === 'group') } : {}), ...(callState.features.video ? { video: () => calling.call(selected.id, 'video', selected.kind === 'group') } : {}), voiceLabel: 'Internet call' } : undefined;
165
174
  const setSelected = (row) => { setInternal(row); onSelectConversation?.(row); };
166
175
  const [showMaps, setShowMaps] = useState(false), mapConnection = useMessengerMaps(maps), mapsAvailable = mapConnection.available;
@@ -185,5 +194,5 @@ function ExpoMessengerContent({ inbox, contacts = emptyContacts, initialConversa
185
194
  const account = calling?.deviceCheck ? { name: 'Your account', ...notificationAccount, deviceCheck: calling.deviceCheck, renderCallPreview: (stream) => renderNativeCallVideo({ stream, local: true, style: { width: '100%', height: '100%' } }) } : notificationAccount;
186
195
  const knownContact = contacts[selected?.contactId ?? ''];
187
196
  const contact = useMemo(() => selected?.contactId === props.userId ? { name: 'Notes to self' } : selected?.kind === 'group' ? { name: selected.name ?? 'Group' } : knownContact ?? { name: selected?.contactId ?? 'Chat' }, [selected?.contactId, selected?.kind, selected?.name, props.userId, knownContact]);
188
- return _jsxs(View, { style: { flex: 1, minHeight: 0 }, children: [_jsx(MessengerMapsNotice, { error: mapConnection.error, retry: mapConnection.retry }), showMaps && maps ? _jsx(RobonoMaps, { interfaceLocale: mapsLocale, workspace: maps, contacts: contacts, onClose: () => setShowMaps(false) }) : _jsx(ExpoMessagingScreen, { ...props, conversationActions: conversationActions, account: account, contact: contact, participants: props.participants ?? contacts, extras: selected ? props.extras : undefined, callActions: selected && selected.contactId !== props.userId ? { ...autoCalls, ...props.callActions, phoneNumber: contacts[selected.contactId ?? '']?.phoneNumber ?? props.callActions?.phoneNumber } : undefined, onBack: () => { props.client.stop(); setSelected(null); void inbox.refresh().catch(() => { }); }, renderConversation: screen => selected ? _jsx(MessagingCallingScreen, { ...screen, onCall: screen.callActions?.voice, onVideoCall: screen.callActions?.video, callLabel: "Internet call", unansweredCallId: callState.unanswered?.conversationId === selected.id ? callState.unanswered.id : undefined, onDismissCallMessage: calling?.dismissUnanswered }) : _jsxs(MessagingProvider, { ...screen, appearance: props.appearance ?? inboxState.appearance ?? undefined, children: [_jsx(MessagingInbox, { directory: props.directory, onOpenDirectoryContact: props.onOpenDirectoryContact, viewMemory: inboxMemory, client: inbox, userId: props.userId, contacts: contacts, companyName: props.companyName, appearance: props.appearance, active: props.active !== false, headerActions: _jsx(MessagingAccountMenu, { onNewConversation: props.onNewConversation, onPublicRooms: inboxState.publicRoomsAvailable ? () => setPublicRooms(true) : undefined, onMaps: mapsAvailable ? () => setShowMaps(true) : undefined, onNewGroup: inboxState.groupCreationAvailable ? () => setNewGroup(true) : undefined }), onSelect: open, onDeleted: id => props.client.forgetConversation(id) }), publicRooms && _jsx(MessagingPublicRooms, { inbox: inbox, accent: (props.appearance ?? inboxState.appearance ?? defaultMessagingSettings().appearance).colors.accent, createRequestId: () => props.client.createForwardId(), onClose: () => setPublicRooms(false), onJoined: (id, name) => { setPublicRooms(false); open(inbox.getSnapshot().conversations.find(c => c.id === id) ?? { id, kind: 'group', name, contactId: null, lastMessage: null, unreadCount: 0, canSend: true }); } }), newGroup && _jsx(MessagingGroupEditor, { client: props.client, inbox: inbox, userId: props.userId, contacts: contacts, groups: inboxState.groups, accent: (props.appearance ?? inboxState.appearance ?? defaultMessagingSettings().appearance).colors.accent, onClose: () => setNewGroup(false), onSaved: (id, name) => { setNewGroup(false); const row = inbox.getSnapshot().conversations.find(c => c.id === id) ?? { id, kind: 'group', name, contactId: null, lastMessage: null, unreadCount: 0, canSend: true }; open(row); } }), props.inboxOverlay] }) }), _jsx(ExpoMessengerCalls, { calling: calling, state: callState })] });
197
+ return _jsxs(View, { style: { flex: 1, minHeight: 0 }, children: [_jsx(MessengerMapsNotice, { error: mapConnection.error, retry: mapConnection.retry }), showMaps && maps ? _jsx(RobonoMaps, { interfaceLocale: mapsLocale, workspace: maps, contacts: contacts, onClose: () => setShowMaps(false) }) : _jsx(ExpoMessagingScreen, { ...props, conversationActions: conversationActions, account: account, contact: contact, participants: props.participants ?? contacts, extras: selected ? props.extras : undefined, callActions: selected && selected.contactId !== props.userId ? { ...autoCalls, ...props.callActions, phoneNumber: contacts[selected.contactId ?? '']?.phoneNumber ?? props.callActions?.phoneNumber } : undefined, onBack: () => { props.client.stop(); setSelected(null); void inbox.refresh().catch(() => { }); }, renderConversation: screen => selected ? _jsx(MessagingCallingScreen, { ...screen, onCall: screen.callActions?.voice, onVideoCall: screen.callActions?.video, callLabel: "Internet call", unansweredCallId: callState.unanswered?.conversationId === selected.id ? callState.unanswered.id : undefined, onDismissCallMessage: calling?.dismissUnanswered }) : _jsxs(MessagingProvider, { ...screen, appearance: props.appearance ?? inboxState.appearance ?? undefined, children: [_jsx(MessagingInbox, { manageUpdates: false, directory: props.directory, onOpenDirectoryContact: props.onOpenDirectoryContact, viewMemory: inboxMemory, client: inbox, userId: props.userId, contacts: contacts, companyName: props.companyName, appearance: props.appearance, active: props.active !== false, headerActions: _jsx(MessagingAccountMenu, { onNewConversation: props.onNewConversation, onPublicRooms: inboxState.publicRoomsAvailable ? () => setPublicRooms(true) : undefined, onMaps: mapsAvailable ? () => setShowMaps(true) : undefined, onNewGroup: inboxState.groupCreationAvailable ? () => setNewGroup(true) : undefined }), onSelect: open, onDeleted: id => props.client.forgetConversation(id) }), publicRooms && _jsx(MessagingPublicRooms, { inbox: inbox, accent: (props.appearance ?? inboxState.appearance ?? defaultMessagingSettings().appearance).colors.accent, createRequestId: () => props.client.createForwardId(), onClose: () => setPublicRooms(false), onJoined: (id, name) => { setPublicRooms(false); open(inbox.getSnapshot().conversations.find(c => c.id === id) ?? { id, kind: 'group', name, contactId: null, lastMessage: null, unreadCount: 0, canSend: true }); } }), newGroup && _jsx(MessagingGroupEditor, { client: props.client, inbox: inbox, userId: props.userId, contacts: contacts, groups: inboxState.groups, accent: (props.appearance ?? inboxState.appearance ?? defaultMessagingSettings().appearance).colors.accent, onClose: () => setNewGroup(false), onSaved: (id, name) => { setNewGroup(false); const row = inbox.getSnapshot().conversations.find(c => c.id === id) ?? { id, kind: 'group', name, contactId: null, lastMessage: null, unreadCount: 0, canSend: true }; open(row); } }), props.inboxOverlay] }) }), _jsx(ExpoMessengerCalls, { calling: calling, state: callState })] });
189
198
  }
@@ -0,0 +1,7 @@
1
+ import * as Notifications from 'expo-notifications';
2
+ export declare function notificationData(value: unknown): Record<string, unknown> | undefined;
3
+ export declare function presentedNotificationData(notification: Notifications.Notification): Record<string, unknown> | undefined;
4
+ export declare const rememberNotificationAccount: (scope: string, enabled: boolean) => Promise<void>;
5
+ export declare function notificationWasRead(value: unknown): Promise<boolean>;
6
+ export declare function dismissReadNotification(value: unknown): Promise<boolean>;
7
+ export declare function registerNotificationCleanup(): Promise<void>;
@@ -0,0 +1,96 @@
1
+ import * as Notifications from 'expo-notifications';
2
+ import * as SecureStore from 'expo-secure-store';
3
+ import * as TaskManager from 'expo-task-manager';
4
+ import { parseMessagingReadNotification, readNotificationCovers, androidMessagingNotificationData } from '@robono/messaging';
5
+ const readKey = (scope) => 'robono.messaging.notification.read.' + scope;
6
+ const task = 'robono.messaging.read-cleanup.v1', accountsKey = 'robono.messaging.notification.accounts.v1';
7
+ let queue = Promise.resolve();
8
+ const serial = (fn) => { const next = queue.then(fn, fn); queue = next.catch(() => { }); return next; };
9
+ export function notificationData(value) {
10
+ if (!value || typeof value !== 'object')
11
+ return;
12
+ const d = value;
13
+ if (typeof d.event === 'string')
14
+ return d;
15
+ for (const v of [d.body, d.dataString, d.data?.dataString, d.data, d.notification?.request?.content?.data]) {
16
+ let decoded = v;
17
+ try {
18
+ if (typeof v === 'string')
19
+ decoded = JSON.parse(v);
20
+ }
21
+ catch {
22
+ continue;
23
+ }
24
+ if (decoded && decoded !== value && typeof decoded === 'object') {
25
+ if (typeof decoded.event === 'string')
26
+ return decoded;
27
+ if (decoded.body && typeof decoded.body === 'object' && typeof decoded.body.event === 'string')
28
+ return decoded.body;
29
+ }
30
+ }
31
+ }
32
+ export function presentedNotificationData(notification) { return notificationData(notification.request.content.data) ?? androidMessagingNotificationData(notification.request.identifier); }
33
+ async function accounts() { try {
34
+ const v = JSON.parse(await SecureStore.getItemAsync(accountsKey) ?? '[]');
35
+ return Array.isArray(v) ? v.filter(x => typeof x === 'string' && /^[a-f0-9]{64}$/.test(x)) : [];
36
+ }
37
+ catch {
38
+ return [];
39
+ } }
40
+ export const rememberNotificationAccount = (scope, enabled) => serial(async () => {
41
+ const list = await accounts();
42
+ if (!enabled)
43
+ await SecureStore.deleteItemAsync(readKey(scope));
44
+ await SecureStore.setItemAsync(accountsKey, JSON.stringify(enabled ? [...new Set([...list, scope])] : list.filter(s => s !== scope)), { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY });
45
+ });
46
+ // Compact recent-read hints stay below the native secure-storage size limit.
47
+ // The authoritative foreground reconciliation covers older reads and cache misses.
48
+ async function savedReads(scope) {
49
+ try {
50
+ const data = JSON.parse(await SecureStore.getItemAsync(readKey(scope)) ?? '[]');
51
+ return Array.isArray(data) ? data.map(r => Array.isArray(r) ? { event: 'robono.messaging.read', accountScope: scope, conversationId: r[0], messageId: r[1], kind: r[2], savedAt: r[3] } : r).filter(r => parseMessagingReadNotification(r) && r.savedAt > Date.now() - 7 * 86400000) : [];
52
+ }
53
+ catch {
54
+ return [];
55
+ }
56
+ }
57
+ export async function notificationWasRead(value) {
58
+ const data = notificationData(value);
59
+ if (data?.event !== 'robono.messaging' || typeof data.accountScope !== 'string' || !/^[a-f0-9]{64}$/.test(data.accountScope))
60
+ return false;
61
+ return serial(async () => (await savedReads(data.accountScope)).some(read => readNotificationCovers(read, data)));
62
+ }
63
+ export async function dismissReadNotification(value) {
64
+ const read = parseMessagingReadNotification(notificationData(value));
65
+ if (!read)
66
+ return false;
67
+ return serial(async () => {
68
+ if (!(await accounts()).includes(read.accountScope))
69
+ return false;
70
+ const reads = await savedReads(read.accountScope), previous = reads.find(r => r.conversationId === read.conversationId && r.kind === read.kind && (read.kind !== 'message' || r.messageId === read.messageId));
71
+ const newer = !previous || read.messageId.length > previous.messageId.length || read.messageId.length === previous.messageId.length && read.messageId >= previous.messageId;
72
+ if (newer)
73
+ await SecureStore.setItemAsync(readKey(read.accountScope), JSON.stringify([...reads.filter(r => r !== previous), { ...read, savedAt: Date.now() }].slice(-16).map(r => [r.conversationId, r.messageId, r.kind, r.savedAt])), { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY });
74
+ for (const n of await Notifications.getPresentedNotificationsAsync())
75
+ if (readNotificationCovers(read, presentedNotificationData(n)))
76
+ await Notifications.dismissNotificationAsync(n.request.identifier);
77
+ return true;
78
+ });
79
+ }
80
+ // Loaded by the public Expo entry point, including headless background launches.
81
+ if (!TaskManager.isTaskDefined(task))
82
+ TaskManager.defineTask(task, async ({ data, error }) => {
83
+ if (!error) {
84
+ if (await dismissReadNotification(data))
85
+ return;
86
+ const event = notificationData(data);
87
+ if (event && await notificationWasRead(event))
88
+ for (const n of await Notifications.getPresentedNotificationsAsync()) {
89
+ const d = presentedNotificationData(n);
90
+ if (d?.accountScope === event.accountScope && d?.conversationId === event.conversationId && d?.messageId === event.messageId)
91
+ await Notifications.dismissNotificationAsync(n.request.identifier);
92
+ }
93
+ }
94
+ });
95
+ export async function registerNotificationCleanup() { if (!await TaskManager.isTaskRegisteredAsync(task))
96
+ await Notifications.registerTaskAsync(task); }
@@ -17,6 +17,7 @@ export interface ExpoMessagingNotificationOptions {
17
17
  /** One restored account. Never prompts on mount, replaces a global handler or opens an unverified call. */
18
18
  export declare function connectExpoMessagingNotifications(options: ExpoMessagingNotificationOptions): Promise<{
19
19
  ready: Promise<void>;
20
+ reconcile: () => Promise<void>;
20
21
  /** Call only after the user chooses Enable notifications in your interface. */
21
22
  enable(): Promise<boolean>;
22
23
  /** Await before revoking your login session, so the old account's token is removed. */
@@ -1,8 +1,9 @@
1
1
  import * as Notifications from 'expo-notifications';
2
2
  import * as Crypto from 'expo-crypto';
3
3
  import * as SecureStore from 'expo-secure-store';
4
- import { Platform } from 'react-native';
5
- import { createMessagingNotificationRouter, parseMessagingNotification } from '@robono/messaging';
4
+ import { Platform, AppState } from 'react-native';
5
+ import { notificationData, presentedNotificationData, dismissReadNotification, notificationWasRead, rememberNotificationAccount, registerNotificationCleanup } from './expo-notification-cleanup.js';
6
+ import { createMessagingNotificationRouter, parseMessagingNotification, parseMessagingReadNotification } from '@robono/messaging';
6
7
  /** One restored account. Never prompts on mount, replaces a global handler or opens an unverified call. */
7
8
  export async function connectExpoMessagingNotifications(options) {
8
9
  if (!['ios', 'android'].includes(Platform.OS))
@@ -31,6 +32,7 @@ export async function connectExpoMessagingNotifications(options) {
31
32
  if (status.userId !== options.userId || typeof status.accountScope !== 'string' || !/^[a-f\d]{64}$/.test(status.accountScope))
32
33
  throw Error('The notification session does not match the signed-in account.');
33
34
  accountScope = status.accountScope;
35
+ await rememberNotificationAccount(status.accountScope, true);
34
36
  const router = createMessagingNotificationRouter({ accountScope: status.accountScope, authorize: options.authorize, open: options.open, refresh: options.refresh });
35
37
  const register = (token) => {
36
38
  lastToken = token;
@@ -49,8 +51,11 @@ export async function connectExpoMessagingNotifications(options) {
49
51
  await options.systemCalls.configure(status.accountScope, () => { if (lastToken && !closing && !disposed)
50
52
  void register(lastToken).catch(options.onError); });
51
53
  const tokenListener = Notifications.addPushTokenListener(token => { void register(token).catch(options.onError); });
52
- const handle = async (data, opened = false) => { if (!data || disposed || closing)
53
- return false; if (data.accountScope === accountScope && ['calling.incoming', 'calling.dismissed', 'calling.group_incoming', 'calling.group_dismissed'].includes(String(data.event)) && options.onCall) {
54
+ const handle = async (raw, opened = false) => { const data = notificationData(raw); if (!data || disposed || closing)
55
+ return false; if (data.accountScope === accountScope && await dismissReadNotification(data)) {
56
+ await options.refresh();
57
+ return true;
58
+ } if (data.accountScope === accountScope && ['calling.incoming', 'calling.dismissed', 'calling.group_incoming', 'calling.group_dismissed'].includes(String(data.event)) && options.onCall) {
54
59
  if (String(data.event).endsWith('dismissed')) {
55
60
  const shown = await Notifications.getPresentedNotificationsAsync();
56
61
  await Promise.all(shown.filter(n => n.request.content.data?.accountScope === accountScope && n.request.content.data?.call_id === data.call_id).map(n => Notifications.dismissNotificationAsync(n.request.identifier)));
@@ -68,6 +73,22 @@ export async function connectExpoMessagingNotifications(options) {
68
73
  }
69
74
  };
70
75
  const opened = Notifications.addNotificationResponseReceivedListener(value => { void response(value).catch(options.onError); });
76
+ let reconciling;
77
+ const reconcile = () => reconciling ??= (async () => {
78
+ if (disposed || closing)
79
+ return;
80
+ const shown = (await Notifications.getPresentedNotificationsAsync()).map(n => ({ id: n.request.identifier, event: parseMessagingNotification(presentedNotificationData(n)) })).filter(n => n.event?.accountScope === accountScope);
81
+ for (let i = 0; i < shown.length; i += 100) {
82
+ const batch = shown.slice(i, i + 100), result = await request({ operation: 'notification-reconcile', messages: batch.map(n => ({ conversationId: n.event.conversationId, messageId: n.event.messageId })) });
83
+ if (disposed || closing || result.accountScope !== accountScope || !Array.isArray(result.stale))
84
+ return;
85
+ for (const n of batch)
86
+ if (result.stale.some((m) => m.conversationId === n.event.conversationId && m.messageId === n.event.messageId))
87
+ await Notifications.dismissNotificationAsync(n.id);
88
+ }
89
+ })().finally(() => { reconciling = undefined; });
90
+ const foreground = AppState.addEventListener('change', state => { if (state === 'active')
91
+ void reconcile().catch(options.onError); });
71
92
  const ready = (async () => {
72
93
  if (Platform.OS === 'android') {
73
94
  await Notifications.setNotificationChannelAsync('robono-messages', { name: 'Messages', importance: Notifications.AndroidImportance.HIGH });
@@ -76,12 +97,14 @@ export async function connectExpoMessagingNotifications(options) {
76
97
  }
77
98
  if ((await Notifications.getPermissionsAsync()).granted)
78
99
  await register(await Notifications.getDevicePushTokenAsync());
100
+ await registerNotificationCleanup();
79
101
  await response(await Notifications.getLastNotificationResponseAsync());
102
+ await reconcile();
80
103
  })();
81
104
  void ready.catch(options.onError);
82
- const dispose = () => { disposed = true; router.dispose(); tokenListener.remove(); received.remove(); opened.remove(); void options.systemCalls?.disconnect().catch(options.onError); };
105
+ const dispose = () => { disposed = true; router.dispose(); tokenListener.remove(); received.remove(); opened.remove(); foreground.remove(); void options.systemCalls?.disconnect().catch(options.onError); };
83
106
  return {
84
- ready,
107
+ ready, reconcile,
85
108
  /** Call only after the user chooses Enable notifications in your interface. */
86
109
  async enable() { if (disposed || closing)
87
110
  return false; const permission = await Notifications.requestPermissionsAsync(); if (!permission.granted)
@@ -92,7 +115,12 @@ export async function connectExpoMessagingNotifications(options) {
92
115
  await request({ operation: 'remove-device', deviceId });
93
116
  }
94
117
  finally {
95
- dispose();
118
+ try {
119
+ await rememberNotificationAccount(accountScope, false);
120
+ }
121
+ finally {
122
+ dispose();
123
+ }
96
124
  } },
97
125
  dispose,
98
126
  };
@@ -100,7 +128,9 @@ export async function connectExpoMessagingNotifications(options) {
100
128
  /** Compose with the host's existing handler. Suppress only this account's open conversation. */
101
129
  export function withMessagingNotificationPresentation(handler, current) {
102
130
  return { ...handler, handleNotification: async (notification) => {
103
- const event = parseMessagingNotification(notification.request.content.data), active = current();
131
+ const data = notificationData(notification.request.content.data), event = parseMessagingNotification(data), active = current();
132
+ if (parseMessagingReadNotification(data) || await notificationWasRead(data))
133
+ return { shouldPlaySound: false, shouldSetBadge: false, shouldShowBanner: false, shouldShowList: false };
104
134
  if (event && (event.accountScope !== active.accountScope || event.conversationId === active.conversationId))
105
135
  return { shouldPlaySound: false, shouldSetBadge: false, shouldShowBanner: false, shouldShowList: false };
106
136
  return handler.handleNotification(notification);
@@ -581,7 +581,7 @@ function ExpoMessagingScreenContent({ storage, audioSession, renderConversation,
581
581
  else {
582
582
  message.current = null;
583
583
  chosen.current = options.attachmentId;
584
- media = !options.source && !options.attachmentId && options.intent !== 'preview' && ((options.maxCount ?? 1) > 1 || options.mixedLibrary) ? await controller.pickMany(kind, options.maxCount ?? 1, options.mixedLibrary) : await controller.pick(kind, options.source, options.source === 'call-video' ? 'preview' : options.intent === 'preview' ? 'preview' : 'attach');
584
+ media = !options.source && !options.attachmentId && options.intent !== 'preview' && ((options.maxCount ?? 1) > 1 || options.mixedLibrary) ? await controller.pickMany(kind, options.maxCount ?? 1, options.mixedLibrary) : await controller.pick(kind, options.source, options.intent === 'preview' ? 'preview' : 'attach');
585
585
  }
586
586
  const selection = media ? (Array.isArray(media) ? media : [media]) : [];
587
587
  try {
package/dist/inbox.d.ts CHANGED
@@ -19,8 +19,9 @@ export interface MessagingInboxProps extends MessagingDirectoryOptions {
19
19
  searchText?: (conversation: ConversationSummary) => string;
20
20
  appearance?: MessagingAppearance;
21
21
  active?: boolean;
22
+ manageUpdates?: boolean;
22
23
  onSelect: (conversation: ConversationSummary, messageId?: string) => void;
23
24
  onDeleted?: (conversationId: string) => Promise<void> | void;
24
25
  }
25
26
  /** Compact Messenger chat rows: avatar, name, last message, time and unread badge. */
26
- export declare function MessagingInbox({ client, userId, contacts, appearance, active, onSelect, onDeleted, companyName, headerActions, searchText, selectedId, query: controlledQuery, onSearchChange, viewMemory, directory, onOpenDirectoryContact }: MessagingInboxProps): React.JSX.Element;
27
+ export declare function MessagingInbox({ client, userId, contacts, appearance, active, manageUpdates, onSelect, onDeleted, companyName, headerActions, searchText, selectedId, query: controlledQuery, onSearchChange, viewMemory, directory, onOpenDirectoryContact }: MessagingInboxProps): React.JSX.Element;
package/dist/inbox.js CHANGED
@@ -14,14 +14,15 @@ import { AppState, FlatList, Image, Platform, Pressable, ScrollView, View } from
14
14
  import { defaultMessagingSettings } from '@robono/messaging';
15
15
  import { MessagingPopup, MessagingMenuSurface, MessagingPopupHeaderBoundary, useMessagingPopupColors, messagingPopupBackdrop } from './popup.js';
16
16
  /** Compact Messenger chat rows: avatar, name, last message, time and unread badge. */
17
- export function MessagingInbox({ client, userId, contacts = {}, appearance, active = true, onSelect, onDeleted, companyName, headerActions, searchText, selectedId, query: controlledQuery, onSearchChange, viewMemory, directory = [], onOpenDirectoryContact }) {
17
+ export function MessagingInbox({ client, userId, contacts = {}, appearance, active = true, manageUpdates = true, onSelect, onDeleted, companyName, headerActions, searchText, selectedId, query: controlledQuery, onSearchChange, viewMemory, directory = [], onOpenDirectoryContact }) {
18
18
  const { text: uiText, locale: uiLocale, number: uiNumber, count: uiCount } = useRobonoLocale();
19
19
  const state = useSyncExternalStore(client.subscribe, client.getSnapshot, client.getSnapshot), design = messagingScreenAppearance(appearance ?? state.appearance ?? defaultMessagingSettings().appearance), c = messagingFriendsColors(design), friends = design.screens?.friends;
20
20
  const messagingPopupColors = useMessagingPopupColors(design, 'alerts');
21
- useEffect(() => { const update = (value) => { if (active && (value === null || value === 'active'))
21
+ useEffect(() => { if (!manageUpdates)
22
+ return; const update = (value) => { if (active && (value === null || value === 'active'))
22
23
  client.start();
23
24
  else
24
- client.stop(); }; update(AppState.currentState); const sub = AppState.addEventListener('change', update); return () => { sub.remove(); client.stop(); }; }, [client, active]);
25
+ client.stop(); }; update(AppState.currentState); const sub = AppState.addEventListener('change', update); return () => { sub.remove(); client.stop(); }; }, [client, active, manageUpdates]);
25
26
  const ownMemory = useRef(createInboxViewMemory()), memory = viewMemory ?? ownMemory.current;
26
27
  const [localQuery, setLocalQuery] = useState(memory.query);
27
28
  const query = friends?.showSearch === false ? '' : controlledQuery ?? localQuery;