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

BrowserPreviewRouteScreen.tsx

238 lines9.1 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 } from "@t3tools/contracts";
6import { normalizePreviewUrl, previewPdfAssetUrl } from "@t3tools/shared/preview";
7import * as Option from "effect/Option";
8import { msg, useGT, useMessages } from "gt-react-native";
9import { useEffect, useRef, useState } from "react";
10import { Platform, View } from "react-native";
11import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
12​
13import { ControlPill } from "../../components/ui/ControlPill";
14import { Menu } from "../../components/ui/Menu";
15import { useContentTopInset } from "../../components/ui/useBarInset";
16import { m } from "../../i18n/messages";
17import { useAppForeground } from "../../lib/appState";
18​
19import { useThreadServerBrowserTabs } from "../../state/preview";
20import { usePreparedConnection } from "../../state/session";
21import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
22import { BrowserChrome } from "./BrowserBar";
23import { BrowserTabMenu } from "./BrowserTabMenu";
24import { browserTabTitle, browserTabUrl, latestBrowserTab } from "./browserTabs";
25import {
26 PreviewStreamWebView,
27 type PreviewPictureInPictureState,
28 type PreviewStreamRef,
29} from "./PreviewStreamWebView";
30​
31const NO_PICTURE_IN_PICTURE: PreviewPictureInPictureState = { supported: false, active: false };
32​
33type BrowserPreviewRouteScreenProps = StaticScreenProps<{
34 readonly environmentId: string;
35 readonly threadId: string;
36 readonly tabId?: string;
37}>;
38​
39export function BrowserPreviewRouteScreen({ route }: BrowserPreviewRouteScreenProps) {
40 const navigation = useNavigation();
41 const onClose = () => navigation.goBack();
42 const { environmentId, threadId } = route.params;
43 if (!environmentId?.trim() || !threadId?.trim()) {
44 return <BrowserUnavailableScreen onClose={onClose} />;
45 }
46 return (
47 <BrowserPreviewScreen
48 environmentId={EnvironmentId.make(environmentId)}
49 threadId={ThreadId.make(threadId)}
50 initialTabId={route.params.tabId ?? null}
51 onClose={onClose}
52 />
53 );
55​
56function BrowserUnavailableScreen({ onClose }: { readonly onClose: () => void }) {
57 const gt = useGT();
58 const insets = useSafeAreaInsets();
59 const contentTopInset = useContentTopInset();
60 return (
61 <View
62 className="flex-1 bg-sheet"
63 style={{ paddingTop: contentTopInset, paddingBottom: insets.bottom }}
64 >
65 <SheetHeader
66 title={gt({ context: "screen title" })`Browser`}
67 onClose={onClose}
68 accessibilityLabel={gt`Close browser`}
69 />
70 </View>
71 );
73​
74function BrowserPreviewScreen({
75 environmentId,
76 threadId,
77 initialTabId,
78 onClose,
79}: {
80 readonly environmentId: EnvironmentId;
81 readonly threadId: ThreadId;
82 readonly initialTabId: string | null;
83 readonly onClose: () => void;
84}) {
85 const gt = useGT();
86 const resolveMessage = useMessages();
87 const { themeVariables } = useAppearancePreferences();
88 const prepared = usePreparedConnection(environmentId);
89 const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;
90 const focused = useIsFocused();
91 const foreground = useAppForeground();
92 const [selectedTabId, setSelectedTabId] = useState(initialTabId);
93 const [pictureInPicture, setPictureInPicture] = useState(NO_PICTURE_IN_PICTURE);
94 const [streaming, setStreaming] = useState(false);
95 const [canControl, setCanControl] = useState(false);
96 const streamRef = useRef<PreviewStreamRef>(null);
97 const { tabs, loaded } = useThreadServerBrowserTabs({ environmentId, threadId, enabled: true });
98 const tab = tabs.find((entry) => entry.tabId === selectedTabId) ?? latestBrowserTab(tabs);
99 const pdfUri =
100 tab?.navStatus._tag === "Success" ? previewPdfAssetUrl(tab.navStatus.url, httpBaseUrl) : null;
101 const tabId = tab?.tabId ?? null;
102 if (tabId !== null && tabId !== selectedTabId) {
103 setPictureInPicture(NO_PICTURE_IN_PICTURE);
104 setSelectedTabId(tabId);
105 }
106 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes the focused route through the navigator once the thread has no browser tabs left
107 useEffect(() => {
108 if (focused && loaded && tabs.length === 0) onClose();
109 }, [focused, loaded, tabs.length, onClose]);
110 const onPictureInPicture = (state: PreviewPictureInPictureState, detail?: string) => {
111 setPictureInPicture({ supported: state.supported, active: state.active });
112 if (detail) Dialog.alert(m(msg("Picture in picture is unavailable")), detail);
113 };
114 const selectTab = (next: string) => {
115 setPictureInPicture(NO_PICTURE_IN_PICTURE);
116 setSelectedTabId(next);
117 };
118 const live = (focused && foreground) || pictureInPicture.active;
119​
120 const ready = streaming && canControl;
121 const command: PreviewStreamRef["command"] = (input) => streamRef.current?.command(input);
122 const showPictureInPicture =
123 // Android WebView cannot play video in picture in picture.
124 Platform.OS === "ios" &&
125 pictureInPicture.supported &&
126 (pictureInPicture.active || pdfUri === null);
127​
128 return (
129 // The route spans the Duo's rail, so the screen insets its own sides.
130 <SafeAreaView
131 edges={["left", "right"]}
132 style={{ flex: 1, backgroundColor: themeVariables["--color-sheet-solid"] }}
133 >
134 <BrowserChrome
135 key={tab ? `address:${tab.tabId}` : "address"}
136 scrollsUnderBar={false}
137 bar={{
138 url: tab ? browserTabUrl(tab) : "",
139 editable: ready,
140 canGoBack: ready && (tab?.canGoBack ?? false),
141 onClose,
142 onBack: () => command({ type: "history", delta: -1 }),
143 onReload: () => command({ type: "reload" }),
144 onSubmit: (value) => {
145 const url = normalizedOrNull(value);
146 if (url === null)
147 Dialog.alert(
148 m(msg("Could not open this address")),
149 m(msg("Enter an http or https URL.")),
150 );
151 else command({ type: "navigate", url });
152 },
153 trailing: (
154 <>
155 {showPictureInPicture ? (
156 <ControlPill
157 icon={{
158 ios: pictureInPicture.active ? "pip.exit" : "pip.enter",
159 android: "visibility",
160 }}
161 accessibilityLabel={
162 pictureInPicture.active ? gt`Exit picture in picture` : gt`Picture in picture`
163 }
164 onPress={() => streamRef.current?.togglePictureInPicture()}
165 />
166 ) : null}
167 {tabs.length > 1 ? (
168 <Menu
169 accessible
170 accessibilityLabel={gt({ context: "browser tabs menu" })`Tabs`}
171 accessibilityRole="button"
172 actions={tabs.map((entry) => ({
173 id: entry.tabId,
174 title: browserTabTitle(entry, resolveMessage),
175 subtitle: browserTabUrl(entry),
176 state: entry.tabId === tabId ? "on" : "off",
177 }))}
178 onPressAction={({ nativeEvent }) => selectTab(nativeEvent.event)}
179 >
180 <ControlPill
181 icon="square.on.square"
182 accessibilityLabel={gt({ context: "browser tabs menu" })`Tabs`}
183 />
184 </Menu>
185 ) : null}
186 {tab ? (
187 <BrowserTabMenu
188 environmentId={environmentId}
189 tab={tab}
190 streaming={streaming}
191 onPaste={ready ? () => streamRef.current?.paste() : undefined}
192 onReleaseControl={ready ? () => command({ type: "releaseControl" }) : undefined}
193 />
194 ) : null}
195 </>
196 ),
197 }}
198 >
199 {({ onScrollDirection }) =>
200 tab ? (
201 live ? (
202 <PreviewStreamWebView
203 key={`stream:${tab.tabId}`}
204 environmentId={environmentId}
205 threadId={threadId}
206 tabId={tab.tabId}
207 pdfUri={pdfUri}
208 ref={streamRef}
209 interactive
210 background={themeVariables["--color-sheet-solid"]}
211 onPictureInPicture={onPictureInPicture}
212 onStreamingChange={setStreaming}
213 onScrollDirection={onScrollDirection}
214 onControl={(control) => setCanControl(control?.controller === "you")}
215 />
216 ) : (
217 <View className="flex-1" />
218 )
219 ) : (
220 <View className="flex-1 items-center justify-center">
221 {focused && foreground ? (
222 <AppActivityIndicator color={themeVariables["--color-icon"]} />
223 ) : null}
224 </View>
225 )
226 }
227 </BrowserChrome>
228 </SafeAreaView>
229 );
231​
232function normalizedOrNull(value: string): string | null {
233 try {
234 return normalizePreviewUrl(value);
235 } catch {
236 return null;
237 }