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

V5StackHeader.ios.tsx

275 lines10.6 KB

1import type {
2 NativeStackHeaderItem,
3 NativeStackHeaderItemMenu,
4 NativeStackNavigationOptions,
5} from "@react-navigation/native-stack";
6import { isValidElement, useRef } from "react";
7import { Platform, StyleSheet } from "react-native";
8import { useMobileNavigationTheme } from "../lib/useMobileNavigationTheme";
9import { 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 // Use actions even for checked entries: the app owns their durable state.
73 return [
74 {
75 id: childId,
76 type: "menuItem" as const,
77 itemType: "action" as const,
78 title: "label" in item ? item.label : item.title,
79 icon: convertIcon(item.icon),
80 onPress: item.disabled ? undefined : item.onPress,
81 keepsMenuPresented: item.keepsMenuPresented,
82 disabled: item.disabled,
83 destructive: item.destructive,
84 subtitle:
85 ("subtitle" in item ? item.subtitle : undefined) ??
86 ("description" in item ? item.description : undefined),
87 state: item.state,
88 },
89 ];
90 });
91 return { id, type: "menu", title: menu.title, children };
93​
94function convertItems(items: NativeStackHeaderItem[], prefix: string): HeaderItem[] {
95 return items.map((item, index): HeaderItem => {
96 const id =
97 item.type === "spacing" ? `${prefix}:${index}` : (item.identifier ?? `${prefix}:${index}`);
98 switch (item.type) {
99 case "spacing":
100 return { type: "spacer", id, sizing: "fixed", width: item.spacing };
101 case "custom":
102 return {
103 type: "item",
104 id,
105 render: () => item.element,
106 hidesSharedBackground: item.hidesSharedBackground,
107 };
108 case "menu":
109 return {
110 type: "item",
111 id,
112 identifier: item.identifier,
113 title: item.label || item.accessibilityLabel || undefined,
114 axisBehavior: item.axisBehavior,
115 icon: convertIcon(item.icon),
116 menu: item.disabled ? undefined : convertMenu(item.menu, `${id}:menu`),
117 hidesSharedBackground: item.hidesSharedBackground,
118 };
119 case "button":
120 return {
121 type: "item",
122 id,
123 identifier: item.identifier,
124 title: item.label || item.accessibilityLabel || undefined,
125 axisBehavior: item.axisBehavior,
126 icon: convertIcon(item.icon),
127 onPress: item.disabled ? undefined : item.onPress,
128 hidesSharedBackground: item.hidesSharedBackground,
129 };
130 }
131 });
133​
134/** Translate the existing screen options to v5's native header API. */
135export function V5StackHeader(props: {
136 readonly options: Options;
137 readonly canGoBack: boolean;
138 readonly primary?: boolean;
139}) {
140 const { options } = props;
141 const theme = useMobileNavigationTheme();
142 const nativeMetrics = useNativeLayoutMetrics();
143 const searchRef = useRef<SearchBarCommands>(null);
144 const itemProps = { tintColor: options.headerTintColor, canGoBack: props.canGoBack };
145 const leading = convertItems(options.unstable_headerLeftItems?.(itemProps) ?? [], "leading");
146 const trailing = convertItems(
147 [
148 ...(options.unstable_headerCenterItems?.() ?? []),
149 ...(options.unstable_headerRightItems?.(itemProps) ?? []),
150 ],
151 "trailing",
152 );
153 const toolbar = options.unstable_headerToolbarItems?.() ?? [];
154 const mailSearch = toolbar.find(
155 (item): item is HeaderBarButtonMailSearchToolbarItem => item.type === "mailSearchToolbar",
156 );
157 const bottomSearch = Boolean(mailSearch) && Platform.OS === "ios" && !Platform.isPad;
158 const bottom = toolbar.flatMap<HeaderItem>((item, index) => {
159 if (item.type === "mailSearchToolbar") return [];
160 if (item.type === "searchBarPlacement")
161 return [{ type: "item", id: `toolbar-search:${index}`, searchBarPlacement: true }];
162 return convertItems([item], `toolbar:${index}`);
163 });
164 if (mailSearch) {
165 if (mailSearch.filterMenu)
166 bottom.push({
167 type: "item",
168 id: mailSearch.filterButtonId ?? "filter",
169 axisBehavior: bottomSearch ? "horizontalOnly" : undefined,
170 icon: {
171 type: "sfSymbol",
172 name: mailSearch.filterSystemImageName ?? "line.3.horizontal.decrease",
173 },
174 menu: convertMenu(mailSearch.filterMenu, "filter-menu"),
175 });
176 if (bottomSearch) {
177 if (bottom.length)
178 bottom.push({ type: "spacer", id: "before-search", sizing: "fixed", width: 8 });
179 bottom.push({
180 type: "item",
181 id: "home-search",
182 axisBehavior: "horizontalOnly",
183 searchBarPlacement: true,
184 });
185 if (mailSearch.onComposePress)
186 bottom.push({ type: "spacer", id: "after-search", sizing: "fixed", width: 8 });
187 }
188 if (mailSearch.onComposePress)
189 bottom.push({
190 type: "item",
191 id: mailSearch.composeButtonId ?? "compose",
192 axisBehavior: bottomSearch ? "horizontalOnly" : undefined,
193 icon: { type: "sfSymbol", name: mailSearch.composeSystemImageName ?? "square.and.pencil" },
194 onPress: mailSearch.onComposePress,
195 });
196 }
197 // Expanded Duo panes put toolbar actions in the side bar. Folded phones
198 // keep their bottom search toolbar. UIKit keeps the
199 // primary column's navigation items beside its title and the detail's in
200 // the rail; a conventional UIToolbar can otherwise leave them inaccessible.
201 if (
202 nativeMetrics?.horizontalSizeClass === "regular" &&
203 nativeMetrics.verticalBarEdge !== "none"
204 ) {
205 trailing.push(...bottom);
206 bottom.length = 0;
207 }
208 const left = options.headerLeft?.(itemProps);
209 const right = options.headerRight?.(itemProps);
210 if (!options.unstable_headerLeftItems && isValidElement(left))
211 leading.push({ type: "item", id: "custom-left", render: () => left });
212 if (!options.unstable_headerRightItems && isValidElement(right))
213 trailing.push({ type: "item", id: "custom-right", render: () => right });
214 const title = typeof options.headerTitle === "string" ? options.headerTitle : options.title;
215 const titleElement =
216 typeof options.headerTitle === "function"
217 ? options.headerTitle({ children: title ?? "", tintColor: options.headerTintColor })
218 : undefined;
219 const searchOptions = options.headerSearchBarOptions;
220 const titleStyle = StyleSheet.flatten(options.headerTitleStyle);
221 const headerStyle = StyleSheet.flatten(options.headerStyle);
222 const appearance = {
223 backgroundColor:
224 headerStyle?.backgroundColor ??
225 (options.headerTransparent ? "transparent" : theme.colors.card),
226 shadowColor: options.headerShadowVisible === false ? "transparent" : undefined,
227 titleFontSize: titleStyle?.fontSize,
228 titleFontFamily: titleStyle?.fontFamily,
229 titleFontWeight: titleStyle?.fontWeight,
230 titleFontColor: titleStyle?.color,
231 subtitleFontSize: options.headerSubtitleStyle?.fontSize,
232 subtitleFontColor: options.headerSubtitleStyle?.color,
233 };
234 return (
235 <Stack.HeaderConfig
236 hidden={options.headerShown === false}
237 transparent={options.headerTransparent}
238 title={title}
239 subtitle={options.unstable_headerSubtitle ?? options.headerSubtitle}
240 backButtonHidden={options.headerBackVisible === false}
241 ios={{
242 navigationItemStyle: options.unstable_navigationItemStyle,
243 tintColor: options.headerTintColor,
244 searchBar:
245 mailSearch || searchOptions ? (
246 <SearchBar
247 {...searchOptions}
248 ref={searchOptions?.ref ?? searchRef}
249 hideNavigationBar={false}
250 hideWhenScrolling={false}
251 allowToolbarIntegration={searchOptions?.allowToolbarIntegration ?? true}
252 placement={bottomSearch ? "integrated" : (searchOptions?.placement ?? "automatic")}
253 placeholder={mailSearch?.placeholder ?? searchOptions?.placeholder ?? "Search"}
254 onChangeText={(event) => {
255 mailSearch?.onSearchTextChange?.(event.nativeEvent.text);
256 searchOptions?.onChangeText?.(event);
257 }}
258 />
259 ) : undefined,
260 toolbarItems: bottom,
261 leadingItems: leading,
262 trailingItems: trailing,
263 titleItem: isValidElement(titleElement)
264 ? { id: "title", render: () => titleElement }
265 : undefined,
266 largeTitleEnabled: options.headerLargeTitle,
267 backButtonDisplayMode: options.headerBackButtonDisplayMode ?? "minimal",
268 backButtonMenuEnabled: options.headerBackButtonMenuEnabled ?? true,
269 backButtonTitle: options.headerBackTitle,
270 standardAppearance: appearance,
271 scrollEdgeAppearance: appearance,
272 }}
273 />
274 );