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

V5StackHeader.ios.tsx

253 lines9.8 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 {
10 SearchBar,
11 Stack,
12 type HeaderBarButtonMailSearchToolbarItem,
13 type SearchBarCommands,
14 type StackHeaderConfigProps,
15 type StackHeaderMenuElementIOS,
16 type StackHeaderMenuIOS,
17 type HeaderBarButtonItemWithMenu,
18 type HeaderBarButtonSearchBarPlacementItem,
19} from "react-native-screens";
20​
21type HeaderItem = NonNullable<NonNullable<StackHeaderConfigProps["ios"]>["leadingItems"]>[number];
22type ToolbarItem =
23 | NativeStackHeaderItem
24 | HeaderBarButtonMailSearchToolbarItem
25 | HeaderBarButtonSearchBarPlacementItem;
26type Options = NativeStackNavigationOptions & {
27 readonly unstable_navigationItemStyle?: "editor" | "navigator";
28 readonly headerSubtitle?: string;
29 readonly unstable_headerSubtitle?: string;
30 readonly headerSubtitleStyle?: { color?: string; fontSize?: number; fontFamily?: string };
31 readonly unstable_headerCenterItems?: () => NativeStackHeaderItem[];
32 readonly unstable_headerToolbarItems?: () => ToolbarItem[];
33};
34​
35type MenuElementInput =
36 | NativeStackHeaderItemMenu["menu"]["items"][number]
37 | HeaderBarButtonItemWithMenu["menu"]["items"][number];
38type MenuInput = { readonly title?: string; readonly items: readonly MenuElementInput[] };
39​
40function convertIcon(
41 icon:
42 | Extract<NativeStackHeaderItem, { type: "button" }>["icon"]
43 | HeaderBarButtonItemWithMenu["icon"],
44) {
45 if (!icon) return undefined;
46 if (icon.type === "image")
47 return icon.tinted === false
48 ? { type: "imageSource" as const, imageSource: icon.source }
49 : { type: "templateSource" as const, templateSource: icon.source };
50 return icon;
52​
53function convertMenu(menu: MenuInput, id: string): StackHeaderMenuIOS {
54 const children = menu.items.flatMap<StackHeaderMenuElementIOS>((item, index) => {
55 if ("hidden" in item && item.hidden) return [];
56 const childId = `${id}:${index}`;
57 if (item.type === "submenu") {
58 return [
59 {
60 ...convertMenu({ items: item.items }, childId),
61 title: "label" in item ? item.label : item.title,
62 displayInline:
63 "inline" in item
64 ? item.inline
65 : "displayInline" in item
66 ? item.displayInline
67 : undefined,
68 },
69 ];
70 }
71 // Use actions even for checked entries: the app owns their durable state.
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 { type: "spacer", id, sizing: "fixed", width: item.spacing };
100 case "custom":
101 return {
102 type: "item",
103 id,
104 render: () => item.element,
105 hidesSharedBackground: item.hidesSharedBackground,
106 };
107 case "menu":
108 return {
109 type: "item",
110 id,
111 identifier: item.identifier,
112 title: item.label || item.accessibilityLabel || undefined,
113 icon: convertIcon(item.icon),
114 menu: item.disabled ? undefined : convertMenu(item.menu, `${id}:menu`),
115 hidesSharedBackground: item.hidesSharedBackground,
116 };
117 case "button":
118 return {
119 type: "item",
120 id,
121 identifier: item.identifier,
122 title: item.label || item.accessibilityLabel || undefined,
123 icon: convertIcon(item.icon),
124 onPress: item.disabled ? undefined : item.onPress,
125 hidesSharedBackground: item.hidesSharedBackground,
126 };
127 }
128 });
130​
131/** Translate the existing screen options to v5's native header API. */
132export function V5StackHeader(props: {
133 readonly options: Options;
134 readonly canGoBack: boolean;
135 readonly primary?: boolean;
136}) {
137 const { options } = props;
138 const theme = useMobileNavigationTheme();
139 const searchRef = useRef<SearchBarCommands>(null);
140 const itemProps = { tintColor: options.headerTintColor, canGoBack: props.canGoBack };
141 const leading = convertItems(options.unstable_headerLeftItems?.(itemProps) ?? [], "leading");
142 const trailing = convertItems(
143 [
144 ...(options.unstable_headerCenterItems?.() ?? []),
145 ...(options.unstable_headerRightItems?.(itemProps) ?? []),
146 ],
147 "trailing",
148 );
149 const toolbar = options.unstable_headerToolbarItems?.() ?? [];
150 const mailSearch = toolbar.find(
151 (item): item is HeaderBarButtonMailSearchToolbarItem => item.type === "mailSearchToolbar",
152 );
153 const bottomSearch = Boolean(mailSearch) && Platform.OS === "ios" && !Platform.isPad;
154 const bottom = toolbar.flatMap<HeaderItem>((item, index) => {
155 if (item.type === "mailSearchToolbar") return [];
156 if (item.type === "searchBarPlacement")
157 return [{ type: "item", id: `toolbar-search:${index}`, searchBarPlacement: true }];
158 return convertItems([item], `toolbar:${index}`);
159 });
160 if (mailSearch) {
161 if (mailSearch.filterMenu)
162 bottom.push({
163 type: "item",
164 id: mailSearch.filterButtonId ?? "filter",
165 icon: {
166 type: "sfSymbol",
167 name: mailSearch.filterSystemImageName ?? "line.3.horizontal.decrease",
168 },
169 menu: convertMenu(mailSearch.filterMenu, "filter-menu"),
170 });
171 if (bottomSearch) {
172 if (bottom.length)
173 bottom.push({ type: "spacer", id: "before-search", sizing: "fixed", width: 8 });
174 bottom.push({ type: "item", id: "home-search", searchBarPlacement: true });
175 if (mailSearch.onComposePress)
176 bottom.push({ type: "spacer", id: "after-search", sizing: "fixed", width: 8 });
177 }
178 if (mailSearch.onComposePress)
179 bottom.push({
180 type: "item",
181 id: mailSearch.composeButtonId ?? "compose",
182 icon: { type: "sfSymbol", name: mailSearch.composeSystemImageName ?? "square.and.pencil" },
183 onPress: mailSearch.onComposePress,
184 });
185 }
186 const left = options.headerLeft?.(itemProps);
187 const right = options.headerRight?.(itemProps);
188 if (!options.unstable_headerLeftItems && isValidElement(left))
189 leading.push({ type: "item", id: "custom-left", render: () => left });
190 if (!options.unstable_headerRightItems && isValidElement(right))
191 trailing.push({ type: "item", id: "custom-right", render: () => right });
192 const title = typeof options.headerTitle === "string" ? options.headerTitle : options.title;
193 const titleElement =
194 typeof options.headerTitle === "function"
195 ? options.headerTitle({ children: title ?? "", tintColor: options.headerTintColor })
196 : undefined;
197 const searchOptions = options.headerSearchBarOptions;
198 const titleStyle = StyleSheet.flatten(options.headerTitleStyle);
199 const headerStyle = StyleSheet.flatten(options.headerStyle);
200 const appearance = {
201 backgroundColor:
202 headerStyle?.backgroundColor ??
203 (options.headerTransparent ? "transparent" : theme.colors.card),
204 shadowColor: options.headerShadowVisible === false ? "transparent" : undefined,
205 titleFontSize: titleStyle?.fontSize,
206 titleFontFamily: titleStyle?.fontFamily,
207 titleFontWeight: titleStyle?.fontWeight,
208 titleFontColor: titleStyle?.color,
209 subtitleFontSize: options.headerSubtitleStyle?.fontSize,
210 subtitleFontColor: options.headerSubtitleStyle?.color,
211 };
212 return (
213 <Stack.HeaderConfig
214 hidden={options.headerShown === false}
215 transparent={options.headerTransparent}
216 title={title}
217 subtitle={options.unstable_headerSubtitle ?? options.headerSubtitle}
218 backButtonHidden={options.headerBackVisible === false}
219 ios={{
220 navigationItemStyle: options.unstable_navigationItemStyle,
221 tintColor: options.headerTintColor,
222 searchBar:
223 mailSearch || searchOptions ? (
224 <SearchBar
225 {...searchOptions}
226 ref={searchOptions?.ref ?? searchRef}
227 hideNavigationBar={false}
228 hideWhenScrolling={false}
229 allowToolbarIntegration={searchOptions?.allowToolbarIntegration ?? true}
230 placement={bottomSearch ? "integrated" : (searchOptions?.placement ?? "automatic")}
231 placeholder={mailSearch?.placeholder ?? searchOptions?.placeholder ?? "Search"}
232 onChangeText={(event) => {
233 mailSearch?.onSearchTextChange?.(event.nativeEvent.text);
234 searchOptions?.onChangeText?.(event);
235 }}
236 />
237 ) : undefined,
238 toolbarItems: bottom,
239 leadingItems: leading,
240 trailingItems: trailing,
241 titleItem: isValidElement(titleElement)
242 ? { id: "title", render: () => titleElement }
243 : undefined,
244 largeTitleEnabled: options.headerLargeTitle,
245 backButtonDisplayMode: options.headerBackButtonDisplayMode ?? "minimal",
246 backButtonMenuEnabled: options.headerBackButtonMenuEnabled ?? true,
247 backButtonTitle: options.headerBackTitle,
248 standardAppearance: appearance,
249 scrollEdgeAppearance: appearance,
250 }}
251 />
252 );