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