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