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

NativeHeaderToolbar.test.tsx

239 lines8.4 KB

1import type { NativeStackHeaderItem } from "@react-navigation/native-stack";
2import { act, createContext, startTransition, Suspense, type ReactElement } from "react";
3import { createRoot, type Root } from "react-dom/client";
4import { afterEach, expect, it, vi } from "vite-plus/test";
5​
6type HeaderOptions = {
7 unstable_headerLeftItems?: () => NativeStackHeaderItem[];
8 unstable_headerRightItems?: () => NativeStackHeaderItem[];
9 unstable_headerToolbarItems?: () => NativeStackHeaderItem[];
10};
11​
12const harness = vi.hoisted(() => ({
13 params: { path: ["first", "guide.pdf"] },
14 appliedOptions: {} as HeaderOptions,
15 renderedItems: [] as NativeStackHeaderItem[],
16 setOptionsCalls: 0,
17}));
18​
19// Native headers retain the actions materialized when navigation applies options. Like React
20// Navigation, the header renders again only when the options are no longer shallowly equal.
21vi.mock("@react-navigation/native", async () => {
22 // vi.mock factories run before the file's imports.
23 const { createContext } = await vi.importActual<typeof import("react")>("react");
24 const navigation = {
25 setOptions(options: HeaderOptions) {
26 harness.setOptionsCalls += 1;
27 const previous: Record<string, unknown> = harness.appliedOptions;
28 const next: Record<string, unknown> = { ...previous, ...options };
29 harness.appliedOptions = next;
30 if (
31 Object.keys(next).length === Object.keys(previous).length &&
32 Object.keys(next).every((key) => next[key] === previous[key])
33 )
34 return;
35 harness.renderedItems =
36 options.unstable_headerLeftItems?.() ??
37 options.unstable_headerRightItems?.() ??
38 options.unstable_headerToolbarItems?.() ??
39 [];
40 },
41 };
42 return {
43 // Outside a workspace tab slot the header writes to the route's navigation.
44 NavigationRouteContext: createContext(undefined),
45 useNavigation: () => navigation,
46 useRoute: () => ({ key: "file", name: "ThreadFile", params: harness.params }),
47 };
48});
49​
50import { NativeHeaderToolbar } from "./NativeHeaderToolbar";
51​
52let root: Root | null = null;
53​
54// Like React Navigation's NavigationStateContext, whose default value throws when
55// read. React restores a context's default outside render, so layout effects see it.
56const ContainerStateContext = createContext<object>({
57 get getIsInitial(): never {
58 throw new Error("Couldn't find a navigation context.");
59 },
60});
61const containerState = {};
62​
63function ConnectingToolbar(props: { readonly label: string }) {
64 return (
65 <NativeHeaderToolbar placement="right">
66 <NativeHeaderToolbar.Custom>
67 <span aria-label={props.label} />
68 </NativeHeaderToolbar.Custom>
69 </NativeHeaderToolbar>
70 );
72​
73function renderConnecting(label: string) {
74 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
75 root ??= createRoot(document.createElement("div"));
76 act(() =>
77 root!.render(
78 <ContainerStateContext value={containerState}>
79 <ConnectingToolbar label={label} />
80 </ContainerStateContext>,
81 ),
82 );
84​
85function renderedCustomLabel() {
86 const item = harness.renderedItems[0];
87 if (item?.type !== "custom") throw new Error("Expected the custom header element");
88 return (item.element as ReactElement<{ "aria-label": string }>).props["aria-label"];
90​
91afterEach(() => {
92 act(() => root?.unmount());
93 root = null;
94 harness.appliedOptions = {};
95 harness.renderedItems = [];
96 harness.setOptionsCalls = 0;
97 vi.unstubAllGlobals();
98});
99​
100it.each(["left", "right", "bottom"] as const)(
101 "dispatches retained %s actions to the latest committed handlers without registering again",
102 (placement) => {
103 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
104 root = createRoot(document.createElement("div"));
105 const onPress = vi.fn();
106 const render = (path: string) =>
107 act(() =>
108 root!.render(
109 <NativeHeaderToolbar placement={placement}>
110 <NativeHeaderToolbar.Button label="Open" onPress={() => onPress("button", path)} />
111 <NativeHeaderToolbar.Menu title="File">
112 <NativeHeaderToolbar.MenuAction onPress={() => onPress("menu", path)}>
113 Open
114 </NativeHeaderToolbar.MenuAction>
115 <NativeHeaderToolbar.Menu title="More">
116 <NativeHeaderToolbar.MenuAction onPress={() => onPress("nested", path)}>
117 Open
118 </NativeHeaderToolbar.MenuAction>
119 </NativeHeaderToolbar.Menu>
120 </NativeHeaderToolbar.Menu>
121 </NativeHeaderToolbar>,
122 ),
123 );
124​
125 render("first/guide.pdf");
126 const [button, menu] = harness.renderedItems;
127 if (button?.type !== "button" || menu?.type !== "menu") {
128 throw new Error("Expected the native button and menu");
129 }
130 const [action, submenu] = menu.menu.items;
131 if (action?.type !== "action" || submenu?.type !== "submenu") {
132 throw new Error("Expected the direct action and submenu");
133 }
134 const nested = submenu.items[0];
135 if (nested?.type !== "action") throw new Error("Expected the nested action");
136 const press = () => {
137 button.onPress?.();
138 action.onPress?.();
139 nested.onPress?.();
140 };
141 press();
142 expect(onPress.mock.calls).toEqual([
143 ["button", "first/guide.pdf"],
144 ["menu", "first/guide.pdf"],
145 ["nested", "first/guide.pdf"],
146 ]);
147 onPress.mockClear();
148 const registrations = harness.setOptionsCalls;
149 expect(registrations).toBeGreaterThan(0);
150​
151 render("second/guide.pdf");
152​
153 expect(harness.setOptionsCalls).toBe(registrations);
154 expect(harness.renderedItems).toEqual([button, menu]);
155 press();
156 expect(onPress.mock.calls).toEqual([
157 ["button", "second/guide.pdf"],
158 ["menu", "second/guide.pdf"],
159 ["nested", "second/guide.pdf"],
160 ]);
161 },
162);
163​
164it("applies a custom header element rendered inside a navigation container", () => {
165 renderConnecting("Connecting");
166 expect(renderedCustomLabel()).toBe("Connecting");
167​
168 const applied = harness.setOptionsCalls;
169 renderConnecting("Connecting");
170 expect(harness.setOptionsCalls).toBe(applied);
171​
172 renderConnecting("Reconnecting");
173 expect(renderedCustomLabel()).toBe("Reconnecting");
174});
175​
176it("keeps committed handlers while a replacement render suspends", () => {
177 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
178 root = createRoot(document.createElement("div"));
179 const onPress = vi.fn();
180 const pending = new Promise<never>(() => {});
181 function Suspend(): never {
182 throw pending;
183 }
184 const toolbar = (value: string, suspend = false) => (
185 <Suspense fallback={null}>
186 <NativeHeaderToolbar>
187 <NativeHeaderToolbar.Button label="Open" onPress={() => onPress(value)} />
188 </NativeHeaderToolbar>
189 {suspend && <Suspend />}
190 </Suspense>
191 );
192 act(() => root!.render(toolbar("committed")));
193 const button = harness.renderedItems[0];
194 if (button?.type !== "button") throw new Error("Expected the native button");
195​
196 act(() => startTransition(() => root!.render(toolbar("pending", true))));
197 button.onPress?.();
198 expect(onPress.mock.calls).toEqual([["committed"]]);
199​
200 act(() => root!.render(toolbar("replacement")));
201 button.onPress?.();
202 expect(onPress.mock.calls).toEqual([["committed"], ["replacement"]]);
203});
204​
205it("isolates toolbar handlers and ignores retained actions after their toolbar unmounts", () => {
206 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
207 root = createRoot(document.createElement("div"));
208 const onPress = vi.fn();
209 const toolbar = (id: string, value: string) => (
210 <NativeHeaderToolbar key={id}>
211 <NativeHeaderToolbar.Button label={id} onPress={() => onPress(id, value)} />
212 </NativeHeaderToolbar>
213 );
214 act(() => root!.render([toolbar("first", "initial")]));
215 const first = harness.renderedItems[0];
216 if (first?.type !== "button") throw new Error("Expected the first native button");
217 act(() => root!.render([toolbar("first", "initial"), toolbar("second", "initial")]));
218 const second = harness.renderedItems[0];
219 if (second?.type !== "button") throw new Error("Expected the second native button");
220​
221 act(() => root!.render([toolbar("first", "updated"), toolbar("second", "updated")]));
222 first.onPress?.();
223 second.onPress?.();
224 expect(onPress.mock.calls).toEqual([
225 ["first", "updated"],
226 ["second", "updated"],
227 ]);
228​
229 onPress.mockClear();
230 act(() => root!.render([toolbar("second", "remaining")]));
231 first.onPress?.();
232 second.onPress?.();
233 expect(onPress.mock.calls).toEqual([["second", "remaining"]]);
234​
235 onPress.mockClear();
236 act(() => root!.render(null));
237 second.onPress?.();
238 expect(onPress).not.toHaveBeenCalled();
239});