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

StackHeader.tsx

232 lines8.3 KB

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