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

StackHeader.tsx

194 lines6.7 KB

1import { useNavigation, type ParamListBase } from "@react-navigation/native";
2import type {
3 NativeStackHeaderItemMenu,
4 NativeStackNavigationOptions,
5 NativeStackNavigationProp,
6} from "@react-navigation/native-stack";
7import { 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>>();
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;
57​
58function optionsSignature(value: unknown, seen = new WeakSet<object>()): string {
59 if (value === null) return "null";
60 switch (typeof value) {
61 case "boolean":
62 case "number":
63 case "string":
64 return JSON.stringify(value);
65 case "undefined":
66 return "undefined";
67 case "function":
68 // Header factories are frequently recreated inline. Their source is
69 // stable across equivalent renders, while a reference comparison would
70 // make navigation.setOptions re-enter the navigator indefinitely.
71 return `function:${Function.prototype.toString.call(value)}`;
72 case "symbol":
73 return `symbol:${String(value)}`;
74 case "bigint":
75 return `bigint:${String(value)}`;
76 case "object": {
77 const object = value as object;
78 if (seen.has(object)) return "[circular]";
79 seen.add(object);
80 if (Array.isArray(value)) {
81 return `[${value.map((entry) => optionsSignature(entry, seen)).join(",")}]`;
82 }
83 // React refs carry mutable native instances that must not make static
84 // screen options appear different after every render.
85 if ("current" in object) return "[ref]";
86 return `{${Object.keys(value as Record<string, unknown>)
87 .sort()
88 .map(
89 (key) =>
90 `${JSON.stringify(key)}:${optionsSignature((value as Record<string, unknown>)[key], seen)}`,
91 )
92 .join(",")}}`;
93 }
94 }
95 return String(value);
97​
98function stabilizeOptionFunctions(
99 value: unknown,
100 path: string,
101 latestFunctions: Map<string, (...args: unknown[]) => unknown>,
102 wrappers: Map<string, (...args: unknown[]) => unknown>,
103 seen = new WeakSet<object>(),
104): unknown {
105 if (typeof value === "function") {
106 latestFunctions.set(path, value as (...args: unknown[]) => unknown);
107 let wrapper = wrappers.get(path);
108 if (!wrapper) {
109 wrapper = (...args: unknown[]) => {
110 return latestFunctions.get(path)?.(...args);
111 };
112 wrappers.set(path, wrapper);
113 }
114 return wrapper;
115 }
116 if (Array.isArray(value)) {
117 if (seen.has(value)) return value;
118 seen.add(value);
119 return value.map((entry, index) =>
120 stabilizeOptionFunctions(entry, `${path}[${index}]`, latestFunctions, wrappers, seen),
121 );
122 }
123 if (value !== null && typeof value === "object") {
124 if (seen.has(value) || "current" in value) return value;
125 seen.add(value);
126 return Object.fromEntries(
127 Object.entries(value as Record<string, unknown>).map(([key, entry]) => [
128 key,
129 stabilizeOptionFunctions(entry, `${path}.${key}`, latestFunctions, wrappers, seen),
130 ]),
131 );
132 }
133 return value;
135​
136export function NativeStackScreenOptions(props: {
137 readonly options?: AppNativeStackNavigationOptions;
138 /**
139 * Causes dynamic native header factories to be reapplied when their closed-over
140 * menu content changes. Factory functions are intentionally stabilized, so
141 * their source alone cannot capture a menu that was initially empty while
142 * asynchronous data was loading.
143 */
144 readonly optionsVersion?: unknown;
145 readonly listeners?: Record<string, (event: never) => void>;
146 readonly name?: string;
147}) {
148 const navigation = useNativeStackNavigation();
149 const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true;
150 const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);
151 const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
152 const optionFunctionWrappersRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
153 const normalizedOptions = useMemo(() => normalizeScreenOptions(props.options), [props.options]);
154 const stableOptions = normalizedOptions
155 ? (stabilizeOptionFunctions(
156 normalizedOptions,
157 "options",
158 latestOptionFunctionsRef.current,
159 optionFunctionWrappersRef.current,
160 ) as NativeStackNavigationOptions)
161 : undefined;
162​
163 useLayoutEffect(() => {
164 if (!tabActive) {
165 lastAppliedOptionsSignatureRef.current = undefined;
166 return;
167 }
168 if (!navigation || !stableOptions) {
169 return;
170 }
171 const signature = optionsSignature([stableOptions, props.optionsVersion]);
172 if (lastAppliedOptionsSignatureRef.current === signature) {
173 return;
174 }
175 lastAppliedOptionsSignatureRef.current = signature;
176 navigation.setOptions(stableOptions);
177 }, [navigation, props.optionsVersion, stableOptions, tabActive]);
178​
179 useEffect(() => {
180 if (!navigation || !props.listeners) {
181 return;
182 }
183 const subscriptions = Object.entries(props.listeners).map(([eventName, listener]) =>
184 navigation.addListener(eventName as never, listener as never),
185 );
186 return () => {
187 for (const unsubscribe of subscriptions) {
188 unsubscribe();
189 }
190 };
191 }, [navigation, props.listeners]);
192​
193 return null;