Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

V5StackHeader.ios.tsx

374 lines15.3 KB

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;
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 };
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 disabled: item.disabled,
128 variant: item.variant,
129 tintColor: item.tintColor,
130 hidesSharedBackground: item.hidesSharedBackground,
131 };
132 case "button":
133 return {
134 type: "item",
135 id,
136 identifier: item.identifier,
137 title: item.label || item.accessibilityLabel || undefined,
138 axisBehavior: item.axisBehavior,
139 icon: convertIcon(item.icon),
140 onPress: item.disabled ? undefined : item.onPress,
141 disabled: item.disabled,
142 visibilityPriority:
143 item.visibilityPriority === "default" ? "standard" : item.visibilityPriority,
144 variant: item.variant,
145 tintColor: item.tintColor,
146 hidesSharedBackground: item.hidesSharedBackground,
147 };
148 }
149 });
151​
152export function V5StackHeader(props: {
153 readonly options: Options;
154 readonly canGoBack: boolean;
155 /** Workspace split columns share the vertical bar with the workspace tab bar. */
156 readonly column?: "primary" | "detail";
157 /** The workspace's compose action, shown as its own group in this column's bar. */
158 readonly onCompose?: () => void;
159}) {
160 const { options } = props;
161 const theme = useMobileNavigationTheme();
162 const nativeMetrics = useNativeLayoutMetrics();
163 const deviceType = useDeviceType();
164 const keyboardVisible = useKeyboardState((state) => state.isVisible);
165 const searchRef = useRef<SearchBarCommands>(null);
166 const itemProps = { tintColor: options.headerTintColor, canGoBack: props.canGoBack };
167 const leading = convertItems(options.unstable_headerLeftItems?.(itemProps) ?? [], "leading");
168 const trailing = convertItems(
169 [
170 ...(options.unstable_headerCenterItems?.() ?? []),
171 ...(options.unstable_headerRightItems?.(itemProps) ?? []),
172 ],
173 "trailing",
174 );
175 const toolbar = options.unstable_headerToolbarItems?.() ?? [];
176 const mailSearch = toolbar.find(
177 (item): item is HeaderBarButtonMailSearchToolbarItem => item.type === "mailSearchToolbar",
178 );
179 const bottomSearch = Boolean(mailSearch) && deviceType !== "pad";
180 // A vertical bar keeps fixed spaces at full length and separates items itself.
181 const spacesSearch = bottomSearch && (nativeMetrics?.verticalBarEdge ?? "none") === "none";
182 const bottom = toolbar.flatMap<HeaderItem>((item, index) => {
183 if (item.type === "mailSearchToolbar") return [];
184 if (item.type === "searchBarPlacement")
185 return [{ type: "item", id: `toolbar-search:${index}`, searchBarPlacement: true }];
186 return convertItems([item], `toolbar:${index}`);
187 });
188 if (mailSearch) {
189 if (mailSearch.filterMenu)
190 bottom.push({
191 type: "item",
192 id: mailSearch.filterButtonId ?? "filter",
193 icon: {
194 type: "sfSymbol",
195 name: mailSearch.filterSystemImageName ?? "line.3.horizontal.decrease",
196 },
197 menu: convertMenu(mailSearch.filterMenu, "filter-menu"),
198 });
199 if (bottomSearch) {
200 if (spacesSearch && bottom.length)
201 bottom.push({ type: "spacer", id: "before-search", sizing: "fixed", width: 8 });
202 bottom.push({ type: "item", id: "home-search", searchBarPlacement: true });
203 if (spacesSearch && mailSearch.onComposePress)
204 bottom.push({ type: "spacer", id: "after-search", sizing: "fixed", width: 8 });
205 }
206 if (mailSearch.onComposePress)
207 bottom.push({
208 type: "item",
209 id: mailSearch.composeButtonId ?? "compose",
210 identifier: "workspace-trailing-action",
211 icon: { type: "sfSymbol", name: mailSearch.composeSystemImageName ?? "square.and.pencil" },
212 onPress: mailSearch.onComposePress,
213 });
214 }
215 // UIKit doesn't stack a column's toolbar against the workspace tab bar, which owns the
216 // bottom of the vertical bar and draws over it. Those columns keep the group in their
217 // navigation items. Integrated search stays in the column's horizontal bottom toolbar.
218 if (
219 props.column &&
220 nativeMetrics &&
221 nativeMetrics.verticalBarEdge !== "none" &&
222 (props.column === "detail" ||
223 (nativeMetrics.horizontalSizeClass === "compact" &&
224 !toolbar.some((item) => item.type === "searchBarPlacement")))
225 ) {
226 if (trailing.length && bottom.length)
227 trailing.push({ type: "spacer", id: "toolbar-group", sizing: "fixed", width: 8 });
228 trailing.push(...bottom);
229 bottom.length = 0;
230 }
231 if (props.onCompose) {
232 const compose: HeaderItem = {
233 type: "item",
234 id: "workspace-compose",
235 title: "New task",
236 icon: { type: "sfSymbol", name: "square.and.pencil" },
237 onPress: props.onCompose,
238 };
239 if (trailing.length)
240 trailing.push({ type: "spacer", id: "compose-group", sizing: "fixed", width: 8 });
241 trailing.push(compose);
242 }
243 // The vertical bar has no keyboard accessory row, so it carries its own dismiss. A regular-width
244 // primary column draws a horizontal bar beside the detail column's vertical one. The first
245 // trailing item sits at the bar's far end; the flexible space keeps it next to the keyboard.
246 if (
247 keyboardVisible &&
248 nativeMetrics &&
249 nativeMetrics.verticalBarEdge !== "none" &&
250 (props.column !== "primary" || nativeMetrics.horizontalSizeClass === "compact")
251 ) {
252 trailing.unshift(
253 {
254 type: "item",
255 id: "dismiss-keyboard",
256 title: "Dismiss keyboard",
257 icon: { type: "sfSymbol", name: "keyboard.chevron.compact.down" },
258 onPress: () => void KeyboardController.dismiss(),
259 // The folded bar is short; keep this out of the overflow menu.
260 visibilityPriority: "high",
261 },
262 { type: "spacer", id: "dismiss-keyboard-space", sizing: "flexible" },
263 );
264 }
265 const left = options.headerLeft?.(itemProps);
266 const right = options.headerRight?.(itemProps);
267 if (!options.unstable_headerLeftItems && isValidElement(left))
268 leading.push({ type: "item", id: "custom-left", render: () => left });
269 if (!options.unstable_headerRightItems && isValidElement(right))
270 trailing.push({ type: "item", id: "custom-right", render: () => right });
271 const title = typeof options.headerTitle === "string" ? options.headerTitle : options.title;
272 const titleElement =
273 typeof options.headerTitle === "function"
274 ? options.headerTitle({ children: title ?? "", tintColor: options.headerTintColor })
275 : undefined;
276 const searchOptions = options.headerSearchBarOptions;
277 const autofocusRef = searchOptions?.ref ?? searchRef;
278 // iOS ignores the native autoFocus prop, and SearchBar's imperative handle changes every
279 // commit, so a ref callback would refocus on each render; focus once after the header mounts.
280 // 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
281 useEffect(() => {
282 if (!searchOptions?.autoFocus) return;
283 const frame = requestAnimationFrame(() => autofocusRef.current?.focus());
284 return () => cancelAnimationFrame(frame);
285 }, [searchOptions?.autoFocus, autofocusRef]);
286 const searchButton = !bottomSearch && searchOptions?.placement === "integratedButton";
287 const itemsWidth =
288 BAR_MARGINS +
289 (props.canGoBack && options.headerBackVisible !== false ? BAR_BUTTON_WIDTH : 0) +
290 (searchButton ? BAR_BUTTON_WIDTH : 0) +
291 [...leading, ...trailing].reduce(
292 (width, item) =>
293 width +
294 (item.type === "spacer"
295 ? item.sizing === "fixed"
296 ? item.width
297 : 0
298 : // The keyboard dismiss rides the vertical bar, not beside the title.
299 item.id === "dismiss-keyboard"
300 ? 0
301 : BAR_BUTTON_WIDTH),
302 0,
303 );
304 const titleStyle = StyleSheet.flatten(options.headerTitleStyle);
305 const headerStyle = StyleSheet.flatten(options.headerStyle);
306 const appearance = {
307 // Clear colors remove UIKit material; let translucent bars supply their own blur background.
308 backgroundColor: options.headerTransparent
309 ? undefined
310 : (headerStyle?.backgroundColor ?? theme.colors.card),
311 shadowColor: options.headerShadowVisible === false ? "transparent" : undefined,
312 titleFontSize: titleStyle?.fontSize,
313 titleFontFamily: titleStyle?.fontFamily,
314 titleFontWeight: titleStyle?.fontWeight,
315 titleFontColor: titleStyle?.color,
316 subtitleFontSize: options.headerSubtitleStyle?.fontSize,
317 subtitleFontColor: options.headerSubtitleStyle?.color,
318 };
319 return (
320 <HeaderItemsWidthContext value={itemsWidth}>
321 <Stack.HeaderConfig
322 hidden={options.headerShown === false}
323 transparent={options.headerTransparent}
324 title={title}
325 subtitle={options.unstable_headerSubtitle ?? options.headerSubtitle}
326 backButtonHidden={options.headerBackVisible === false}
327 ios={{
328 navigationItemStyle: options.unstable_navigationItemStyle,
329 // Opt-ins apply only where the Duo is short: folded, or held landscape. The Duo
330 // resolves `automatic` to minimize on scroll, so the tall unfolded display opts out.
331 minimizationBehavior: !isDuoDevice(deviceType)
332 ? undefined
333 : deviceType === "duo-unfolded" &&
334 nativeMetrics &&
335 nativeMetrics.height > nativeMetrics.width
336 ? "never"
337 : options.unstable_headerMinimizationBehavior,
338 tintColor: options.headerTintColor,
339 searchBar:
340 mailSearch || searchOptions ? (
341 <SearchBar
342 {...searchOptions}
343 ref={searchOptions?.ref ?? searchRef}
344 hideNavigationBar={false}
345 hideWhenScrolling={false}
346 allowToolbarIntegration={searchOptions?.allowToolbarIntegration ?? true}
347 placement={bottomSearch ? "integrated" : (searchOptions?.placement ?? "automatic")}
348 placeholder={mailSearch?.placeholder ?? searchOptions?.placeholder ?? "Search"}
349 onFocus={(event) => {
350 searchOptions?.onFocus?.(event);
351 }}
352 onChangeText={(event) => {
353 mailSearch?.onSearchTextChange?.(event.nativeEvent.text);
354 searchOptions?.onChangeText?.(event);
355 }}
356 />
357 ) : undefined,
358 toolbarItems: bottom,
359 leadingItems: leading,
360 trailingItems: trailing,
361 titleItem: isValidElement(titleElement)
362 ? { id: "title", render: () => titleElement }
363 : undefined,
364 largeTitleEnabled: options.headerLargeTitle,
365 backButtonDisplayMode: options.headerBackButtonDisplayMode ?? "minimal",
366 backButtonMenuEnabled: options.headerBackButtonMenuEnabled ?? true,
367 backButtonTitle: options.headerBackTitle,
368 standardAppearance: appearance,
369 scrollEdgeAppearance: appearance,
370 }}
371 />
372 </HeaderItemsWidthContext>
373 );