Open History to see the last commit
1import { useNavigation, type ParamListBase } from "@react-navigation/native";
2import type {
3 NativeStackHeaderItemMenu,
4 NativeStackNavigationOptions,
5 NativeStackNavigationProp,
6} from "@react-navigation/native-stack";
7import { isValidElement, use, useEffect, useLayoutEffect, useMemo, useRef } from "react";
8import { NativeWorkspaceTabActivityContext } from "./v5-workspace-context";
9import type { ColorValue } from "react-native";
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 nativeContentInsetHorizontally?: boolean;
23 readonly nativeSidebarFilter?: NativeStackHeaderItemMenu;
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
58// React tags elements, component types and contexts with `$$typeof`; their other
59// fields are React internals. In development an element's `_owner` is a fiber that
60// reaches the whole tree, including contexts that hold their default value outside
61// render, and React Navigation's NavigationStateContext default throws when read.
62function isReactObject(value: object): boolean {
63 return "$$typeof" in value;
64}
65
66const identityIds = new WeakMap<object, number>();
67let nextIdentityId = 0;
68
69function identitySignature(value: unknown): string {
70 if (value === null || (typeof value !== "object" && typeof value !== "function")) {
71 return String(value);
72 }
73 let id = identityIds.get(value);
74 if (id === undefined) {
75 id = nextIdentityId++;
76 identityIds.set(value, id);
77 }
78 return `identity:${id}`;
79}
80
81function optionsSignature(value: unknown, seen = new WeakSet<object>()): string {
82 if (value === null) return "null";
83 switch (typeof value) {
84 case "boolean":
85 case "number":
86 case "string":
87 return JSON.stringify(value);
88 case "undefined":
89 return "undefined";
90 case "function":
91 // Header factories are frequently recreated inline. Their source is
92 // stable across equivalent renders, while a reference comparison would
93 // make navigation.setOptions re-enter the navigator indefinitely.
94 return `function:${Function.prototype.toString.call(value)}`;
95 case "symbol":
96 return `symbol:${String(value)}`;
97 case "bigint":
98 return `bigint:${String(value)}`;
99 case "object": {
100 const object = value as object;
101 if (isValidElement(object)) {
102 // Elements are recreated on every render, so compare what they render.
103 return `element:${identitySignature(object.type)}:${String(object.key)}:${optionsSignature(object.props, seen)}`;
104 }
105 if (isReactObject(object)) return identitySignature(object);
106 if (seen.has(object)) return "[circular]";
107 seen.add(object);
108 if (Array.isArray(value)) {
109 return `[${value.map((entry) => optionsSignature(entry, seen)).join(",")}]`;
110 }
111 // React refs carry mutable native instances that must not make static
112 // screen options appear different after every render.
113 if ("current" in object) return "[ref]";
114 return `{${Object.keys(value as Record<string, unknown>)
115 .sort()
116 .map(
117 (key) =>
118 `${JSON.stringify(key)}:${optionsSignature((value as Record<string, unknown>)[key], seen)}`,
119 )
120 .join(",")}}`;
121 }
122 }
123 return String(value);
124}
125
126function stabilizeOptionFunctions(
127 value: unknown,
128 path: string,
129 latestFunctions: Map<string, (...args: unknown[]) => unknown>,
130 wrappers: Map<string, (...args: unknown[]) => unknown>,
131 seen = new WeakSet<object>(),
132): unknown {
133 if (typeof value === "function") {
134 latestFunctions.set(path, value as (...args: unknown[]) => unknown);
135 let wrapper = wrappers.get(path);
136 if (!wrapper) {
137 wrapper = (...args: unknown[]) => {
138 return latestFunctions.get(path)?.(...args);
139 };
140 wrappers.set(path, wrapper);
141 }
142 return wrapper;
143 }
144 if (Array.isArray(value)) {
145 if (seen.has(value)) return value;
146 seen.add(value);
147 return value.map((entry, index) =>
148 stabilizeOptionFunctions(entry, `${path}[${index}]`, latestFunctions, wrappers, seen),
149 );
150 }
151 if (value !== null && typeof value === "object") {
152 if (seen.has(value) || "current" in value || isReactObject(value)) return value;
153 seen.add(value);
154 return Object.fromEntries(
155 Object.entries(value as Record<string, unknown>).map(([key, entry]) => [
156 key,
157 stabilizeOptionFunctions(entry, `${path}.${key}`, latestFunctions, wrappers, seen),
158 ]),
159 );
160 }
161 return value;
162}
163
164export function NativeStackScreenOptions(props: {
165 readonly options?: AppNativeStackNavigationOptions;
166 /**
167 * Causes dynamic native header factories to be reapplied when their closed-over
168 * menu content changes. Factory functions are intentionally stabilized, so
169 * their source alone cannot capture a menu that was initially empty while
170 * asynchronous data was loading.
171 */
172 readonly optionsVersion?: unknown;
173 readonly listeners?: Record<string, (event: never) => void>;
174 readonly name?: string;
175}) {
176 const navigation = useNativeStackNavigation();
177 const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true;
178 const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);
179 const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
180 const optionFunctionWrappersRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
181 const normalizedOptions = useMemo(() => normalizeScreenOptions(props.options), [props.options]);
182 const stableOptions = normalizedOptions
183 ? (stabilizeOptionFunctions(
184 normalizedOptions,
185 "options",
186 latestOptionFunctionsRef.current,
187 optionFunctionWrappersRef.current,
188 ) as NativeStackNavigationOptions)
189 : undefined;
190
191 useLayoutEffect(() => {
192 if (!tabActive) {
193 lastAppliedOptionsSignatureRef.current = undefined;
194 return;
195 }
196 if (!navigation || !stableOptions) {
197 return;
198 }
199 const signature = optionsSignature([stableOptions, props.optionsVersion]);
200 if (lastAppliedOptionsSignatureRef.current === signature) {
201 return;
202 }
203 lastAppliedOptionsSignatureRef.current = signature;
204 navigation.setOptions(stableOptions);
205 }, [navigation, props.optionsVersion, stableOptions, tabActive]);
206
207 useEffect(() => {
208 if (!navigation || !props.listeners) {
209 return;
210 }
211 const subscriptions = Object.entries(props.listeners).map(([eventName, listener]) =>
212 navigation.addListener(eventName as never, listener as never),
213 );
214 return () => {
215 for (const unsubscribe of subscriptions) {
216 unsubscribe();
217 }
218 };
219 }, [navigation, props.listeners]);
220
221 return null;
222}