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

BrowserPreviewRouteScreen.tsx

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