Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions dashboard/src/RequireSession.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="grid min-h-dvh place-items-center text-muted" role="status">
{t("app.loading")}
</div>
);
return <Starting />;
}
const reason = endedBecause(session.error);
if (session.status === "error") {
Expand Down
24 changes: 24 additions & 0 deletions dashboard/src/components/States.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<div className="grid min-h-dvh place-items-center text-muted" role="status">
{t("app.loading")}
</div>
);
}

export function Loading() {
const { t } = useTranslation();
return (
Expand All @@ -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 <Failed onRetry={() => window.location.reload()} />;
}

/** The same, for a page outside the dashboard's frame, such as signing in. */
export function StartFailed() {
return (
<div className="grid min-h-dvh place-items-center p-4">
<PageFailed />
</div>
);
}

export function Missing() {
const { t } = useTranslation();
return (
Expand Down
4 changes: 2 additions & 2 deletions dashboard/src/layout/Shell.test.tsx
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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");
});

Expand Down
41 changes: 41 additions & 0 deletions dashboard/src/lib/upgrade.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
34 changes: 34 additions & 0 deletions dashboard/src/lib/upgrade.ts
Original file line number Diff line number Diff line change
@@ -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<Path> | 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;
}
14 changes: 14 additions & 0 deletions dashboard/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions dashboard/src/pages/Policies.test.tsx
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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"));
});
});
8 changes: 5 additions & 3 deletions dashboard/src/pages/SignIn.test.tsx
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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.",
),
);
});

Expand Down
33 changes: 33 additions & 0 deletions dashboard/src/router.test.tsx
Original file line number Diff line number Diff line change
@@ -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();
});
});
Loading
Loading