The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 313 lines 13.4 KB
Raw
1 import { useGT, useMessages } from "gt-react-native";
2 import {
3 WORKSPACE_TAB_LABELS,
4 NAVIGATION_TAB_ICONS,
5 useEnabledNavigationTabs,
6 } from "./navigation-tabs";
7 import {
8 useEffect,
9 useLayoutEffect,
10 useRef,
11 useState,
12 type Dispatch,
13 type ReactNode,
14 type SetStateAction,
15 } from "react";
16 import { View, useWindowDimensions, type NativeSyntheticEvent } from "react-native";
17 import { Tabs, type TabSelectedEvent, type TabSelectionRejectedEvent } from "react-native-screens";
18
19 import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext";
20 import type { NavigationTab } from "./navigation-tab-order";
21 import {
22 NATIVE_WORKSPACE_TAB_SLOTS,
23 workspaceTabForNativeSlot,
24 workspaceUsesColumns,
25 } from "./workspace-tabs-state";
26 import {
27 NativeWorkspaceTabActivityContext,
28 WorkspaceColumnMetricsContext,
29 WorkspaceSlotOptionsContext,
30 } from "../../../native/v5-workspace-context";
31 import type { NativeLayoutMetrics } from "../../../lib/reserved-regions";
32 import {
33 useCompactWorkspaceTabs,
34 useFloatingWorkspaceTabs,
35 useSystemWorkspaceTabBar,
36 } from "./useSystemWorkspaceTabBar";
37 import { useControlTheme } from "../../../components/ui/useControlTheme";
38 import { useDeviceType } from "../../../native/native-layout-metrics";
39 import { WorkspaceSidebarTabs } from "./WorkspaceSidebarTabs";
40 import { useAdaptiveWorkspaceLayout, useWorkspacePaneState } from "../AdaptiveWorkspaceLayout";
41 import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab";
42 import { useWorkspaceCompose } from "./useWorkspaceCompose";
43
44 const PULL_REQUEST_ICON = require("../../../../assets/icons/pull-request.png");
45 const ISSUE_ICON = require("../../../../assets/icons/issue.png");
46
47 /** Retain each native controller tree; removing its root can leave RNS's stack empty. */
48 function RetainedWorkspaceTab(props: {
49 readonly slot: string;
50 readonly tab: NavigationTab;
51 readonly active: boolean;
52 /** Render a slot that hasn't been shown yet: its header, and the page it opens with. */
53 readonly prewarm: boolean;
54 readonly setMountedSlots: Dispatch<SetStateAction<ReadonlySet<string>>>;
55 readonly setPrewarmRequests: Dispatch<SetStateAction<ReadonlyMap<string, number>>>;
56 readonly children: (workspace: SlotWorkspace, headerOnly: boolean) => ReactNode;
57 }) {
58 const workspace = useWorkspaceTabs()!;
59 // Whether this slot is the visible one, read by cleanups after the switch has committed.
60 const activeRef = useRef(props.active);
61 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed active flag to a ref that header cleanups read after the tab switch commits
62 useLayoutEffect(() => {
63 activeRef.current = props.active;
64 }, [props.active]);
65 const isActive = () => activeRef.current;
66 const [content, setContent] = useState(
67 props.active
68 ? { source: workspace, workspace, children: props.children, headerOnly: false }
69 : null,
70 );
71 const stale = content?.source !== workspace || content?.children !== props.children;
72 if (props.active && (content?.headerOnly !== false || stale))
73 setContent({ source: workspace, workspace, children: props.children, headerOnly: false });
74 // A slot not shown yet follows the workspace, so the page it opens with stays current.
75 else if (!props.active && props.prewarm && (content === null || (content.headerOnly && stale)))
76 setContent({
77 source: workspace,
78 workspace: {
79 ...workspace,
80 settingsOpen: props.slot === "settings",
81 state: { ...workspace.state, selectedTab: props.tab },
82 },
83 children: props.children,
84 headerOnly: true,
85 });
86 const activity = {
87 active: props.active,
88 isActive,
89 headerOnly: content?.headerOnly === true,
90 };
91 const [optionsByRoute, setOptionsByRoute] = useState<ReadonlyMap<string, object>>(new Map());
92 // Stable, so writers and the cleanups that depend on them don't re-run on every write.
93 const setRouteOptions = (routeKey: string, options: object) =>
94 setOptionsByRoute((current) =>
95 new Map(current).set(routeKey, { ...current.get(routeKey), ...options }),
96 );
97 const slotOptions = { byRoute: optionsByRoute, set: setRouteOptions };
98 const mounted = content !== null && !content.headerOnly;
99 const headerOnly = content?.headerOnly === true;
100 const { slot, setMountedSlots, setPrewarmRequests } = props;
101 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the slot's mount to the host, which uncovers the tab then
102 useEffect(() => {
103 if (!mounted) return;
104 // Each header write commits in the render after it; the slot is ready once a frame passes
105 // without one, which is when its native header and content are in place.
106 const frame = requestAnimationFrame(() =>
107 setMountedSlots((current) => (current.has(slot) ? current : new Set(current).add(slot))),
108 );
109 return () => cancelAnimationFrame(frame);
110 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- each header write re-arms the frame
111 }, [mounted, optionsByRoute, slot, setMountedSlots]);
112 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a replacement slot (e.g. a re-enabled fourth tab) must report its own mount
113 useEffect(
114 () => () =>
115 setMountedSlots((current) => {
116 if (!current.has(slot)) return current;
117 const next = new Set(current);
118 next.delete(slot);
119 return next;
120 }),
121 [slot, setMountedSlots],
122 );
123 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks UIKit to prewarm a hidden header after each write, since bar items it rebuilds fade in on their own first entry
124 useEffect(() => {
125 if (!headerOnly || optionsByRoute.size === 0) return;
126 const frame = requestAnimationFrame(() =>
127 setPrewarmRequests((current) => new Map(current).set(slot, (current.get(slot) ?? 0) + 1)),
128 );
129 return () => cancelAnimationFrame(frame);
130 }, [headerOnly, optionsByRoute, slot, setPrewarmRequests]);
131 return content ? (
132 <NativeWorkspaceTabActivityContext value={activity}>
133 <WorkspaceSlotOptionsContext value={slotOptions}>
134 <WorkspaceTabsContext value={content.workspace}>
135 {content.children(content.workspace, content.headerOnly)}
136 </WorkspaceTabsContext>
137 </WorkspaceSlotOptionsContext>
138 </NativeWorkspaceTabActivityContext>
139 ) : null;
140 }
141
142 type SlotWorkspace = NonNullable<ReturnType<typeof useWorkspaceTabs>>;
143
144 export function WorkspaceNativeTabs(props: {
145 /** Renders a slot's tree for its own tab, which can lay out differently from the shown one. */
146 readonly children: (workspace: SlotWorkspace, headerOnly: boolean) => ReactNode;
147 readonly hidden: boolean;
148 /** The sidebar column draws the tabs itself, so they leave with it. */
149 readonly tabsInSidebarColumn?: boolean;
150 }) {
151 const gt = useGT();
152 const m = useMessages();
153 const workspace = useWorkspaceTabs()!;
154 const order = useEnabledNavigationTabs();
155 const primaryTabs = order.slice(0, 4);
156 const overflow = order[4];
157 const selectTab = useSelectWorkspaceTab();
158 const [provenance, setProvenance] = useState(0);
159 const systemTabBar = useSystemWorkspaceTabBar();
160 const deviceType = useDeviceType();
161 const compactTabs = useCompactWorkspaceTabs();
162 const { layout } = useAdaptiveWorkspaceLayout();
163 const { panes } = useWorkspacePaneState();
164 // The tabs belong to the sidebar; over a page with the sidebar hidden they'd cover the composer.
165 const hiddenWithSidebar =
166 deviceType === "pad" &&
167 layout.usesSplitView &&
168 workspaceUsesColumns(workspace.state.selectedTab, workspace.settingsOpen) &&
169 !panes.primarySidebarVisible;
170 const floatingTabs = useFloatingWorkspaceTabs();
171 const { width } = useWindowDimensions();
172 const { colors } = useControlTheme();
173 const selectedTab = workspace.state.selectedTab;
174 const selectedSlot = workspace.settingsOpen ? -1 : primaryTabs.indexOf(selectedTab);
175 const selectedScreenKey =
176 selectedSlot === -1 ? "settings" : NATIVE_WORKSPACE_TAB_SLOTS[selectedSlot]!;
177 // A slot renders its body the first time it's selected. Until it has, UIKit keeps the last
178 // tab's snapshot over it, so the switch never shows a half-built tab.
179 const [mountedSlots, setMountedSlots] = useState<ReadonlySet<string>>(() => new Set());
180 // Once the first tab is up, the others mount their headers for UIKit to put in the window
181 // once: iOS 26 fades bar items in the first time they enter it, which a first visit would show.
182 const [prewarm, setPrewarm] = useState(false);
183 const [columnMetrics, setColumnMetrics] = useState<ReadonlyMap<string, NativeLayoutMetrics>>(
184 () => new Map(),
185 );
186 const sharedColumnMetrics = {
187 byColumn: columnMetrics,
188 publish: (column: string, metrics: NativeLayoutMetrics) =>
189 setColumnMetrics((current) =>
190 JSON.stringify(current.get(column)) === JSON.stringify(metrics)
191 ? current
192 : new Map(current).set(column, metrics),
193 ),
194 };
195 const [prewarmRequests, setPrewarmRequests] = useState<ReadonlyMap<string, number>>(
196 () => new Map(),
197 );
198 const prewarmReady = mountedSlots.size > 0;
199 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- waits for the JS thread to go idle after the first tab mounts
200 useEffect(() => {
201 if (!prewarmReady || prewarm) return;
202 const handle = requestIdleCallback(() => setPrewarm(true), { timeout: 2_000 });
203 return () => cancelIdleCallback(handle);
204 }, [prewarmReady, prewarm]);
205 const request = { selectedScreenKey, baseProvenance: provenance };
206 return (
207 <View style={{ flex: 1 }}>
208 <WorkspaceColumnMetricsContext value={sharedColumnMetrics}>
209 <Tabs.Host
210 navStateRequest={request}
211 tabBarHidden={props.hidden || !systemTabBar}
212 ios={{
213 tabBarControllerMode: "tabBar",
214 tabBarMinimizeBehavior: "never",
215 tabBarTintColor: colors["--color-primary"],
216 }}
217 onTabSelectionRejected={({
218 nativeEvent,
219 }: NativeSyntheticEvent<TabSelectionRejectedEvent>) =>
220 setProvenance(nativeEvent.provenance)
221 }
222 onTabSelected={({ nativeEvent }: NativeSyntheticEvent<TabSelectedEvent>) => {
223 setProvenance(nativeEvent.provenance);
224 if (nativeEvent.actionOrigin === "programmatic-js") return;
225 const tab = workspaceTabForNativeSlot(primaryTabs, nativeEvent.selectedScreenKey);
226 if (tab) selectTab(tab);
227 }}
228 >
229 {NATIVE_WORKSPACE_TAB_SLOTS.map((slot, index) => {
230 const settings = slot === "settings";
231 const tab = settings ? (overflow ?? selectedTab) : primaryTabs[index];
232 if (!tab) return null;
233 return (
234 <Tabs.Screen
235 // Stable slot controllers keep UIKit's stacks attached when a section moves into Settings.
236 key={slot}
237 screenKey={slot}
238 title=""
239 tabBarItemAccessibilityLabel={
240 settings ? gt("Settings") : m(WORKSPACE_TAB_LABELS[tab])
241 }
242 ios={{
243 prewarmRequest: prewarmRequests.get(slot) ?? 0,
244 contentReady: mountedSlots.has(slot),
245 icon: settings
246 ? { type: "sfSymbol", name: "gearshape" }
247 : tab === "pullRequests"
248 ? { type: "templateSource", templateSource: PULL_REQUEST_ICON }
249 : tab === "issues"
250 ? { type: "templateSource", templateSource: ISSUE_ICON }
251 : { type: "sfSymbol", name: NAVIGATION_TAB_ICONS[tab] },
252 selectedIcon:
253 !settings && tab === "threads"
254 ? { type: "sfSymbol", name: "text.bubble.fill" }
255 : undefined,
256 overrideScrollViewContentInsetAdjustmentBehavior: false,
257 }}
258 >
259 <RetainedWorkspaceTab
260 slot={slot}
261 tab={tab}
262 prewarm={prewarm}
263 setMountedSlots={setMountedSlots}
264 setPrewarmRequests={setPrewarmRequests}
265 active={settings ? selectedSlot === -1 : selectedSlot === index}
266 >
267 {props.children}
268 </RetainedWorkspaceTab>
269 </Tabs.Screen>
270 );
271 })}
272 </Tabs.Host>
273 </WorkspaceColumnMetricsContext>
274 {(deviceType === "pad" ||
275 compactTabs ||
276 (layout.variant === "medium" &&
277 !workspaceUsesColumns(selectedTab, workspace.settingsOpen))) &&
278 !props.hidden &&
279 !props.tabsInSidebarColumn &&
280 !hiddenWithSidebar ? (
281 <View
282 pointerEvents="box-none"
283 style={{
284 position: "absolute",
285 left: 0,
286 bottom: 0,
287 // UIKit can shrink the sidebar to 280pt independently of its preferred width.
288 width:
289 deviceType === "pad" && (floatingTabs || layout.usesSplitView)
290 ? Math.min(280, layout.listPaneWidth ?? width, width)
291 : (layout.listPaneWidth ?? width),
292 height: 128,
293 }}
294 >
295 <WorkspaceSidebarTabsFooter />
296 </View>
297 ) : null}
298 </View>
299 );
300 }
301
302 /** The workspace tabs at the foot of the sidebar. */
303 export function WorkspaceSidebarTabsFooter() {
304 const compose = useWorkspaceCompose();
305 const compact = useFloatingWorkspaceTabs();
306 return (
307 <WorkspaceSidebarTabs
308 compact={compact}
309 reserveComposeSpace={compact}
310 onNewTask={compact ? compose?.onPress : undefined}
311 />
312 );
313 }