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 };
344 }
345
346 return null;
347}
348
349function collectToolbarItems(children: ReactNode): NativeStackHeaderItem[] {
350 const items: NativeStackHeaderItem[] = [];
351 Children.forEach(children, (child) => {
352 const item = convertToolbarChild(child);
353 if (item) {
354 items.push(item);
355 }
356 });
357 return items;
358}
359
360function NativeHeaderToolbarRoot(props: {
361 readonly placement?: "left" | "right" | "bottom";
362 readonly children?: ReactNode;
363}) {
364 const navigation = useNativeStackNavigation();
365 const items = useMemo(() => collectToolbarItems(props.children), [props.children]);
366
367 useEffect(() => {
368 if (!navigation) {
369 return;
370 }
371 if (props.placement === "bottom") {
372 navigation.setOptions({
373 unstable_headerToolbarItems: () => items,
374 } as NativeStackOptionsWithToolbar);
375 return () => {
376 navigation.setOptions({
377 unstable_headerToolbarItems: () => [],
378 } as NativeStackOptionsWithToolbar);
379 };
380 }
381 if (props.placement === "left") {
382 navigation.setOptions({ unstable_headerLeftItems: () => items });
383 return () => {
384 navigation.setOptions({ unstable_headerLeftItems: () => [] });
385 };
386 }
387 navigation.setOptions({ unstable_headerRightItems: () => items });
388 return () => {
389 navigation.setOptions({ unstable_headerRightItems: () => [] });
390 };
391 }, [items, navigation, props.placement]);
392
393 return null;
394}
395
396function NativeHeaderToolbarButton(_props: {
397 readonly accessibilityLabel?: string;
398 readonly disabled?: boolean;
399 readonly icon?: string;
400 readonly label?: string;
401 readonly onPress?: () => void;
402 readonly separateBackground?: boolean;
403 readonly tintColor?: ColorValue;
404}) {
405 return null;
406}
407NativeHeaderToolbarButton.displayName = "NativeHeaderToolbarButton";
408
409function NativeHeaderToolbarMenu(_props: {
410 readonly accessibilityLabel?: string;
411 readonly children?: ReactNode;
412 readonly disabled?: boolean;
413 readonly icon?: string;
414 readonly inline?: boolean;
415 readonly separateBackground?: boolean;
416 readonly tintColor?: ColorValue;
417 readonly title?: string;
418}) {
419 return null;
420}
421NativeHeaderToolbarMenu.displayName = "NativeHeaderToolbarMenu";
422
423function NativeHeaderToolbarMenuAction(_props: {
424 readonly children?: ReactNode;
425 readonly destructive?: boolean;
426 readonly disabled?: boolean;
427 readonly discoverabilityLabel?: string;
428 readonly icon?: string;
429 readonly isOn?: boolean;
430 readonly onPress?: () => void;
431 readonly subtitle?: string;
432}) {
433 return null;
434}
435NativeHeaderToolbarMenuAction.displayName = "NativeHeaderToolbarMenuAction";
436
437function NativeHeaderToolbarLabel(_props: { readonly children?: ReactNode }) {
438 return null;
439}
440NativeHeaderToolbarLabel.displayName = "NativeHeaderToolbarLabel";
441
442function NativeHeaderToolbarSpacer(_props: {
443 readonly sharesBackground?: boolean;
444 readonly width?: number;
445}) {
446 return null;
447}
448NativeHeaderToolbarSpacer.displayName = "NativeHeaderToolbarSpacer";
449
450function NativeHeaderToolbarSearchBarSlot() {
451 return null;
452}
453NativeHeaderToolbarSearchBarSlot.displayName = "NativeHeaderToolbarSearchBarSlot";
454
455export const NativeHeaderToolbar = Object.assign(NativeHeaderToolbarRoot, {
456 Button: NativeHeaderToolbarButton,
457 Label: NativeHeaderToolbarLabel,
458 Menu: Object.assign(NativeHeaderToolbarMenu, {
459 Action: NativeHeaderToolbarMenuAction,
460 }),
461 MenuAction: NativeHeaderToolbarMenuAction,
462 SearchBarSlot: NativeHeaderToolbarSearchBarSlot,
463 Spacer: NativeHeaderToolbarSpacer,
464});