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