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

BrowserPreviewRouteScreen.tsx

274 lines9.7 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 { 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 = useCallback(() => navigation.goBack(), [navigation]);
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 );
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 useEffect(() => {
99 if (focused && loaded && tabs.length === 0) onClose();
100 }, [focused, loaded, tabs.length, onClose]);
101 const onPictureInPicture = useCallback((state: PreviewPictureInPictureState, detail?: string) => {
102 setPictureInPicture({ supported: state.supported, active: state.active });
103 if (detail) Dialog.alert("Picture in picture is unavailable", detail);
104 }, []);
105 const selectTab = (next: string) => {
106 setPictureInPicture(NO_PICTURE_IN_PICTURE);
107 setSelectedTabId(next);
108 };
109 const live = (focused && foreground) || pictureInPicture.active;
110​
111 return (
112 <View className="flex-1 bg-sheet" style={{ paddingBottom: insets.bottom }}>
113 <AppBar
114 title={tab ? browserTabTitle(tab) : "Browser"}
115 sidebar={false}
116 onBack={onClose}
117 options={{ headerBackVisible: false }}
118 actions={
119 // Android WebView cannot play video in picture in picture.
120 Platform.OS === "ios" &&
121 pictureInPicture.supported &&
122 (pictureInPicture.active || pdfUri === null)
123 ? [
124 {
125 accessibilityLabel: pictureInPicture.active
126 ? "Exit picture in picture"
127 : "Picture in picture",
128 icon: {
129 ios: pictureInPicture.active ? "pip.exit" : "pip.enter",
130 android: "visibility",
131 },
132 selected: pictureInPicture.active,
133 onPress: () => streamRef.current?.togglePictureInPicture(),
134 },
135 ]
136 : []
137 }
138 menus={
139 tabs.length > 1
140 ? [
141 {
142 title: "Tabs",
143 icon: "square.on.square",
144 items: tabs.map((entry) => ({
145 id: entry.tabId,
146 title: browserTabTitle(entry),
147 subtitle: browserTabUrl(entry),
148 selected: entry.tabId === tabId,
149 onPress: () => selectTab(entry.tabId),
150 })),
151 },
152 ]
153 : []
154 }
155 />
156 {Platform.OS === "ios" ? (
157 <SheetHeader
158 title={tab ? browserTabTitle(tab) : "Browser"}
159 onClose={onClose}
160 accessibilityLabel="Close browser"
161 />
162 ) : null}
163 {tab ? (
164 <>
165 <BrowserAddressBar
166 key={`address:${tab.tabId}`}
167 environmentId={environmentId}
168 tab={tab}
169 streaming={streaming}
170 ready={streaming && canControl}
171 onCommand={(input) => streamRef.current?.command(input)}
172 onPaste={() => streamRef.current?.paste()}
173 />
174 {live ? (
175 <PreviewStreamWebView
176 key={`stream:${tab.tabId}`}
177 environmentId={environmentId}
178 threadId={threadId}
179 tabId={tab.tabId}
180 pdfUri={pdfUri}
181 ref={streamRef}
182 interactive
183 background={themeVariables["--color-sheet-solid"]}
184 onPictureInPicture={onPictureInPicture}
185 onStreamingChange={setStreaming}
186 onControl={(control) => setCanControl(control?.controller === "you")}
187 />
188 ) : (
189 <View className="flex-1" />
190 )}
191 </>
192 ) : (
193 <View className="flex-1 items-center justify-center">
194 {focused && foreground ? (
195 <AppActivityIndicator color={themeVariables["--color-icon"]} />
196 ) : null}
197 </View>
198 )}
199 </View>
200 );
202​
203function BrowserAddressBar({
204 environmentId,
205 tab,
206 ready,
207 streaming,
208 onCommand,
209 onPaste,
210}: {
211 readonly environmentId: EnvironmentId;
212 readonly tab: PreviewSessionSnapshot;
213 readonly ready: boolean;
214 readonly streaming: boolean;
215 readonly onCommand: PreviewStreamRef["command"];
216 readonly onPaste: () => void;
217}) {
218 const url = browserTabUrl(tab);
219 const [draft, setDraft] = useState<string | null>(null);
220 const submit = () => {
221 const value = draft ?? url;
222 setDraft(null);
223 try {
224 onCommand({ type: "navigate", url: normalizePreviewUrl(value) });
225 } catch {
226 Dialog.alert("Could not open this address", "Enter an http or https URL.");
227 }
228 };
229 return (
230 <View className="flex-row items-center gap-1 px-2 pb-2">
231 <ControlPill
232 icon="chevron.left"
233 accessibilityLabel="Back"
234 disabled={!ready || !tab.canGoBack}
235 onPress={() => onCommand({ type: "history", delta: -1 })}
236 />
237 <ControlPill
238 icon="chevron.right"
239 accessibilityLabel="Forward"
240 disabled={!ready || !tab.canGoForward}
241 onPress={() => onCommand({ type: "history", delta: 1 })}
242 />
243 <TextInput
244 accessibilityLabel="Address"
245 editable={ready}
246 value={draft ?? url}
247 onChangeText={setDraft}
248 onBlur={() => setDraft(null)}
249 onSubmitEditing={submit}
250 placeholder="Enter a URL"
251 placeholderTextColorClassName="accent-placeholder"
252 autoCapitalize="none"
253 autoCorrect={false}
254 keyboardType="url"
255 returnKeyType="go"
256 selectTextOnFocus
257 lineBreakModeIOS="tail"
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
267 environmentId={environmentId}
268 tab={tab}
269 streaming={streaming}
270 onPaste={ready ? onPaste : undefined}
271 />
272 </View>
273 );