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 { useMobileNavigationTheme } from "../lib/useMobileNavigationTheme";
9import { useDeviceType, 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 deviceType = useDeviceType();
148 const searchRef = useRef<SearchBarCommands>(null);
149 const itemProps = { tintColor: options.headerTintColor, canGoBack: props.canGoBack };
150 const leading = convertItems(options.unstable_headerLeftItems?.(itemProps) ?? [], "leading");
151 const trailing = convertItems(
152 [
153 ...(options.unstable_headerCenterItems?.() ?? []),
154 ...(options.unstable_headerRightItems?.(itemProps) ?? []),
155 ],
156 "trailing",
157 );
158 const toolbar = options.unstable_headerToolbarItems?.() ?? [];
159 const mailSearch = toolbar.find(
160 (item): item is HeaderBarButtonMailSearchToolbarItem => item.type === "mailSearchToolbar",
161 );
162 const bottomSearch = Boolean(mailSearch) && deviceType !== "pad";
163 const bottom = toolbar.flatMap<HeaderItem>((item, index) => {
164 if (item.type === "mailSearchToolbar") return [];
165 if (item.type === "searchBarPlacement")
166 return [{ type: "item", id: `toolbar-search:${index}`, searchBarPlacement: true }];
167 return convertItems([item], `toolbar:${index}`);
168 });
169 if (mailSearch) {
170 if (mailSearch.filterMenu)
171 bottom.push({
172 type: "item",
173 id: mailSearch.filterButtonId ?? "filter",
174 axisBehavior: bottomSearch ? "horizontalOnly" : undefined,
175 icon: {
176 type: "sfSymbol",
177 name: mailSearch.filterSystemImageName ?? "line.3.horizontal.decrease",
178 },
179 menu: convertMenu(mailSearch.filterMenu, "filter-menu"),
180 });
181 if (bottomSearch) {
182 if (bottom.length)
183 bottom.push({ type: "spacer", id: "before-search", sizing: "fixed", width: 8 });
184 bottom.push({
185 type: "item",
186 id: "home-search",
187 axisBehavior: "horizontalOnly",
188 searchBarPlacement: true,
189 });
190 if (mailSearch.onComposePress)
191 bottom.push({ type: "spacer", id: "after-search", sizing: "fixed", width: 8 });
192 }
193 if (mailSearch.onComposePress)
194 bottom.push({
195 type: "item",
196 id: mailSearch.composeButtonId ?? "compose",
197 axisBehavior: bottomSearch ? "horizontalOnly" : undefined,
198 identifier: "workspace-trailing-action",
199 icon: { type: "sfSymbol", name: mailSearch.composeSystemImageName ?? "square.and.pencil" },
200 onPress: mailSearch.onComposePress,
201 });
202 }
203 // Duo keeps compose at the bottom of a visible sidebar. On a single panel,
204 // the primary column owns the rail too; its separate UIToolbar is inaccessible.
205 if (
206 nativeMetrics &&
207 nativeMetrics.verticalBarEdge !== "none" &&
208 (!props.primary || nativeMetrics.horizontalSizeClass === "compact")
209 ) {
210 trailing.push(...bottom);
211 bottom.length = 0;
212 }
213 const left = options.headerLeft?.(itemProps);
214 const right = options.headerRight?.(itemProps);
215 if (!options.unstable_headerLeftItems && isValidElement(left))
216 leading.push({ type: "item", id: "custom-left", render: () => left });
217 if (!options.unstable_headerRightItems && isValidElement(right))
218 trailing.push({ type: "item", id: "custom-right", render: () => right });
219 const title = typeof options.headerTitle === "string" ? options.headerTitle : options.title;
220 const titleElement =
221 typeof options.headerTitle === "function"
222 ? options.headerTitle({ children: title ?? "", tintColor: options.headerTintColor })
223 : undefined;
224 const searchOptions = options.headerSearchBarOptions;
225 const autofocusRef = searchOptions?.ref ?? searchRef;
226 const searchHasFocus = useRef(false);
227 useEffect(() => {
228 searchHasFocus.current = false;
229 if (!searchOptions?.autoFocus) return;
230 // UIKit attaches integrated search during the toolbar transition. Native
231 // onFocus acknowledges readiness; a single frame can reach it too early.
232 const deadline = Date.now() + 500;
233 let frame = 0;
234 const focusWhenAttached = () => {
235 if (searchHasFocus.current) return;
236 autofocusRef.current?.focus();
237 if (Date.now() < deadline) frame = requestAnimationFrame(focusWhenAttached);
238 };
239 frame = requestAnimationFrame(focusWhenAttached);
240 return () => cancelAnimationFrame(frame);
241 }, [searchOptions?.autoFocus, autofocusRef]);
242 const titleStyle = StyleSheet.flatten(options.headerTitleStyle);
243 const headerStyle = StyleSheet.flatten(options.headerStyle);
244 const appearance = {
245 // A clear color also removes UIKit's material. Let UIKit supply it for
246 // translucent bars so scrolling content can appear beneath native blur.
247 backgroundColor: options.headerTransparent
248 ? undefined
249 : (headerStyle?.backgroundColor ?? theme.colors.card),
250 shadowColor: options.headerShadowVisible === false ? "transparent" : undefined,
251 titleFontSize: titleStyle?.fontSize,
252 titleFontFamily: titleStyle?.fontFamily,
253 titleFontWeight: titleStyle?.fontWeight,
254 titleFontColor: titleStyle?.color,
255 subtitleFontSize: options.headerSubtitleStyle?.fontSize,
256 subtitleFontColor: options.headerSubtitleStyle?.color,
257 };
258 return (
259 <Stack.HeaderConfig
260 hidden={options.headerShown === false}
261 transparent={options.headerTransparent}
262 title={title}
263 subtitle={options.unstable_headerSubtitle ?? options.headerSubtitle}
264 backButtonHidden={options.headerBackVisible === false}
265 ios={{
266 navigationItemStyle: options.unstable_navigationItemStyle,
267 tintColor: options.headerTintColor,
268 searchBar:
269 mailSearch || searchOptions ? (
270 <SearchBar
271 {...searchOptions}
272 ref={searchOptions?.ref ?? searchRef}
273 hideNavigationBar={false}
274 hideWhenScrolling={false}
275 allowToolbarIntegration={searchOptions?.allowToolbarIntegration ?? true}
276 placement={bottomSearch ? "integrated" : (searchOptions?.placement ?? "automatic")}
277 placeholder={mailSearch?.placeholder ?? searchOptions?.placeholder ?? "Search"}
278 onFocus={(event) => {
279 searchHasFocus.current = true;
280 searchOptions?.onFocus?.(event);
281 }}
282 onChangeText={(event) => {
283 mailSearch?.onSearchTextChange?.(event.nativeEvent.text);
284 searchOptions?.onChangeText?.(event);
285 }}
286 />
287 ) : undefined,
288 toolbarItems: bottom,
289 leadingItems: leading,
290 trailingItems: trailing,
291 titleItem: isValidElement(titleElement)
292 ? { id: "title", render: () => titleElement }
293 : undefined,
294 largeTitleEnabled: options.headerLargeTitle,
295 backButtonDisplayMode: options.headerBackButtonDisplayMode ?? "minimal",
296 backButtonMenuEnabled: options.headerBackButtonMenuEnabled ?? true,
297 backButtonTitle: options.headerBackTitle,
298 standardAppearance: appearance,
299 scrollEdgeAppearance: appearance,
300 }}
301 />
302 );
303}