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 useRef,
15 type ReactElement,
16 type ReactNode,
17} from "react";
18import type { ColorValue } from "react-native";
19
20export {
21 nativeHeaderScrollEdgeEffects,
22 nativeTopScrollEdgeEffect,
23 type NativeHeaderScrollEdgeEffects,
24 type NativeTopScrollEdgeEffect,
25} from "./scrollEdgeEffects";
26
27export type AppNativeStackNavigationOptions = Omit<
28 NativeStackNavigationOptions,
29 "headerTintColor" | "unstable_headerLeftItems" | "unstable_headerRightItems"
30> & {
31 readonly headerTintColor?: string | ColorValue;
32 readonly unstable_headerCenterItems?: unknown;
33 readonly unstable_headerLeftItems?: unknown;
34 readonly unstable_headerRightItems?: unknown;
35 readonly unstable_headerSubtitle?: unknown;
36 readonly unstable_headerToolbarItems?: unknown;
37 readonly unstable_navigationItemStyle?: unknown;
38};
39
40function useNativeStackNavigation(): NativeStackNavigationProp<ParamListBase> | null {
41 return useNavigation<NativeStackNavigationProp<ParamListBase>>();
42}
43
44function normalizeScreenOptions(
45 options: AppNativeStackNavigationOptions | undefined,
46): NativeStackNavigationOptions | undefined {
47 if (!options) {
48 return options;
49 }
50
51 const normalized = { ...options } as NativeStackNavigationOptions & {
52 unstable_navigationItemStyle?: unknown;
53 unstable_headerCenterItems?: unknown;
54 unstable_headerSubtitle?: unknown;
55 unstable_headerToolbarItems?: unknown;
56 };
57
58 if (normalized.headerTintColor !== undefined) {
59 normalized.headerTintColor = String(normalized.headerTintColor);
60 }
61
62 return normalized as NativeStackNavigationOptions;
63}
64
65function optionsSignature(value: unknown, seen = new WeakSet<object>()): string {
66 if (value === null) return "null";
67 switch (typeof value) {
68 case "boolean":
69 case "number":
70 case "string":
71 return JSON.stringify(value);
72 case "undefined":
73 return "undefined";
74 case "function":
75 // Header factories are frequently recreated inline. Their source is
76 // stable across equivalent renders, while a reference comparison would
77 // make navigation.setOptions re-enter the navigator indefinitely.
78 return `function:${Function.prototype.toString.call(value)}`;
79 case "symbol":
80 return `symbol:${String(value)}`;
81 case "bigint":
82 return `bigint:${String(value)}`;
83 case "object": {
84 const object = value as object;
85 if (seen.has(object)) return "[circular]";
86 seen.add(object);
87 if (Array.isArray(value)) {
88 return `[${value.map((entry) => optionsSignature(entry, seen)).join(",")}]`;
89 }
90 // React refs carry mutable native instances that must not make static
91 // screen options appear different after every render.
92 if ("current" in object) return "[ref]";
93 return `{${Object.keys(value as Record<string, unknown>)
94 .sort()
95 .map(
96 (key) =>
97 `${JSON.stringify(key)}:${optionsSignature((value as Record<string, unknown>)[key], seen)}`,
98 )
99 .join(",")}}`;
100 }
101 }
102 return String(value);
103}
104
105function stabilizeOptionFunctions(
106 value: unknown,
107 path: string,
108 latestFunctions: Map<string, (...args: unknown[]) => unknown>,
109 wrappers: Map<string, (...args: unknown[]) => unknown>,
110 seen = new WeakSet<object>(),
111): unknown {
112 if (typeof value === "function") {
113 latestFunctions.set(path, value as (...args: unknown[]) => unknown);
114 let wrapper = wrappers.get(path);
115 if (!wrapper) {
116 wrapper = (...args: unknown[]) => {
117 return latestFunctions.get(path)?.(...args);
118 };
119 wrappers.set(path, wrapper);
120 }
121 return wrapper;
122 }
123 if (Array.isArray(value)) {
124 if (seen.has(value)) return value;
125 seen.add(value);
126 return value.map((entry, index) =>
127 stabilizeOptionFunctions(entry, `${path}[${index}]`, latestFunctions, wrappers, seen),
128 );
129 }
130 if (value !== null && typeof value === "object") {
131 if (seen.has(value) || "current" in value) return value;
132 seen.add(value);
133 return Object.fromEntries(
134 Object.entries(value as Record<string, unknown>).map(([key, entry]) => [
135 key,
136 stabilizeOptionFunctions(entry, `${path}.${key}`, latestFunctions, wrappers, seen),
137 ]),
138 );
139 }
140 return value;
141}
142
143export function NativeStackScreenOptions(props: {
144 readonly options?: AppNativeStackNavigationOptions;
145 /**
146 * Causes dynamic native header factories to be reapplied when their closed-over
147 * menu content changes. Factory functions are intentionally stabilized, so
148 * their source alone cannot capture a menu that was initially empty while
149 * asynchronous data was loading.
150 */
151 readonly optionsVersion?: unknown;
152 readonly listeners?: Record<string, (event: never) => void>;
153 readonly name?: string;
154}) {
155 const navigation = useNativeStackNavigation();
156 const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);
157 const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
158 const optionFunctionWrappersRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
159 const normalizedOptions = useMemo(() => normalizeScreenOptions(props.options), [props.options]);
160 const stableOptions = normalizedOptions
161 ? (stabilizeOptionFunctions(
162 normalizedOptions,
163 "options",
164 latestOptionFunctionsRef.current,
165 optionFunctionWrappersRef.current,
166 ) as NativeStackNavigationOptions)
167 : undefined;
168
169 useLayoutEffect(() => {
170 if (!navigation || !stableOptions) {
171 return;
172 }
173 const signature = optionsSignature([stableOptions, props.optionsVersion]);
174 // Avoid re-entering navigation state when semantically equal options are
175 // reapplied every layout (common when callers pass unstable object literals).
176 if (lastAppliedOptionsSignatureRef.current === signature) {
177 return;
178 }
179 lastAppliedOptionsSignatureRef.current = signature;
180 navigation.setOptions(stableOptions);
181 }, [navigation, props.optionsVersion, stableOptions]);
182
183 useEffect(() => {
184 if (!navigation || !props.listeners) {
185 return;
186 }
187 const subscriptions = Object.entries(props.listeners).map(([eventName, listener]) =>
188 navigation.addListener(eventName as never, listener as never),
189 );
190 return () => {
191 for (const unsubscribe of subscriptions) {
192 unsubscribe();
193 }
194 };
195 }, [navigation, props.listeners]);
196
197 return null;
198}
199
200function labelFromChildren(children: ReactNode): string {
201 const parts: string[] = [];
202 Children.forEach(children, (child) => {
203 if (typeof child === "string" || typeof child === "number") {
204 parts.push(String(child));
205 } else if (isValidElement<{ children?: ReactNode }>(child)) {
206 parts.push(labelFromChildren(child.props.children));
207 }
208 });
209 return parts.join("");
210}
211
212type NativeStackHeaderIcon = NonNullable<
213 Extract<NativeStackHeaderItem, { type: "button" }>["icon"]
214>;
215type NativeStackOptionsWithToolbar = NativeStackNavigationOptions & {
216 unstable_headerToolbarItems?: () => NativeStackHeaderItem[];
217};
218
219function iconFromProp(icon: unknown): NativeStackHeaderIcon | undefined {
220 if (typeof icon !== "string") {
221 return undefined;
222 }
223 return { type: "sfSymbol", name: icon as never };
224}
225
226type ToolbarElementProps = Record<string, unknown> & { readonly children?: ReactNode };
227
228function elementTypeName(element: ReactElement): string | undefined {
229 const type = element.type;
230 if (typeof type === "function") {
231 return (type as { displayName?: string; name?: string }).displayName ?? type.name;
232 }
233 return undefined;
234}
235
236function convertMenuAction(
237 element: ReactElement<ToolbarElementProps>,
238): NativeStackHeaderItemMenu["menu"]["items"][number] | null {
239 const typeName = elementTypeName(element);
240 if (typeName === "NativeHeaderToolbarMenuAction") {
241 const label = labelFromChildren(element.props.children);
242 return {
243 type: "action",
244 label,
245 description: typeof element.props.subtitle === "string" ? element.props.subtitle : undefined,
246 disabled: Boolean(element.props.disabled),
247 icon: iconFromProp(element.props.icon),
248 onPress:
249 typeof element.props.onPress === "function"
250 ? (element.props.onPress as () => void)
251 : () => undefined,
252 state: element.props.isOn === true ? "on" : undefined,
253 destructive: Boolean(element.props.destructive),
254 discoverabilityLabel:
255 typeof element.props.discoverabilityLabel === "string"
256 ? element.props.discoverabilityLabel
257 : undefined,
258 };
259 }
260
261 if (typeName === "NativeHeaderToolbarMenu") {
262 return {
263 type: "submenu",
264 label:
265 typeof element.props.title === "string"
266 ? element.props.title
267 : labelFromChildren(element.props.children),
268 icon: iconFromProp(element.props.icon),
269 inline: Boolean(element.props.inline),
270 items: collectMenuItems(element.props.children),
271 };
272 }
273
274 return null;
275}
276
277function collectMenuItems(children: ReactNode): NativeStackHeaderItemMenu["menu"]["items"] {
278 const items: NativeStackHeaderItemMenu["menu"]["items"] = [];
279 Children.forEach(children, (child) => {
280 if (!isValidElement<ToolbarElementProps>(child)) {
281 return;
282 }
283 const item = convertMenuAction(child);
284 if (item) {
285 items.push(item);
286 return;
287 }
288 items.push(...collectMenuItems(child.props.children));
289 });
290 return items;
291}
292
293function convertToolbarChild(child: ReactNode): NativeStackHeaderItem | null {
294 if (!isValidElement<ToolbarElementProps>(child)) {
295 return null;
296 }
297
298 const typeName = elementTypeName(child);
299 if (typeName === "NativeHeaderToolbarButton") {
300 return {
301 type: "button",
302 label: typeof child.props.label === "string" ? child.props.label : "",
303 accessibilityLabel:
304 typeof child.props.accessibilityLabel === "string"
305 ? child.props.accessibilityLabel
306 : undefined,
307 disabled: Boolean(child.props.disabled),
308 icon: iconFromProp(child.props.icon),
309 onPress:
310 typeof child.props.onPress === "function"
311 ? (child.props.onPress as () => void)
312 : () => undefined,
313 sharesBackground: !child.props.separateBackground,
314 tintColor: child.props.tintColor as ColorValue | undefined,
315 variant: "plain",
316 };
317 }
318
319 if (typeName === "NativeHeaderToolbarMenu") {
320 return {
321 type: "menu",
322 label: typeof child.props.title === "string" ? child.props.title : "",
323 accessibilityLabel:
324 typeof child.props.accessibilityLabel === "string"
325 ? child.props.accessibilityLabel
326 : undefined,
327 disabled: Boolean(child.props.disabled),
328 icon: iconFromProp(child.props.icon),
329 menu: {
330 title: typeof child.props.title === "string" ? child.props.title : undefined,
331 items: collectMenuItems(child.props.children),
332 },
333 sharesBackground: !child.props.separateBackground,
334 tintColor: child.props.tintColor as ColorValue | undefined,
335 variant: "plain",
336 };
337 }
338
339 if (typeName === "NativeHeaderToolbarSpacer") {
340 return {
341 type: "spacing",
342 spacing: typeof child.props.width === "number" ? child.props.width : 8,
343 flexible: Boolean(child.props.flexible),
344 } as NativeStackHeaderItem;
345 }
346
347 return null;
348}
349
350function collectToolbarItems(children: ReactNode): NativeStackHeaderItem[] {
351 const items: NativeStackHeaderItem[] = [];
352 Children.forEach(children, (child) => {
353 const item = convertToolbarChild(child);
354 if (item) {
355 if (item.type === "spacing") {
356 // Native inserts spacing items at `index`, treating a missing index
357 // as 0 — which would move the spacer in front of earlier siblings.
358 (item as { index?: number }).index = items.length;
359 }
360 items.push(item);
361 }
362 });
363 return items;
364}
365
366function NativeHeaderToolbarRoot(props: {
367 readonly placement?: "left" | "right" | "bottom";
368 readonly children?: ReactNode;
369}) {
370 const navigation = useNativeStackNavigation();
371 const items = useMemo(() => collectToolbarItems(props.children), [props.children]);
372
373 useEffect(() => {
374 if (!navigation) {
375 return;
376 }
377 if (props.placement === "bottom") {
378 navigation.setOptions({
379 unstable_headerToolbarItems: () => items,
380 } as NativeStackOptionsWithToolbar);
381 return () => {
382 navigation.setOptions({
383 unstable_headerToolbarItems: () => [],
384 } as NativeStackOptionsWithToolbar);
385 };
386 }
387 if (props.placement === "left") {
388 navigation.setOptions({ unstable_headerLeftItems: () => items });
389 return () => {
390 navigation.setOptions({ unstable_headerLeftItems: () => [] });
391 };
392 }
393 navigation.setOptions({ unstable_headerRightItems: () => items });
394 return () => {
395 navigation.setOptions({ unstable_headerRightItems: () => [] });
396 };
397 }, [items, navigation, props.placement]);
398
399 return null;
400}
401
402function NativeHeaderToolbarButton(_props: {
403 readonly accessibilityLabel?: string;
404 readonly disabled?: boolean;
405 readonly icon?: string;
406 readonly label?: string;
407 readonly onPress?: () => void;
408 readonly separateBackground?: boolean;
409 readonly tintColor?: ColorValue;
410}) {
411 return null;
412}
413NativeHeaderToolbarButton.displayName = "NativeHeaderToolbarButton";
414
415function NativeHeaderToolbarMenu(_props: {
416 readonly accessibilityLabel?: string;
417 readonly children?: ReactNode;
418 readonly disabled?: boolean;
419 readonly icon?: string;
420 readonly inline?: boolean;
421 readonly separateBackground?: boolean;
422 readonly tintColor?: ColorValue;
423 readonly title?: string;
424}) {
425 return null;
426}
427NativeHeaderToolbarMenu.displayName = "NativeHeaderToolbarMenu";
428
429function NativeHeaderToolbarMenuAction(_props: {
430 readonly children?: ReactNode;
431 readonly destructive?: boolean;
432 readonly disabled?: boolean;
433 readonly discoverabilityLabel?: string;
434 readonly icon?: string;
435 readonly isOn?: boolean;
436 readonly onPress?: () => void;
437 readonly subtitle?: string;
438}) {
439 return null;
440}
441NativeHeaderToolbarMenuAction.displayName = "NativeHeaderToolbarMenuAction";
442
443function NativeHeaderToolbarLabel(_props: { readonly children?: ReactNode }) {
444 return null;
445}
446NativeHeaderToolbarLabel.displayName = "NativeHeaderToolbarLabel";
447
448function NativeHeaderToolbarSpacer(_props: {
449 readonly flexible?: boolean;
450 readonly sharesBackground?: boolean;
451 readonly width?: number;
452}) {
453 return null;
454}
455NativeHeaderToolbarSpacer.displayName = "NativeHeaderToolbarSpacer";
456
457function NativeHeaderToolbarSearchBarSlot() {
458 return null;
459}
460NativeHeaderToolbarSearchBarSlot.displayName = "NativeHeaderToolbarSearchBarSlot";
461
462export const NativeHeaderToolbar = Object.assign(NativeHeaderToolbarRoot, {
463 Button: NativeHeaderToolbarButton,
464 Label: NativeHeaderToolbarLabel,
465 Menu: Object.assign(NativeHeaderToolbarMenu, {
466 Action: NativeHeaderToolbarMenuAction,
467 }),
468 MenuAction: NativeHeaderToolbarMenuAction,
469 SearchBarSlot: NativeHeaderToolbarSearchBarSlot,
470 Spacer: NativeHeaderToolbarSpacer,
471});