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

NativeHeaderToolbar.tsx

369 lines12.5 KB

1import { useRoute } from "@react-navigation/native";
2import type {
3 NativeStackHeaderItem,
4 NativeStackHeaderItemMenu,
5 NativeStackNavigationOptions,
6} from "@react-navigation/native-stack";
7import {
8 Children,
9 isValidElement,
10 useLayoutEffect,
11 useMemo,
12 useRef,
13 use,
14 type ReactElement,
15 type ReactNode,
16} from "react";
17import type { ColorValue } from "react-native";
18import type { HeaderBarButtonSearchBarPlacementItem } from "react-native-screens";
19import { NativeWorkspaceTabActivityContext } from "./v5-workspace-context";
20import { NativeStackScreenOptions, useScreenOptionsWriter } from "./StackHeader";
21​
22function labelFromChildren(children: ReactNode): string {
23 const parts: string[] = [];
24 Children.forEach(children, (child) => {
25 if (typeof child === "string" || typeof child === "number") {
26 parts.push(String(child));
27 } else if (isValidElement<{ children?: ReactNode }>(child)) {
28 parts.push(labelFromChildren(child.props.children));
29 }
30 });
31 return parts.join("");
33​
34type NativeStackHeaderIcon = NonNullable<
35 Extract<NativeStackHeaderItem, { type: "button" }>["icon"]
36>;
37type NativeStackHeaderAxisBehavior = Extract<
38 NativeStackHeaderItem,
39 { type: "button" }
40>["axisBehavior"];
41type NativeStackHeaderVisibilityPriority = Extract<
42 NativeStackHeaderItem,
43 { type: "button" }
44>["visibilityPriority"];
45type NativeToolbarItem = NativeStackHeaderItem | HeaderBarButtonSearchBarPlacementItem;
46type NativeStackOptionsWithToolbar = NativeStackNavigationOptions & {
47 unstable_headerToolbarItems?: () => NativeToolbarItem[];
48};
49​
50function iconFromProp(icon: unknown): NativeStackHeaderIcon | undefined {
51 if (typeof icon === "string") return { type: "sfSymbol", name: icon as never };
52 if (
53 typeof icon === "object" &&
54 icon !== null &&
55 "type" in icon &&
56 icon.type === "image" &&
57 "source" in icon
58 ) {
59 return icon as NativeStackHeaderIcon;
60 }
61 return undefined;
63​
64type RegisterHandler = (handler: unknown) => () => void;
65​
66type ToolbarElementProps = Record<string, unknown> & { readonly children?: ReactNode };
67​
68function elementTypeName(element: ReactElement): string | undefined {
69 const type = element.type;
70 if (typeof type === "function") {
71 return (type as { displayName?: string; name?: string }).displayName ?? type.name;
72 }
73 return undefined;
75​
76function convertMenuAction(
77 element: ReactElement<ToolbarElementProps>,
78 register: RegisterHandler,
79): NativeStackHeaderItemMenu["menu"]["items"][number] | null {
80 const typeName = elementTypeName(element);
81 if (typeName === "NativeHeaderToolbarMenuAction") {
82 const label = labelFromChildren(element.props.children);
83 return {
84 type: "action",
85 label,
86 description: typeof element.props.subtitle === "string" ? element.props.subtitle : undefined,
87 disabled: Boolean(element.props.disabled),
88 icon: iconFromProp(element.props.icon),
89 onPress: register(element.props.onPress),
90 state: element.props.isOn === true ? "on" : undefined,
91 destructive: Boolean(element.props.destructive),
92 discoverabilityLabel:
93 typeof element.props.discoverabilityLabel === "string"
94 ? element.props.discoverabilityLabel
95 : undefined,
96 };
97 }
98​
99 if (typeName === "NativeHeaderToolbarMenu") {
100 return {
101 type: "submenu",
102 label: typeof element.props.title === "string" ? element.props.title : "",
103 icon: iconFromProp(element.props.icon),
104 inline: Boolean(element.props.inline),
105 items: collectMenuItems(element.props.children, register),
106 };
107 }
108​
109 return null;
111​
112function collectMenuItems(
113 children: ReactNode,
114 register: RegisterHandler,
115): NativeStackHeaderItemMenu["menu"]["items"] {
116 const items: NativeStackHeaderItemMenu["menu"]["items"] = [];
117 Children.forEach(children, (child) => {
118 if (!isValidElement<ToolbarElementProps>(child)) {
119 return;
120 }
121 const item = convertMenuAction(child, register);
122 if (item) {
123 items.push(item);
124 return;
125 }
126 items.push(...collectMenuItems(child.props.children, register));
127 });
128 return items;
130​
131function convertToolbarChild(
132 child: ReactNode,
133 register: RegisterHandler,
134): NativeToolbarItem | null {
135 if (!isValidElement<ToolbarElementProps>(child)) {
136 return null;
137 }
138​
139 const typeName = elementTypeName(child);
140 if (typeName === "NativeHeaderToolbarCustom" && isValidElement(child.props.children)) {
141 return { type: "custom", element: child.props.children };
142 }
143 if (typeName === "NativeHeaderToolbarSearchBarSlot") {
144 return { type: "searchBarPlacement" };
145 }
146​
147 if (typeName === "NativeHeaderToolbarButton") {
148 return {
149 type: "button",
150 label:
151 typeof child.props.label === "string"
152 ? child.props.label
153 : String(child.props.accessibilityLabel ?? ""),
154 accessibilityLabel:
155 typeof child.props.accessibilityLabel === "string"
156 ? child.props.accessibilityLabel
157 : undefined,
158 axisBehavior: child.props.axisBehavior as NativeStackHeaderAxisBehavior,
159 disabled: Boolean(child.props.disabled),
160 icon: iconFromProp(child.props.icon),
161 onPress: register(child.props.onPress),
162 sharesBackground: !child.props.separateBackground,
163 tintColor: child.props.tintColor as ColorValue | undefined,
164 variant:
165 child.props.variant === "done" || child.props.variant === "prominent"
166 ? child.props.variant
167 : "plain",
168 identifier: typeof child.props.identifier === "string" ? child.props.identifier : undefined,
169 visibilityPriority: child.props.visibilityPriority as NativeStackHeaderVisibilityPriority,
170 };
171 }
172​
173 if (typeName === "NativeHeaderToolbarMenu") {
174 return {
175 type: "menu",
176 label: typeof child.props.title === "string" ? child.props.title : "",
177 accessibilityLabel:
178 typeof child.props.accessibilityLabel === "string"
179 ? child.props.accessibilityLabel
180 : undefined,
181 disabled: Boolean(child.props.disabled),
182 axisBehavior: child.props.axisBehavior as NativeStackHeaderAxisBehavior,
183 icon: iconFromProp(child.props.icon),
184 menu: {
185 title: typeof child.props.title === "string" ? child.props.title : undefined,
186 items: collectMenuItems(child.props.children, register),
187 },
188 sharesBackground: !child.props.separateBackground,
189 tintColor: child.props.tintColor as ColorValue | undefined,
190 variant:
191 child.props.variant === "done" || child.props.variant === "prominent"
192 ? child.props.variant
193 : "plain",
194 identifier: typeof child.props.identifier === "string" ? child.props.identifier : undefined,
195 };
196 }
197​
198 if (typeName === "NativeHeaderToolbarSpacer") {
199 return {
200 type: "spacing",
201 spacing: typeof child.props.width === "number" ? child.props.width : 8,
202 flexible: Boolean(child.props.flexible),
203 } as NativeStackHeaderItem;
204 }
205​
206 return null;
208​
209function collectToolbarItems(children: ReactNode, register: RegisterHandler): NativeToolbarItem[] {
210 const items: NativeToolbarItem[] = [];
211 Children.forEach(children, (child) => {
212 const item = convertToolbarChild(child, register);
213 if (item) {
214 if (item.type === "spacing") {
215 // Native defaults missing spacing-item indices to zero, moving spacers before earlier siblings.
216 (item as { index?: number }).index = items.length;
217 }
218 items.push(item);
219 }
220 });
221 return items;
223​
224function NativeHeaderToolbarRoot(props: {
225 readonly placement?: "left" | "right" | "bottom";
226 readonly children?: ReactNode;
227}) {
228 const setOptions = useScreenOptionsWriter();
229 const route = useRoute();
230 const tabActivity = use(NativeWorkspaceTabActivityContext);
231 const isTabActive = tabActivity?.isActive;
232 const committedHandlers = useRef<(() => void)[]>([]);
233 const { items, handlers } = useMemo(() => {
234 const handlers: (() => void)[] = [];
235 const register: RegisterHandler = (handler) => {
236 const index = handlers.length;
237 handlers.push(typeof handler === "function" ? (handler as () => void) : () => undefined);
238 return () => committedHandlers.current[index]?.();
239 };
240 return { items: collectToolbarItems(props.children, register), handlers };
241 }, [props.children, committedHandlers]);
242 // Native retains actions when unchanged presentation skips re-registration.
243 // Publish only committed handlers; abandoned renders must not replace them.
244 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed toolbar handlers to the ref native actions call; discarded renders must not leak
245 useLayoutEffect(() => {
246 committedHandlers.current = handlers;
247 return () => {
248 committedHandlers.current = [];
249 };
250 }, [handlers, committedHandlers]);
251 // UIKit's search placement item belongs to the toolbar, never a header group.
252 const headerItems = items.filter(
253 (item): item is NativeStackHeaderItem => item.type !== "searchBarPlacement",
254 );
255​
256 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears this placement's native header items through the navigator when the toolbar unmounts
257 useLayoutEffect(() => {
258 if (!setOptions) return;
259 return () => {
260 if (isTabActive && !isTabActive()) return;
261 if (props.placement === "bottom") {
262 setOptions({
263 unstable_headerToolbarItems: () => [],
264 } as NativeStackOptionsWithToolbar);
265 } else if (props.placement === "left") {
266 setOptions({ unstable_headerLeftItems: () => [] });
267 } else {
268 setOptions({ unstable_headerRightItems: () => [] });
269 }
270 };
271 }, [setOptions, props.placement, isTabActive]);
272​
273 return (
274 <NativeStackScreenOptions
275 optionsVersion={[items, route.params]}
276 options={
277 props.placement === "bottom"
278 ? { unstable_headerToolbarItems: () => items }
279 : props.placement === "left"
280 ? { unstable_headerLeftItems: () => headerItems }
281 : { unstable_headerRightItems: () => headerItems }
282 }
283 />
284 );
286​
287function NativeHeaderToolbarButton(_props: {
288 readonly accessibilityLabel?: string;
289 readonly axisBehavior?: NativeStackHeaderAxisBehavior;
290 readonly disabled?: boolean;
291 readonly icon?: string | Extract<NativeStackHeaderIcon, { type: "image" }>;
292 readonly label?: string;
293 readonly onPress?: () => void;
294 readonly separateBackground?: boolean;
295 readonly tintColor?: ColorValue;
296 readonly variant?: "plain" | "done" | "prominent";
297 readonly identifier?: string;
298 readonly visibilityPriority?: NativeStackHeaderVisibilityPriority;
299}) {
300 return null;
302NativeHeaderToolbarButton.displayName = "NativeHeaderToolbarButton";
303​
304function NativeHeaderToolbarMenu(_props: {
305 readonly accessibilityLabel?: string;
306 readonly axisBehavior?: NativeStackHeaderAxisBehavior;
307 readonly children?: ReactNode;
308 readonly disabled?: boolean;
309 readonly icon?: string;
310 readonly identifier?: string;
311 readonly inline?: boolean;
312 readonly separateBackground?: boolean;
313 readonly tintColor?: ColorValue;
314 readonly title?: string;
315 readonly variant?: "plain" | "done" | "prominent";
316}) {
317 return null;
319NativeHeaderToolbarMenu.displayName = "NativeHeaderToolbarMenu";
320​
321function NativeHeaderToolbarMenuAction(_props: {
322 readonly children?: ReactNode;
323 readonly destructive?: boolean;
324 readonly disabled?: boolean;
325 readonly discoverabilityLabel?: string;
326 readonly icon?: string;
327 readonly isOn?: boolean;
328 readonly onPress?: () => void;
329 readonly subtitle?: string;
330}) {
331 return null;
333NativeHeaderToolbarMenuAction.displayName = "NativeHeaderToolbarMenuAction";
334​
335function NativeHeaderToolbarCustom(_props: { readonly children: ReactElement }) {
336 return null;
338NativeHeaderToolbarCustom.displayName = "NativeHeaderToolbarCustom";
339​
340function NativeHeaderToolbarLabel(_props: { readonly children?: ReactNode }) {
341 return null;
343NativeHeaderToolbarLabel.displayName = "NativeHeaderToolbarLabel";
344​
345function NativeHeaderToolbarSpacer(_props: {
346 readonly flexible?: boolean;
347 readonly sharesBackground?: boolean;
348 readonly width?: number;
349}) {
350 return null;
352NativeHeaderToolbarSpacer.displayName = "NativeHeaderToolbarSpacer";
353​
354function NativeHeaderToolbarSearchBarSlot() {
355 return null;
357NativeHeaderToolbarSearchBarSlot.displayName = "NativeHeaderToolbarSearchBarSlot";
358​
359export const NativeHeaderToolbar = Object.assign(NativeHeaderToolbarRoot, {
360 Button: NativeHeaderToolbarButton,
361 Custom: NativeHeaderToolbarCustom,
362 Label: NativeHeaderToolbarLabel,
363 Menu: Object.assign(NativeHeaderToolbarMenu, {
364 Action: NativeHeaderToolbarMenuAction,
365 }),
366 MenuAction: NativeHeaderToolbarMenuAction,
367 SearchBarSlot: NativeHeaderToolbarSearchBarSlot,
368 Spacer: NativeHeaderToolbarSpacer,
369});