Open History to see the last commit
1import { Toolbar } from "../../components/ui/Toolbar";
2import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3import * as Dialog from "../../components/ui/Dialog";
4import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
5import { createNativeStackNavigator } from "@react-navigation/native-stack";
6import {
7 EnvironmentId,
8 FILL_PREVIEW_VIEWPORT,
9 ThreadId,
10 type PreviewSessionSnapshot,
11} from "@t3tools/contracts";
12import { normalizePreviewUrl } from "@t3tools/shared/preview";
13import { useCallback, useEffect, useRef, useState } from "react";
14import { AppState, Platform, TextInput, View } from "react-native";
15import { useSafeAreaInsets } from "react-native-safe-area-context";
16
17import { ControlPill } from "../../components/ui/ControlPill";
18import { AppBar } from "../../components/ui/AppBar";
19
20import { useThreadServerBrowserTabs } from "../../state/preview";
21import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
22import { BrowserTabMenu } from "./BrowserTabMenu";
23import { browserTabTitle, browserTabUrl, latestBrowserTab } from "./browserTabs";
24import {
25 PreviewStreamWebView,
26 type PreviewPictureInPictureState,
27 type PreviewStreamRef,
28} from "./PreviewStreamWebView";
29
30const BrowserPreviewStack = createNativeStackNavigator<{ BrowserPreview: undefined }>();
31
32const NO_PICTURE_IN_PICTURE: PreviewPictureInPictureState = { supported: false, active: false };
33
34type BrowserPreviewRouteScreenProps = StaticScreenProps<{
35 readonly environmentId: string;
36 readonly threadId: string;
37 readonly tabId?: string;
38}>;
39
40/** The nested native stack supplies the navigation bar inside the modal. */
41export function BrowserPreviewRouteScreen({ route }: BrowserPreviewRouteScreenProps) {
42 const navigation = useNavigation();
43 const onClose = useCallback(() => navigation.goBack(), [navigation]);
44 return (
45 <View collapsable={false} className="flex-1 bg-sheet">
46 <BrowserPreviewStack.Navigator
47 screenOptions={{
48 headerShown: Platform.OS === "ios",
49 headerBackVisible: false,
50 headerShadowVisible: false,
51 headerTransparent: false,
52 headerTitleStyle: { fontSize: 17, fontWeight: "600" },
53 }}
54 >
55 <BrowserPreviewStack.Screen name="BrowserPreview">
56 {() => (
57 <BrowserPreviewScreen
58 environmentId={EnvironmentId.make(route.params.environmentId)}
59 threadId={ThreadId.make(route.params.threadId)}
60 initialTabId={route.params.tabId ?? null}
61 onClose={onClose}
62 />
63 )}
64 </BrowserPreviewStack.Screen>
65 </BrowserPreviewStack.Navigator>
66 </View>
67 );
68}
69
70function BrowserPreviewScreen({
71 environmentId,
72 threadId,
73 initialTabId,
74 onClose,
75}: {
76 readonly environmentId: EnvironmentId;
77 readonly threadId: ThreadId;
78 readonly initialTabId: string | null;
79 readonly onClose: () => void;
80}) {
81 const insets = useSafeAreaInsets();
82 const { themeVariables } = useAppearancePreferences();
83 const focused = useIsFocused();
84 const [foreground, setForeground] = useState(AppState.currentState !== "background");
85 const [selectedTabId, setSelectedTabId] = useState(initialTabId);
86 const [pictureInPicture, setPictureInPicture] = useState(NO_PICTURE_IN_PICTURE);
87 // Address bar commands only reach a page that is streaming.
88 const [streaming, setStreaming] = useState(false);
89 const [canControl, setCanControl] = useState(false);
90 const streamRef = useRef<PreviewStreamRef>(null);
91 const { tabs, loaded } = useThreadServerBrowserTabs({ environmentId, threadId, enabled: true });
92 const tab = tabs.find((entry) => entry.tabId === selectedTabId) ?? latestBrowserTab(tabs);
93 const tabId = tab?.tabId ?? null;
94 // Pin the fallback so another tab's activity does not switch the view.
95 if (tabId !== null && tabId !== selectedTabId) {
96 setPictureInPicture(NO_PICTURE_IN_PICTURE);
97 setSelectedTabId(tabId);
98 }
99 useEffect(() => {
100 const subscription = AppState.addEventListener("change", (state) =>
101 setForeground(state !== "background"),
102 );
103 return () => subscription.remove();
104 }, []);
105 useEffect(() => {
106 if (focused && loaded && tabs.length === 0) onClose();
107 }, [focused, loaded, tabs.length, onClose]);
108 const onPictureInPicture = useCallback((state: PreviewPictureInPictureState, detail?: string) => {
109 setPictureInPicture({ supported: state.supported, active: state.active });
110 if (detail) Dialog.alert("Picture in picture is unavailable", detail);
111 }, []);
112 const selectTab = (next: string) => {
113 setPictureInPicture(NO_PICTURE_IN_PICTURE);
114 setSelectedTabId(next);
115 };
116 // System picture in picture keeps showing this stream after the app leaves the foreground.
117 const live = (focused && foreground) || pictureInPicture.active;
118
119 return (
120 <View className="flex-1 bg-sheet" style={{ paddingBottom: insets.bottom }}>
121 <AppBar
122 title={tab ? browserTabTitle(tab) : "Browser"}
123 sidebar={false}
124 onBack={onClose}
125 options={{ headerBackVisible: false }}
126 actions={
127 // Android WebView cannot play video in picture in picture.
128 Platform.OS === "ios" && pictureInPicture.supported
129 ? [
130 {
131 accessibilityLabel: pictureInPicture.active
132 ? "Exit picture in picture"
133 : "Picture in picture",
134 icon: {
135 ios: pictureInPicture.active ? "pip.exit" : "pip.enter",
136 android: "visibility",
137 },
138 selected: pictureInPicture.active,
139 onPress: () => streamRef.current?.togglePictureInPicture(),
140 },
141 ]
142 : []
143 }
144 menus={
145 tabs.length > 1
146 ? [
147 {
148 title: "Tabs",
149 icon: "square.on.square",
150 items: tabs.map((entry) => ({
151 id: entry.tabId,
152 title: browserTabTitle(entry),
153 subtitle: browserTabUrl(entry),
154 selected: entry.tabId === tabId,
155 onPress: () => selectTab(entry.tabId),
156 })),
157 },
158 ]
159 : []
160 }
161 />
162 {Platform.OS === "ios" ? (
163 <Toolbar placement="left">
164 <Toolbar.Button
165 icon="xmark"
166 accessibilityLabel="Close browser"
167 onPress={onClose}
168 separateBackground
169 />
170 </Toolbar>
171 ) : null}
172 {tab ? (
173 <>
174 <BrowserAddressBar
175 key={`address:${tab.tabId}`}
176 environmentId={environmentId}
177 tab={tab}
178 streaming={streaming}
179 ready={streaming && canControl}
180 onCommand={(input) => streamRef.current?.command(input)}
181 />
182 {live ? (
183 <PreviewStreamWebView
184 key={`stream:${tab.tabId}`}
185 environmentId={environmentId}
186 threadId={threadId}
187 tabId={tab.tabId}
188 ref={streamRef}
189 interactive
190 background={themeVariables["--color-sheet-solid"]}
191 onPictureInPicture={onPictureInPicture}
192 onStreamingChange={setStreaming}
193 onControl={(control) => setCanControl(control?.controller === "you")}
194 />
195 ) : (
196 <View className="flex-1" />
197 )}
198 </>
199 ) : (
200 <View className="flex-1 items-center justify-center">
201 {focused && foreground ? (
202 <AppActivityIndicator color={themeVariables["--color-icon"]} />
203 ) : null}
204 </View>
205 )}
206 </View>
207 );
208}
209
210function BrowserAddressBar({
211 environmentId,
212 tab,
213 ready,
214 streaming,
215 onCommand,
216}: {
217 readonly environmentId: EnvironmentId;
218 readonly tab: PreviewSessionSnapshot;
219 /** The viewer controls the page, so navigation and reload apply. */
220 readonly ready: boolean;
221 /** The menu's changes need no control, only a live tab. */
222 readonly streaming: boolean;
223 readonly onCommand: PreviewStreamRef["command"];
224}) {
225 const url = browserTabUrl(tab);
226 // Null while not editing, so agent navigation keeps the field current.
227 const [draft, setDraft] = useState<string | null>(null);
228 const submit = () => {
229 const value = draft ?? url;
230 setDraft(null);
231 try {
232 onCommand({ type: "navigate", url: normalizePreviewUrl(value) });
233 } catch {
234 Dialog.alert("Could not open this address", "Enter an http or https URL.");
235 }
236 };
237 return (
238 <View className="flex-row items-center gap-1 px-2 pb-2">
239 <ControlPill
240 icon="chevron.left"
241 accessibilityLabel="Back"
242 disabled={!ready || !tab.canGoBack}
243 onPress={() => onCommand({ type: "history", delta: -1 })}
244 />
245 <ControlPill
246 icon="chevron.right"
247 accessibilityLabel="Forward"
248 disabled={!ready || !tab.canGoForward}
249 onPress={() => onCommand({ type: "history", delta: 1 })}
250 />
251 <TextInput
252 accessibilityLabel="Address"
253 editable={ready}
254 value={draft ?? url}
255 onChangeText={setDraft}
256 onBlur={() => setDraft(null)}
257 onSubmitEditing={submit}
258 placeholder="Enter a URL"
259 placeholderTextColorClassName="accent-placeholder"
260 autoCapitalize="none"
261 autoCorrect={false}
262 keyboardType="url"
263 returnKeyType="go"
264 selectTextOnFocus
265 className="h-10 min-w-0 flex-1 rounded-full border border-input-border bg-input px-4 font-sans text-sm text-foreground"
266 />
267 <ControlPill
268 icon="arrow.clockwise"
269 accessibilityLabel="Reload page"
270 disabled={!ready}
271 onPress={() => onCommand({ type: "reload" })}
272 />
273 <BrowserTabMenu environmentId={environmentId} tab={tab} disabled={!streaming} />
274 </View>
275 );
276}