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 NativeToolbarItem = NativeStackHeaderItem | HeaderBarButtonSearchBarPlacementItem;
46type NativeStackOptionsWithToolbar = NativeStackNavigationOptions & {
47 unstable_headerToolbarItems?: () => NativeToolbarItem[];
48};
49
50function iconFromProp(icon: unknown): NativeStackHeaderIcon | undefined {
51 if (typeof icon === "string") return { type: "sfSymbol", name: icon as never };
52 if (
53 typeof icon === "object" &&
54 icon !== null &&
55 "type" in icon &&
56 icon.type === "image" &&
57 "source" in icon
58 ) {
59 return icon as NativeStackHeaderIcon;
60 }
61 return undefined;
62}
63
64type ToolbarElementProps = Record<string, unknown> & { readonly children?: ReactNode };
65
66function elementTypeName(element: ReactElement): string | undefined {
67 const type = element.type;
68 if (typeof type === "function") {
69 return (type as { displayName?: string; name?: string }).displayName ?? type.name;
70 }
71 return undefined;
72}
73
74function convertMenuAction(
75 element: ReactElement<ToolbarElementProps>,
76): NativeStackHeaderItemMenu["menu"]["items"][number] | null {
77 const typeName = elementTypeName(element);
78 if (typeName === "NativeHeaderToolbarMenuAction") {
79 const label = labelFromChildren(element.props.children);
80 return {
81 type: "action",
82 label,
83 description: typeof element.props.subtitle === "string" ? element.props.subtitle : undefined,
84 disabled: Boolean(element.props.disabled),
85 icon: iconFromProp(element.props.icon),
86 onPress:
87 typeof element.props.onPress === "function"
88 ? (element.props.onPress as () => void)
89 : () => undefined,
90 state: element.props.isOn === true ? "on" : undefined,
91 destructive: Boolean(element.props.destructive),
92 discoverabilityLabel:
93 typeof element.props.discoverabilityLabel === "string"
94 ? element.props.discoverabilityLabel
95 : undefined,
96 };
97 }
98
99 if (typeName === "NativeHeaderToolbarMenu") {
100 return {
101 type: "submenu",
102 label:
103 typeof element.props.title === "string"
104 ? element.props.title
105 : labelFromChildren(element.props.children),
106 icon: iconFromProp(element.props.icon),
107 inline: Boolean(element.props.inline),
108 items: collectMenuItems(element.props.children),
109 };
110 }
111
112 return null;
113}
114
115function collectMenuItems(children: ReactNode): NativeStackHeaderItemMenu["menu"]["items"] {
116 const items: NativeStackHeaderItemMenu["menu"]["items"] = [];
117 Children.forEach(children, (child) => {
118 if (!isValidElement<ToolbarElementProps>(child)) {
119 return;
120 }
121 const item = convertMenuAction(child);
122 if (item) {
123 items.push(item);
124 return;
125 }
126 items.push(...collectMenuItems(child.props.children));
127 });
128 return items;
129}
130
131function convertToolbarChild(child: ReactNode): NativeToolbarItem | null {
132 if (!isValidElement<ToolbarElementProps>(child)) {
133 return null;
134 }
135
136 const typeName = elementTypeName(child);
137 if (typeName === "NativeHeaderToolbarCustom" && isValidElement(child.props.children)) {
138 return { type: "custom", element: child.props.children };
139 }
140 if (typeName === "NativeHeaderToolbarSearchBarSlot") {
141 return { type: "searchBarPlacement" };
142 }
143
144 if (typeName === "NativeHeaderToolbarButton") {
145 return {
146 type: "button",
147 label:
148 typeof child.props.label === "string"
149 ? child.props.label
150 : String(child.props.accessibilityLabel ?? ""),
151 accessibilityLabel:
152 typeof child.props.accessibilityLabel === "string"
153 ? child.props.accessibilityLabel
154 : undefined,
155 axisBehavior: child.props.axisBehavior as NativeStackHeaderAxisBehavior,
156 disabled: Boolean(child.props.disabled),
157 icon: iconFromProp(child.props.icon),
158 onPress:
159 typeof child.props.onPress === "function"
160 ? (child.props.onPress as () => void)
161 : () => undefined,
162 sharesBackground: !child.props.separateBackground,
163 tintColor: child.props.tintColor as ColorValue | undefined,
164 variant:
165 child.props.variant === "done" || child.props.variant === "prominent"
166 ? child.props.variant
167 : "plain",
168 identifier: typeof child.props.identifier === "string" ? child.props.identifier : undefined,
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 inserts spacing items at `index`, treating a missing index
215 // as 0 — which would move the spacer in front of earlier siblings.
216 (item as { index?: number }).index = items.length;
217 }
218 items.push(item);
219 }
220 });
221 return items;
222}
223
224function NativeHeaderToolbarRoot(props: {
225 readonly placement?: "left" | "right" | "bottom";
226 readonly children?: ReactNode;
227}) {
228 const navigation = useNativeStackNavigation();
229 const route = useRoute();
230 const tabActivity = use(NativeWorkspaceTabActivityContext);
231 const isTabActive = tabActivity?.isActive;
232 const items = useMemo(() => collectToolbarItems(props.children), [props.children]);
233 // UIKit's search placement item belongs to the toolbar, never a header group.
234 const headerItems = useMemo(
235 () => items.filter((item): item is NativeStackHeaderItem => item.type !== "searchBarPlacement"),
236 [items],
237 );
238
239 useLayoutEffect(() => {
240 if (!navigation) return;
241 return () => {
242 if (isTabActive && !isTabActive()) return;
243 if (props.placement === "bottom") {
244 navigation.setOptions({
245 unstable_headerToolbarItems: () => [],
246 } as NativeStackOptionsWithToolbar);
247 } else if (props.placement === "left") {
248 navigation.setOptions({ unstable_headerLeftItems: () => [] });
249 } else {
250 navigation.setOptions({ unstable_headerRightItems: () => [] });
251 }
252 };
253 }, [navigation, props.placement, isTabActive]);
254
255 return (
256 <NativeStackScreenOptions
257 optionsVersion={[items, route.params]}
258 options={
259 props.placement === "bottom"
260 ? { unstable_headerToolbarItems: () => items }
261 : props.placement === "left"
262 ? { unstable_headerLeftItems: () => headerItems }
263 : { unstable_headerRightItems: () => headerItems }
264 }
265 />
266 );
267}
268
269function NativeHeaderToolbarButton(_props: {
270 readonly accessibilityLabel?: string;
271 readonly axisBehavior?: NativeStackHeaderAxisBehavior;
272 readonly disabled?: boolean;
273 readonly icon?: string | Extract<NativeStackHeaderIcon, { type: "image" }>;
274 readonly label?: string;
275 readonly onPress?: () => void;
276 readonly separateBackground?: boolean;
277 readonly tintColor?: ColorValue;
278 readonly variant?: "plain" | "done" | "prominent";
279 readonly identifier?: string;
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});