Open History to see the last commit
1import { SheetHeader } from "../../components/ui/SheetHeader";
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 { EnvironmentId, ThreadId, type PreviewSessionSnapshot } from "@t3tools/contracts";
7import { normalizePreviewUrl, previewPdfAssetUrl } from "@t3tools/shared/preview";
8import * as Option from "effect/Option";
9import { useEffect, useRef, useState } from "react";
10import { Platform, TextInput, View } from "react-native";
11import { useSafeAreaInsets } from "react-native-safe-area-context";
12
13import { ControlPill } from "../../components/ui/ControlPill";
14import { useAppForeground } from "../../lib/appState";
15import { AppBar } from "../../components/ui/AppBar";
16
17import { useThreadServerBrowserTabs } from "../../state/preview";
18import { usePreparedConnection } from "../../state/session";
19import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
20import { BrowserTabMenu } from "./BrowserTabMenu";
21import { browserTabTitle, browserTabUrl, latestBrowserTab } from "./browserTabs";
22import {
23 PreviewStreamWebView,
24 type PreviewPictureInPictureState,
25 type PreviewStreamRef,
26} from "./PreviewStreamWebView";
27
28const BrowserPreviewStack = createNativeStackNavigator<{ BrowserPreview: undefined }>();
29
30const NO_PICTURE_IN_PICTURE: PreviewPictureInPictureState = { supported: false, active: false };
31
32type BrowserPreviewRouteScreenProps = StaticScreenProps<{
33 readonly environmentId: string;
34 readonly threadId: string;
35 readonly tabId?: string;
36}>;
37
38export function BrowserPreviewRouteScreen({ route }: BrowserPreviewRouteScreenProps) {
39 const navigation = useNavigation();
40 const onClose = () => navigation.goBack();
41 return (
42 <View collapsable={false} className="flex-1 bg-sheet">
43 <BrowserPreviewStack.Navigator
44 screenOptions={{
45 headerShown: Platform.OS === "ios",
46 headerBackVisible: false,
47 headerShadowVisible: false,
48 headerTransparent: false,
49 headerTitleStyle: { fontSize: 17, fontWeight: "600" },
50 }}
51 >
52 <BrowserPreviewStack.Screen name="BrowserPreview">
53 {() => (
54 <BrowserPreviewScreen
55 environmentId={EnvironmentId.make(route.params.environmentId)}
56 threadId={ThreadId.make(route.params.threadId)}
57 initialTabId={route.params.tabId ?? null}
58 onClose={onClose}
59 />
60 )}
61 </BrowserPreviewStack.Screen>
62 </BrowserPreviewStack.Navigator>
63 </View>
64 );
65}
66
67function BrowserPreviewScreen({
68 environmentId,
69 threadId,
70 initialTabId,
71 onClose,
72}: {
73 readonly environmentId: EnvironmentId;
74 readonly threadId: ThreadId;
75 readonly initialTabId: string | null;
76 readonly onClose: () => void;
77}) {
78 const insets = useSafeAreaInsets();
79 const { themeVariables } = useAppearancePreferences();
80 const prepared = usePreparedConnection(environmentId);
81 const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;
82 const focused = useIsFocused();
83 const foreground = useAppForeground();
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 pdfUri =
92 tab?.navStatus._tag === "Success" ? previewPdfAssetUrl(tab.navStatus.url, httpBaseUrl) : null;
93 const tabId = tab?.tabId ?? null;
94 if (tabId !== null && tabId !== selectedTabId) {
95 setPictureInPicture(NO_PICTURE_IN_PICTURE);
96 setSelectedTabId(tabId);
97 }
98 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes the focused route through the navigator once the thread has no browser tabs left
99 useEffect(() => {
100 if (focused && loaded && tabs.length === 0) onClose();
101 }, [focused, loaded, tabs.length, onClose]);
102 const onPictureInPicture = (state: PreviewPictureInPictureState, detail?: string) => {
103 setPictureInPicture({ supported: state.supported, active: state.active });
104 if (detail) Dialog.alert("Picture in picture is unavailable", detail);
105 };
106 const selectTab = (next: string) => {
107 setPictureInPicture(NO_PICTURE_IN_PICTURE);
108 setSelectedTabId(next);
109 };
110 const live = (focused && foreground) || pictureInPicture.active;
111
112 return (
113 <View className="flex-1 bg-sheet" style={{ paddingBottom: insets.bottom }}>
114 <AppBar
115 title={tab ? browserTabTitle(tab) : "Browser"}
116 sidebar={false}
117 onBack={onClose}
118 options={{ headerBackVisible: false }}
119 actions={
120 // Android WebView cannot play video in picture in picture.
121 Platform.OS === "ios" &&
122 pictureInPicture.supported &&
123 (pictureInPicture.active || pdfUri === null)
124 ? [
125 {
126 accessibilityLabel: pictureInPicture.active
127 ? "Exit picture in picture"
128 : "Picture in picture",
129 icon: {
130 ios: pictureInPicture.active ? "pip.exit" : "pip.enter",
131 android: "visibility",
132 },
133 selected: pictureInPicture.active,
134 onPress: () => streamRef.current?.togglePictureInPicture(),
135 },
136 ]
137 : []
138 }
139 menus={
140 tabs.length > 1
141 ? [
142 {
143 title: "Tabs",
144 icon: "square.on.square",
145 items: tabs.map((entry) => ({
146 id: entry.tabId,
147 title: browserTabTitle(entry),
148 subtitle: browserTabUrl(entry),
149 selected: entry.tabId === tabId,
150 onPress: () => selectTab(entry.tabId),
151 })),
152 },
153 ]
154 : []
155 }
156 />
157 {Platform.OS === "ios" ? (
158 <SheetHeader
159 title={tab ? browserTabTitle(tab) : "Browser"}
160 onClose={onClose}
161 accessibilityLabel="Close browser"
162 />
163 ) : null}
164 {tab ? (
165 <>
166 <BrowserAddressBar
167 key={`address:${tab.tabId}`}
168 environmentId={environmentId}
169 tab={tab}
170 streaming={streaming}
171 ready={streaming && canControl}
172 onCommand={(input) => streamRef.current?.command(input)}
173 onPaste={() => streamRef.current?.paste()}
174 />
175 {live ? (
176 <PreviewStreamWebView
177 key={`stream:${tab.tabId}`}
178 environmentId={environmentId}
179 threadId={threadId}
180 tabId={tab.tabId}
181 pdfUri={pdfUri}
182 ref={streamRef}
183 interactive
184 background={themeVariables["--color-sheet-solid"]}
185 onPictureInPicture={onPictureInPicture}
186 onStreamingChange={setStreaming}
187 onControl={(control) => setCanControl(control?.controller === "you")}
188 />
189 ) : (
190 <View className="flex-1" />
191 )}
192 </>
193 ) : (
194 <View className="flex-1 items-center justify-center">
195 {focused && foreground ? (
196 <AppActivityIndicator color={themeVariables["--color-icon"]} />
197 ) : null}
198 </View>
199 )}
200 </View>
201 );
202}
203
204function BrowserAddressBar({
205 environmentId,
206 tab,
207 ready,
208 streaming,
209 onCommand,
210 onPaste,
211}: {
212 readonly environmentId: EnvironmentId;
213 readonly tab: PreviewSessionSnapshot;
214 readonly ready: boolean;
215 readonly streaming: boolean;
216 readonly onCommand: PreviewStreamRef["command"];
217 readonly onPaste: () => void;
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 lineBreakModeIOS="tail"
259 className="h-10 min-w-0 flex-1 rounded-full border border-input-border bg-input px-4 font-sans text-sm text-foreground"
260 />
261 <ControlPill
262 icon="arrow.clockwise"
263 accessibilityLabel="Reload page"
264 disabled={!ready}
265 onPress={() => onCommand({ type: "reload" })}
266 />
267 <BrowserTabMenu
268 environmentId={environmentId}
269 tab={tab}
270 streaming={streaming}
271 onPaste={ready ? onPaste : undefined}
272 />
273 </View>
274 );
275}