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

BrowserTabMenu.tsx

204 lines7.8 KB

1import * as Dialog from "../../components/ui/Dialog";
2import { useAtomValue } from "@effect/atom-react";
3import type { MenuAction } from "@react-native-menu/menu";
4import {
5 DEFAULT_PREVIEW_ZOOM_FACTOR,
6 type EnvironmentId,
7 FILL_PREVIEW_VIEWPORT,
8 PREVIEW_ZOOM_LEVELS,
9 type PreviewAdjustInput,
10 type PreviewSessionSnapshot,
11 type PreviewViewportSetting,
12} from "@t3tools/contracts";
13import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
14import { msg, useGT, useMessages } from "gt-react-native";
15​
16import { ControlPill } from "../../components/ui/ControlPill";
17import { Menu } from "../../components/ui/Menu";
18import { m } from "../../i18n/messages";
19import { previewEnvironment } from "../../state/preview";
20import { useAtomCommand } from "../../state/use-atom-command";
21import { browserTabUrl, loopbackUrlForDevice } from "./browserTabs";
22import { useOpenLocalPreview } from "./useOpenLocalPreview";
23​
24const APPEARANCES = [
25 {
26 id: "system",
27 title: msg("System", { $context: "appearance option, follow the system theme" }),
28 },
29 { id: "light", title: msg("Light", { $context: "appearance option" }) },
30 { id: "dark", title: msg("Dark", { $context: "appearance option" }) },
31] as const;
32​
33const VIEWPORTS = [
34 { id: "fill", title: msg("Fit to screen"), setting: FILL_PREVIEW_VIEWPORT },
35 ...(["Phone", "Tablet", "Desktop"] as const).flatMap((category) => {
36 const preset = PREVIEW_VIEWPORT_PRESETS.find((candidate) => candidate.category === category);
37 if (!preset) return [];
38 const setting: PreviewViewportSetting = {
39 _tag: "preset",
40 presetId: preset.id,
41 width: preset.width,
42 height: preset.height,
43 };
44 const title =
45 category === "Phone"
46 ? msg("Phone ({device})", { device: preset.label })
47 : category === "Tablet"
48 ? msg("Tablet ({device})", { device: preset.label })
49 : msg("Desktop ({device})", { device: preset.label });
50 return [{ id: `preset:${preset.id}`, title, setting }];
51 }),
52];
53​
54export function BrowserTabMenu({
55 environmentId,
56 tab,
57 streaming,
58 onPaste,
59 onReleaseControl,
60}: {
61 readonly environmentId: EnvironmentId;
62 readonly tab: PreviewSessionSnapshot;
63 readonly streaming: boolean;
64 readonly onPaste?: () => void;
65 readonly onReleaseControl?: () => void;
66}) {
67 const openLocalPreview = useOpenLocalPreview();
68 const adjust = useAtomCommand(previewEnvironment.adjust, "browser tab change");
69 const resize = useAtomCommand(previewEnvironment.resize, "browser viewport change");
70 const close = useAtomCommand(previewEnvironment.close, "browser tab close");
71 const canClose = useAtomValue(previewEnvironment.close.permissionAtom(environmentId));
72 const gt = useGT();
73 const resolveMessage = useMessages();
74 const target = { threadId: tab.threadId as PreviewAdjustInput["threadId"], tabId: tab.tabId };
75 const colorScheme = tab.colorScheme ?? "system";
76 const zoomFactor = tab.zoomFactor ?? DEFAULT_PREVIEW_ZOOM_FACTOR;
77 const zoomIndex = PREVIEW_ZOOM_LEVELS.indexOf(zoomFactor);
78 const zoomTo = (step: -1 | 1) =>
79 PREVIEW_ZOOM_LEVELS[
80 Math.min(Math.max((zoomIndex < 0 ? 7 : zoomIndex) + step, 0), PREVIEW_ZOOM_LEVELS.length - 1)
81 ]!;
82 const viewportId =
83 tab.viewport === undefined || tab.viewport._tag === "fill"
84 ? "fill"
85 : tab.viewport._tag === "preset"
86 ? `preset:${tab.viewport.presetId}`
87 : "custom";
88​
89 const closeAction: MenuAction = {
90 id: "close",
91 title: gt("Close tab"),
92 image: "xmark",
93 attributes: { destructive: true, disabled: !canClose },
94 };
95 const deviceUrl = loopbackUrlForDevice(browserTabUrl(tab));
96 // The device preview has its own webview and tunnel, so it doesn't wait for the stream.
97 const openOnDevice: MenuAction[] = deviceUrl
98 ? [{ id: "open-on-device", title: gt("Open on this device"), image: "iphone" }]
99 : [];
100 const actions: MenuAction[] = [
101 ...openOnDevice,
102 ...(onPaste
103 ? [{ id: "paste", title: gt("Paste", { $context: "verb" }), image: "doc.on.clipboard" }]
104 : []),
105 ...(onReleaseControl
106 ? [{ id: "release-control", title: gt("Release control"), image: "hand.raised" }]
107 : []),
108 { id: "hard-reload", title: gt("Hard reload"), image: "arrow.clockwise.circle" },
109 {
110 id: "appearance",
111 title: gt("Appearance"),
112 image: "circle.lefthalf.filled",
113 subactions: APPEARANCES.map((option) => ({
114 id: `appearance:${option.id}`,
115 title: resolveMessage(option.title),
116 state: option.id === colorScheme ? "on" : "off",
117 })),
118 },
119 {
120 id: "zoom",
121 title: gt("Zoom ({percent}%)", { percent: Math.round(zoomFactor * 100) }),
122 image: "plus.magnifyingglass",
123 subactions: [
124 { id: "zoom:in", title: gt("Zoom in"), image: "plus.magnifyingglass" },
125 { id: "zoom:out", title: gt("Zoom out"), image: "minus.magnifyingglass" },
126 { id: "zoom:reset", title: gt("Actual size"), image: "1.magnifyingglass" },
127 ],
128 },
129 {
130 id: "viewport",
131 title: gt("Viewport"),
132 image: "rectangle.and.arrow.up.right.and.arrow.down.left",
133 subactions: VIEWPORTS.map((option) => ({
134 id: `viewport:${option.id}`,
135 title: resolveMessage(option.title),
136 state: option.id === viewportId ? "on" : "off",
137 })),
138 },
139 {
140 id: "site-data",
141 title: gt("Site data"),
142 image: "trash",
143 subactions: [
144 { id: "clear:cookies", title: gt("Clear cookies"), attributes: { destructive: true } },
145 { id: "clear:cache", title: gt("Clear cache"), attributes: { destructive: true } },
146 ],
147 },
148 closeAction,
149 ];
150​
151 const run = async (change: Omit<PreviewAdjustInput, "threadId" | "tabId">) => {
152 const result = await adjust({ environmentId, input: { ...target, ...change } });
153 if (result._tag === "Failure") Dialog.alert(m(msg("Could not change this browser tab")));
154 };
155​
156 const onAction = (id: string) => {
157 if (id === "close") {
158 void close({ environmentId, input: target }).then((result) => {
159 if (result._tag === "Failure") Dialog.alert(m(msg("Could not close this browser tab")));
160 });
161 return;
162 }
163 if (id === "open-on-device" && deviceUrl) {
164 return openLocalPreview({ environmentId, threadId: tab.threadId }, deviceUrl);
165 }
166 if (id === "paste") return onPaste?.();
167 if (id === "release-control") return onReleaseControl?.();
168 if (id === "hard-reload") return void run({ hardReload: true });
169 if (id === "zoom:in") return void run({ zoomFactor: zoomTo(1) });
170 if (id === "zoom:out") return void run({ zoomFactor: zoomTo(-1) });
171 if (id === "zoom:reset") return void run({ zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR });
172 if (id === "clear:cookies") return void run({ clear: "cookies" });
173 if (id === "clear:cache") return void run({ clear: "cache" });
174 if (id.startsWith("appearance:")) {
175 const option = APPEARANCES.find((candidate) => `appearance:${candidate.id}` === id);
176 if (option) void run({ colorScheme: option.id });
177 return;
178 }
179 if (id.startsWith("viewport:")) {
180 const option = VIEWPORTS.find((candidate) => `viewport:${candidate.id}` === id);
181 if (!option) return;
182 void resize({ environmentId, input: { ...target, viewport: option.setting } }).then(
183 (result) => {
184 if (result._tag === "Failure") Dialog.alert(m(msg("Could not change the viewport")));
185 },
186 );
187 }
188 };
189​
190 return (
191 <Menu
192 // Remount when streaming changes, so an open menu never keeps offering
193 // the other state's actions.
194 key={streaming ? "streaming" : "idle"}
195 accessible
196 accessibilityLabel={gt("Browser tab options")}
197 accessibilityRole="button"
198 actions={streaming ? actions : [...openOnDevice, closeAction]}
199 onPressAction={({ nativeEvent }) => onAction(nativeEvent.event)}
200 >
201 <ControlPill icon="ellipsis" accessibilityLabel={gt("Browser tab options")} />
202 </Menu>
203 );