Open History to see the last commit
1import { useNavigation, type ParamListBase } from "@react-navigation/native";
2import type {
3 NativeStackHeaderItem,
4 NativeStackHeaderItemMenu,
5 NativeStackNavigationOptions,
6 NativeStackNavigationProp,
7} from "@react-navigation/native-stack";
8import {
9 Children,
10 isValidElement,
11 useLayoutEffect,
12 useMemo,
13 type ReactElement,
14 type ReactNode,
15} from "react";
16import type { ColorValue } from "react-native";
17import type { HeaderBarButtonSearchBarPlacementItem } from "react-native-screens";
18
19function useNativeStackNavigation(): NativeStackNavigationProp<ParamListBase> | null {
20 return useNavigation<NativeStackNavigationProp<ParamListBase>>();
21}
22
23function labelFromChildren(children: ReactNode): string {
24 const parts: string[] = [];
25 Children.forEach(children, (child) => {
26 if (typeof child === "string" || typeof child === "number") {
27 parts.push(String(child));
28 } else if (isValidElement<{ children?: ReactNode }>(child)) {
29 parts.push(labelFromChildren(child.props.children));
30 }
31 });
32 return parts.join("");
33}
34
35type NativeStackHeaderIcon = NonNullable<
36 Extract<NativeStackHeaderItem, { type: "button" }>["icon"]
37>;
38type NativeStackHeaderAxisBehavior = Extract<
39 NativeStackHeaderItem,
40 { type: "button" }
41>["axisBehavior"];
42type NativeToolbarItem = NativeStackHeaderItem | HeaderBarButtonSearchBarPlacementItem;
43type NativeStackOptionsWithToolbar = NativeStackNavigationOptions & {
44 unstable_headerToolbarItems?: () => NativeToolbarItem[];
45};
46
47function iconFromProp(icon: unknown): NativeStackHeaderIcon | undefined {
48 if (typeof icon !== "string") {
49 return undefined;
50 }
51 return { type: "sfSymbol", name: icon as never };
52}
53
54type ToolbarElementProps = Record<string, unknown> & { readonly children?: ReactNode };
55
56function elementTypeName(element: ReactElement): string | undefined {
57 const type = element.type;
58 if (typeof type === "function") {
59 return (type as { displayName?: string; name?: string }).displayName ?? type.name;
60 }
61 return undefined;
62}
63
64function convertMenuAction(
65 element: ReactElement<ToolbarElementProps>,
66): NativeStackHeaderItemMenu["menu"]["items"][number] | null {
67 const typeName = elementTypeName(element);
68 if (typeName === "NativeHeaderToolbarMenuAction") {
69 const label = labelFromChildren(element.props.children);
70 return {
71 type: "action",
72 label,
73 description: typeof element.props.subtitle === "string" ? element.props.subtitle : undefined,
74 disabled: Boolean(element.props.disabled),
75 icon: iconFromProp(element.props.icon),
76 onPress:
77 typeof element.props.onPress === "function"
78 ? (element.props.onPress as () => void)
79 : () => undefined,
80 state: element.props.isOn === true ? "on" : undefined,
81 destructive: Boolean(element.props.destructive),
82 discoverabilityLabel:
83 typeof element.props.discoverabilityLabel === "string"
84 ? element.props.discoverabilityLabel
85 : undefined,
86 };
87 }
88
89 if (typeName === "NativeHeaderToolbarMenu") {
90 return {
91 type: "submenu",
92 label:
93 typeof element.props.title === "string"
94 ? element.props.title
95 : labelFromChildren(element.props.children),
96 icon: iconFromProp(element.props.icon),
97 inline: Boolean(element.props.inline),
98 items: collectMenuItems(element.props.children),
99 };
100 }
101
102 return null;
103}
104
105function collectMenuItems(children: ReactNode): NativeStackHeaderItemMenu["menu"]["items"] {
106 const items: NativeStackHeaderItemMenu["menu"]["items"] = [];
107 Children.forEach(children, (child) => {
108 if (!isValidElement<ToolbarElementProps>(child)) {
109 return;
110 }
111 const item = convertMenuAction(child);
112 if (item) {
113 items.push(item);
114 return;
115 }
116 items.push(...collectMenuItems(child.props.children));
117 });
118 return items;
119}
120
121function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {
122 if (!isValidElement<ToolbarElementProps>(child)) {
123 return null;
124 }
125
126 const typeName = elementTypeName(child);
127 if (typeName === "NativeHeaderToolbarCustom" && isValidElement(child.props.children)) {
128 return { type: "custom", element: child.props.children };
129 }
130 if (typeName === "NativeHeaderToolbarSearchBarSlot") {
131 return { type: "searchBarPlacement" };
132 }
133
134 if (typeName === "NativeHeaderToolbarButton") {
135 return {
136 type: "button",
137 label:
138 typeof child.props.label === "string"
139 ? child.props.label
140 : String(child.props.accessibilityLabel ?? ""),
141 accessibilityLabel:
142 typeof child.props.accessibilityLabel === "string"
143 ? child.props.accessibilityLabel
144 : undefined,
145 axisBehavior: child.props.axisBehavior as NativeStackHeaderAxisBehavior,
146 disabled: Boolean(child.props.disabled),
147 icon: iconFromProp(child.props.icon),
148 onPress:
149 typeof child.props.onPress === "function"
150 ? (child.props.onPress as () => void)
151 : () => undefined,
152 sharesBackground: !child.props.separateBackground,
153 tintColor: child.props.tintColor as ColorValue | undefined,
154 variant: "plain",
155 };
156 }
157
158 if (typeName === "NativeHeaderToolbarMenu") {
159 return {
160 type: "menu",
161 label: typeof child.props.title === "string" ? child.props.title : "",
162 accessibilityLabel:
163 typeof child.props.accessibilityLabel === "string"
164 ? child.props.accessibilityLabel
165 : undefined,
166 disabled: Boolean(child.props.disabled),
167 icon: iconFromProp(child.props.icon),
168 menu: {
169 title: typeof child.props.title === "string" ? child.props.title : undefined,
170 items: collectMenuItems(child.props.children),
171 },
172 sharesBackground: !child.props.separateBackground,
173 tintColor: child.props.tintColor as ColorValue | undefined,
174 variant: "plain",
175 };
176 }
177
178 if (typeName === "NativeHeaderToolbarSpacer") {
179 return {
180 type: "spacing",
181 spacing: typeof child.props.width === "number" ? child.props.width : 8,
182 flexible: Boolean(child.props.flexible),
183 } as NativeStackHeaderItem;
184 }
185
186 return null;
187}
188
189function collectToolbarItems(children: ReactNode): NativeToolbarItem[] {
190 const items: NativeToolbarItem[] = [];
191 Children.forEach(children, (child) => {
192 const item = convertToolbarChild(child);
193 if (item) {
194 if (item.type === "spacing") {
195 // Native inserts spacing items at `index`, treating a missing index
196 // as 0 — which would move the spacer in front of earlier siblings.
197 (item as { index?: number }).index = items.length;
198 }
199 items.push(item);
200 }
201 });
202 return items;
203}
204
205function NativeHeaderToolbarRoot(props: {
206 readonly placement?: "left" | "right" | "bottom";
207 readonly children?: ReactNode;
208}) {
209 const navigation = useNativeStackNavigation();
210 const items = useMemo(() => collectToolbarItems(props.children), [props.children]);
211
212 // Swap toolbar owners before paint so split and compact headers cannot clear each other.
213 useLayoutEffect(() => {
214 if (!navigation) {
215 return;
216 }
217 if (props.placement === "bottom") {
218 navigation.setOptions({
219 unstable_headerToolbarItems: () => items,
220 } as NativeStackOptionsWithToolbar);
221 return () => {
222 navigation.setOptions({
223 unstable_headerToolbarItems: () => [],
224 } as NativeStackOptionsWithToolbar);
225 };
226 }
227 // UIKit's search placement item belongs to the toolbar, never a header group.
228 const headerItems = items.filter(
229 (item): item is NativeStackHeaderItem => item.type !== "searchBarPlacement",
230 );
231 if (props.placement === "left") {
232 navigation.setOptions({ unstable_headerLeftItems: () => headerItems });
233 return () => {
234 navigation.setOptions({ unstable_headerLeftItems: () => [] });
235 };
236 }
237 navigation.setOptions({ unstable_headerRightItems: () => headerItems });
238 return () => {
239 navigation.setOptions({ unstable_headerRightItems: () => [] });
240 };
241 }, [items, navigation, props.placement]);
242
243 return null;
244}
245
246function NativeHeaderToolbarButton(_props: {
247 readonly accessibilityLabel?: string;
248 readonly axisBehavior?: NativeStackHeaderAxisBehavior;
249 readonly disabled?: boolean;
250 readonly icon?: string;
251 readonly label?: string;
252 readonly onPress?: () => void;
253 readonly separateBackground?: boolean;
254 readonly tintColor?: ColorValue;
255}) {
256 return null;
257}
258NativeHeaderToolbarButton.displayName = "NativeHeaderToolbarButton";
259
260function NativeHeaderToolbarMenu(_props: {
261 readonly accessibilityLabel?: string;
262 readonly children?: ReactNode;
263 readonly disabled?: boolean;
264 readonly icon?: string;
265 readonly inline?: boolean;
266 readonly separateBackground?: boolean;
267 readonly tintColor?: ColorValue;
268 readonly title?: string;
269}) {
270 return null;
271}
272NativeHeaderToolbarMenu.displayName = "NativeHeaderToolbarMenu";
273
274function NativeHeaderToolbarMenuAction(_props: {
275 readonly children?: ReactNode;
276 readonly destructive?: boolean;
277 readonly disabled?: boolean;
278 readonly discoverabilityLabel?: string;
279 readonly icon?: string;
280 readonly isOn?: boolean;
281 readonly onPress?: () => void;
282 readonly subtitle?: string;
283}) {
284 return null;
285}
286NativeHeaderToolbarMenuAction.displayName = "NativeHeaderToolbarMenuAction";
287
288/** Renders an arbitrary element as a bar item, e.g. a spinner standing in for a button. */
289function NativeHeaderToolbarCustom(_props: { readonly children: ReactElement }) {
290 return null;
291}
292NativeHeaderToolbarCustom.displayName = "NativeHeaderToolbarCustom";
293
294function NativeHeaderToolbarLabel(_props: { readonly children?: ReactNode }) {
295 return null;
296}
297NativeHeaderToolbarLabel.displayName = "NativeHeaderToolbarLabel";
298
299function NativeHeaderToolbarSpacer(_props: {
300 readonly flexible?: boolean;
301 readonly sharesBackground?: boolean;
302 readonly width?: number;
303}) {
304 return null;
305}
306NativeHeaderToolbarSpacer.displayName = "NativeHeaderToolbarSpacer";
307
308function NativeHeaderToolbarSearchBarSlot() {
309 return null;
310}
311NativeHeaderToolbarSearchBarSlot.displayName = "NativeHeaderToolbarSearchBarSlot";
312
313export const NativeHeaderToolbar = Object.assign(NativeHeaderToolbarRoot, {
314 Button: NativeHeaderToolbarButton,
315 Custom: NativeHeaderToolbarCustom,
316 Label: NativeHeaderToolbarLabel,
317 Menu: Object.assign(NativeHeaderToolbarMenu, {
318 Action: NativeHeaderToolbarMenuAction,
319 }),
320 MenuAction: NativeHeaderToolbarMenuAction,
321 SearchBarSlot: NativeHeaderToolbarSearchBarSlot,
322 Spacer: NativeHeaderToolbarSpacer,
323});