From fd09592b024e9e762b006a40bf19bfc23718ee6d Mon Sep 17 00:00:00 2001 From: alkhatibdev Date: Tue, 17 Nov 2026 13:18:24 +0400 Subject: [PATCH] perf: the dashboard fetches each page the first time it is opened Signed-off-by: alkhatibdev --- dashboard/src/RequireSession.tsx | 9 +- dashboard/src/components/States.tsx | 24 +++++ dashboard/src/layout/Shell.test.tsx | 4 +- dashboard/src/lib/upgrade.test.ts | 41 +++++++ dashboard/src/lib/upgrade.ts | 34 ++++++ dashboard/src/main.tsx | 14 +++ dashboard/src/pages/Policies.test.tsx | 4 +- dashboard/src/pages/SignIn.test.tsx | 8 +- dashboard/src/router.test.tsx | 33 ++++++ dashboard/src/router.tsx | 148 +++++++++++++++++++------- dashboard/vite.config.ts | 18 ++++ 11 files changed, 282 insertions(+), 55 deletions(-) create mode 100644 dashboard/src/lib/upgrade.test.ts create mode 100644 dashboard/src/lib/upgrade.ts create mode 100644 dashboard/src/router.test.tsx diff --git a/dashboard/src/RequireSession.tsx b/dashboard/src/RequireSession.tsx index dbd713f..5743caf 100644 --- a/dashboard/src/RequireSession.tsx +++ b/dashboard/src/RequireSession.tsx @@ -1,21 +1,16 @@ import type { ReactNode } from "react"; -import { useTranslation } from "react-i18next"; import { Navigate, useLocation } from "react-router"; +import { Starting } from "@/components/States"; import { endedBecause, useSession } from "@/session"; /** The pages behind sign-in. Anyone else is sent to sign in, and brought back after. */ export function RequireSession({ children }: { children: ReactNode }) { - const { t } = useTranslation(); const location = useLocation(); const session = useSession(); if (session.status === "pending") { - return ( -
- {t("app.loading")} -
- ); + return ; } const reason = endedBecause(session.error); if (session.status === "error") { diff --git a/dashboard/src/components/States.tsx b/dashboard/src/components/States.tsx index 3790be4..a5446b9 100644 --- a/dashboard/src/components/States.tsx +++ b/dashboard/src/components/States.tsx @@ -4,6 +4,16 @@ import { Link } from "react-router"; import { Button } from "@/components/ui/button"; +/** The whole window, while the dashboard starts and there is no page to show yet. */ +export function Starting() { + const { t } = useTranslation(); + return ( +
+ {t("app.loading")} +
+ ); +} + export function Loading() { const { t } = useTranslation(); return ( @@ -29,6 +39,20 @@ export function Failed({ onRetry }: { onRetry?: () => void }) { ); } +/** A page that could not be fetched or drawn. Loading it again from the server is the way back. */ +export function PageFailed() { + return window.location.reload()} />; +} + +/** The same, for a page outside the dashboard's frame, such as signing in. */ +export function StartFailed() { + return ( +
+ +
+ ); +} + export function Missing() { const { t } = useTranslation(); return ( diff --git a/dashboard/src/layout/Shell.test.tsx b/dashboard/src/layout/Shell.test.tsx index 5b4c7a3..606a4f5 100644 --- a/dashboard/src/layout/Shell.test.tsx +++ b/dashboard/src/layout/Shell.test.tsx @@ -1,4 +1,4 @@ -import { screen } from "@testing-library/react"; +import { screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it } from "vitest"; @@ -46,7 +46,7 @@ describe("the shell", () => { const box = (await screen.findAllByRole("searchbox"))[0]!; await userEvent.type(box, "Can a user see their data?{Enter}"); - expect(router.state.location.pathname).toBe("/search"); + await waitFor(() => expect(router.state.location.pathname).toBe("/search")); expect(router.state.location.search).toBe("?q=Can%20a%20user%20see%20their%20data%3F"); }); diff --git a/dashboard/src/lib/upgrade.test.ts b/dashboard/src/lib/upgrade.test.ts new file mode 100644 index 0000000..6c1c884 --- /dev/null +++ b/dashboard/src/lib/upgrade.test.ts @@ -0,0 +1,41 @@ +import { beforeEach, describe, expect, it } from "vitest"; + +import { reloadTarget } from "./upgrade"; + +const CURRENT = "https://dpolens.example/library?law=gdpr"; + +describe("reloadTarget", () => { + beforeEach(() => { + window.sessionStorage.clear(); + }); + + const storage = () => window.sessionStorage; + + it("loads the page somebody was opening", () => { + const opening = { pathname: "/clauses/gdpr-art-5", search: "?lang=en", hash: "#p-1" }; + expect(reloadTarget(opening, CURRENT, storage, 1_000_000)).toBe( + "/clauses/gdpr-art-5?lang=en#p-1", + ); + }); + + it("loads the page that is open when nobody was going anywhere", () => { + expect(reloadTarget(undefined, CURRENT, storage, 1_000_000)).toBe(CURRENT); + }); + + it("leaves the error showing when a file is still missing right after a load", () => { + expect(reloadTarget(undefined, CURRENT, storage, 1_000_000)).toBe(CURRENT); + expect(reloadTarget(undefined, CURRENT, storage, 1_009_999)).toBeNull(); + }); + + it("tries again once the pause has passed", () => { + expect(reloadTarget(undefined, CURRENT, storage, 1_000_000)).toBe(CURRENT); + expect(reloadTarget(undefined, CURRENT, storage, 1_010_000)).toBe(CURRENT); + }); + + it("does not reload where the attempt cannot be noted", () => { + const blocked = () => { + throw new DOMException("The operation is insecure.", "SecurityError"); + }; + expect(reloadTarget(undefined, CURRENT, blocked, 1_000_000)).toBeNull(); + }); +}); diff --git a/dashboard/src/lib/upgrade.ts b/dashboard/src/lib/upgrade.ts new file mode 100644 index 0000000..7909978 --- /dev/null +++ b/dashboard/src/lib/upgrade.ts @@ -0,0 +1,34 @@ +import { createPath, type Path } from "react-router"; + +const RELOADED_AT = "dpolens.reloadedAt"; + +/** Long enough for a fresh load to have finished, so a second failure is not an upgrade. */ +const PAUSE_MS = 10_000; + +/** + * Where to load from the server when a page's file cannot be fetched, or null to + * leave the error showing. + * + * An upgrade replaces the dashboard's files, and a tab opened before it still asks + * for the old ones. A full load of the page somebody was opening brings the new + * files. When the last full load for this reason was moments ago, the file is + * missing for some other reason, and loading again would only repeat. + */ +export function reloadTarget( + opening: Partial | undefined, + current: string, + storage: () => Storage, + now: number = Date.now(), +): string | null { + try { + const store = storage(); + if (now - Number(store.getItem(RELOADED_AT)) < PAUSE_MS) { + return null; + } + store.setItem(RELOADED_AT, String(now)); + } catch { + // Without anywhere to note the attempt, a reload could repeat for ever. + return null; + } + return opening ? createPath(opening) : current; +} diff --git a/dashboard/src/main.tsx b/dashboard/src/main.tsx index de23547..ad7c9e8 100644 --- a/dashboard/src/main.tsx +++ b/dashboard/src/main.tsx @@ -14,9 +14,23 @@ import { createRoot } from "react-dom/client"; import { RouterProvider } from "react-router/dom"; import { ApiError } from "./api/client"; +import { reloadTarget } from "./lib/upgrade"; import { router } from "./router"; import { SESSION } from "./session"; +// A page's file that cannot be fetched is, most often, from before an upgrade. +window.addEventListener("vite:preloadError", (event) => { + const target = reloadTarget( + router.state.navigation.location, + window.location.href, + () => window.sessionStorage, + ); + if (target !== null) { + event.preventDefault(); + window.location.assign(target); + } +}); + const client: QueryClient = new QueryClient({ queryCache: new QueryCache({ // A session that ends while a page is open sends the next call back a 401. diff --git a/dashboard/src/pages/Policies.test.tsx b/dashboard/src/pages/Policies.test.tsx index 3a5e900..7a0952c 100644 --- a/dashboard/src/pages/Policies.test.tsx +++ b/dashboard/src/pages/Policies.test.tsx @@ -1,4 +1,4 @@ -import { screen, within } from "@testing-library/react"; +import { screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it } from "vitest"; @@ -155,6 +155,6 @@ describe("policies", () => { const { router } = renderAt("/policies"); await screen.findAllByRole("navigation", { name: "Main" }); - expect(router.state.location.pathname).toBe("/library"); + await waitFor(() => expect(router.state.location.pathname).toBe("/library")); }); }); diff --git a/dashboard/src/pages/SignIn.test.tsx b/dashboard/src/pages/SignIn.test.tsx index 0d613a1..12fb178 100644 --- a/dashboard/src/pages/SignIn.test.tsx +++ b/dashboard/src/pages/SignIn.test.tsx @@ -1,4 +1,4 @@ -import { screen } from "@testing-library/react"; +import { screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it } from "vitest"; @@ -104,8 +104,10 @@ describe("signing in", () => { serve({ "GET /v1/sessions/current": problem("unauthenticated", 401) }); renderAt("/sign-in?reason=idle"); - expect(await screen.findByRole("status")).toHaveTextContent( - "You were signed out after a while without activity.", + await waitFor(() => + expect(screen.getByRole("status")).toHaveTextContent( + "You were signed out after a while without activity.", + ), ); }); diff --git a/dashboard/src/router.test.tsx b/dashboard/src/router.test.tsx new file mode 100644 index 0000000..5b2a73a --- /dev/null +++ b/dashboard/src/router.test.tsx @@ -0,0 +1,33 @@ +import { screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import { signedIn } from "@/test/fixtures"; +import { renderAt } from "@/test/render"; +import { problem, serve } from "@/test/server"; + +// As if these pages' files had gone with an upgrade, or the network had dropped. +vi.mock("@/pages/Search", () => { + throw new TypeError("Failed to fetch dynamically imported module"); +}); +vi.mock("@/pages/SignIn", () => { + throw new TypeError("Failed to fetch dynamically imported module"); +}); + +describe("a page whose file cannot be fetched", () => { + it("says so inside the frame, and offers to load it again", async () => { + serve({ "GET /v1/sessions/current": { body: signedIn } }); + renderAt("/search?q=retention"); + + expect(await screen.findByRole("alert")).toHaveTextContent("This didn't load."); + expect(screen.getByRole("button", { name: "Try again" })).toBeInTheDocument(); + expect(screen.getAllByRole("navigation", { name: "Main" }).length).toBeGreaterThan(0); + }); + + it("says so on a page outside the frame", async () => { + serve({ "GET /v1/sessions/current": problem("unauthenticated", 401) }); + renderAt("/sign-in"); + + expect(await screen.findByRole("alert")).toHaveTextContent("This didn't load."); + expect(screen.getByRole("button", { name: "Try again" })).toBeInTheDocument(); + }); +}); diff --git a/dashboard/src/router.tsx b/dashboard/src/router.tsx index d07d8e9..cc94067 100644 --- a/dashboard/src/router.tsx +++ b/dashboard/src/router.tsx @@ -1,66 +1,132 @@ -import { createBrowserRouter } from "react-router"; +import { createBrowserRouter, Outlet } from "react-router"; +import { PageFailed, StartFailed, Starting } from "@/components/States"; import { Shell } from "@/layout/Shell"; -import { ClausePage } from "@/pages/Clause"; -import { ComparePage } from "@/pages/Compare"; -import { DocumentPage } from "@/pages/Document"; -import { GovernancePage } from "@/pages/Governance"; import { Home } from "@/pages/Home"; -import { LibraryPage } from "@/pages/Library"; import { NotFoundPage } from "@/pages/NotFound"; -import { OverviewPage } from "@/pages/Overview"; -import { PeoplePage } from "@/pages/People"; -import { PoliciesPage } from "@/pages/Policies"; -import { PolicyDraftPage } from "@/pages/PolicyDraft"; -import { QuestionsPage } from "@/pages/Questions"; -import { RolePage } from "@/pages/Role"; -import { RolesPage } from "@/pages/Roles"; -import { SearchPage } from "@/pages/Search"; -import { SelectedLawsPage } from "@/pages/SelectedLaws"; -import { SettingsPage } from "@/pages/Settings"; -import { SetupPage } from "@/pages/Setup"; -import { SignInPage } from "@/pages/SignIn"; -import { TokensPage } from "@/pages/Tokens"; -import { WelcomePage } from "@/pages/Welcome"; import { RequireSession } from "@/RequireSession"; +// Each page is a file of its own in the build, fetched the first time somebody +// opens it, so the dashboard starts without loading every page it has. Each +// `lazy` is a function: written as an object, the tests' routers answered "No +// route matches" for a page's first visit. export const routes = [ - { path: "/sign-in", element: }, - { path: "/welcome", element: }, + { + path: "/sign-in", + HydrateFallback: Starting, + ErrorBoundary: StartFailed, + lazy: async () => ({ Component: (await import("@/pages/SignIn")).SignInPage }), + }, + { + path: "/welcome", + HydrateFallback: Starting, + ErrorBoundary: StartFailed, + lazy: async () => ({ Component: (await import("@/pages/Welcome")).WelcomePage }), + }, { path: "/setup", + HydrateFallback: Starting, + ErrorBoundary: StartFailed, element: ( - + ), + children: [ + { + index: true, + lazy: async () => ({ Component: (await import("@/pages/Setup")).SetupPage }), + }, + ], }, { path: "/", + HydrateFallback: Starting, + ErrorBoundary: StartFailed, element: ( ), children: [ - { index: true, element: }, - { path: "overview", element: }, - { path: "logs", element: }, - { path: "logs/governance", element: }, - { path: "library", element: }, - { path: "library/:slug", element: }, - { path: "library/:slug/compare", element: }, - { path: "clauses/:key", element: }, - { path: "policies", element: }, - { path: "policies/:slug/draft", element: }, - { path: "search", element: }, - { path: "laws", element: }, - { path: "users", element: }, - { path: "users/roles", element: }, - { path: "users/roles/:id", element: }, - { path: "tokens", element: }, - { path: "settings", element: }, - { path: "*", element: }, + { + // A page that fails says so inside the frame, so the menu stays. + ErrorBoundary: PageFailed, + children: [ + { index: true, element: }, + { + path: "overview", + lazy: async () => ({ Component: (await import("@/pages/Overview")).OverviewPage }), + }, + { + path: "logs", + lazy: async () => ({ Component: (await import("@/pages/Questions")).QuestionsPage }), + }, + { + path: "logs/governance", + lazy: async () => ({ + Component: (await import("@/pages/Governance")).GovernancePage, + }), + }, + { + path: "library", + lazy: async () => ({ Component: (await import("@/pages/Library")).LibraryPage }), + }, + { + path: "library/:slug", + lazy: async () => ({ Component: (await import("@/pages/Document")).DocumentPage }), + }, + { + path: "library/:slug/compare", + lazy: async () => ({ Component: (await import("@/pages/Compare")).ComparePage }), + }, + { + path: "clauses/:key", + lazy: async () => ({ Component: (await import("@/pages/Clause")).ClausePage }), + }, + { + path: "policies", + lazy: async () => ({ Component: (await import("@/pages/Policies")).PoliciesPage }), + }, + { + path: "policies/:slug/draft", + lazy: async () => ({ + Component: (await import("@/pages/PolicyDraft")).PolicyDraftPage, + }), + }, + { + path: "search", + lazy: async () => ({ Component: (await import("@/pages/Search")).SearchPage }), + }, + { + path: "laws", + lazy: async () => ({ + Component: (await import("@/pages/SelectedLaws")).SelectedLawsPage, + }), + }, + { + path: "users", + lazy: async () => ({ Component: (await import("@/pages/People")).PeoplePage }), + }, + { + path: "users/roles", + lazy: async () => ({ Component: (await import("@/pages/Roles")).RolesPage }), + }, + { + path: "users/roles/:id", + lazy: async () => ({ Component: (await import("@/pages/Role")).RolePage }), + }, + { + path: "tokens", + lazy: async () => ({ Component: (await import("@/pages/Tokens")).TokensPage }), + }, + { + path: "settings", + lazy: async () => ({ Component: (await import("@/pages/Settings")).SettingsPage }), + }, + { path: "*", element: }, + ], + }, ], }, ]; diff --git a/dashboard/vite.config.ts b/dashboard/vite.config.ts index f34e3fe..471e81f 100644 --- a/dashboard/vite.config.ts +++ b/dashboard/vite.config.ts @@ -22,6 +22,24 @@ export default defineConfig({ // Every asset as a file of its own, never a data: URL, so the dashboard's // Content-Security-Policy can allow fonts and images from itself alone. assetsInlineLimit: 0, + rolldownOptions: { + output: { + // The libraries are two files apart from the dashboard's own code, React + // and the router in one and the rest in the other, each under the size + // Vite warns about. They change only when a library is upgraded, so a + // browser keeps them from one DPOLens release to the next. + codeSplitting: { + groups: [ + { + name: "react", + test: /node_modules[\\/](react|react-dom|react-router|scheduler)[\\/]/, + priority: 2, + }, + { name: "vendor", test: /node_modules[\\/]/, priority: 1 }, + ], + }, + }, + }, }, test: { environment: "jsdom",