Open History to see the last commit
1import { useNavigation, type ParamListBase } from "@react-navigation/native";
2import type {
3 NativeStackNavigationOptions,
4 NativeStackNavigationProp,
5} from "@react-navigation/native-stack";
6import { useEffect, useLayoutEffect, useMemo, useRef } from "react";
7import type { ColorValue } from "react-native";
8
9export { NativeHeaderToolbar } from "./NativeHeaderToolbar";
10
11export {
12 nativeHeaderScrollEdgeEffects,
13 nativeTopScrollEdgeEffect,
14 type NativeHeaderScrollEdgeEffects,
15 type NativeTopScrollEdgeEffect,
16} from "./scrollEdgeEffects";
17
18export type AppNativeStackNavigationOptions = Omit<
19 NativeStackNavigationOptions,
20 "headerTintColor" | "unstable_headerLeftItems" | "unstable_headerRightItems"
21> & {
22 /** Nested navigator leaves apply their own horizontal safe area. */
23 readonly nativeContentInsetHorizontally?: boolean;
24 readonly headerTintColor?: string | ColorValue;
25 readonly unstable_headerCenterItems?: unknown;
26 readonly unstable_headerLeftItems?: unknown;
27 readonly unstable_headerRightItems?: unknown;
28 readonly unstable_headerSubtitle?: unknown;
29 readonly unstable_headerToolbarItems?: unknown;
30 readonly unstable_navigationItemStyle?: unknown;
31};
32
33function useNativeStackNavigation(): NativeStackNavigationProp<ParamListBase> | null {
34 return useNavigation<NativeStackNavigationProp<ParamListBase>>();
35}
36
37function normalizeScreenOptions(
38 options: AppNativeStackNavigationOptions | undefined,
39): NativeStackNavigationOptions | undefined {
40 if (!options) {
41 return options;
42 }
43
44 const normalized = { ...options } as NativeStackNavigationOptions & {
45 unstable_navigationItemStyle?: unknown;
46 unstable_headerCenterItems?: unknown;
47 unstable_headerSubtitle?: unknown;
48 unstable_headerToolbarItems?: unknown;
49 };
50
51 if (normalized.headerTintColor !== undefined) {
52 normalized.headerTintColor = String(normalized.headerTintColor);
53 }
54
55 return normalized as NativeStackNavigationOptions;
56}
57
58function optionsSignature(value: unknown, seen = new WeakSet<object>()): string {
59 if (value === null) return "null";
60 switch (typeof value) {
61 case "boolean":
62 case "number":
63 case "string":
64 return JSON.stringify(value);
65 case "undefined":
66 return "undefined";
67 case "function":
68 // Header factories are frequently recreated inline. Their source is
69 // stable across equivalent renders, while a reference comparison would
70 // make navigation.setOptions re-enter the navigator indefinitely.
71 return `function:${Function.prototype.toString.call(value)}`;
72 case "symbol":
73 return `symbol:${String(value)}`;
74 case "bigint":
75 return `bigint:${String(value)}`;
76 case "object": {
77 const object = value as object;
78 if (seen.has(object)) return "[circular]";
79 seen.add(object);
80 if (Array.isArray(value)) {
81 return `[${value.map((entry) => optionsSignature(entry, seen)).join(",")}]`;
82 }
83 // React refs carry mutable native instances that must not make static
84 // screen options appear different after every render.
85 if ("current" in object) return "[ref]";
86 return `{${Object.keys(value as Record<string, unknown>)
87 .sort()
88 .map(
89 (key) =>
90 `${JSON.stringify(key)}:${optionsSignature((value as Record<string, unknown>)[key], seen)}`,
91 )
92 .join(",")}}`;
93 }
94 }
95 return String(value);
96}
97
98function stabilizeOptionFunctions(
99 value: unknown,
100 path: string,
101 latestFunctions: Map<string, (...args: unknown[]) => unknown>,
102 wrappers: Map<string, (...args: unknown[]) => unknown>,
103 seen = new WeakSet<object>(),
104): unknown {
105 if (typeof value === "function") {
106 latestFunctions.set(path, value as (...args: unknown[]) => unknown);
107 let wrapper = wrappers.get(path);
108 if (!wrapper) {
109 wrapper = (...args: unknown[]) => {
110 return latestFunctions.get(path)?.(...args);
111 };
112 wrappers.set(path, wrapper);
113 }
114 return wrapper;
115 }
116 if (Array.isArray(value)) {
117 if (seen.has(value)) return value;
118 seen.add(value);
119 return value.map((entry, index) =>
120 stabilizeOptionFunctions(entry, `${path}[${index}]`, latestFunctions, wrappers, seen),
121 );
122 }
123 if (value !== null && typeof value === "object") {
124 if (seen.has(value) || "current" in value) return value;
125 seen.add(value);
126 return Object.fromEntries(
127 Object.entries(value as Record<string, unknown>).map(([key, entry]) => [
128 key,
129 stabilizeOptionFunctions(entry, `${path}.${key}`, latestFunctions, wrappers, seen),
130 ]),
131 );
132 }
133 return value;
134}
135
136export function NativeStackScreenOptions(props: {
137 readonly options?: AppNativeStackNavigationOptions;
138 /**
139 * Causes dynamic native header factories to be reapplied when their closed-over
140 * menu content changes. Factory functions are intentionally stabilized, so
141 * their source alone cannot capture a menu that was initially empty while
142 * asynchronous data was loading.
143 */
144 readonly optionsVersion?: unknown;
145 readonly listeners?: Record<string, (event: never) => void>;
146 readonly name?: string;
147}) {
148 const navigation = useNativeStackNavigation();
149 const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);
150 const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
151 const optionFunctionWrappersRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
152 const normalizedOptions = useMemo(() => normalizeScreenOptions(props.options), [props.options]);
153 const stableOptions = normalizedOptions
154 ? (stabilizeOptionFunctions(
155 normalizedOptions,
156 "options",
157 latestOptionFunctionsRef.current,
158 optionFunctionWrappersRef.current,
159 ) as NativeStackNavigationOptions)
160 : undefined;
161
162 useLayoutEffect(() => {
163 if (!navigation || !stableOptions) {
164 return;
165 }
166 const signature = optionsSignature([stableOptions, props.optionsVersion]);
167 // Avoid re-entering navigation state when semantically equal options are
168 // reapplied every layout (common when callers pass unstable object literals).
169 if (lastAppliedOptionsSignatureRef.current === signature) {
170 return;
171 }
172 lastAppliedOptionsSignatureRef.current = signature;
173 navigation.setOptions(stableOptions);
174 }, [navigation, props.optionsVersion, stableOptions]);
175
176 useEffect(() => {
177 if (!navigation || !props.listeners) {
178 return;
179 }
180 const subscriptions = Object.entries(props.listeners).map(([eventName, listener]) =>
181 navigation.addListener(eventName as never, listener as never),
182 );
183 return () => {
184 for (const unsubscribe of subscriptions) {
185 unsubscribe();
186 }
187 };
188 }, [navigation, props.listeners]);
189
190 return null;
191}