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