@openpeepshq/rn-components 0.13.0 → 0.13.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/rn-components",
3
- "version": "0.13.0",
3
+ "version": "0.13.1",
4
4
  "description": "React Native community screens and shared UI (extracted from the Black Ambition app) for the OpenPeeps stack.",
5
5
  "source": "./src/index.ts",
6
6
  "main": "./src/index.ts",
@@ -142,8 +142,8 @@
142
142
  "timezones-list": "^3.1.0",
143
143
  "validator": "^13.15.23",
144
144
  "zustand": "^5.0.3",
145
- "@openpeepshq/common": "^0.7.0",
146
- "@openpeepshq/react": "^0.13.0"
145
+ "@openpeepshq/react": "^0.14.1",
146
+ "@openpeepshq/common": "^0.8.0"
147
147
  },
148
148
  "devDependencies": {
149
149
  "@babel/core": "^7.26.7",
@@ -4,8 +4,9 @@ import {
4
4
  useLocalParticipant,
5
5
  useRoomContext,
6
6
  } from '@livekit/react-native';
7
- import { Room, RoomEvent } from 'livekit-client';
7
+ import { MediaDeviceFailure, Room, RoomEvent } from 'livekit-client';
8
8
  import { useTranslation } from 'react-i18next';
9
+ import Toast from 'react-native-toast-message';
9
10
  import {
10
11
  CheckIcon,
11
12
  MicIcon,
@@ -20,6 +21,21 @@ import { DropdownMenuItem } from '../ui/dropdown-menu';
20
21
  import { ThemedText } from '../ui/themed-text';
21
22
  import { JamToolbarButton, toneIconClass } from './JamToolbarButton';
22
23
 
24
+ /**
25
+ * Fire-and-forget failure flows (mic toggle, permission probes) can race and
26
+ * stack duplicate toasts for a single rejection; deduplicate through a
27
+ * module-level in-flight guard.
28
+ */
29
+ let micToastInFlight = false;
30
+ const showMicToast = (msg: string) => {
31
+ if (micToastInFlight) return;
32
+ micToastInFlight = true;
33
+ Toast.show({ type: 'error', text1: msg });
34
+ setTimeout(() => {
35
+ micToastInFlight = false;
36
+ }, 3000);
37
+ };
38
+
23
39
  type DeviceType = 'mic' | 'camera' | 'speaker';
24
40
  export type JamIconType = ReturnType<typeof iconWithClassName>;
25
41
 
@@ -162,15 +178,27 @@ export const useAudioOutputs = () => {
162
178
 
163
179
  /** In-room microphone control. Native exposes no selectable mic list. */
164
180
  export const JamMicSelector = () => {
181
+ const { t } = useTranslation();
165
182
  const { localParticipant, isMicrophoneEnabled } = useLocalParticipant();
166
183
 
167
184
  return (
168
185
  <DeviceSelectorPill
169
186
  enabled={isMicrophoneEnabled}
170
187
  onToggle={() =>
171
- void localParticipant
188
+ localParticipant
172
189
  .setMicrophoneEnabled(!isMicrophoneEnabled)
173
- .catch(() => undefined)
190
+ .catch((err: unknown) => {
191
+ // Surface mic-enable failures to the user instead of swallowing them.
192
+ console.warn('[jams:mic] setMicrophoneEnabled failed', err);
193
+ const denied =
194
+ MediaDeviceFailure.getFailure(err) ===
195
+ MediaDeviceFailure.PermissionDenied;
196
+ showMicToast(
197
+ denied
198
+ ? t('jams.mic.lobbyProbeFailed')
199
+ : t('jams.mic.enableFailed')
200
+ );
201
+ })
174
202
  }
175
203
  onIcon={MicIcon}
176
204
  offIcon={MicOffIcon}
@@ -1,7 +1,18 @@
1
- import React, { useEffect, useState } from 'react';
2
- import { Pressable, StyleSheet, View } from 'react-native';
1
+ import React, { useCallback, useEffect, useRef, useState } from 'react';
2
+ import {
3
+ Alert,
4
+ AppState,
5
+ Linking,
6
+ Pressable,
7
+ StyleSheet,
8
+ View,
9
+ } from 'react-native';
3
10
  import { VideoView, useRoomContext } from '@livekit/react-native';
4
- import { createLocalVideoTrack, type LocalVideoTrack } from 'livekit-client';
11
+ import {
12
+ createLocalAudioTrack,
13
+ createLocalVideoTrack,
14
+ type LocalVideoTrack,
15
+ } from 'livekit-client';
5
16
  import { useTranslation } from 'react-i18next';
6
17
  import {
7
18
  type JamJoinParams,
@@ -69,6 +80,9 @@ const usePreviewTrack = (
69
80
  * authenticated users get a device-selection card: a centered card with a
70
81
  * square camera preview, mic/speaker/camera controls, and a join button.
71
82
  * Background blur is web-only (no track processor on React Native).
83
+ *
84
+ * When audio is enabled, a transient one-shot probe verifies mic access
85
+ * before the user joins (iOS permission prompt appears here, not mid-join).
72
86
  */
73
87
  export const JamLobby = ({ onJoin }: JamLobbyProps) => {
74
88
  const { t } = useTranslation();
@@ -86,7 +100,7 @@ export const JamLobby = ({ onJoin }: JamLobbyProps) => {
86
100
 
87
101
  const [settings, updateSettings] = useJamLocalSettings();
88
102
 
89
- const [audioEnabled, setAudioEnabled] = useState(true);
103
+ const [audioEnabled, setAudioEnabled] = useState(settings.micEnabled);
90
104
  const [videoEnabled, setVideoEnabled] = useState(false);
91
105
  const [videoDeviceId, setVideoDeviceId] = useState('');
92
106
  const { devices: videoDevices } = useCameraDevices(useRoomContext());
@@ -94,6 +108,91 @@ export const JamLobby = ({ onJoin }: JamLobbyProps) => {
94
108
 
95
109
  const videoTrack = usePreviewTrack(videoEnabled, videoDeviceId, setError);
96
110
 
111
+ // Probe mic access when audio is enabled (mount and toggle-on). One alert per
112
+ // visit: a denied probe is remembered so every later probe only clears the
113
+ // stale error message instead of re-popping the alert.
114
+ const probingRef = useRef(false);
115
+ const probeRearmRef = useRef(false);
116
+ const permissionDeniedRef = useRef(false);
117
+ const probeMic = useCallback(
118
+ async (enabled: boolean) => {
119
+ if (!enabled || probingRef.current) return;
120
+ probingRef.current = true;
121
+ try {
122
+ const track = await createLocalAudioTrack();
123
+ track.stop();
124
+ setError(undefined);
125
+ } catch (err: unknown) {
126
+ console.warn('[jams:mic] lobby probe failed', err);
127
+ const denied =
128
+ err instanceof Error &&
129
+ (err.name === 'NotAllowedError' ||
130
+ err.name === 'PermissionDeniedError');
131
+ const firstDenial = denied && !permissionDeniedRef.current;
132
+ if (firstDenial) {
133
+ permissionDeniedRef.current = true;
134
+ }
135
+ setError(
136
+ denied ? t('jams.mic.lobbyProbeFailed') : t('jams.mic.enableFailed')
137
+ );
138
+ if (firstDenial) {
139
+ Alert.alert(
140
+ t('jams.mic.permissionTitle'),
141
+ t('jams.mic.permissionMessage'),
142
+ [
143
+ { text: t('common.actions.cancel'), style: 'cancel' },
144
+ {
145
+ text: t('media.permissions.openSettings'),
146
+ onPress: () => void Linking.openSettings(),
147
+ },
148
+ ]
149
+ );
150
+ }
151
+ } finally {
152
+ probingRef.current = false;
153
+ // A toggle-on during this probe re-arms it: run once more so the
154
+ // final "on" state is the one actually probed.
155
+ if (probeRearmRef.current) {
156
+ probeRearmRef.current = false;
157
+ void probeMic(true);
158
+ }
159
+ }
160
+ },
161
+ [t, setError]
162
+ );
163
+
164
+ useEffect(() => {
165
+ // Gate inside the effect: React runs effects even when the guest form is
166
+ // returned, so guests must not get an iOS mic prompt (review #2155).
167
+ if (!canAccess) return;
168
+ void probeMic(audioEnabled);
169
+ }, [canAccess, audioEnabled, probeMic]);
170
+
171
+ // After returning from Settings, `permissionDeniedRef` may still hold a stale
172
+ // denial: probe again on foreground (with the guard cleared) so a granted
173
+ // permission clears the error banner instead of leaving a stale message.
174
+ const appState = useRef(AppState.currentState);
175
+ useEffect(() => {
176
+ if (!audioEnabled || !canAccess) return;
177
+ const sub = AppState.addEventListener('change', (state) => {
178
+ if (appState.current.match(/inactive|background/) && state === 'active') {
179
+ permissionDeniedRef.current = false;
180
+ void probeMic(audioEnabled);
181
+ }
182
+ appState.current = state;
183
+ });
184
+ return () => sub.remove();
185
+ }, [canAccess, audioEnabled, probeMic]);
186
+
187
+ const handleAudioToggle = useCallback(() => {
188
+ const next = !audioEnabled;
189
+ setAudioEnabled(next);
190
+ updateSettings({ micEnabled: next });
191
+ // Re-arm only while a probe is in flight: otherwise the queued probe from
192
+ // the audioEnabled change already covers the final "on" state.
193
+ if (next && probingRef.current) probeRearmRef.current = true;
194
+ }, [audioEnabled, updateSettings]);
195
+
97
196
  if (!canAccess) {
98
197
  return <JamGuestForm />;
99
198
  }
@@ -148,7 +247,7 @@ export const JamLobby = ({ onJoin }: JamLobbyProps) => {
148
247
  <View className="mt-4 w-full flex-row items-center justify-center gap-x-4">
149
248
  <DeviceSelectorPill
150
249
  enabled={audioEnabled}
151
- onToggle={() => setAudioEnabled((on) => !on)}
250
+ onToggle={handleAudioToggle}
152
251
  onIcon={MicIcon}
153
252
  offIcon={MicOffIcon}
154
253
  deviceType="mic"
@@ -1,6 +1,10 @@
1
- import React, { useEffect } from 'react';
1
+ import React, { useCallback, useEffect, useRef } from 'react';
2
+ import { Alert, Linking, Platform } from 'react-native';
2
3
  import { AudioSession, useRoomContext } from '@livekit/react-native';
3
4
  import type { DisconnectReason } from 'livekit-client';
5
+ import { MediaDeviceFailure } from 'livekit-client';
6
+ import Toast from 'react-native-toast-message';
7
+ import { useTranslation } from 'react-i18next';
4
8
  import { useStableLiveKitRoom } from '../../lib/livekit/useStableLiveKitRoom';
5
9
  import { JamConference } from './JamConference';
6
10
 
@@ -14,6 +18,43 @@ export interface JamVideoCallProps {
14
18
  onDisconnected?: (reason?: DisconnectReason) => void;
15
19
  }
16
20
 
21
+ const openSettings = () => {
22
+ void Linking.openSettings();
23
+ };
24
+
25
+ /**
26
+ * `Alert.alert` cannot be re-triggered while the same alert is already
27
+ * showing; fire-and-forget toast/permission flows can race on both platforms
28
+ * (dual toasts for one failure, or a rejected alert promise). Deduplicate
29
+ * through a module-level in-flight guard so a burst of failures surfaces one
30
+ * message instead of stacking toasts.
31
+ */
32
+ let micToastInFlight = false;
33
+ const showMicToast = (msg: string) => {
34
+ if (micToastInFlight) return;
35
+ micToastInFlight = true;
36
+ Toast.show({ type: 'error', text1: msg });
37
+ setTimeout(() => {
38
+ micToastInFlight = false;
39
+ }, 3000);
40
+ };
41
+
42
+ /**
43
+ * LiveKit can emit several failure events for one rejection; coalesce them
44
+ * into a single permission alert with a short cooldown, and swallow the
45
+ * "alert already presented" throw that iOS raises for overlaps.
46
+ */
47
+ let lastMicAlertAt = 0;
48
+ const showMicPermissionAlertModule = (alert: () => void) => {
49
+ if (Date.now() - lastMicAlertAt < 8000) return;
50
+ lastMicAlertAt = Date.now();
51
+ try {
52
+ alert();
53
+ } catch {
54
+ // An identical alert is already on screen.
55
+ }
56
+ };
57
+
17
58
  /**
18
59
  * Connects the app-level LiveKit `Room` (provided by the host via
19
60
  * `RoomContext.Provider`) and renders {@link JamConference}. The room object is
@@ -27,15 +68,108 @@ export const JamVideoCall = ({
27
68
  video = true,
28
69
  onDisconnected,
29
70
  }: JamVideoCallProps) => {
71
+ const { t } = useTranslation();
30
72
  const room = useRoomContext();
31
73
 
74
+ // Session is a hard failure on iPad (#2108): iOS will not capture mic audio
75
+ // without an active audio session, so configure and start it on iOS before
76
+ // connect. Android gains nothing from the iOS-only
77
+ // `setAppleAudioConfiguration` — configuring Apple audio there rejects and
78
+ // previously aborted the whole setup — so the session is skipped there
79
+ // entirely (the native module starts its own session on first use).
80
+ const audioSessionReady = useRef(false);
32
81
  useEffect(() => {
33
- void AudioSession.startAudioSession();
82
+ if (Platform.OS !== 'ios') return;
83
+ void (async () => {
84
+ try {
85
+ await AudioSession.setAppleAudioConfiguration({
86
+ audioCategory: 'playAndRecord',
87
+ audioCategoryOptions: ['defaultToSpeaker', 'allowBluetooth'],
88
+ audioMode: 'videoChat',
89
+ });
90
+ await AudioSession.startAudioSession();
91
+ audioSessionReady.current = true;
92
+ } catch (err: unknown) {
93
+ // Non-fatal: connect still proceeds, but iOS capture stays silent
94
+ // until the SignalConnected retry below re-arms the session.
95
+ console.warn('[jams:mic] AudioSession setup failed', err);
96
+ }
97
+ })();
34
98
  return () => {
99
+ audioSessionReady.current = false;
35
100
  void AudioSession.stopAudioSession();
36
101
  };
37
102
  }, []);
38
103
 
104
+ // One permission alert at a time: LiveKit can emit several failure events
105
+ // (SignalConnected + MediaDevicesError) for the same rejection, and
106
+ // `Alert.alert` throws when the identical alert is already visible.
107
+ const showMicPermissionAlert = useCallback(() => {
108
+ showMicPermissionAlertModule(() =>
109
+ Alert.alert(
110
+ t('jams.mic.permissionTitle'),
111
+ t('jams.mic.permissionMessage'),
112
+ [
113
+ { text: t('common.actions.cancel'), style: 'cancel' },
114
+ { text: t('media.permissions.openSettings'), onPress: openSettings },
115
+ ]
116
+ )
117
+ );
118
+ }, [t]);
119
+
120
+ // Surface room-level mic failures. `onError` is NOT mic-specific — the same
121
+ // callback also fires for camera-enable rejections and connect failures —
122
+ // so gate the mic copy on a real device denial: only "permission denied"
123
+ // (which here can only come from a mic/camera capture rejection) shows
124
+ // mic-specific copy plus the settings alert; everything else is logged and
125
+ // left to the generic paths that carry the failure `kind`.
126
+ const handleError = useCallback(
127
+ (error: Error) => {
128
+ const denied =
129
+ MediaDeviceFailure.getFailure(error) ===
130
+ MediaDeviceFailure.PermissionDenied;
131
+ if (!denied) {
132
+ console.warn(
133
+ '[jams:mic] non-permission failure (not mic-gated)',
134
+ error
135
+ );
136
+ return;
137
+ }
138
+ console.warn('[jams:mic] mic permission denied', error);
139
+ showMicToast(t('jams.mic.lobbyProbeFailed'));
140
+ showMicPermissionAlert();
141
+ },
142
+ [t, showMicPermissionAlert]
143
+ );
144
+
145
+ // `kind` disambiguates the device source; only genuine mic failures get
146
+ // mic copy here (short copy in the toast, long copy in the settings alert).
147
+ const handleMediaDeviceFailure = useCallback(
148
+ (
149
+ failure?: ReturnType<typeof MediaDeviceFailure.getFailure>,
150
+ kind?: string
151
+ ) => {
152
+ if (kind !== 'audioinput') return;
153
+ console.warn('[jams:mic] media device failure', kind, failure);
154
+ showMicToast(
155
+ failure === MediaDeviceFailure.PermissionDenied
156
+ ? t('jams.mic.lobbyProbeFailed')
157
+ : t('jams.mic.enableFailed')
158
+ );
159
+ if (failure === MediaDeviceFailure.PermissionDenied) {
160
+ showMicPermissionAlert();
161
+ }
162
+ },
163
+ [t, showMicPermissionAlert]
164
+ );
165
+
166
+ const handleDisconnected = useCallback(
167
+ (reason?: DisconnectReason) => {
168
+ onDisconnected?.(reason);
169
+ },
170
+ [onDisconnected]
171
+ );
172
+
39
173
  useStableLiveKitRoom(room, {
40
174
  token,
41
175
  serverUrl,
@@ -43,7 +177,27 @@ export const JamVideoCall = ({
43
177
  audio,
44
178
  video,
45
179
  screen: false,
46
- onDisconnected,
180
+ onError: handleError,
181
+ onMediaDeviceFailure: handleMediaDeviceFailure,
182
+ onDisconnected: handleDisconnected,
183
+ onSignalConnected: async () => {
184
+ // iOS capture is silent without an active session; if the pre-connect
185
+ // setup was skipped (Android) or failed, re-arm it right before the
186
+ // mic is enabled so the first attempt is not a guaranteed loss.
187
+ if (Platform.OS === 'ios' && !audioSessionReady.current) {
188
+ try {
189
+ await AudioSession.setAppleAudioConfiguration({
190
+ audioCategory: 'playAndRecord',
191
+ audioCategoryOptions: ['defaultToSpeaker', 'allowBluetooth'],
192
+ audioMode: 'videoChat',
193
+ });
194
+ await AudioSession.startAudioSession();
195
+ audioSessionReady.current = true;
196
+ } catch (err: unknown) {
197
+ console.warn('[jams:mic] AudioSession retry failed', err);
198
+ }
199
+ }
200
+ },
47
201
  });
48
202
 
49
203
  return <JamConference />;
@@ -2,6 +2,7 @@ import React, { type ReactNode } from 'react';
2
2
  import { Pressable, ScrollView, StyleSheet, View } from 'react-native';
3
3
  import {
4
4
  isTrackReference,
5
+ type TrackReference,
5
6
  type TrackReferenceOrPlaceholder,
6
7
  useParticipants,
7
8
  useRoomContext,
@@ -19,6 +20,7 @@ import {
19
20
  import { ThemedText } from '../ui/themed-text';
20
21
  import { AvatarWithName } from '../profile/AvatarWithName';
21
22
  import { JamCallParticipant } from './JamCallParticipant';
23
+ import { useLateTrackMediaStream } from './useLateTrackMediaStream';
22
24
 
23
25
  export interface JamVideoLayoutProps {
24
26
  /** One camera track reference (or placeholder) per participant. */
@@ -182,6 +184,10 @@ const ScreenSharingLayout = ({
182
184
  const profile = parseParticipantMetadata(
183
185
  screenShareTrack.participant.metadata
184
186
  ).profile;
187
+ const videoTrack = isTrackReference(screenShareTrack)
188
+ ? screenShareTrack.publication.track
189
+ : undefined;
190
+ const mediaStreamEpoch = useLateTrackMediaStream(videoTrack);
185
191
 
186
192
  return (
187
193
  <View className="size-full gap-2">
@@ -191,9 +197,10 @@ const ScreenSharingLayout = ({
191
197
  <ThemedText>{t('jams.screenShare.presenting')}</ThemedText>
192
198
  </View>
193
199
  <View className="relative min-h-0 w-full flex-1 overflow-hidden rounded-xl border border-border">
194
- {isTrackReference(screenShareTrack) ? (
200
+ {videoTrack ? (
195
201
  <VideoTrack
196
- trackRef={screenShareTrack}
202
+ key={`${videoTrack.sid}-${mediaStreamEpoch}`}
203
+ trackRef={screenShareTrack as TrackReference}
197
204
  style={StyleSheet.absoluteFill}
198
205
  objectFit="contain"
199
206
  />
@@ -0,0 +1,145 @@
1
+ /**
2
+ * useLateTrackMediaStream: reports how many video tracks the track's media
3
+ * stream currently has, and re-reports each time that count rises — both on
4
+ * `addtrack` events and while the post-mount poll is still running. That is
5
+ * what lets the screen-share VideoTrack remount — and its native view
6
+ * re-resolve — once a share that started after we joined delivers its video
7
+ * track, including the first share where `addtrack` fires before the layout
8
+ * is mounted.
9
+ */
10
+ import React, { act } from 'react';
11
+ import TestRenderer from 'react-test-renderer';
12
+ import { useLateTrackMediaStream } from './useLateTrackMediaStream';
13
+
14
+ // Minimal stand-in for the webrtc MediaStream surface the hook touches.
15
+ const makeMediaStream = (initialVideoTracks = 0) => {
16
+ const videoTracks: unknown[] = Array.from({ length: initialVideoTracks });
17
+ const listeners: Array<() => void> = [];
18
+ return {
19
+ getVideoTracks: () => videoTracks,
20
+ addEventListener: (_type: string, listener: () => void) =>
21
+ listeners.push(listener),
22
+ removeEventListener: (_type: string, listener: () => void) => {
23
+ const index = listeners.indexOf(listener);
24
+ if (index !== -1) listeners.splice(index, 1);
25
+ },
26
+ // Test helper, not part of the real MediaStream API.
27
+ addVideoTrack() {
28
+ videoTracks.push({});
29
+ listeners.forEach((listener) => listener());
30
+ },
31
+ };
32
+ };
33
+
34
+ type Stream = ReturnType<typeof makeMediaStream>;
35
+
36
+ type TrackLike = { mediaStream?: Stream };
37
+
38
+ const renderHook = (initial: TrackLike | undefined) => {
39
+ let track = initial;
40
+ const captured: number[] = [];
41
+ const Probe = () => {
42
+ captured[0] = useLateTrackMediaStream(
43
+ track as unknown as Parameters<typeof useLateTrackMediaStream>[0]
44
+ );
45
+ return null;
46
+ };
47
+ let renderer!: TestRenderer.ReactTestRenderer;
48
+ act(() => {
49
+ renderer = TestRenderer.create(React.createElement(Probe));
50
+ });
51
+ return {
52
+ get current() {
53
+ return captured[0];
54
+ },
55
+ rerender(next: TrackLike | undefined) {
56
+ track = next;
57
+ act(() => {
58
+ renderer.update(React.createElement(Probe));
59
+ });
60
+ },
61
+ unmount() {
62
+ act(() => {
63
+ renderer.unmount();
64
+ });
65
+ },
66
+ };
67
+ };
68
+
69
+ describe('useLateTrackMediaStream', () => {
70
+ it('reports zero when there is no track or stream', () => {
71
+ const hook = renderHook(undefined);
72
+ expect(hook.current).toBe(0);
73
+ hook.unmount();
74
+ });
75
+
76
+ it('reports the existing video track count on first render', () => {
77
+ const hook = renderHook({ mediaStream: makeMediaStream(1) });
78
+ expect(hook.current).toBe(1);
79
+ hook.unmount();
80
+ });
81
+
82
+ it('increments when the stream gains a video track late', () => {
83
+ const stream = makeMediaStream(0);
84
+ const hook = renderHook({ mediaStream: stream });
85
+ expect(hook.current).toBe(0);
86
+
87
+ act(() => {
88
+ stream.addVideoTrack();
89
+ });
90
+ expect(hook.current).toBe(1);
91
+ hook.unmount();
92
+ });
93
+
94
+ it('picks up the video track via the poll when no addtrack listener saw it', () => {
95
+ jest.useFakeTimers();
96
+ try {
97
+ const stream = makeMediaStream(0);
98
+ const hook = renderHook({ mediaStream: stream });
99
+ expect(hook.current).toBe(0);
100
+
101
+ // Simulate the first-share race: the track is added while the layout is
102
+ // not yet mounted, so no `addtrack` listener receives an event.
103
+ stream.getVideoTracks().push({});
104
+ act(() => {
105
+ jest.advanceTimersByTime(150);
106
+ });
107
+ expect(hook.current).toBe(1);
108
+ hook.unmount();
109
+ } finally {
110
+ jest.useRealTimers();
111
+ }
112
+ });
113
+
114
+ it('follows the current stream when the track changes', () => {
115
+ jest.useFakeTimers();
116
+ try {
117
+ const first = makeMediaStream(0);
118
+ const second = makeMediaStream(1);
119
+ const hook = renderHook({ mediaStream: first });
120
+ expect(hook.current).toBe(0);
121
+
122
+ act(() => {
123
+ first.addVideoTrack();
124
+ });
125
+ expect(hook.current).toBe(1);
126
+
127
+ hook.rerender({ mediaStream: second });
128
+ expect(hook.current).toBe(1);
129
+
130
+ // The old stream no longer drives the value.
131
+ act(() => {
132
+ first.addVideoTrack();
133
+ });
134
+ expect(hook.current).toBe(1);
135
+
136
+ act(() => {
137
+ second.addVideoTrack();
138
+ });
139
+ expect(hook.current).toBe(2);
140
+ hook.unmount();
141
+ } finally {
142
+ jest.useRealTimers();
143
+ }
144
+ });
145
+ });
@@ -0,0 +1,61 @@
1
+ import { useEffect, useState } from 'react';
2
+ import type { Track } from 'livekit-client';
3
+ import type { MediaStream } from '@livekit/react-native-webrtc';
4
+
5
+ // The RN runtime mediaStream is the @livekit/react-native-webrtc MediaStream,
6
+ // even though livekit-client's web types annotate it as the DOM MediaStream.
7
+ const asWebRtcStream = (track?: Track): MediaStream | undefined =>
8
+ track?.mediaStream as MediaStream | undefined;
9
+
10
+ /**
11
+ * The number of video tracks on the track's media stream, kept in sync with
12
+ * `addtrack` events plus a short post-mount poll.
13
+ *
14
+ * A screen share that starts after we have joined is attached to the native
15
+ * `RTCView` by a one-time `streamURL` lookup of the stream's video track. When
16
+ * that lookup runs before the stream carries its video track, iOS gives up (no
17
+ * retry) and the tile stays black until we leave and rejoin. Re-keying the
18
+ * `VideoTrack` with this count remounts the native view once the stream gains
19
+ * its video track, giving the lookup a second chance when it can succeed.
20
+ *
21
+ * The poll is not redundant with the `addtrack` listener: on the first share,
22
+ * `addtrack` fires inside the native SDP-apply batch, before the room re-emits
23
+ * the publication that mounts this layout — so the event can fire before the
24
+ * listener exists.
25
+ *
26
+ * Camera tiles don't need this: they remount on the track object itself
27
+ * (see `JamCallParticipant`), which is a different (renegotiation) case.
28
+ */
29
+ export const useLateTrackMediaStream = (track?: Track) => {
30
+ const mediaStream = asWebRtcStream(track);
31
+ const [videoTrackCount, setVideoTrackCount] = useState(
32
+ () => asWebRtcStream(track)?.getVideoTracks().length ?? 0
33
+ );
34
+
35
+ useEffect(() => {
36
+ if (!mediaStream) {
37
+ setVideoTrackCount(0);
38
+ return;
39
+ }
40
+ const refresh = () =>
41
+ setVideoTrackCount(mediaStream.getVideoTracks().length);
42
+ refresh();
43
+ // 20 x 150 ms (~3 s) covers the first-share negotiation window; stop as
44
+ // soon as the stream carries its track so an already-attached share
45
+ // causes no further remounts.
46
+ let attempts = 0;
47
+ const timer = setInterval(() => {
48
+ refresh();
49
+ if (mediaStream.getVideoTracks().length > 0 || ++attempts >= 20) {
50
+ clearInterval(timer);
51
+ }
52
+ }, 150);
53
+ mediaStream.addEventListener('addtrack', refresh);
54
+ return () => {
55
+ clearInterval(timer);
56
+ mediaStream.removeEventListener('addtrack', refresh);
57
+ };
58
+ }, [mediaStream]);
59
+
60
+ return videoTrackCount;
61
+ };