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

V5StackHeader.ios.tsx

312 lines12.2 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 { 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;
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 };
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 variant: item.variant,
132 tintColor: item.tintColor,
133 hidesSharedBackground: item.hidesSharedBackground,
134 };
135 }
136 });
138​
139export function V5StackHeader(props: {
140 readonly options: Options;
141 readonly canGoBack: boolean;
142 readonly primary?: boolean;
143 readonly sidebarFilter?: NativeStackHeaderItemMenu;
144}) {
145 const { options } = props;
146 const theme = useMobileNavigationTheme();
147 const nativeMetrics = useNativeLayoutMetrics();
148 const deviceType = useDeviceType();
149 const searchRef = useRef<SearchBarCommands>(null);
150 const usesDuoToolbarRail =
151 deviceType === "duo-unfolded" && (nativeMetrics?.verticalBarEdge ?? "none") !== "none";
152 const itemProps = { tintColor: options.headerTintColor, canGoBack: props.canGoBack };
153 const leading = convertItems(options.unstable_headerLeftItems?.(itemProps) ?? [], "leading");
154 const trailingItems = [
155 ...(options.unstable_headerCenterItems?.() ?? []),
156 ...(options.unstable_headerRightItems?.(itemProps) ?? []),
157 ];
158 // Keep the sidebar's filter actions when UIKit moves the menu to the detail rail.
159 if (usesDuoToolbarRail && !props.primary && props.sidebarFilter) {
160 trailingItems.push({
161 ...props.sidebarFilter,
162 identifier: "home-filter",
163 axisBehavior: "verticalPreferred",
164 });
165 }
166 const trailing = convertItems(trailingItems, "trailing");
167 const toolbar = options.unstable_headerToolbarItems?.() ?? [];
168 const mailSearch = toolbar.find(
169 (item): item is HeaderBarButtonMailSearchToolbarItem => item.type === "mailSearchToolbar",
170 );
171 const bottomSearch = Boolean(mailSearch) && deviceType !== "pad";
172 const bottom = toolbar.flatMap<HeaderItem>((item, index) => {
173 if (item.type === "mailSearchToolbar") return [];
174 if (item.type === "searchBarPlacement")
175 return [{ type: "item", id: `toolbar-search:${index}`, searchBarPlacement: true }];
176 return convertItems([item], `toolbar:${index}`);
177 });
178 if (mailSearch) {
179 if (mailSearch.filterMenu)
180 bottom.push({
181 type: "item",
182 id: mailSearch.filterButtonId ?? "filter",
183 axisBehavior: bottomSearch ? "horizontalOnly" : undefined,
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 (bottom.length)
192 bottom.push({ type: "spacer", id: "before-search", sizing: "fixed", width: 8 });
193 bottom.push({
194 type: "item",
195 id: "home-search",
196 axisBehavior: "horizontalOnly",
197 searchBarPlacement: true,
198 });
199 if (mailSearch.onComposePress)
200 bottom.push({ type: "spacer", id: "after-search", sizing: "fixed", width: 8 });
201 }
202 if (mailSearch.onComposePress)
203 bottom.push({
204 type: "item",
205 id: mailSearch.composeButtonId ?? "compose",
206 axisBehavior: bottomSearch ? "horizontalOnly" : undefined,
207 identifier: "workspace-trailing-action",
208 icon: { type: "sfSymbol", name: mailSearch.composeSystemImageName ?? "square.and.pencil" },
209 onPress: mailSearch.onComposePress,
210 });
211 }
212 // Duo keeps compose at the bottom of a visible sidebar. On a single panel,
213 // the primary column owns the rail too; its separate UIToolbar is inaccessible.
214 if (
215 nativeMetrics &&
216 nativeMetrics.verticalBarEdge !== "none" &&
217 (!props.primary || nativeMetrics.horizontalSizeClass === "compact")
218 ) {
219 trailing.push(...bottom);
220 bottom.length = 0;
221 }
222 const left = options.headerLeft?.(itemProps);
223 const right = options.headerRight?.(itemProps);
224 if (!options.unstable_headerLeftItems && isValidElement(left))
225 leading.push({ type: "item", id: "custom-left", render: () => left });
226 if (!options.unstable_headerRightItems && isValidElement(right))
227 trailing.push({ type: "item", id: "custom-right", render: () => right });
228 const title = typeof options.headerTitle === "string" ? options.headerTitle : options.title;
229 const titleElement =
230 typeof options.headerTitle === "function"
231 ? options.headerTitle({ children: title ?? "", tintColor: options.headerTintColor })
232 : undefined;
233 const searchOptions = options.headerSearchBarOptions;
234 const autofocusRef = searchOptions?.ref ?? searchRef;
235 const searchHasFocus = useRef(false);
236 useEffect(() => {
237 searchHasFocus.current = false;
238 if (!searchOptions?.autoFocus) return;
239 // UIKit attaches integrated search during the toolbar transition. Native
240 // onFocus acknowledges readiness; a single frame can reach it too early.
241 const deadline = Date.now() + 500;
242 let frame = 0;
243 const focusWhenAttached = () => {
244 if (searchHasFocus.current) return;
245 autofocusRef.current?.focus();
246 if (Date.now() < deadline) frame = requestAnimationFrame(focusWhenAttached);
247 };
248 frame = requestAnimationFrame(focusWhenAttached);
249 return () => cancelAnimationFrame(frame);
250 }, [searchOptions?.autoFocus, autofocusRef]);
251 const titleStyle = StyleSheet.flatten(options.headerTitleStyle);
252 const headerStyle = StyleSheet.flatten(options.headerStyle);
253 const appearance = {
254 // A clear color also removes UIKit's material. Let UIKit supply it for
255 // translucent bars so scrolling content can appear beneath native blur.
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 tintColor: options.headerTintColor,
277 searchBar:
278 mailSearch || searchOptions ? (
279 <SearchBar
280 {...searchOptions}
281 ref={searchOptions?.ref ?? searchRef}
282 hideNavigationBar={false}
283 hideWhenScrolling={false}
284 allowToolbarIntegration={searchOptions?.allowToolbarIntegration ?? true}
285 placement={bottomSearch ? "integrated" : (searchOptions?.placement ?? "automatic")}
286 placeholder={mailSearch?.placeholder ?? searchOptions?.placeholder ?? "Search"}
287 onFocus={(event) => {
288 searchHasFocus.current = true;
289 searchOptions?.onFocus?.(event);
290 }}
291 onChangeText={(event) => {
292 mailSearch?.onSearchTextChange?.(event.nativeEvent.text);
293 searchOptions?.onChangeText?.(event);
294 }}
295 />
296 ) : undefined,
297 toolbarItems: bottom,
298 leadingItems: leading,
299 trailingItems: trailing,
300 titleItem: isValidElement(titleElement)
301 ? { id: "title", render: () => titleElement }
302 : undefined,
303 largeTitleEnabled: options.headerLargeTitle,
304 backButtonDisplayMode: options.headerBackButtonDisplayMode ?? "minimal",
305 backButtonMenuEnabled: options.headerBackButtonMenuEnabled ?? true,
306 backButtonTitle: options.headerBackTitle,
307 standardAppearance: appearance,
308 scrollEdgeAppearance: appearance,
309 }}
310 />
311 );