Open History to see the last commit
1import type {
2 NativeStackHeaderItem,
3 NativeStackHeaderItemMenu,
4 NativeStackNavigationOptions,
5} from "@react-navigation/native-stack";
6import { isValidElement, useEffect, useRef } from "react";
7import { StyleSheet } from "react-native";
8import { KeyboardController, useKeyboardState } from "react-native-keyboard-controller";
9import { isDuoDevice } from "../lib/device-type";
10import { useMobileNavigationTheme } from "../lib/useMobileNavigationTheme";
11import { useDeviceType, useNativeLayoutMetrics } from "../native/native-layout-metrics";
12import {
13 SearchBar,
14 Stack,
15 type HeaderBarButtonMailSearchToolbarItem,
16 type SearchBarCommands,
17 type StackHeaderConfigProps,
18 type StackHeaderMinimizationBehaviorIOS,
19 type StackHeaderMenuElementIOS,
20 type StackHeaderMenuIOS,
21 type HeaderBarButtonItemWithMenu,
22 type HeaderBarButtonSearchBarPlacementItem,
23} from "react-native-screens";
24
25type HeaderItem = NonNullable<NonNullable<StackHeaderConfigProps["ios"]>["leadingItems"]>[number];
26type ToolbarItem =
27 | NativeStackHeaderItem
28 | HeaderBarButtonMailSearchToolbarItem
29 | HeaderBarButtonSearchBarPlacementItem;
30type Options = NativeStackNavigationOptions & {
31 readonly unstable_navigationItemStyle?: "editor" | "navigator";
32 readonly unstable_headerMinimizationBehavior?: StackHeaderMinimizationBehaviorIOS;
33 readonly headerSubtitle?: string;
34 readonly unstable_headerSubtitle?: string;
35 readonly headerSubtitleStyle?: { color?: string; fontSize?: number; fontFamily?: string };
36 readonly unstable_headerCenterItems?: () => NativeStackHeaderItem[];
37 readonly unstable_headerToolbarItems?: () => ToolbarItem[];
38};
39
40type MenuElementInput =
41 | NativeStackHeaderItemMenu["menu"]["items"][number]
42 | HeaderBarButtonItemWithMenu["menu"]["items"][number];
43type MenuInput = { readonly title?: string; readonly items: readonly MenuElementInput[] };
44
45function convertIcon(
46 icon:
47 | Extract<NativeStackHeaderItem, { type: "button" }>["icon"]
48 | HeaderBarButtonItemWithMenu["icon"],
49) {
50 if (!icon) return undefined;
51 if (icon.type === "image")
52 return icon.tinted === false
53 ? { type: "imageSource" as const, imageSource: icon.source }
54 : { type: "templateSource" as const, templateSource: icon.source };
55 return icon;
56}
57
58function convertMenu(menu: MenuInput, id: string): StackHeaderMenuIOS {
59 const children = menu.items.flatMap<StackHeaderMenuElementIOS>((item, index) => {
60 if ("hidden" in item && item.hidden) return [];
61 const childId = `${id}:${index}`;
62 if (item.type === "submenu") {
63 return [
64 {
65 ...convertMenu({ items: item.items }, childId),
66 title: "label" in item ? item.label : item.title,
67 displayInline:
68 "inline" in item
69 ? item.inline
70 : "displayInline" in item
71 ? item.displayInline
72 : undefined,
73 },
74 ];
75 }
76 return [
77 {
78 id: childId,
79 type: "menuItem" as const,
80 itemType: "action" as const,
81 title: "label" in item ? item.label : item.title,
82 icon: convertIcon(item.icon),
83 onPress: item.disabled ? undefined : item.onPress,
84 keepsMenuPresented: item.keepsMenuPresented,
85 disabled: item.disabled,
86 destructive: item.destructive,
87 subtitle:
88 ("subtitle" in item ? item.subtitle : undefined) ??
89 ("description" in item ? item.description : undefined),
90 state: item.state,
91 },
92 ];
93 });
94 return { id, type: "menu", title: menu.title, children };
95}
96
97function convertItems(items: NativeStackHeaderItem[], prefix: string): HeaderItem[] {
98 return items.map((item, index): HeaderItem => {
99 const id =
100 item.type === "spacing" ? `${prefix}:${index}` : (item.identifier ?? `${prefix}:${index}`);
101 switch (item.type) {
102 case "spacing":
103 return "flexible" in item && item.flexible === true
104 ? { type: "spacer", id, sizing: "flexible" }
105 : { type: "spacer", id, sizing: "fixed", width: item.spacing };
106 case "custom":
107 return {
108 type: "item",
109 id,
110 render: () => item.element,
111 hidesSharedBackground: item.hidesSharedBackground,
112 };
113 case "menu":
114 return {
115 type: "item",
116 id,
117 identifier: item.identifier,
118 title: item.label || item.accessibilityLabel || undefined,
119 axisBehavior: item.axisBehavior,
120 icon: convertIcon(item.icon),
121 menu: item.disabled ? undefined : convertMenu(item.menu, `${id}:menu`),
122 variant: item.variant,
123 tintColor: item.tintColor,
124 hidesSharedBackground: item.hidesSharedBackground,
125 };
126 case "button":
127 return {
128 type: "item",
129 id,
130 identifier: item.identifier,
131 title: item.label || item.accessibilityLabel || undefined,
132 axisBehavior: item.axisBehavior,
133 icon: convertIcon(item.icon),
134 onPress: item.disabled ? undefined : item.onPress,
135 visibilityPriority:
136 item.visibilityPriority === "default" ? "standard" : item.visibilityPriority,
137 variant: item.variant,
138 tintColor: item.tintColor,
139 hidesSharedBackground: item.hidesSharedBackground,
140 };
141 }
142 });
143}
144
145export function V5StackHeader(props: {
146 readonly options: Options;
147 readonly canGoBack: boolean;
148 /** Workspace split columns share the vertical bar with the workspace tab bar. */
149 readonly column?: "primary" | "detail";
150 /** The workspace's compose action, shown as its own group in this column's bar. */
151 readonly onCompose?: () => void;
152}) {
153 const { options } = props;
154 const theme = useMobileNavigationTheme();
155 const nativeMetrics = useNativeLayoutMetrics();
156 const deviceType = useDeviceType();
157 const keyboardVisible = useKeyboardState((state) => state.isVisible);
158 const searchRef = useRef<SearchBarCommands>(null);
159 const itemProps = { tintColor: options.headerTintColor, canGoBack: props.canGoBack };
160 const leading = convertItems(options.unstable_headerLeftItems?.(itemProps) ?? [], "leading");
161 const trailing = convertItems(
162 [
163 ...(options.unstable_headerCenterItems?.() ?? []),
164 ...(options.unstable_headerRightItems?.(itemProps) ?? []),
165 ],
166 "trailing",
167 );
168 const toolbar = options.unstable_headerToolbarItems?.() ?? [];
169 const mailSearch = toolbar.find(
170 (item): item is HeaderBarButtonMailSearchToolbarItem => item.type === "mailSearchToolbar",
171 );
172 const bottomSearch = Boolean(mailSearch) && deviceType !== "pad";
173 // A vertical bar keeps fixed spaces at full length and separates items itself.
174 const spacesSearch = bottomSearch && (nativeMetrics?.verticalBarEdge ?? "none") === "none";
175 const bottom = toolbar.flatMap<HeaderItem>((item, index) => {
176 if (item.type === "mailSearchToolbar") return [];
177 if (item.type === "searchBarPlacement")
178 return [{ type: "item", id: `toolbar-search:${index}`, searchBarPlacement: true }];
179 return convertItems([item], `toolbar:${index}`);
180 });
181 if (mailSearch) {
182 if (mailSearch.filterMenu)
183 bottom.push({
184 type: "item",
185 id: mailSearch.filterButtonId ?? "filter",
186 icon: {
187 type: "sfSymbol",
188 name: mailSearch.filterSystemImageName ?? "line.3.horizontal.decrease",
189 },
190 menu: convertMenu(mailSearch.filterMenu, "filter-menu"),
191 });
192 if (bottomSearch) {
193 if (spacesSearch && bottom.length)
194 bottom.push({ type: "spacer", id: "before-search", sizing: "fixed", width: 8 });
195 bottom.push({ type: "item", id: "home-search", searchBarPlacement: true });
196 if (spacesSearch && mailSearch.onComposePress)
197 bottom.push({ type: "spacer", id: "after-search", sizing: "fixed", width: 8 });
198 }
199 if (mailSearch.onComposePress)
200 bottom.push({
201 type: "item",
202 id: mailSearch.composeButtonId ?? "compose",
203 identifier: "workspace-trailing-action",
204 icon: { type: "sfSymbol", name: mailSearch.composeSystemImageName ?? "square.and.pencil" },
205 onPress: mailSearch.onComposePress,
206 });
207 }
208 // UIKit doesn't stack a column's toolbar against the workspace tab bar, which owns the
209 // bottom of the vertical bar and draws over it. Those columns keep the group in their
210 // navigation items. Integrated search stays in the column's horizontal bottom toolbar.
211 if (
212 props.column &&
213 nativeMetrics &&
214 nativeMetrics.verticalBarEdge !== "none" &&
215 (props.column === "detail" ||
216 (nativeMetrics.horizontalSizeClass === "compact" &&
217 !toolbar.some((item) => item.type === "searchBarPlacement")))
218 ) {
219 if (trailing.length && bottom.length)
220 trailing.push({ type: "spacer", id: "toolbar-group", sizing: "fixed", width: 8 });
221 trailing.push(...bottom);
222 bottom.length = 0;
223 }
224 if (props.onCompose) {
225 const compose: HeaderItem = {
226 type: "item",
227 id: "workspace-compose",
228 title: "New task",
229 icon: { type: "sfSymbol", name: "square.and.pencil" },
230 onPress: props.onCompose,
231 };
232 if (trailing.length)
233 trailing.push({ type: "spacer", id: "compose-group", sizing: "fixed", width: 8 });
234 trailing.push(compose);
235 }
236 // The vertical bar has no keyboard accessory row, so it carries its own dismiss. A regular-width
237 // primary column draws a horizontal bar beside the detail column's vertical one. The first
238 // trailing item sits at the bar's far end; the flexible space keeps it next to the keyboard.
239 if (
240 keyboardVisible &&
241 nativeMetrics &&
242 nativeMetrics.verticalBarEdge !== "none" &&
243 (props.column !== "primary" || nativeMetrics.horizontalSizeClass === "compact")
244 ) {
245 trailing.unshift(
246 {
247 type: "item",
248 id: "dismiss-keyboard",
249 title: "Dismiss keyboard",
250 icon: { type: "sfSymbol", name: "keyboard.chevron.compact.down" },
251 onPress: () => void KeyboardController.dismiss(),
252 // The folded bar is short; keep this out of the overflow menu.
253 visibilityPriority: "high",
254 },
255 { type: "spacer", id: "dismiss-keyboard-space", sizing: "flexible" },
256 );
257 }
258 const left = options.headerLeft?.(itemProps);
259 const right = options.headerRight?.(itemProps);
260 if (!options.unstable_headerLeftItems && isValidElement(left))
261 leading.push({ type: "item", id: "custom-left", render: () => left });
262 if (!options.unstable_headerRightItems && isValidElement(right))
263 trailing.push({ type: "item", id: "custom-right", render: () => right });
264 const title = typeof options.headerTitle === "string" ? options.headerTitle : options.title;
265 const titleElement =
266 typeof options.headerTitle === "function"
267 ? options.headerTitle({ children: title ?? "", tintColor: options.headerTintColor })
268 : undefined;
269 const searchOptions = options.headerSearchBarOptions;
270 const autofocusRef = searchOptions?.ref ?? searchRef;
271 useEffect(() => {
272 if (!searchOptions?.autoFocus) return;
273 const frame = requestAnimationFrame(() => autofocusRef.current?.focus());
274 return () => cancelAnimationFrame(frame);
275 }, [searchOptions?.autoFocus, autofocusRef]);
276 const titleStyle = StyleSheet.flatten(options.headerTitleStyle);
277 const headerStyle = StyleSheet.flatten(options.headerStyle);
278 const appearance = {
279 // Clear colors remove UIKit material; let translucent bars supply their own blur background.
280 backgroundColor: options.headerTransparent
281 ? undefined
282 : (headerStyle?.backgroundColor ?? theme.colors.card),
283 shadowColor: options.headerShadowVisible === false ? "transparent" : undefined,
284 titleFontSize: titleStyle?.fontSize,
285 titleFontFamily: titleStyle?.fontFamily,
286 titleFontWeight: titleStyle?.fontWeight,
287 titleFontColor: titleStyle?.color,
288 subtitleFontSize: options.headerSubtitleStyle?.fontSize,
289 subtitleFontColor: options.headerSubtitleStyle?.color,
290 };
291 return (
292 <Stack.HeaderConfig
293 hidden={options.headerShown === false}
294 transparent={options.headerTransparent}
295 title={title}
296 subtitle={options.unstable_headerSubtitle ?? options.headerSubtitle}
297 backButtonHidden={options.headerBackVisible === false}
298 ios={{
299 navigationItemStyle: options.unstable_navigationItemStyle,
300 // Opt-ins apply only where the Duo is short: folded, or held landscape. The Duo
301 // resolves `automatic` to minimize on scroll, so the tall unfolded display opts out.
302 minimizationBehavior: !isDuoDevice(deviceType)
303 ? undefined
304 : deviceType === "duo-unfolded" &&
305 nativeMetrics &&
306 nativeMetrics.height > nativeMetrics.width
307 ? "never"
308 : options.unstable_headerMinimizationBehavior,
309 tintColor: options.headerTintColor,
310 searchBar:
311 mailSearch || searchOptions ? (
312 <SearchBar
313 {...searchOptions}
314 ref={searchOptions?.ref ?? searchRef}
315 hideNavigationBar={false}
316 hideWhenScrolling={false}
317 allowToolbarIntegration={searchOptions?.allowToolbarIntegration ?? true}
318 placement={bottomSearch ? "integrated" : (searchOptions?.placement ?? "automatic")}
319 placeholder={mailSearch?.placeholder ?? searchOptions?.placeholder ?? "Search"}
320 onFocus={(event) => {
321 searchOptions?.onFocus?.(event);
322 }}
323 onChangeText={(event) => {
324 mailSearch?.onSearchTextChange?.(event.nativeEvent.text);
325 searchOptions?.onChangeText?.(event);
326 }}
327 />
328 ) : undefined,
329 toolbarItems: bottom,
330 leadingItems: leading,
331 trailingItems: trailing,
332 titleItem: isValidElement(titleElement)
333 ? { id: "title", render: () => titleElement }
334 : undefined,
335 largeTitleEnabled: options.headerLargeTitle,
336 backButtonDisplayMode: options.headerBackButtonDisplayMode ?? "minimal",
337 backButtonMenuEnabled: options.headerBackButtonMenuEnabled ?? true,
338 backButtonTitle: options.headerBackTitle,
339 standardAppearance: appearance,
340 scrollEdgeAppearance: appearance,
341 }}
342 />
343 );
344}