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