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 { Platform, StyleSheet } from "react-native";
8import { useMobileNavigationTheme } from "../lib/useMobileNavigationTheme";
9import { useNativeLayoutMetrics } from "../native/native-layout-metrics";
10import {
11 SearchBar,
12 Stack,
13 type HeaderBarButtonMailSearchToolbarItem,
14 type SearchBarCommands,
15 type StackHeaderConfigProps,
16 type StackHeaderMenuElementIOS,
17 type StackHeaderMenuIOS,
18 type HeaderBarButtonItemWithMenu,
19 type HeaderBarButtonSearchBarPlacementItem,
20} from "react-native-screens";
21
22type HeaderItem = NonNullable<NonNullable<StackHeaderConfigProps["ios"]>["leadingItems"]>[number];
23type ToolbarItem =
24 | NativeStackHeaderItem
25 | HeaderBarButtonMailSearchToolbarItem
26 | HeaderBarButtonSearchBarPlacementItem;
27type Options = NativeStackNavigationOptions & {
28 readonly unstable_navigationItemStyle?: "editor" | "navigator";
29 readonly headerSubtitle?: string;
30 readonly unstable_headerSubtitle?: string;
31 readonly headerSubtitleStyle?: { color?: string; fontSize?: number; fontFamily?: string };
32 readonly unstable_headerCenterItems?: () => NativeStackHeaderItem[];
33 readonly unstable_headerToolbarItems?: () => ToolbarItem[];
34};
35
36type MenuElementInput =
37 | NativeStackHeaderItemMenu["menu"]["items"][number]
38 | HeaderBarButtonItemWithMenu["menu"]["items"][number];
39type MenuInput = { readonly title?: string; readonly items: readonly MenuElementInput[] };
40
41function convertIcon(
42 icon:
43 | Extract<NativeStackHeaderItem, { type: "button" }>["icon"]
44 | HeaderBarButtonItemWithMenu["icon"],
45) {
46 if (!icon) return undefined;
47 if (icon.type === "image")
48 return icon.tinted === false
49 ? { type: "imageSource" as const, imageSource: icon.source }
50 : { type: "templateSource" as const, templateSource: icon.source };
51 return icon;
52}
53
54function convertMenu(menu: MenuInput, id: string): StackHeaderMenuIOS {
55 const children = menu.items.flatMap<StackHeaderMenuElementIOS>((item, index) => {
56 if ("hidden" in item && item.hidden) return [];
57 const childId = `${id}:${index}`;
58 if (item.type === "submenu") {
59 return [
60 {
61 ...convertMenu({ items: item.items }, childId),
62 title: "label" in item ? item.label : item.title,
63 displayInline:
64 "inline" in item
65 ? item.inline
66 : "displayInline" in item
67 ? item.displayInline
68 : undefined,
69 },
70 ];
71 }
72 return [
73 {
74 id: childId,
75 type: "menuItem" as const,
76 itemType: "action" as const,
77 title: "label" in item ? item.label : item.title,
78 icon: convertIcon(item.icon),
79 onPress: item.disabled ? undefined : item.onPress,
80 keepsMenuPresented: item.keepsMenuPresented,
81 disabled: item.disabled,
82 destructive: item.destructive,
83 subtitle:
84 ("subtitle" in item ? item.subtitle : undefined) ??
85 ("description" in item ? item.description : undefined),
86 state: item.state,
87 },
88 ];
89 });
90 return { id, type: "menu", title: menu.title, children };
91}
92
93function convertItems(items: NativeStackHeaderItem[], prefix: string): HeaderItem[] {
94 return items.map((item, index): HeaderItem => {
95 const id =
96 item.type === "spacing" ? `${prefix}:${index}` : (item.identifier ?? `${prefix}:${index}`);
97 switch (item.type) {
98 case "spacing":
99 return "flexible" in item && item.flexible === true
100 ? { type: "spacer", id, sizing: "flexible" }
101 : { type: "spacer", id, sizing: "fixed", width: item.spacing };
102 case "custom":
103 return {
104 type: "item",
105 id,
106 render: () => item.element,
107 hidesSharedBackground: item.hidesSharedBackground,
108 };
109 case "menu":
110 return {
111 type: "item",
112 id,
113 identifier: item.identifier,
114 title: item.label || item.accessibilityLabel || undefined,
115 axisBehavior: item.axisBehavior,
116 icon: convertIcon(item.icon),
117 menu: item.disabled ? undefined : convertMenu(item.menu, `${id}:menu`),
118 variant: item.variant,
119 tintColor: item.tintColor,
120 hidesSharedBackground: item.hidesSharedBackground,
121 };
122 case "button":
123 return {
124 type: "item",
125 id,
126 identifier: item.identifier,
127 title: item.label || item.accessibilityLabel || undefined,
128 axisBehavior: item.axisBehavior,
129 icon: convertIcon(item.icon),
130 onPress: item.disabled ? undefined : item.onPress,
131 variant: item.variant,
132 tintColor: item.tintColor,
133 hidesSharedBackground: item.hidesSharedBackground,
134 };
135 }
136 });
137}
138
139export function V5StackHeader(props: {
140 readonly options: Options;
141 readonly canGoBack: boolean;
142 readonly primary?: boolean;
143}) {
144 const { options } = props;
145 const theme = useMobileNavigationTheme();
146 const nativeMetrics = useNativeLayoutMetrics();
147 const searchRef = useRef<SearchBarCommands>(null);
148 const itemProps = { tintColor: options.headerTintColor, canGoBack: props.canGoBack };
149 const leading = convertItems(options.unstable_headerLeftItems?.(itemProps) ?? [], "leading");
150 const trailing = convertItems(
151 [
152 ...(options.unstable_headerCenterItems?.() ?? []),
153 ...(options.unstable_headerRightItems?.(itemProps) ?? []),
154 ],
155 "trailing",
156 );
157 const toolbar = options.unstable_headerToolbarItems?.() ?? [];
158 const mailSearch = toolbar.find(
159 (item): item is HeaderBarButtonMailSearchToolbarItem => item.type === "mailSearchToolbar",
160 );
161 const bottomSearch = Boolean(mailSearch) && Platform.OS === "ios" && !Platform.isPad;
162 const bottom = toolbar.flatMap<HeaderItem>((item, index) => {
163 if (item.type === "mailSearchToolbar") return [];
164 if (item.type === "searchBarPlacement")
165 return [{ type: "item", id: `toolbar-search:${index}`, searchBarPlacement: true }];
166 return convertItems([item], `toolbar:${index}`);
167 });
168 if (mailSearch) {
169 if (mailSearch.filterMenu)
170 bottom.push({
171 type: "item",
172 id: mailSearch.filterButtonId ?? "filter",
173 axisBehavior: bottomSearch ? "horizontalOnly" : undefined,
174 icon: {
175 type: "sfSymbol",
176 name: mailSearch.filterSystemImageName ?? "line.3.horizontal.decrease",
177 },
178 menu: convertMenu(mailSearch.filterMenu, "filter-menu"),
179 });
180 if (bottomSearch) {
181 if (bottom.length)
182 bottom.push({ type: "spacer", id: "before-search", sizing: "fixed", width: 8 });
183 bottom.push({
184 type: "item",
185 id: "home-search",
186 axisBehavior: "horizontalOnly",
187 searchBarPlacement: true,
188 });
189 if (mailSearch.onComposePress)
190 bottom.push({ type: "spacer", id: "after-search", sizing: "fixed", width: 8 });
191 }
192 if (mailSearch.onComposePress)
193 bottom.push({
194 type: "item",
195 id: mailSearch.composeButtonId ?? "compose",
196 axisBehavior: bottomSearch ? "horizontalOnly" : undefined,
197 identifier: "workspace-trailing-action",
198 icon: { type: "sfSymbol", name: mailSearch.composeSystemImageName ?? "square.and.pencil" },
199 onPress: mailSearch.onComposePress,
200 });
201 }
202 // Duo keeps compose at the bottom of a visible sidebar. On a single panel,
203 // the primary column owns the rail too; its separate UIToolbar is inaccessible.
204 if (
205 nativeMetrics &&
206 nativeMetrics.verticalBarEdge !== "none" &&
207 (!props.primary || nativeMetrics.horizontalSizeClass === "compact")
208 ) {
209 trailing.push(...bottom);
210 bottom.length = 0;
211 }
212 const left = options.headerLeft?.(itemProps);
213 const right = options.headerRight?.(itemProps);
214 if (!options.unstable_headerLeftItems && isValidElement(left))
215 leading.push({ type: "item", id: "custom-left", render: () => left });
216 if (!options.unstable_headerRightItems && isValidElement(right))
217 trailing.push({ type: "item", id: "custom-right", render: () => right });
218 const title = typeof options.headerTitle === "string" ? options.headerTitle : options.title;
219 const titleElement =
220 typeof options.headerTitle === "function"
221 ? options.headerTitle({ children: title ?? "", tintColor: options.headerTintColor })
222 : undefined;
223 const searchOptions = options.headerSearchBarOptions;
224 const autofocusRef = searchOptions?.ref ?? searchRef;
225 const searchHasFocus = useRef(false);
226 useEffect(() => {
227 searchHasFocus.current = false;
228 if (!searchOptions?.autoFocus) return;
229 // UIKit attaches integrated search during the toolbar transition. Native
230 // onFocus acknowledges readiness; a single frame can reach it too early.
231 const deadline = Date.now() + 500;
232 let frame = 0;
233 const focusWhenAttached = () => {
234 if (searchHasFocus.current) return;
235 autofocusRef.current?.focus();
236 if (Date.now() < deadline) frame = requestAnimationFrame(focusWhenAttached);
237 };
238 frame = requestAnimationFrame(focusWhenAttached);
239 return () => cancelAnimationFrame(frame);
240 }, [searchOptions?.autoFocus, autofocusRef]);
241 const titleStyle = StyleSheet.flatten(options.headerTitleStyle);
242 const headerStyle = StyleSheet.flatten(options.headerStyle);
243 const appearance = {
244 // A clear color also removes UIKit's material. Let UIKit supply it for
245 // translucent bars so scrolling content can appear beneath native blur.
246 backgroundColor: options.headerTransparent
247 ? undefined
248 : (headerStyle?.backgroundColor ?? theme.colors.card),
249 shadowColor: options.headerShadowVisible === false ? "transparent" : undefined,
250 titleFontSize: titleStyle?.fontSize,
251 titleFontFamily: titleStyle?.fontFamily,
252 titleFontWeight: titleStyle?.fontWeight,
253 titleFontColor: titleStyle?.color,
254 subtitleFontSize: options.headerSubtitleStyle?.fontSize,
255 subtitleFontColor: options.headerSubtitleStyle?.color,
256 };
257 return (
258 <Stack.HeaderConfig
259 hidden={options.headerShown === false}
260 transparent={options.headerTransparent}
261 title={title}
262 subtitle={options.unstable_headerSubtitle ?? options.headerSubtitle}
263 backButtonHidden={options.headerBackVisible === false}
264 ios={{
265 navigationItemStyle: options.unstable_navigationItemStyle,
266 tintColor: options.headerTintColor,
267 searchBar:
268 mailSearch || searchOptions ? (
269 <SearchBar
270 {...searchOptions}
271 ref={searchOptions?.ref ?? searchRef}
272 hideNavigationBar={false}
273 hideWhenScrolling={false}
274 allowToolbarIntegration={searchOptions?.allowToolbarIntegration ?? true}
275 placement={bottomSearch ? "integrated" : (searchOptions?.placement ?? "automatic")}
276 placeholder={mailSearch?.placeholder ?? searchOptions?.placeholder ?? "Search"}
277 onFocus={(event) => {
278 searchHasFocus.current = true;
279 searchOptions?.onFocus?.(event);
280 }}
281 onChangeText={(event) => {
282 mailSearch?.onSearchTextChange?.(event.nativeEvent.text);
283 searchOptions?.onChangeText?.(event);
284 }}
285 />
286 ) : undefined,
287 toolbarItems: bottom,
288 leadingItems: leading,
289 trailingItems: trailing,
290 titleItem: isValidElement(titleElement)
291 ? { id: "title", render: () => titleElement }
292 : undefined,
293 largeTitleEnabled: options.headerLargeTitle,
294 backButtonDisplayMode: options.headerBackButtonDisplayMode ?? "minimal",
295 backButtonMenuEnabled: options.headerBackButtonMenuEnabled ?? true,
296 backButtonTitle: options.headerBackTitle,
297 standardAppearance: appearance,
298 scrollEdgeAppearance: appearance,
299 }}
300 />
301 );
302}