Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BrowserPreviewRouteScreen.tsx

279 lines9.9 KB

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