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

V5StackHeader.ios.tsx

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