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