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