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

V5StackHeader.ios.tsx

320 lines12.9 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 { 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;
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 };
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 });
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. Integrated search stays in the column's horizontal bottom toolbar.
209 if (
210 props.column &&
211 nativeMetrics &&
212 nativeMetrics.verticalBarEdge !== "none" &&
213 (props.column === "detail" ||
214 (nativeMetrics.horizontalSizeClass === "compact" &&
215 !toolbar.some((item) => item.type === "searchBarPlacement")))
216 ) {
217 if (trailing.length && bottom.length)
218 trailing.push({ type: "spacer", id: "toolbar-group", sizing: "fixed", width: 8 });
219 trailing.push(...bottom);
220 bottom.length = 0;
221 }
222 if (props.onCompose) {
223 const compose: HeaderItem = {
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 if (trailing.length)
231 trailing.push({ type: "spacer", id: "compose-group", sizing: "fixed", width: 8 });
232 trailing.push(compose);
233 }
234 const left = options.headerLeft?.(itemProps);
235 const right = options.headerRight?.(itemProps);
236 if (!options.unstable_headerLeftItems && isValidElement(left))
237 leading.push({ type: "item", id: "custom-left", render: () => left });
238 if (!options.unstable_headerRightItems && isValidElement(right))
239 trailing.push({ type: "item", id: "custom-right", render: () => right });
240 const title = typeof options.headerTitle === "string" ? options.headerTitle : options.title;
241 const titleElement =
242 typeof options.headerTitle === "function"
243 ? options.headerTitle({ children: title ?? "", tintColor: options.headerTintColor })
244 : undefined;
245 const searchOptions = options.headerSearchBarOptions;
246 const autofocusRef = searchOptions?.ref ?? searchRef;
247 useEffect(() => {
248 if (!searchOptions?.autoFocus) return;
249 const frame = requestAnimationFrame(() => autofocusRef.current?.focus());
250 return () => cancelAnimationFrame(frame);
251 }, [searchOptions?.autoFocus, autofocusRef]);
252 const titleStyle = StyleSheet.flatten(options.headerTitleStyle);
253 const headerStyle = StyleSheet.flatten(options.headerStyle);
254 const appearance = {
255 // Clear colors remove UIKit material; let translucent bars supply their own blur background.
256 backgroundColor: options.headerTransparent
257 ? undefined
258 : (headerStyle?.backgroundColor ?? theme.colors.card),
259 shadowColor: options.headerShadowVisible === false ? "transparent" : undefined,
260 titleFontSize: titleStyle?.fontSize,
261 titleFontFamily: titleStyle?.fontFamily,
262 titleFontWeight: titleStyle?.fontWeight,
263 titleFontColor: titleStyle?.color,
264 subtitleFontSize: options.headerSubtitleStyle?.fontSize,
265 subtitleFontColor: options.headerSubtitleStyle?.color,
266 };
267 return (
268 <Stack.HeaderConfig
269 hidden={options.headerShown === false}
270 transparent={options.headerTransparent}
271 title={title}
272 subtitle={options.unstable_headerSubtitle ?? options.headerSubtitle}
273 backButtonHidden={options.headerBackVisible === false}
274 ios={{
275 navigationItemStyle: options.unstable_navigationItemStyle,
276 // Opt-ins apply only where the Duo is short: folded, or held landscape. The Duo
277 // resolves `automatic` to minimize on scroll, so the tall unfolded display opts out.
278 minimizationBehavior: !isDuoDevice(deviceType)
279 ? undefined
280 : deviceType === "duo-unfolded" &&
281 nativeMetrics &&
282 nativeMetrics.height > nativeMetrics.width
283 ? "never"
284 : options.unstable_headerMinimizationBehavior,
285 tintColor: options.headerTintColor,
286 searchBar:
287 mailSearch || searchOptions ? (
288 <SearchBar
289 {...searchOptions}
290 ref={searchOptions?.ref ?? searchRef}
291 hideNavigationBar={false}
292 hideWhenScrolling={false}
293 allowToolbarIntegration={searchOptions?.allowToolbarIntegration ?? true}
294 placement={bottomSearch ? "integrated" : (searchOptions?.placement ?? "automatic")}
295 placeholder={mailSearch?.placeholder ?? searchOptions?.placeholder ?? "Search"}
296 onFocus={(event) => {
297 searchOptions?.onFocus?.(event);
298 }}
299 onChangeText={(event) => {
300 mailSearch?.onSearchTextChange?.(event.nativeEvent.text);
301 searchOptions?.onChangeText?.(event);
302 }}
303 />
304 ) : undefined,
305 toolbarItems: bottom,
306 leadingItems: leading,
307 trailingItems: trailing,
308 titleItem: isValidElement(titleElement)
309 ? { id: "title", render: () => titleElement }
310 : undefined,
311 largeTitleEnabled: options.headerLargeTitle,
312 backButtonDisplayMode: options.headerBackButtonDisplayMode ?? "minimal",
313 backButtonMenuEnabled: options.headerBackButtonMenuEnabled ?? true,
314 backButtonTitle: options.headerBackTitle,
315 standardAppearance: appearance,
316 scrollEdgeAppearance: appearance,
317 }}
318 />
319 );