Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

StackHeader.tsx

255 lines9.3 KB

1import {
2 NavigationContext,
3 NavigationRouteContext,
4 type ParamListBase,
5} from "@react-navigation/native";
6import type {
7 NativeStackNavigationOptions,
8 NativeStackNavigationProp,
9} from "@react-navigation/native-stack";
10import { isValidElement, use, useEffect, useLayoutEffect, useMemo, useRef } from "react";
11import {
12 NativeWorkspaceTabActivityContext,
13 WorkspaceSlotOptionsContext,
14} from "./v5-workspace-context";
15import type { ColorValue } from "react-native";
16​
17export {
18 nativeHeaderScrollEdgeEffects,
19 type NativeHeaderScrollEdgeEffects,
20 type NativeTopScrollEdgeEffect,
21} from "./scrollEdgeEffects";
22​
23export type AppNativeStackNavigationOptions = Omit<
24 NativeStackNavigationOptions,
25 "headerTintColor" | "unstable_headerLeftItems" | "unstable_headerRightItems"
26> & {
27 readonly nativeContentInsetHorizontally?: boolean;
28 readonly headerTintColor?: string | ColorValue;
29 readonly unstable_headerCenterItems?: unknown;
30 readonly unstable_headerLeftItems?: unknown;
31 readonly unstable_headerRightItems?: unknown;
32 readonly unstable_headerSubtitle?: unknown;
33 readonly unstable_headerToolbarItems?: unknown;
34 readonly unstable_navigationItemStyle?: unknown;
35 readonly unstable_headerMinimizationBehavior?: unknown;
36};
37​
38function useNativeStackNavigation(): NativeStackNavigationProp<ParamListBase> | null {
39 const navigation = use(NavigationContext);
40 return navigation ? (navigation as NativeStackNavigationProp<ParamListBase>) : null;
42​
43function normalizeScreenOptions(
44 options: AppNativeStackNavigationOptions | undefined,
45): NativeStackNavigationOptions | undefined {
46 if (!options) {
47 return options;
48 }
49​
50 const normalized = { ...options } as NativeStackNavigationOptions & {
51 unstable_navigationItemStyle?: unknown;
52 unstable_headerCenterItems?: unknown;
53 unstable_headerSubtitle?: unknown;
54 unstable_headerToolbarItems?: unknown;
55 };
56​
57 if (normalized.headerTintColor !== undefined) {
58 normalized.headerTintColor = String(normalized.headerTintColor);
59 }
60​
61 return normalized as NativeStackNavigationOptions;
63​
64// React tags elements, component types and contexts with `$$typeof`; their other
65// fields are React internals. In development an element's `_owner` is a fiber that
66// reaches the whole tree, including contexts that hold their default value outside
67// render, and React Navigation's NavigationStateContext default throws when read.
68function isReactObject(value: object): boolean {
69 return "$$typeof" in value;
71​
72const identityIds = new WeakMap<object, number>();
73let nextIdentityId = 0;
74​
75function identitySignature(value: unknown): string {
76 if (value === null || (typeof value !== "object" && typeof value !== "function")) {
77 return String(value);
78 }
79 let id = identityIds.get(value);
80 if (id === undefined) {
81 id = nextIdentityId++;
82 identityIds.set(value, id);
83 }
84 return `identity:${id}`;
86​
87function optionsSignature(value: unknown, seen = new WeakSet<object>()): string {
88 if (value === null) return "null";
89 switch (typeof value) {
90 case "boolean":
91 case "number":
92 case "string":
93 return JSON.stringify(value);
94 case "undefined":
95 return "undefined";
96 case "function":
97 // Compare factory source; inline references change every render and would loop setOptions.
98 return `function:${Function.prototype.toString.call(value)}`;
99 case "symbol":
100 return `symbol:${String(value)}`;
101 case "bigint":
102 return `bigint:${String(value)}`;
103 case "object": {
104 const object = value as object;
105 if (isValidElement(object)) {
106 // Elements are recreated on every render, so compare what they render.
107 return `element:${identitySignature(object.type)}:${String(object.key)}:${optionsSignature(object.props, seen)}`;
108 }
109 if (isReactObject(object)) return identitySignature(object);
110 if (seen.has(object)) return "[circular]";
111 seen.add(object);
112 if (Array.isArray(value)) {
113 return `[${value.map((entry) => optionsSignature(entry, seen)).join(",")}]`;
114 }
115 // Ignore mutable native refs when comparing static screen options.
116 if ("current" in object) return "[ref]";
117 return `{${Object.keys(value as Record<string, unknown>)
118 .sort()
119 .map(
120 (key) =>
121 `${JSON.stringify(key)}:${optionsSignature((value as Record<string, unknown>)[key], seen)}`,
122 )
123 .join(",")}}`;
124 }
125 }
126 return String(value);
128​
129function stabilizeOptionFunctions(
130 value: unknown,
131 path: string,
132 latestFunctions: Map<string, (...args: unknown[]) => unknown>,
133 wrappers: Map<string, (...args: unknown[]) => unknown>,
134 seen = new WeakSet<object>(),
135): unknown {
136 if (typeof value === "function") {
137 latestFunctions.set(path, value as (...args: unknown[]) => unknown);
138 let wrapper = wrappers.get(path);
139 if (!wrapper) {
140 wrapper = (...args: unknown[]) => {
141 return latestFunctions.get(path)?.(...args);
142 };
143 wrappers.set(path, wrapper);
144 }
145 return wrapper;
146 }
147 if (Array.isArray(value)) {
148 if (seen.has(value)) return value;
149 seen.add(value);
150 return value.map((entry, index) =>
151 stabilizeOptionFunctions(entry, `${path}[${index}]`, latestFunctions, wrappers, seen),
152 );
153 }
154 if (value !== null && typeof value === "object") {
155 if (seen.has(value) || "current" in value || isReactObject(value)) return value;
156 seen.add(value);
157 return Object.fromEntries(
158 Object.entries(value as Record<string, unknown>).map(([key, entry]) => [
159 key,
160 stabilizeOptionFunctions(entry, `${path}.${key}`, latestFunctions, wrappers, seen),
161 ]),
162 );
163 }
164 return value;
166​
167/**
168 * Sets the current screen's options. Inside a workspace tab slot they're kept for that slot, so
169 * slots rendering the same route never overwrite each other's header.
170 */
171export function useScreenOptionsWriter() {
172 const navigation = useNativeStackNavigation();
173 const setSlotOptions = use(WorkspaceSlotOptionsContext)?.set;
174 const routeKey = use(NavigationRouteContext)?.key;
175 return useMemo(() => {
176 if (setSlotOptions && routeKey !== undefined)
177 return (options: NativeStackNavigationOptions) => setSlotOptions(routeKey, options);
178 return navigation
179 ? (options: NativeStackNavigationOptions) => navigation.setOptions(options)
180 : null;
181 }, [navigation, routeKey, setSlotOptions]);
183​
184export function NativeStackScreenOptions(props: {
185 readonly options?: AppNativeStackNavigationOptions;
186 /** Reapply factories when captured data changes; source equality misses asynchronous menu content. */
187 readonly optionsVersion?: unknown;
188 readonly listeners?: Record<string, (event: never) => void>;
189 readonly name?: string;
190}) {
191 const navigation = useNativeStackNavigation();
192 const setOptions = useScreenOptionsWriter();
193 const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true;
194 const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);
195 const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
196 const optionFunctionWrappersRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
197​
198 // Stabilizing records each factory's latest closure, so it runs in the commit
199 // phase: a render React discards must not leak its closures into the header.
200 // It runs before the tab check so wrappers already installed in an inactive
201 // tab's header still call the newest closures.
202 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes stabilized header options to the navigator after commit so discarded renders leave no closures
203 useLayoutEffect(() => {
204 const normalizedOptions = normalizeScreenOptions(props.options);
205 const stableOptions = normalizedOptions
206 ? stabilizeOptionFunctions(
207 normalizedOptions,
208 "options",
209 latestOptionFunctionsRef.current,
210 optionFunctionWrappersRef.current,
211 )
212 : undefined;
213 if (!tabActive) {
214 lastAppliedOptionsSignatureRef.current = undefined;
215 return;
216 }
217 if (!setOptions || !normalizedOptions) {
218 return;
219 }
220 const signature = optionsSignature([stableOptions, props.optionsVersion]);
221 if (lastAppliedOptionsSignatureRef.current === signature) {
222 return;
223 }
224 lastAppliedOptionsSignatureRef.current = signature;
225 // React Navigation keeps a screen's descriptor while its options are shallowly equal. The
226 // stabilized factories keep their identity, so one whose output changed needs a new wrapper
227 // to reach the header.
228 optionFunctionWrappersRef.current = new Map();
229 setOptions(
230 stabilizeOptionFunctions(
231 normalizedOptions,
232 "options",
233 latestOptionFunctionsRef.current,
234 optionFunctionWrappersRef.current,
235 ) as NativeStackNavigationOptions,
236 );
237 }, [setOptions, props.options, props.optionsVersion, tabActive]);
238​
239 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes the given listeners to navigator events for the screen's lifetime
240 useEffect(() => {
241 if (!navigation || !props.listeners) {
242 return;
243 }
244 const subscriptions = Object.entries(props.listeners).map(([eventName, listener]) =>
245 navigation.addListener(eventName as never, listener as never),
246 );
247 return () => {
248 for (const unsubscribe of subscriptions) {
249 unsubscribe();
250 }
251 };
252 }, [navigation, props.listeners]);
253​
254 return null;