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

StackHeader.tsx

192 lines6.6 KB

1import { useNavigation, type ParamListBase } from "@react-navigation/native";
2import type {
3 NativeStackNavigationOptions,
4 NativeStackNavigationProp,
5} from "@react-navigation/native-stack";
6import { 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>>();
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;
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);
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;
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 tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true;
148 const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);
149 const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
150 const optionFunctionWrappersRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
151 const normalizedOptions = useMemo(() => normalizeScreenOptions(props.options), [props.options]);
152 const stableOptions = normalizedOptions
153 ? (stabilizeOptionFunctions(
154 normalizedOptions,
155 "options",
156 latestOptionFunctionsRef.current,
157 optionFunctionWrappersRef.current,
158 ) as NativeStackNavigationOptions)
159 : undefined;
160​
161 useLayoutEffect(() => {
162 if (!tabActive) {
163 lastAppliedOptionsSignatureRef.current = undefined;
164 return;
165 }
166 if (!navigation || !stableOptions) {
167 return;
168 }
169 const signature = optionsSignature([stableOptions, props.optionsVersion]);
170 if (lastAppliedOptionsSignatureRef.current === signature) {
171 return;
172 }
173 lastAppliedOptionsSignatureRef.current = signature;
174 navigation.setOptions(stableOptions);
175 }, [navigation, props.optionsVersion, stableOptions, tabActive]);
176​
177 useEffect(() => {
178 if (!navigation || !props.listeners) {
179 return;
180 }
181 const subscriptions = Object.entries(props.listeners).map(([eventName, listener]) =>
182 navigation.addListener(eventName as never, listener as never),
183 );
184 return () => {
185 for (const unsubscribe of subscriptions) {
186 unsubscribe();
187 }
188 };
189 }, [navigation, props.listeners]);
190​
191 return null;