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