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

main
tsx 333 lines 13.4 KB
Raw
1 import { useGT, useLocale, useMessages } from "gt-react-native";
2
3 import { Toolbar } from "./Toolbar";
4 import { AppActivityIndicator } from "./AppActivityIndicator";
5 import type { HeaderBarButtonMailSearchToolbarItem, SearchBarCommands } from "react-native-screens";
6 import { NavigationContext, NavigationRouteContext } from "@react-navigation/native";
7 import { use, useId, useLayoutEffect, useRef, useSyncExternalStore } from "react";
8 import { View } from "react-native";
9 import { createNativeHeaderMenu } from "./nativeHeaderMenu.ios";
10 import { ScreenHeaderButton } from "./ScreenHeaderButton";
11 import { NativeStackScreenOptions, useScreenOptionsWriter } from "../../native/StackHeader";
12 import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
13 import { useDeviceType } from "../../native/native-layout-metrics";
14 import { isDuoDevice } from "../../lib/device-type";
15 import { useAdaptiveWorkspaceLayout } from "../../features/layout/AdaptiveWorkspaceLayout";
16 import { useSidebarToggle } from "../../features/layout/useSidebarToggle";
17 import { InspectorCloseContext } from "../../features/layout/inspector-bar-store";
18 import {
19 createNativeMailSearchToolbarItem,
20 NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
21 } from "../../features/layout/native-mail-search-toolbar";
22 import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider";
23 import type { AppBarMenu, AppBarMenuItem, AppBarProps } from "./AppBar.types";
24 import type { AppSymbolName } from "./AppSymbol";
25 import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar";
26 import { useControlTheme } from "./useControlTheme";
27
28 function iosIcon(icon: AppSymbolName) {
29 return typeof icon === "string" ? icon : icon.ios;
30 }
31
32 type MailMenu = NonNullable<HeaderBarButtonMailSearchToolbarItem["filterMenu"]>;
33 function mailMenuItems(items: ReadonlyArray<AppBarMenuItem>): MailMenu["items"] {
34 return items.map((item) =>
35 "items" in item
36 ? { type: "submenu", title: item.title ?? "", items: mailMenuItems(item.items) }
37 : {
38 type: "action",
39 title: item.title,
40 state: item.selected ? "on" : "off",
41 disabled: item.disabled,
42 onPress: item.onPress,
43 },
44 );
45 }
46
47 export function AppBar(props: AppBarProps) {
48 const gt = useGT();
49 const m = useMessages();
50 const locale = useLocale();
51 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
52 const deviceType = useDeviceType();
53 const headerId = useId();
54 const { layout } = useAdaptiveWorkspaceLayout();
55 const sidebarToggle = useSidebarToggle();
56 const closeInspector = use(InspectorCloseContext);
57 const setOptions = useScreenOptionsWriter();
58 const ownsInspectorBar = closeInspector !== null && !props.embedded && !props.sheet;
59 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- an inspector pane that stops drawing its bar must not leave it in the out-of-tree inspector bar
60 useLayoutEffect(() => {
61 if (!ownsInspectorBar || !setOptions) return;
62 setOptions({ headerShown: true });
63 return () => setOptions({ headerShown: false });
64 }, [ownsInspectorBar, setOptions]);
65 const splitBackPress = props.backInSplitView?.onPress ?? props.onBack;
66 const splitBack =
67 layout.usesSplitView && props.backInSplitView && splitBackPress
68 ? { ...props.backInSplitView, onPress: splitBackPress }
69 : null;
70 const navigation = use(NavigationContext);
71 const route = use(NavigationRouteContext);
72 // A thread opened from another thread sits on it, not beside the list, so it keeps Back.
73 const threadBelow = useSyncExternalStore(
74 (onChange) => navigation?.addListener("state", onChange) ?? (() => {}),
75 () => {
76 const routes = navigation?.getState()?.routes;
77 const index = routes?.findIndex((candidate) => candidate.key === route?.key) ?? -1;
78 return route?.name === "Thread" && index > 0 && routes?.[index - 1]?.name === "Thread";
79 },
80 );
81 const listBeside = layout.usesSplitView && props.onBackToList !== undefined && !threadBelow;
82 const rootBack =
83 !layout.usesSplitView && props.onBackToList && navigation?.canGoBack() === false
84 ? props.onBackToList
85 : props.guardBack && props.onBack
86 ? props.onBack
87 : null;
88 const compose =
89 layout.usesSplitView && !(usesNativeWorkspaceColumns && isDuoDevice(deviceType))
90 ? props.onCompose
91 : undefined;
92 const { themeVariables } = useAppearancePreferences();
93 const { colors } = useControlTheme();
94 const usesNativeMailSearchToolbar = useNativeMailSearchToolbar();
95 const { search, menus } = props;
96 const menu = menus?.[0];
97 const searchBarRef = useRef<SearchBarCommands>(null);
98 const nativeSearchText = useRef(search?.value ?? "");
99 const searchValue = search?.value;
100 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the native search bar keeps its own text; a value the caller changes (a reset) has to be pushed into it
101 useLayoutEffect(() => {
102 if (searchValue === undefined || searchValue === nativeSearchText.current) return;
103 nativeSearchText.current = searchValue;
104 searchBarRef.current?.setText(searchValue);
105 }, [searchValue]);
106 const reportSearchText = (text: string) => {
107 nativeSearchText.current = text;
108 search?.onChangeText(text);
109 };
110 const compactSearch =
111 search !== undefined &&
112 (search.compactToolbar ?? !layout.usesSplitView) &&
113 usesNativeMailSearchToolbar;
114 const trailingMenus = compactSearch ? (menus?.slice(1) ?? []) : (menus ?? []);
115 // The Duo's vertical bar never overflows: items that don't fit slide under the workspace tabs,
116 // and a Live Activity pushes them down further. More than one tool shares one menu there.
117 const groupTrailing =
118 usesNativeWorkspaceColumns &&
119 isDuoDevice(deviceType) &&
120 props.onClose === undefined &&
121 (props.actions?.length ?? 0) + trailingMenus.length > 1;
122 const actions = groupTrailing ? [] : (props.actions ?? []);
123 const visibleMenus: ReadonlyArray<AppBarMenu> = groupTrailing
124 ? [
125 {
126 title: gt("More actions"),
127 icon: "ellipsis",
128 items: [
129 ...(props.actions ?? []).map((action) => ({
130 id: action.accessibilityLabel,
131 title: action.accessibilityLabel,
132 icon: iosIcon(action.icon),
133 subtitle: action.subtitle,
134 disabled: action.disabled || action.loading,
135 selected: action.selected,
136 destructive: action.destructive,
137 onPress: action.onPress,
138 })),
139 ...trailingMenus.map((menu) => ({
140 id: menu.title,
141 title: menu.title,
142 icon: iosIcon(menu.icon),
143 items: menu.items,
144 })),
145 ],
146 },
147 ]
148 : trailingMenus;
149 // Where the mail toolbar isn't used, the Duo keeps search at the bottom of the pane like its
150 // workspace lists; elsewhere inline search is a button in the bar.
151 const duoBottomSearch =
152 search !== undefined &&
153 !compactSearch &&
154 NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED &&
155 isDuoDevice(deviceType);
156 if (props.embedded || props.sheet) return null;
157 return (
158 <>
159 <NativeStackScreenOptions
160 optionsVersion={[props.optionsVersion, compactSearch ? menu : undefined, locale]}
161 options={{
162 headerShown: true,
163 headerBackVisible:
164 props.onClose === undefined &&
165 splitBack === null &&
166 !listBeside &&
167 !(props.guardBack && props.onBack),
168 ...(props.guardBack ? { gestureEnabled: false } : undefined),
169 title: props.title,
170 unstable_headerSubtitle: props.subtitle || undefined,
171 ...(props.matchSearchSurface
172 ? { contentStyle: { backgroundColor: themeVariables["--color-sheet-solid"] } }
173 : undefined),
174 ...(search
175 ? {
176 unstable_headerToolbarItems: compactSearch
177 ? () => [
178 createNativeMailSearchToolbarItem(
179 {
180 showsSearchDismissButton: true,
181 placeholder: search.compactPlaceholder ?? search.placeholder,
182 onSearchTextChange: search.onChangeText,
183 searchTextChangeId: `${headerId}-search-text`,
184 ...(menu
185 ? {
186 filterButtonId: `${headerId}-filter`,
187 filterSystemImageName: iosIcon(menu.icon),
188 filterMenu: { title: menu.title, items: mailMenuItems(menu.items) },
189 }
190 : undefined),
191 },
192 m,
193 ),
194 ]
195 : () => [],
196 headerSearchBarOptions: compactSearch
197 ? undefined
198 : {
199 allowToolbarIntegration: true,
200 ...(duoBottomSearch
201 ? { placement: "integrated" as const }
202 : NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED && search.mode === "inline"
203 ? { placement: "integratedButton" as const }
204 : undefined),
205 autoCapitalize: "none",
206 hideNavigationBar: false,
207 ...(search.mode === "inline" || duoBottomSearch
208 ? { obscureBackground: false }
209 : undefined),
210 placeholder: search.placeholder,
211 ref: searchBarRef,
212 onChangeText: (event) => reportSearchText(event.nativeEvent.text),
213 onCancelButtonPress: () => reportSearchText(""),
214 },
215 }
216 : undefined),
217 }}
218 />
219 {props.onClose ? (
220 <Toolbar placement="left">
221 <Toolbar.Button
222 icon="xmark"
223 accessibilityLabel={props.closeAccessibilityLabel ?? gt("Close")}
224 onPress={props.onClose}
225 />
226 </Toolbar>
227 ) : rootBack || splitBack || sidebarToggle || compose ? (
228 <Toolbar placement="left">
229 {rootBack ? (
230 <ScreenHeaderButton
231 accessibilityLabel={gt("Back")}
232 icon="chevron.left"
233 onPress={rootBack}
234 separateBackground
235 />
236 ) : null}
237 {splitBack ? <ScreenHeaderButton {...splitBack} /> : null}
238 {sidebarToggle ? (
239 <ScreenHeaderButton
240 axisBehavior={usesNativeWorkspaceColumns ? "horizontalOnly" : undefined}
241 accessibilityLabel={sidebarToggle.accessibilityLabel}
242 icon={sidebarToggle.icon}
243 onPress={sidebarToggle.onPress}
244 separateBackground={splitBack ? splitBack.separateBackground : true}
245 />
246 ) : null}
247 {compose ? (
248 <ScreenHeaderButton
249 accessibilityLabel={gt("New task")}
250 label={gt("New task")}
251 icon="square.and.pencil"
252 onPress={compose}
253 separateBackground
254 />
255 ) : null}
256 </Toolbar>
257 ) : null}
258 {actions.length ||
259 visibleMenus.length ||
260 props.trailing ||
261 props.confirm ||
262 closeInspector ? (
263 <Toolbar placement="right">
264 {actions.map(({ loading, ...action }) =>
265 loading ? (
266 <Toolbar.Custom key={action.accessibilityLabel}>
267 <View
268 accessibilityLabel={action.accessibilityLabel}
269 className="size-9 items-center justify-center"
270 >
271 <AppActivityIndicator color={action.tintColor} />
272 </View>
273 </Toolbar.Custom>
274 ) : (
275 <ScreenHeaderButton
276 key={action.accessibilityLabel}
277 {...action}
278 icon={iosIcon(action.icon)}
279 separateBackground={action.separateBackground ?? true}
280 />
281 ),
282 )}
283 {visibleMenus.map(createNativeHeaderMenu)}
284 {props.trailing}
285 {props.confirm?.loading ? (
286 <Toolbar.Custom>
287 <View
288 className="size-11 items-center justify-center"
289 accessible
290 accessibilityLabel={props.confirm.label}
291 accessibilityState={{ busy: true }}
292 >
293 <AppActivityIndicator colorClassName="accent-prominent-action" />
294 </View>
295 </Toolbar.Custom>
296 ) : props.confirm ? (
297 <Toolbar.Button
298 icon="checkmark"
299 variant="prominent"
300 visibilityPriority="high"
301 tintColor={colors["--color-prominent-action"]}
302 accessibilityLabel={props.confirm.label}
303 disabled={props.confirm.disabled}
304 onPress={props.confirm.onPress}
305 />
306 ) : null}
307 {closeInspector ? (
308 <ScreenHeaderButton
309 accessibilityLabel={gt("Close inspector")}
310 icon="xmark"
311 onPress={closeInspector}
312 separateBackground
313 />
314 ) : null}
315 </Toolbar>
316 ) : null}
317 {duoBottomSearch ? (
318 <Toolbar placement="bottom">
319 <Toolbar.SearchBarSlot />
320 </Toolbar>
321 ) : null}
322 </>
323 );
324 }
325
326 export type {
327 AppBarAction,
328 AppBarConfirm,
329 AppBarMenu,
330 AppBarMenuItem,
331 AppBarProps,
332 AppBarSearch,
333 } from "./AppBar.types";