Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

use-section-highlighting.test.tsx

238 lines9.4 KB

1// @vitest-environment happy-dom
2import {
3 Navigate,
4 Outlet,
5 RouterProvider,
6 createMemoryHistory,
7 createRootRoute,
8 createRoute,
9 createRouter,
10 linkOptions,
11 useParams,
12} from "@tanstack/react-router";
13import type { LinkOptions } from "@tanstack/react-router";
14import { act } from "react";
15import { createRoot } from "react-dom/client";
16import type { Root } from "react-dom/client";
17import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
18​
19import {
20 useCloseAppSheet,
21 useIsAppSheetOpen,
22 useOpenAppSheet,
23} from "@/components/app-sheet/app-sheet-store";
24import { setAppSheetView } from "@/components/app-sheet/app-sheet-store";
25import { setInspectorOpen } from "@/components/network/inspector-store";
26import { reportAction } from "@/lib/app-actions";
27import { createSheetAwareHistory, setRecordSheetState } from "@/lib/sheet-aware-history";
28​
29import { getActiveSection, setActiveSection } from "./guide-store";
30import { useWorkspaceSectionHighlighting } from "./use-section-highlighting";
31​
32(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
33​
34/** What the harness exposes: the sheet's real open/close, and whether it's open. */
35let sheet: {
36 open: (sectionId: string, target: LinkOptions) => void;
37 close: () => void;
38 isOpen: boolean;
39};
40​
41function Harness({ isSplit }: { isSplit: boolean }) {
42 useWorkspaceSectionHighlighting(isSplit);
43 sheet = { open: useOpenAppSheet(), close: useCloseAppSheet(), isOpen: useIsAppSheetOpen() };
44 return <Outlet />;
46​
47/** A stand-in route tree with the app screens these tests visit. */
48function renderWorkspace({ isSplit }: { isSplit: boolean }) {
49 const rootRoute = createRootRoute({ component: () => <Harness isSplit={isSplit} /> });
50 const routeTree = rootRoute.addChildren([
51 createRoute({ getParentRoute: () => rootRoute, path: "/", component: () => null }),
52 createRoute({ getParentRoute: () => rootRoute, path: "/analytics", component: () => null }),
53 createRoute({ getParentRoute: () => rootRoute, path: "/settings", component: () => null }),
54 // Like the macOS app: a folder opens its first note.
55 createRoute({
56 getParentRoute: () => rootRoute,
57 path: "/folders/$folderId",
58 component: function OpenFirstNote() {
59 const params = useParams({ strict: false }) as { folderId: string };
60 if (!isSplit) return null;
61 return (
62 <Navigate
63 to="/folders/$folderId/notes/$noteId"
64 params={{ folderId: params.folderId, noteId: "note-03" }}
65 replace
66 />
67 );
68 },
69 }),
70 createRoute({
71 getParentRoute: () => rootRoute,
72 path: "/folders/$folderId/notes/$noteId",
73 component: () => null,
74 }),
75 ]);
76 const history = createSheetAwareHistory(createMemoryHistory({ initialEntries: ["/"] }));
77 const router = createRouter({ routeTree, history });
78 return { router, history };
80​
81let root: Root;
82let container: HTMLElement;
83​
84beforeEach(() => {
85 setActiveSection(null);
86 setInspectorOpen(false);
87 container = document.createElement("div");
88 document.body.append(container);
89 root = createRoot(container);
90});
91​
92afterEach(() => {
93 act(() => root.unmount());
94 container.remove();
95 setRecordSheetState(false);
96});
97​
98/** Waits for the router to finish navigating (some history moves resolve a tick later). */
99async function untilIdle(router: { state: { status: string } }) {
100 for (let tick = 0; tick < 50; tick++) {
101 await new Promise((resolve) => setTimeout(resolve, 0));
102 if (router.state.status === "idle" && tick > 1) return;
103 }
104 throw new Error("The router didn't settle");
106​
107/** Runs `step` and lets the router settle (history.go is asynchronous). */
108async function settle(router: ReturnType<typeof renderWorkspace>["router"], step: () => unknown) {
109 await act(async () => {
110 await step();
111 await untilIdle(router);
112 });
114​
115describe("highlighting on phones (the app in a sheet)", () => {
116 async function mount() {
117 setRecordSheetState(true);
118 const workspace = renderWorkspace({ isSplit: false });
119 await act(async () => {
120 root.render(<RouterProvider router={workspace.router} />);
121 await untilIdle(workspace.router);
122 });
123 return workspace;
124 }
125​
126 it("keeps the highlight when the sheet closes, by Close, Back or Forward", async () => {
127 const { router, history } = await mount();
128 // The guide on its own (sheet closed at "/") doesn't light anything up.
129 expect(getActiveSection()).toBeNull();
130​
131 // Try it, from Aggregations.
132 await settle(router, () => sheet.open("aggregations", linkOptions({ to: "/analytics" })));
133 expect(sheet.isOpen).toBe(true);
134 expect(getActiveSection()).toBe("aggregations");
135​
136 // Close goes back to the entry before the sheet opened ("/").
137 await settle(router, () => sheet.close());
138 expect(sheet.isOpen).toBe(false);
139 expect(router.state.location.pathname).toBe("/");
140 expect(getActiveSection()).toBe("aggregations");
141​
142 // Forward opens the sheet on Analytics again; Back closes it again.
143 await settle(router, () => history.forward());
144 expect(sheet.isOpen).toBe(true);
145 expect(getActiveSection()).toBe("aggregations");
146 await settle(router, () => history.back());
147 expect(sheet.isOpen).toBe(false);
148 expect(getActiveSection()).toBe("aggregations");
149 });
150​
151 it("still follows the app while the sheet is open", async () => {
152 const { router } = await mount();
153 await settle(router, () => sheet.open("aggregations", linkOptions({ to: "/analytics" })));
154 expect(getActiveSection()).toBe("aggregations");
155 // Back to Folders inside the sheet: that's the reader using the app.
156 await settle(router, () => router.navigate({ to: "/" }));
157 expect(sheet.isOpen).toBe(true);
158 expect(getActiveSection()).toBe("introduction");
159 });
160​
161 it("keeps an action's highlight when the Network view closes with the sheet", async () => {
162 const { router } = await mount();
163 await settle(router, () => sheet.open("introduction", linkOptions({ to: "/" })));
164 expect(getActiveSection()).toBe("introduction");
165 await settle(router, () => reportAction({ type: "network.fail-next-set", failNext: true }));
166 expect(getActiveSection()).toBe("rollbacks");
167 await settle(router, () => sheet.close());
168 expect(getActiveSection()).toBe("rollbacks");
169 });
170});
171​
172describe("with the request inspector open", () => {
173 /** A sidebar click: report the action, then follow the link. */
174 const openFolder = (router: ReturnType<typeof renderWorkspace>["router"], folderId: string) => {
175 reportAction({ type: "folder.opened", folderId, smart: folderId === "all" });
176 return router.navigate({ to: "/folders/$folderId", params: { folderId } });
177 };
178​
179 it("on wide screens, the guide follows the folders the reader opens", async () => {
180 const { router } = renderWorkspace({ isSplit: true });
181 await act(async () => {
182 root.render(<RouterProvider router={router} />);
183 await untilIdle(router);
184 });
185 await settle(router, () => router.navigate({ to: "/analytics" }));
186 expect(getActiveSection()).toBe("aggregations");
187 await settle(router, () => setInspectorOpen(true));
188 expect(getActiveSection()).toBe("sync");
189​
190 await settle(router, () => openFolder(router, "personal"));
191 expect(router.state.location.pathname).toBe("/folders/personal/notes/note-03");
192 expect(getActiveSection()).toBe("collections");
193 await settle(router, () => openFolder(router, "all"));
194 expect(getActiveSection()).toBe("live-queries");
195 });
196​
197 it("on phones, with the Network view open, navigating in the sheet still counts", async () => {
198 setRecordSheetState(true);
199 const { router } = renderWorkspace({ isSplit: false });
200 await act(async () => {
201 root.render(<RouterProvider router={router} />);
202 await untilIdle(router);
203 });
204 await settle(router, () => sheet.open("introduction", linkOptions({ to: "/" })));
205 await settle(router, () => setAppSheetView("network"));
206 expect(getActiveSection()).toBe("sync");
207 // Back to the app view, then into a folder (the iPhone layout shows its list).
208 await settle(router, () => setAppSheetView("app"));
209 await settle(router, () => openFolder(router, "personal"));
210 expect(getActiveSection()).toBe("collections");
211 // Back (the history entry before) while the Network view is open again.
212 await settle(router, () => setAppSheetView("network"));
213 await settle(router, () => router.navigate({ to: "/analytics" }));
214 expect(sheet.isOpen).toBe(true);
215 expect(getActiveSection()).toBe("aggregations");
216 setAppSheetView("app");
217 });
218});
219​
220describe("highlighting on wide screens (the app beside the guide)", () => {
221 it("follows navigation, and closing the inspector doesn't move the highlight", async () => {
222 const { router } = renderWorkspace({ isSplit: true });
223 await act(async () => {
224 root.render(<RouterProvider router={router} />);
225 await untilIdle(router);
226 });
227 expect(getActiveSection()).toBe("introduction");
228 await settle(router, () => router.navigate({ to: "/analytics" }));
229 expect(getActiveSection()).toBe("aggregations");
230 await settle(router, () => router.navigate({ to: "/" }));
231 expect(getActiveSection()).toBe("introduction");
232 await settle(router, () => setInspectorOpen(true));
233 expect(getActiveSection()).toBe("sync");
234 // Closing a panel isn't news: Folders still matches Intro, but the highlight stays.
235 await settle(router, () => setInspectorOpen(false));
236 expect(getActiveSection()).toBe("sync");
237 });
238});