Open History to see the last commit
1import { useNavigation, type ParamListBase } from "@react-navigation/native";
2import type {
3 NativeStackHeaderItem,
4 NativeStackHeaderItemMenu,
5 NativeStackNavigationOptions,
6 NativeStackNavigationProp,
7} from "@react-navigation/native-stack";
8import {
9 Children,
10 isValidElement,
11 useEffect,
12 useLayoutEffect,
13 useMemo,
14 useRef,
15 type ReactElement,
16 type ReactNode,
17} from "react";
18import type { ColorValue } from "react-native";
19
20export {
21 nativeHeaderScrollEdgeEffects,
22 nativeTopScrollEdgeEffect,
23 type NativeHeaderScrollEdgeEffects,
24 type NativeTopScrollEdgeEffect,
25} from "./scrollEdgeEffects";
26
27export type AppNativeStackNavigationOptions = Omit<
28 NativeStackNavigationOptions,
29 "headerTintColor" | "unstable_headerLeftItems" | "unstable_headerRightItems"
30> & {
31 readonly headerTintColor?: string | ColorValue;
32 readonly unstable_headerCenterItems?: unknown;
33 readonly unstable_headerLeftItems?: unknown;
34 readonly unstable_headerRightItems?: unknown;
35 readonly unstable_headerSubtitle?: unknown;
36 readonly unstable_headerToolbarItems?: unknown;
37 readonly unstable_navigationItemStyle?: unknown;
38};
39
40function useNativeStackNavigation(): NativeStackNavigationProp<ParamListBase> | null {
41 return useNavigation<NativeStackNavigationProp<ParamListBase>>();
42}
43
44function normalizeScreenOptions(
45 options: AppNativeStackNavigationOptions | undefined,
46): NativeStackNavigationOptions | undefined {
47 if (!options) {
48 return options;
49 }
50
51 const normalized = { ...options } as NativeStackNavigationOptions & {
52 unstable_navigationItemStyle?: unknown;
53 unstable_headerCenterItems?: unknown;
54 unstable_headerSubtitle?: unknown;
55 unstable_headerToolbarItems?: unknown;
56 };
57
58 if (normalized.headerTintColor !== undefined) {
59 normalized.headerTintColor = String(normalized.headerTintColor);
60 }
61
62 return normalized as NativeStackNavigationOptions;
63}
64
65function optionsSignature(value: unknown, seen = new WeakSet<object>()): string {
66 if (value === null) return "null";
67 switch (typeof value) {
68 case "boolean":
69 case "number":
70 case "string":
71 return JSON.stringify(value);
72 case "undefined":
73 return "undefined";
74 case "function":
75 // Header factories are frequently recreated inline. Their source is
76 // stable across equivalent renders, while a reference comparison would
77 // make navigation.setOptions re-enter the navigator indefinitely.
78 return `function:${Function.prototype.toString.call(value)}`;
79 case "symbol":
80 return `symbol:${String(value)}`;
81 case "bigint":
82 return `bigint:${String(value)}`;
83 case "object": {
84 const object = value as object;
85 if (seen.has(object)) return "[circular]";
86 seen.add(object);
87 if (Array.isArray(value)) {
88 return `[${value.map((entry) => optionsSignature(entry, seen)).join(",")}]`;
89 }
90 // React refs carry mutable native instances that must not make static
91 // screen options appear different after every render.
92 if ("current" in object) return "[ref]";
93 return `{${Object.keys(value as Record<string, unknown>)
94 .sort()
95 .map(
96 (key) =>
97 `${JSON.stringify(key)}:${optionsSignature((value as Record<string, unknown>)[key], seen)}`,
98 )
99 .join(",")}}`;
100 }
101 }
102 return String(value);
103}
104
105function stabilizeOptionFunctions(
106 value: unknown,
107 path: string,
108 latestFunctions: Map<string, (...args: unknown[]) => unknown>,
109 wrappers: Map<string, (...args: unknown[]) => unknown>,
110 seen = new WeakSet<object>(),
111): unknown {
112 if (typeof value === "function") {
113 latestFunctions.set(path, value as (...args: unknown[]) => unknown);
114 let wrapper = wrappers.get(path);
115 if (!wrapper) {
116 wrapper = (...args: unknown[]) => {
117 return latestFunctions.get(path)?.(...args);
118 };
119 wrappers.set(path, wrapper);
120 }
121 return wrapper;
122 }
123 if (Array.isArray(value)) {
124 if (seen.has(value)) return value;
125 seen.add(value);
126 return value.map((entry, index) =>
127 stabilizeOptionFunctions(entry, `${path}[${index}]`, latestFunctions, wrappers, seen),
128 );
129 }
130 if (value !== null && typeof value === "object") {
131 if (seen.has(value) || "current" in value) return value;
132 seen.add(value);
133 return Object.fromEntries(
134 Object.entries(value as Record<string, unknown>).map(([key, entry]) => [
135 key,
136 stabilizeOptionFunctions(entry, `${path}.${key}`, latestFunctions, wrappers, seen),
137 ]),
138 );
139 }
140 return value;
141}
142
143export function NativeStackScreenOptions(props: {
144 readonly options?: AppNativeStackNavigationOptions;
145 readonly listeners?: Record<string, (event: never) => void>;
146 readonly name?: string;
147}) {
148 const navigation = useNativeStackNavigation();
149 const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);
150 const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
151 const optionFunctionWrappersRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
152 const normalizedOptions = useMemo(() => normalizeScreenOptions(props.options), [props.options]);
153 const stableOptions = normalizedOptions
154 ? (stabilizeOptionFunctions(
155 normalizedOptions,
156 "options",
157 latestOptionFunctionsRef.current,
158 optionFunctionWrappersRef.current,
159 ) as NativeStackNavigationOptions)
160 : undefined;
161
162 useLayoutEffect(() => {
163 if (!navigation || !stableOptions) {
164 return;
165 }
166 const signature = optionsSignature(stableOptions);
167 // Avoid re-entering navigation state when semantically equal options are
168 // reapplied every layout (common when callers pass unstable object literals).
169 if (lastAppliedOptionsSignatureRef.current === signature) {
170 return;
171 }
172 lastAppliedOptionsSignatureRef.current = signature;
173 navigation.setOptions(stableOptions);
174 }, [navigation, stableOptions]);
175
176 useEffect(() => {
177 if (!navigation || !props.listeners) {
178 return;
179 }
180 const subscriptions = Object.entries(props.listeners).map(([eventName, listener]) =>
181 navigation.addListener(eventName as never, listener as never),
182 );
183 return () => {
184 for (const unsubscribe of subscriptions) {
185 unsubscribe();
186 }
187 };
188 }, [navigation, props.listeners]);
189
190 return null;
191}
192
193function labelFromChildren(children: ReactNode): string {
194 const parts: string[] = [];
195 Children.forEach(children, (child) => {
196 if (typeof child === "string" || typeof child === "number") {
197 parts.push(String(child));
198 } else if (isValidElement<{ children?: ReactNode }>(child)) {
199 parts.push(labelFromChildren(child.props.children));
200 }
201 });
202 return parts.join("");
203}
204
205type NativeStackHeaderIcon = NonNullable<
206 Extract<NativeStackHeaderItem, { type: "button" }>["icon"]
207>;
208type NativeStackOptionsWithToolbar = NativeStackNavigationOptions & {
209 unstable_headerToolbarItems?: () => NativeStackHeaderItem[];
210};
211
212function iconFromProp(icon: unknown): NativeStackHeaderIcon | undefined {
213 if (typeof icon !== "string") {
214 return undefined;
215 }
216 return { type: "sfSymbol", name: icon as never };
217}
218
219type ToolbarElementProps = Record<string, unknown> & { readonly children?: ReactNode };
220
221function elementTypeName(element: ReactElement): string | undefined {
222 const type = element.type;
223 if (typeof type === "function") {
224 return (type as { displayName?: string; name?: string }).displayName ?? type.name;
225 }
226 return undefined;
227}
228
229function convertMenuAction(
230 element: ReactElement<ToolbarElementProps>,
231): NativeStackHeaderItemMenu["menu"]["items"][number] | null {
232 const typeName = elementTypeName(element);
233 if (typeName === "NativeHeaderToolbarMenuAction") {
234 const label = labelFromChildren(element.props.children);
235 return {
236 type: "action",
237 label,
238 description: typeof element.props.subtitle === "string" ? element.props.subtitle : undefined,
239 disabled: Boolean(element.props.disabled),
240 icon: iconFromProp(element.props.icon),
241 onPress:
242 typeof element.props.onPress === "function"
243 ? (element.props.onPress as () => void)
244 : () => undefined,
245 state: element.props.isOn === true ? "on" : undefined,
246 destructive: Boolean(element.props.destructive),
247 discoverabilityLabel:
248 typeof element.props.discoverabilityLabel === "string"
249 ? element.props.discoverabilityLabel
250 : undefined,
251 };
252 }
253
254 if (typeName === "NativeHeaderToolbarMenu") {
255 return {
256 type: "submenu",
257 label:
258 typeof element.props.title === "string"
259 ? element.props.title
260 : labelFromChildren(element.props.children),
261 icon: iconFromProp(element.props.icon),
262 inline: Boolean(element.props.inline),
263 items: collectMenuItems(element.props.children),
264 };
265 }
266
267 return null;
268}
269
270function collectMenuItems(children: ReactNode): NativeStackHeaderItemMenu["menu"]["items"] {
271 const items: NativeStackHeaderItemMenu["menu"]["items"] = [];
272 Children.forEach(children, (child) => {
273 if (!isValidElement<ToolbarElementProps>(child)) {
274 return;
275 }
276 const item = convertMenuAction(child);
277 if (item) {
278 items.push(item);
279 return;
280 }
281 items.push(...collectMenuItems(child.props.children));
282 });
283 return items;
284}
285
286function convertToolbarChild(child: ReactNode): NativeStackHeaderItem | null {
287 if (!isValidElement<ToolbarElementProps>(child)) {
288 return null;
289 }
290
291 const typeName = elementTypeName(child);
292 if (typeName === "NativeHeaderToolbarButton") {
293 return {
294 type: "button",
295 label: typeof child.props.label === "string" ? child.props.label : "",
296 accessibilityLabel:
297 typeof child.props.accessibilityLabel === "string"
298 ? child.props.accessibilityLabel
299 : undefined,
300 disabled: Boolean(child.props.disabled),
301 icon: iconFromProp(child.props.icon),
302 onPress:
303 typeof child.props.onPress === "function"
304 ? (child.props.onPress as () => void)
305 : () => undefined,
306 sharesBackground: !child.props.separateBackground,
307 tintColor: child.props.tintColor as ColorValue | undefined,
308 variant: "plain",
309 };
310 }
311
312 if (typeName === "NativeHeaderToolbarMenu") {
313 return {
314 type: "menu",
315 label: typeof child.props.title === "string" ? child.props.title : "",
316 accessibilityLabel:
317 typeof child.props.accessibilityLabel === "string"
318 ? child.props.accessibilityLabel
319 : undefined,
320 disabled: Boolean(child.props.disabled),
321 icon: iconFromProp(child.props.icon),
322 menu: {
323 title: typeof child.props.title === "string" ? child.props.title : undefined,
324 items: collectMenuItems(child.props.children),
325 },
326 sharesBackground: !child.props.separateBackground,
327 tintColor: child.props.tintColor as ColorValue | undefined,
328 variant: "plain",
329 };
330 }
331
332 if (typeName === "NativeHeaderToolbarSpacer") {
333 return {
334 type: "spacing",
335 spacing: typeof child.props.width === "number" ? child.props.width : 8,
336 };
337 }
338
339 return null;
340}
341
342function collectToolbarItems(children: ReactNode): NativeStackHeaderItem[] {
343 const items: NativeStackHeaderItem[] = [];
344 Children.forEach(children, (child) => {
345 const item = convertToolbarChild(child);
346 if (item) {
347 items.push(item);
348 }
349 });
350 return items;
351}
352
353function NativeHeaderToolbarRoot(props: {
354 readonly placement?: "left" | "right" | "bottom";
355 readonly children?: ReactNode;
356}) {
357 const navigation = useNativeStackNavigation();
358 const items = useMemo(() => collectToolbarItems(props.children), [props.children]);
359
360 useEffect(() => {
361 if (!navigation) {
362 return;
363 }
364 if (props.placement === "bottom") {
365 navigation.setOptions({
366 unstable_headerToolbarItems: () => items,
367 } as NativeStackOptionsWithToolbar);
368 return () => {
369 navigation.setOptions({
370 unstable_headerToolbarItems: () => [],
371 } as NativeStackOptionsWithToolbar);
372 };
373 }
374 if (props.placement === "left") {
375 navigation.setOptions({ unstable_headerLeftItems: () => items });
376 return () => {
377 navigation.setOptions({ unstable_headerLeftItems: () => [] });
378 };
379 }
380 navigation.setOptions({ unstable_headerRightItems: () => items });
381 return () => {
382 navigation.setOptions({ unstable_headerRightItems: () => [] });
383 };
384 }, [items, navigation, props.placement]);
385
386 return null;
387}
388
389function NativeHeaderToolbarButton(_props: {
390 readonly accessibilityLabel?: string;
391 readonly disabled?: boolean;
392 readonly icon?: string;
393 readonly label?: string;
394 readonly onPress?: () => void;
395 readonly separateBackground?: boolean;
396 readonly tintColor?: ColorValue;
397}) {
398 return null;
399}
400NativeHeaderToolbarButton.displayName = "NativeHeaderToolbarButton";
401
402function NativeHeaderToolbarMenu(_props: {
403 readonly accessibilityLabel?: string;
404 readonly children?: ReactNode;
405 readonly disabled?: boolean;
406 readonly icon?: string;
407 readonly inline?: boolean;
408 readonly separateBackground?: boolean;
409 readonly tintColor?: ColorValue;
410 readonly title?: string;
411}) {
412 return null;
413}
414NativeHeaderToolbarMenu.displayName = "NativeHeaderToolbarMenu";
415
416function NativeHeaderToolbarMenuAction(_props: {
417 readonly children?: ReactNode;
418 readonly destructive?: boolean;
419 readonly disabled?: boolean;
420 readonly discoverabilityLabel?: string;
421 readonly icon?: string;
422 readonly isOn?: boolean;
423 readonly onPress?: () => void;
424 readonly subtitle?: string;
425}) {
426 return null;
427}
428NativeHeaderToolbarMenuAction.displayName = "NativeHeaderToolbarMenuAction";
429
430function NativeHeaderToolbarLabel(_props: { readonly children?: ReactNode }) {
431 return null;
432}
433NativeHeaderToolbarLabel.displayName = "NativeHeaderToolbarLabel";
434
435function NativeHeaderToolbarSpacer(_props: {
436 readonly sharesBackground?: boolean;
437 readonly width?: number;
438}) {
439 return null;
440}
441NativeHeaderToolbarSpacer.displayName = "NativeHeaderToolbarSpacer";
442
443function NativeHeaderToolbarSearchBarSlot() {
444 return null;
445}
446NativeHeaderToolbarSearchBarSlot.displayName = "NativeHeaderToolbarSearchBarSlot";
447
448export const NativeHeaderToolbar = Object.assign(NativeHeaderToolbarRoot, {
449 Button: NativeHeaderToolbarButton,
450 Label: NativeHeaderToolbarLabel,
451 Menu: Object.assign(NativeHeaderToolbarMenu, {
452 Action: NativeHeaderToolbarMenuAction,
453 }),
454 MenuAction: NativeHeaderToolbarMenuAction,
455 SearchBarSlot: NativeHeaderToolbarSearchBarSlot,
456 Spacer: NativeHeaderToolbarSpacer,
457});