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