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

LocalPreviewRouteScreen.tsx

226 lines8.6 KB

1import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
2import { EnvironmentId } from "@t3tools/contracts";
3import { normalizePreviewUrl } from "@t3tools/shared/preview";
4import { msg, useGT } from "gt-react-native";
5import { useRef, useState } from "react";
6import { View } from "react-native";
7import { SafeAreaView } from "react-native-safe-area-context";
8​
9import { AppText } from "../../components/ui/AppText";
10import * as Dialog from "../../components/ui/Dialog";
11import { EmptyState } from "../../components/ui/EmptyState";
12import { m } from "../../i18n/messages";
13import { useEnvironments } from "../../state/environments";
14import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
15import { BrowserChrome } from "./BrowserBar";
16import { loopbackUrlForDevice } from "./browserTabs";
17import { TunnelWebView, type TunnelNavigation, type TunnelWebViewRef } from "./TunnelWebView";
18​
19type LocalPreviewRouteScreenProps = StaticScreenProps<{
20 readonly environmentId: string;
21 readonly url: string;
22}>;
23​
24export function LocalPreviewRouteScreen({ route }: LocalPreviewRouteScreenProps) {
25 const navigation = useNavigation();
26 return (
27 <LocalPreviewScreen
28 environmentId={EnvironmentId.make(route.params.environmentId)}
29 url={route.params.url}
30 onClose={() => navigation.goBack()}
31 />
32 );
34​
35/**
36 * Another environment's localhost page rendered by this device's own webview, full screen or, with
37 * `onMaximize`, in the inspector pane.
38 */
39export function LocalPreviewScreen(props: {
40 readonly environmentId: EnvironmentId;
41 readonly url: string;
42 readonly onClose: () => void;
43 readonly onMaximize?: (url: string) => void;
44}) {
45 const { environmentId, onMaximize } = props;
46 const gt = useGT();
47 const initialUrl = forDevice(props.url);
48 const environmentLabel =
49 useEnvironments().presentationById.get(environmentId)?.entry.target.label ??
50 gt("the environment", { $context: "stands in for an environment name in a sentence" });
51 const { themeVariables } = useAppearancePreferences();
52 const webView = useRef<TunnelWebViewRef>(null);
53 const [requested, setRequested] = useState(initialUrl);
54 const [page, setPage] = useState<TunnelNavigation | null>(null);
55 const [failed, setFailed] = useState(false);
56 const [disconnected, setDisconnected] = useState(false);
57 const [outdated, setOutdated] = useState(false);
58 const [debug, setDebug] = useState<string | undefined>(undefined);
59 const [unsupported, setUnsupported] = useState<string | null>(null);
60 // After a failed load the webview reports no URL, so the address stays on the one asked for.
61 const current = (!failed && page?.url) || requested;
62​
63 const open = (value: string) => {
64 const normalized = normalizedOrNull(value);
65 const next = normalized === null ? null : forDevice(normalized);
66 if (next === null) {
67 Dialog.alert(m(msg("Could not open this address")), m(msg("Enter an http or https URL.")));
68 return;
69 }
70 setFailed(false);
71 setRequested(next);
72 void webView.current?.loadUrl(next);
73 };
74 const retry = () => {
75 setFailed(false);
76 void webView.current?.reload();
77 };
78 const back = () => void webView.current?.goBack();
79 const canGoBack = page?.canGoBack ?? false;
80 const pageColor = failed || unsupported !== null ? null : page?.pageColor || null;
81​
82 return (
83 // Full screen spans the Duo's rail, so it insets its own sides; the pane is inset already.
84 <SafeAreaView
85 edges={onMaximize ? [] : ["left", "right"]}
86 style={{ flex: 1, backgroundColor: pageColor ?? themeVariables["--color-sheet-solid"] }}
87 >
88 <BrowserChrome
89 scrollsUnderBar
90 inPane={onMaximize !== undefined}
91 holdExpanded={failed}
92 bar={{
93 url: current,
94 editable: true,
95 canGoBack,
96 onClose: props.onClose,
97 onBack: back,
98 onReload: retry,
99 onSubmit: open,
100 onMaximize: onMaximize ? () => onMaximize(current) : undefined,
101 pageColor,
102 }}
103 >
104 {({ topInset, onScrollDirection }) => (
105 <>
106 <TunnelWebView
107 key={environmentId}
108 ref={webView}
109 className="flex-1"
110 environmentId={environmentId}
111 url={initialUrl}
112 topInset={topInset}
113 onNavigationChange={(next) => {
114 if (next.loading) setFailed(false);
115 setPage(next);
116 }}
117 onScrollDirection={onScrollDirection}
118 onAccess={(available) => setDisconnected(!available)}
119 onLoadError={(failure) => {
120 if (failure.unsupported) return setUnsupported(failure.description);
121 // A link to another port fails with that port's address, not the one typed earlier.
122 if (failure.url) setRequested(failure.url);
123 setDebug(failure.debug);
124 // Without a cause, a refused tunnel request reported through onAccess stands in.
125 if (failure.cause) setDisconnected(failure.cause === "environment");
126 setOutdated(failure.cause === "outdated");
127 setFailed(true);
128 }}
129 />
130 {unsupported !== null ? (
131 <View
132 className="absolute inset-0 items-center justify-center"
133 style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}
134 >
135 <View className="w-full max-w-md">
136 <EmptyState
137 variant="plain"
138 title={gt("This device can't open localhost pages")}
139 detail={gt("{reason} You can still use the streamed browser for this tab.", {
140 reason: unsupported,
141 })}
142 />
143 </View>
144 </View>
145 ) : failed ? (
146 // Opaque, so the webview's own error page never shows through the sheet color.
147 <View
148 className="absolute inset-0 items-center justify-center"
149 style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}
150 >
151 <View className="w-full max-w-md">
152 <EmptyState
153 variant="plain"
154 title={
155 outdated
156 ? gt("Update T3 Code on {environment}", { environment: environmentLabel })
157 : disconnected
158 ? gt("Not connected to {environment}", { environment: environmentLabel })
159 : gt("Can't reach {host}", { host: hostOf(current) })
160 }
161 detail={
162 outdated
163 ? gt(
164 "{environment} runs a version of T3 Code that can't open its localhost pages on this device. Update it there, then try again.",
165 { environment: environmentLabel },
166 )
167 : disconnected
168 ? gt(
169 "Pages on {environment}’s localhost load through its connection. Try again once it reconnects.",
170 { environment: environmentLabel },
171 )
172 : gt(
173 "Nothing is listening on port {port} on {environment}. Start the server there, then try again.",
174 { port: portOf(current), environment: environmentLabel },
175 )
176 }
177 actionLabel={gt("Try again")}
178 onAction={retry}
179 />
180 {debug ? (
181 <AppText
182 selectable
183 className="px-6 text-center font-mono text-xs text-foreground-muted"
184 >
185 {debug}
186 </AppText>
187 ) : null}
188 </View>
189 </View>
190 ) : null}
191 </>
192 )}
193 </BrowserChrome>
194 </SafeAreaView>
195 );
197​
198function portOf(value: string): string {
199 try {
200 const url = new URL(value);
201 return url.port || (url.protocol === "https:" ? "443" : "80");
202 } catch {
203 return "?";
204 }
206​
207function hostOf(value: string): string {
208 try {
209 return new URL(value).host;
210 } catch {
211 return value;
212 }
214​
215// The unspecified address would name the phone itself, so it becomes the environment's localhost.
216function forDevice(url: string): string {
217 return loopbackUrlForDevice(url) ?? url;
219​
220function normalizedOrNull(value: string): string | null {
221 try {
222 return normalizePreviewUrl(value);
223 } catch {
224 return null;
225 }