Open History to see the last commit
1import type { NativeStackHeaderItem } from "@react-navigation/native-stack";
2import { act, createContext, 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 openedDocuments: [] as string[],
18}));
19
20// Native headers retain the actions materialized when navigation applies options. Like React
21// Navigation, the header renders again only when the options are no longer shallowly equal.
22vi.mock("@react-navigation/native", async () => {
23 // vi.mock factories run before the file's imports.
24 const { createContext } = await vi.importActual<typeof import("react")>("react");
25 const navigation = {
26 setOptions(options: HeaderOptions) {
27 harness.setOptionsCalls += 1;
28 const previous: Record<string, unknown> = harness.appliedOptions;
29 const next: Record<string, unknown> = { ...previous, ...options };
30 harness.appliedOptions = next;
31 if (
32 Object.keys(next).length === Object.keys(previous).length &&
33 Object.keys(next).every((key) => next[key] === previous[key])
34 )
35 return;
36 harness.renderedItems =
37 options.unstable_headerLeftItems?.() ??
38 options.unstable_headerRightItems?.() ??
39 options.unstable_headerToolbarItems?.() ??
40 [];
41 },
42 };
43 return {
44 // Outside a workspace tab slot the header writes to the route's navigation.
45 NavigationRouteContext: createContext(undefined),
46 useNavigation: () => navigation,
47 useRoute: () => ({ key: "file", name: "ThreadFile", params: harness.params }),
48 };
49});
50
51import { NativeHeaderToolbar } from "./NativeHeaderToolbar";
52
53let root: Root | null = null;
54type Placement = "left" | "right" | "bottom";
55
56function DocumentToolbar(props: { readonly path: string; readonly placement: Placement }) {
57 return (
58 <NativeHeaderToolbar placement={props.placement}>
59 <NativeHeaderToolbar.Menu title="File actions" icon="ellipsis">
60 <NativeHeaderToolbar.MenuAction onPress={() => harness.openedDocuments.push(props.path)}>
61 Open PDF
62 </NativeHeaderToolbar.MenuAction>
63 </NativeHeaderToolbar.Menu>
64 </NativeHeaderToolbar>
65 );
66}
67
68function renderDocument(path: string, placement: Placement) {
69 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
70 harness.params = { path: path.split("/") };
71 root ??= createRoot(document.createElement("div"));
72 act(() => root!.render(<DocumentToolbar path={path} placement={placement} />));
73}
74
75// Like React Navigation's NavigationStateContext, whose default value throws when
76// read. React restores a context's default outside render, so layout effects see it.
77const ContainerStateContext = createContext<object>({
78 get getIsInitial(): never {
79 throw new Error("Couldn't find a navigation context.");
80 },
81});
82const containerState = {};
83
84function ConnectingToolbar(props: { readonly label: string }) {
85 return (
86 <NativeHeaderToolbar placement="right">
87 <NativeHeaderToolbar.Custom>
88 <span aria-label={props.label} />
89 </NativeHeaderToolbar.Custom>
90 </NativeHeaderToolbar>
91 );
92}
93
94function renderConnecting(label: string) {
95 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
96 root ??= createRoot(document.createElement("div"));
97 act(() =>
98 root!.render(
99 <ContainerStateContext value={containerState}>
100 <ConnectingToolbar label={label} />
101 </ContainerStateContext>,
102 ),
103 );
104}
105
106function renderedCustomLabel() {
107 const item = harness.renderedItems[0];
108 if (item?.type !== "custom") throw new Error("Expected the custom header element");
109 return (item.element as ReactElement<{ "aria-label": string }>).props["aria-label"];
110}
111
112function openRenderedDocument() {
113 const menu = harness.renderedItems[0];
114 if (menu?.type !== "menu") throw new Error("Expected the native file menu");
115 const action = menu.menu.items[0];
116 if (action?.type !== "action") throw new Error("Expected the native Open PDF action");
117 action.onPress?.();
118}
119
120afterEach(() => {
121 act(() => root?.unmount());
122 root = null;
123 harness.appliedOptions = {};
124 harness.renderedItems = [];
125 harness.setOptionsCalls = 0;
126 harness.openedDocuments = [];
127 vi.unstubAllGlobals();
128});
129
130it.each(["left", "right", "bottom"] as const)(
131 "updates the %s header action when switching between documents with the same name",
132 (placement) => {
133 renderDocument("first/guide.pdf", placement);
134 openRenderedDocument();
135 renderDocument("second/guide.pdf", placement);
136 openRenderedDocument();
137
138 expect(harness.openedDocuments).toEqual(["first/guide.pdf", "second/guide.pdf"]);
139 },
140);
141
142it("applies a custom header element rendered inside a navigation container", () => {
143 renderConnecting("Connecting");
144 expect(renderedCustomLabel()).toBe("Connecting");
145
146 const applied = harness.setOptionsCalls;
147 renderConnecting("Connecting");
148 expect(harness.setOptionsCalls).toBe(applied);
149
150 renderConnecting("Reconnecting");
151 expect(renderedCustomLabel()).toBe("Reconnecting");
152});