diff --git a/apps/dev-playground/client/src/components/error-component.tsx b/apps/dev-playground/client/src/components/error-component.tsx deleted file mode 100644 index fd9381b87..000000000 --- a/apps/dev-playground/client/src/components/error-component.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { - Button, - Card, - CardContent, - CardHeader, - CardTitle, -} from "@databricks/appkit-ui/react"; -import { type ErrorComponentProps, Link } from "@tanstack/react-router"; - -export function ErrorComponent({ error }: { error: ErrorComponentProps }) { - return ( - - - Something went wrong - - -

- {error?.error?.message || "An unexpected error occurred"} -

- - - -
-
- ); -} diff --git a/apps/dev-playground/client/src/lib/nav.ts b/apps/dev-playground/client/src/lib/nav.ts index 00df84afe..1e6c78cf7 100644 --- a/apps/dev-playground/client/src/lib/nav.ts +++ b/apps/dev-playground/client/src/lib/nav.ts @@ -16,6 +16,7 @@ import { ServerIcon, ShieldIcon, SigmaIcon, + TriangleAlertIcon, Wand2Icon, ZapIcon, } from "lucide-react"; @@ -194,6 +195,13 @@ export const NAV_GROUPS: ReadonlyArray = [ "Author UI in variants, pick one live in the browser, and let the agent finalize it into source.", icon: Wand2Icon, }, + { + to: "/error-page", + label: "Error Page", + description: + "A route that throws, caught by AppKit's ErrorPage instead of the router's default.", + icon: TriangleAlertIcon, + }, ], }, ]; diff --git a/apps/dev-playground/client/src/routeTree.gen.ts b/apps/dev-playground/client/src/routeTree.gen.ts index 8658c1952..61f0a848b 100644 --- a/apps/dev-playground/client/src/routeTree.gen.ts +++ b/apps/dev-playground/client/src/routeTree.gen.ts @@ -23,6 +23,7 @@ import { Route as LakebaseRouteRouteImport } from './routes/lakebase.route' import { Route as JobsRouteRouteImport } from './routes/jobs.route' import { Route as GenieRouteRouteImport } from './routes/genie.route' import { Route as FilesRouteRouteImport } from './routes/files.route' +import { Route as ErrorPageRouteRouteImport } from './routes/error-page.route' import { Route as DatabaseRouteRouteImport } from './routes/database.route' import { Route as DataVisualizationRouteRouteImport } from './routes/data-visualization.route' import { Route as ChartInferenceRouteRouteImport } from './routes/chart-inference.route' @@ -102,6 +103,11 @@ const FilesRouteRoute = FilesRouteRouteImport.update({ path: '/files', getParentRoute: () => rootRouteImport, } as any) +const ErrorPageRouteRoute = ErrorPageRouteRouteImport.update({ + id: '/error-page', + path: '/error-page', + getParentRoute: () => rootRouteImport, +} as any) const DatabaseRouteRoute = DatabaseRouteRouteImport.update({ id: '/database', path: '/database', @@ -152,6 +158,7 @@ export interface FileRoutesByFullPath { '/chart-inference': typeof ChartInferenceRouteRoute '/data-visualization': typeof DataVisualizationRouteRoute '/database': typeof DatabaseRouteRoute + '/error-page': typeof ErrorPageRouteRoute '/files': typeof FilesRouteRoute '/genie': typeof GenieRouteRoute '/jobs': typeof JobsRouteRoute @@ -176,6 +183,7 @@ export interface FileRoutesByTo { '/chart-inference': typeof ChartInferenceRouteRoute '/data-visualization': typeof DataVisualizationRouteRoute '/database': typeof DatabaseRouteRoute + '/error-page': typeof ErrorPageRouteRoute '/files': typeof FilesRouteRoute '/genie': typeof GenieRouteRoute '/jobs': typeof JobsRouteRoute @@ -201,6 +209,7 @@ export interface FileRoutesById { '/chart-inference': typeof ChartInferenceRouteRoute '/data-visualization': typeof DataVisualizationRouteRoute '/database': typeof DatabaseRouteRoute + '/error-page': typeof ErrorPageRouteRoute '/files': typeof FilesRouteRoute '/genie': typeof GenieRouteRoute '/jobs': typeof JobsRouteRoute @@ -227,6 +236,7 @@ export interface FileRouteTypes { | '/chart-inference' | '/data-visualization' | '/database' + | '/error-page' | '/files' | '/genie' | '/jobs' @@ -251,6 +261,7 @@ export interface FileRouteTypes { | '/chart-inference' | '/data-visualization' | '/database' + | '/error-page' | '/files' | '/genie' | '/jobs' @@ -275,6 +286,7 @@ export interface FileRouteTypes { | '/chart-inference' | '/data-visualization' | '/database' + | '/error-page' | '/files' | '/genie' | '/jobs' @@ -300,6 +312,7 @@ export interface RootRouteChildren { ChartInferenceRouteRoute: typeof ChartInferenceRouteRoute DataVisualizationRouteRoute: typeof DataVisualizationRouteRoute DatabaseRouteRoute: typeof DatabaseRouteRoute + ErrorPageRouteRoute: typeof ErrorPageRouteRoute FilesRouteRoute: typeof FilesRouteRoute GenieRouteRoute: typeof GenieRouteRoute JobsRouteRoute: typeof JobsRouteRoute @@ -416,6 +429,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FilesRouteRouteImport parentRoute: typeof rootRouteImport } + '/error-page': { + id: '/error-page' + path: '/error-page' + fullPath: '/error-page' + preLoaderRoute: typeof ErrorPageRouteRouteImport + parentRoute: typeof rootRouteImport + } '/database': { id: '/database' path: '/database' @@ -484,6 +504,7 @@ const rootRouteChildren: RootRouteChildren = { ChartInferenceRouteRoute: ChartInferenceRouteRoute, DataVisualizationRouteRoute: DataVisualizationRouteRoute, DatabaseRouteRoute: DatabaseRouteRoute, + ErrorPageRouteRoute: ErrorPageRouteRoute, FilesRouteRoute: FilesRouteRoute, GenieRouteRoute: GenieRouteRoute, JobsRouteRoute: JobsRouteRoute, diff --git a/apps/dev-playground/client/src/routes/__root.tsx b/apps/dev-playground/client/src/routes/__root.tsx index 402a80435..b973e1d3a 100644 --- a/apps/dev-playground/client/src/routes/__root.tsx +++ b/apps/dev-playground/client/src/routes/__root.tsx @@ -7,6 +7,7 @@ import { DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, + ErrorPage, TooltipProvider, } from "@databricks/appkit-ui/react"; import { @@ -19,7 +20,6 @@ import { } from "@tanstack/react-router"; import { MenuIcon } from "lucide-react"; -import { ErrorComponent } from "@/components/error-component"; import { ThemeSelector } from "@/components/theme-selector"; import { findNavItemForPath, NAV_GROUPS } from "@/lib/nav"; @@ -122,7 +122,13 @@ function RootComponent() { onCatch={(error) => { console.error(error); }} - errorComponent={(error) => } + errorComponent={({ error }) => ( + // The router's link: going home keeps the app's providers (no page load). + Back to home} + /> + )} > diff --git a/apps/dev-playground/client/src/routes/error-page.route.tsx b/apps/dev-playground/client/src/routes/error-page.route.tsx new file mode 100644 index 000000000..cc0d3deb3 --- /dev/null +++ b/apps/dev-playground/client/src/routes/error-page.route.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from "@tanstack/react-router"; + +export const Route = createFileRoute("/error-page")({ + component: ErrorPageRoute, +}); + +// Throws on render: the CatchBoundary in __root.tsx shows AppKit's ErrorPage. +function ErrorPageRoute(): never { + throw new Error("This route throws on purpose, to show AppKit's error page."); +} diff --git a/apps/dev-playground/tests/error-page.spec.ts b/apps/dev-playground/tests/error-page.spec.ts new file mode 100644 index 000000000..5f542c172 --- /dev/null +++ b/apps/dev-playground/tests/error-page.spec.ts @@ -0,0 +1,31 @@ +import { expect, test } from "@playwright/test"; + +import { setupMockAPI } from "./utils/test-utils"; + +test.describe("Error Page Route Tests", () => { + test.beforeEach(async ({ page }) => { + await setupMockAPI(page); + await page.goto("/error-page", { waitUntil: "networkidle" }); + }); + + test("a route that throws shows AppKit's error page inside the layout", async ({ + page, + }) => { + await expect(page.getByText("Something went wrong")).toBeVisible(); + await expect(page.getByText("Unexpected Application Error")).toHaveCount(0); + await expect(page.getByRole("button", { name: "Reload" })).toBeVisible(); + await expect( + page.getByRole("link", { name: "Back to home" }), + ).toHaveAttribute("href", "/"); + await expect( + page.getByRole("heading", { name: "AppKit Playground" }), + ).toBeVisible(); + }); + + test("shows the thrown error's message in development", async ({ page }) => { + // The suite runs against `pnpm dev`: details show only in development. + await expect( + page.getByText("This route throws on purpose", { exact: false }), + ).toBeVisible(); + }); +}); diff --git a/docs/docs/api/appkit-ui/error-page.md b/docs/docs/api/appkit-ui/error-page.md new file mode 100644 index 000000000..f784bf88c --- /dev/null +++ b/docs/docs/api/appkit-ui/error-page.md @@ -0,0 +1,62 @@ +--- +sidebar_position: 8 +--- + +# Error page + +When a route throws, React Router shows its own built-in error page: a "Hey developer" note while developing, and the error's message and stack in a deployed app. AppKit apps show their own error page instead. It says that something went wrong (for a 404, that the page was not found) and offers **Reload** and **Back to home**; Back to home is the primary action on a 404, where a reload would only repeat the miss. The error's message and stack show only in development (`import.meta.env.DEV`), never in a production build. + +It covers both kinds of route errors: an error thrown while rendering a route (or from a loader or action), and a route error response such as a 404 (`isRouteErrorResponse`). + +## In the app template + +The template's `client/src/App.tsx` sets a `RouteErrorPage` as the `errorElement` of its root layout route, so every page gets it: + +```tsx +const router = createBrowserRouter([ + { + element: , + errorElement: , + children: [ + { path: "/", element: }, + // ... + ], + }, +]); +``` + +`RouteErrorPage` is defined in the same file: edit it to change what your app shows. + +## `ErrorPage` in your own router + +`ErrorPage` from `@databricks/appkit-ui/react` is the same page as a component. Pass it the route's error, and your router's link as `homeLink`, so Back to home navigates inside the app (keeping its state) and under the router's `basename`: + +```tsx +import { ErrorPage } from "@databricks/appkit-ui/react"; +import { Link, useRouteError } from "react-router"; + +function RouteErrorPage() { + return ( + Back to home} + /> + ); +} + +const router = createBrowserRouter([ + { element: , errorElement: , children: [/* ... */] }, +]); +``` + +Without `homeLink`, Back to home is ``, a full page load of the app's root. `ErrorPage` doesn't depend on a router. With TanStack Router, for example: `errorComponent: ({ error }) => Back to home} />`. + +## Replacing it + +React Router renders the nearest `errorElement` (or `ErrorBoundary`) above the route that failed, so a route's own one wins over the default: + +```tsx +{ path: "/orders", element: , errorElement: } +``` + +To replace the page for the whole app, set a different `errorElement` on the root route. diff --git a/docs/static/appkit-ui/styles.gen.css b/docs/static/appkit-ui/styles.gen.css index 47d36b685..bb120c2ec 100644 --- a/docs/static/appkit-ui/styles.gen.css +++ b/docs/static/appkit-ui/styles.gen.css @@ -17,6 +17,7 @@ --container-sm: 24rem; --container-md: 28rem; --container-lg: 32rem; + --container-2xl: 42rem; --text-xs: 0.75rem; --text-xs--line-height: calc(1 / 0.75); --text-sm: 0.875rem; @@ -852,6 +853,9 @@ .max-w-\(--skeleton-width\) { max-width: var(--skeleton-width); } + .max-w-2xl { + max-width: var(--container-2xl); + } .max-w-\[80\%\] { max-width: 80%; } diff --git a/packages/appkit-ui/package.json b/packages/appkit-ui/package.json index f1bf0b1cb..15d86d19a 100644 --- a/packages/appkit-ui/package.json +++ b/packages/appkit-ui/package.json @@ -115,6 +115,7 @@ "@types/react-dom": "19.2.2", "react": "19.2.0", "react-dom": "19.2.0", + "react-router": "7.18.0", "tailwindcss": "4.1.17", "tw-animate-css": "1.4.0" }, diff --git a/packages/appkit-ui/src/react/__tests__/error-page.test.tsx b/packages/appkit-ui/src/react/__tests__/error-page.test.tsx new file mode 100644 index 000000000..247dc96f1 --- /dev/null +++ b/packages/appkit-ui/src/react/__tests__/error-page.test.tsx @@ -0,0 +1,197 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { + createMemoryRouter, + Link, + Outlet, + type RouteObject, + RouterProvider, + useRouteError, +} from "react-router"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { ErrorPage } from "../error-page"; + +// Wired like the app template's App.tsx: the default on the layout route. +function RouteErrorPage() { + return ; +} + +// Wired like the design plugin's router (basename /design). +function RouteErrorPageWithHome() { + return ( + Back to home} + /> + ); +} + +function Orders(): never { + throw new Error("orders failed to render"); +} + +const pages: RouteObject[] = [ + { path: "/", element:

Home

}, + { path: "/orders", Component: Orders }, +]; + +function renderApp( + path: string, + { + children = pages, + withDefault = true, + errorElement = , + basename = undefined as string | undefined, + } = {}, +) { + const layout: RouteObject = { element: , children }; + if (withDefault) layout.errorElement = errorElement; + render( + , + ); +} + +const isPrimary = (el: HTMLElement) => el.className.includes("bg-primary"); + +beforeEach(() => { + // React and React Router log every caught route error. + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(console, "warn").mockImplementation(() => {}); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllEnvs(); + vi.restoreAllMocks(); +}); + +describe("ErrorPage as the default route error element", () => { + test("without it, React Router shows its own default page", async () => { + renderApp("/orders", { withDefault: false }); + expect( + await screen.findByText("Unexpected Application Error!"), + ).toBeTruthy(); + expect(screen.getByText(/Hey developer/)).toBeTruthy(); + }); + + test("a route that throws renders the AppKit error page, not React Router's", async () => { + renderApp("/orders"); + expect(await screen.findByText("Something went wrong")).toBeTruthy(); + expect(screen.queryByText(/Unexpected Application Error/)).toBeNull(); + expect(screen.queryByText(/Hey developer/)).toBeNull(); + // A reload can recover from a thrown error: it is the primary action. + expect(isPrimary(screen.getByRole("button", { name: "Reload" }))).toBe( + true, + ); + const home = screen.getByRole("link", { name: "Back to home" }); + expect(home.getAttribute("href")).toBe("/"); + expect(isPrimary(home)).toBe(false); + }); + + test("a 404 route error response renders it as page not found", async () => { + renderApp("/no-such-page"); + expect(await screen.findByText("Page not found")).toBeTruthy(); + expect(screen.queryByText(/Unexpected Application Error/)).toBeNull(); + expect(screen.queryByText("Something went wrong")).toBeNull(); + // Reloading repeats the miss: Back to home is the primary action. + expect(isPrimary(screen.getByRole("button", { name: "Reload" }))).toBe( + false, + ); + expect(isPrimary(screen.getByRole("link", { name: "Back to home" }))).toBe( + true, + ); + // Development: the status and React Router's message. + expect(screen.getByText(/404 Not Found/).textContent).toMatch( + /No route matches URL "\/no-such-page"/, + ); + expect( + screen.getByRole("link", { name: "Back to home" }).getAttribute("href"), + ).toBe("/"); + }); + + test("shows the message and stack in development", async () => { + renderApp("/orders"); + const details = (await screen.findByText(/orders failed to render/)) + .textContent; + expect(details).toMatch(/at Orders/); + }); + + test("hides the message and stack outside development", async () => { + vi.stubEnv("DEV", false); + renderApp("/orders"); + expect(await screen.findByText("Something went wrong")).toBeTruthy(); + expect(screen.queryByText(/orders failed to render/)).toBeNull(); + expect(document.querySelector("pre")).toBeNull(); + }); + + test("hides a 404's details outside development", async () => { + vi.stubEnv("DEV", false); + renderApp("/no-such-page"); + expect(await screen.findByText("Page not found")).toBeTruthy(); + expect(screen.queryByText(/No route matches/)).toBeNull(); + expect(document.querySelector("pre")).toBeNull(); + }); + + test("a router link as homeLink keeps the basename, e.g. /design", async () => { + renderApp("/design/no-such-page", { + basename: "/design", + errorElement: , + }); + expect(await screen.findByText("Page not found")).toBeTruthy(); + expect( + screen.getByRole("link", { name: "Back to home" }).getAttribute("href"), + ).toBe("/design"); + }); + + test("an app's own errorElement wins over the default", async () => { + renderApp("/orders", { + children: [ + { path: "/orders", Component: Orders, errorElement:

Own error

}, + ], + }); + expect(await screen.findByText("Own error")).toBeTruthy(); + expect(screen.queryByText("Something went wrong")).toBeNull(); + }); +}); + +describe("ErrorPage", () => { + test("shows a thrown non-Error value in development", () => { + render(); + expect(screen.getByText("Something went wrong")).toBeTruthy(); + expect(screen.getByText("plain string")).toBeTruthy(); + }); + + // Each one throws while the page reads it: the page must still render. + const hostile = { + "a value without toString": () => Object.create(null), + "one whose Symbol.toStringTag getter throws too": () => + Object.create(null, { + [Symbol.toStringTag]: { + get() { + throw new Error("toStringTag"); + }, + }, + }), + "one whose status getter throws": () => ({ + get status() { + throw new Error("status"); + }, + statusText: "Not Found", + }), + }; + describe.each([true, false])("DEV: %s", (dev) => { + test.each(Object.entries(hostile))("renders %s", (_, make) => { + vi.stubEnv("DEV", dev); + render(); + expect(screen.getByText("Something went wrong")).toBeTruthy(); + expect(document.querySelector("pre")?.textContent ?? null).toBe( + dev ? "The error can't be shown as text." : null, + ); + }); + }); +}); diff --git a/packages/appkit-ui/src/react/error-page.tsx b/packages/appkit-ui/src/react/error-page.tsx new file mode 100644 index 000000000..fed01f6b8 --- /dev/null +++ b/packages/appkit-ui/src/react/error-page.tsx @@ -0,0 +1,123 @@ +import { FileQuestionMark, TriangleAlert } from "lucide-react"; +import type { ReactElement } from "react"; + +import { Button } from "./ui/button"; +import { + Empty, + EmptyContent, + EmptyDescription, + EmptyHeader, + EmptyMedia, + EmptyTitle, +} from "./ui/empty"; + +/** Props for {@link ErrorPage}. */ +export interface ErrorPageProps { + /** + * What the route threw: an `Error`, a route error response such as React + * Router's 404 (`{ status, statusText, data }`), or any other value. + */ + error: unknown; + /** + * The Back to home link, rendered as one of the page's buttons. Pass your + * router's link so it stays in the app and under its basename, e.g. + * `Back to home`. Defaults to `
`, a full + * page load of the app's root. + */ + homeLink?: ReactElement; +} + +interface RouteErrorResponse { + status: number; + statusText: string; + data?: unknown; +} + +// The shape React Router's isRouteErrorResponse checks: appkit-ui doesn't depend on a router. +function isRouteErrorResponse(error: unknown): error is RouteErrorResponse { + return ( + typeof error === "object" && + error !== null && + "status" in error && + typeof error.status === "number" && + "statusText" in error && + typeof error.statusText === "string" + ); +} + +// Runs in production too: a getter that throws (e.g. `status`) makes it a plain error. +function isNotFound(error: unknown): boolean { + try { + return isRouteErrorResponse(error) && error.status === 404; + } catch { + return false; + } +} + +function details(error: unknown): string { + try { + if (isRouteErrorResponse(error)) { + const data = typeof error.data === "string" ? `\n${error.data}` : ""; + return `${error.status} ${error.statusText}${data}`; + } + if (error instanceof Error) { + const { message, stack = "" } = error; + // V8's stack starts with the message; Firefox's and Safari's don't. + return stack.includes(message) ? stack : `${message}\n${stack}`; + } + return String(error); + } catch { + // String() throws for a value without toString (Object.create(null)), and so can a getter on it. + return "The error can't be shown as text."; + } +} + +/** + * The page for a route that failed, instead of the router's built-in one: it + * says plainly that something went wrong (for a 404 route error response, that + * the page was not found) and offers a reload and the home page. The error's + * message and stack show only in development, never in a production build. + * + * Works with any router: pass React Router's `useRouteError()`, or the `error` + * TanStack Router gives an `errorComponent`. + */ +export function ErrorPage({ + error, + homeLink = Back to home, +}: ErrorPageProps) { + const notFound = isNotFound(error); + return ( + + + + {notFound ? : } + + + {notFound ? "Page not found" : "Something went wrong"} + + + {notFound + ? "There is no page at this address." + : "An unexpected error occurred. Reload the page, or go back to the home page."} + + + {import.meta.env.DEV && ( +
+          {details(error)}
+        
+ )} + + {/* A reload can recover from a thrown error; on a 404 it repeats the miss. */} + + + +
+ ); +} diff --git a/packages/appkit-ui/src/react/index.ts b/packages/appkit-ui/src/react/index.ts index 715f0c46b..9e015547f 100644 --- a/packages/appkit-ui/src/react/index.ts +++ b/packages/appkit-ui/src/react/index.ts @@ -1,4 +1,5 @@ export * from "./charts"; +export * from "./error-page"; export * from "./file-browser"; export * from "./genie"; export * from "./hooks"; diff --git a/packages/appkit/src/plugins/design/tests/design.test.ts b/packages/appkit/src/plugins/design/tests/design.test.ts index efa6840ee..5c71c3470 100644 --- a/packages/appkit/src/plugins/design/tests/design.test.ts +++ b/packages/appkit/src/plugins/design/tests/design.test.ts @@ -158,12 +158,23 @@ describe("entryModule", () => { 'import * as initial from "/src/design/pages/orders.tsx"', ); expect(code).toContain( - 'createBrowserRouter(routes, { basename: "/design" })', + 'createBrowserRouter([{ ErrorBoundary: RouteErrorPage, children: routes }], { basename: "/design" })', ); expect(code).toContain("lazy: async () =>"); expect(code).not.toContain("eager: true }),"); }); + test("router mode: AppKit's error page for route errors", () => { + const code = entryModule("index.tsx", [], true); + expect(code).toContain( + 'import { ErrorPage } from "@databricks/appkit-ui/react"', + ); + expect(code).toContain( + 'createElement(ErrorPage, { error: useRouteError(), homeLink: createElement(Link, { to: "/" }, "Back to home") })', + ); + expect(code).toContain("ErrorBoundary: RouteErrorPage"); + }); + test("routes and lists only non-reserved page files", () => { const code = entryModule("index.tsx", [], true); expect(code).toContain('"!/src/design/pages/index.{tsx,jsx}"'); diff --git a/packages/appkit/src/plugins/design/vite-plugin.ts b/packages/appkit/src/plugins/design/vite-plugin.ts index f7ba626c6..68c9af4e4 100644 --- a/packages/appkit/src/plugins/design/vite-plugin.ts +++ b/packages/appkit/src/plugins/design/vite-plugin.ts @@ -1,5 +1,4 @@ import fs from "node:fs"; -import { createRequire } from "node:module"; import path from "node:path"; import type { Plugin, ViteDevServer } from "vite"; @@ -155,30 +154,25 @@ export function pageState(page: { } /** - * Node's resolution from the design page (the app's own copy): this plugin's - * folder may see a hoisted older version, and Vite returns its nameless pre-bundle. + * The app's own copy: the nearest `node_modules/react-router` from the design + * page up, as Vite resolves it. Not this plugin's folder (it may see a hoisted + * older version), not Vite (it returns its nameless pre-bundle), and not Node's + * resolution (it also searches NODE_PATH, which pnpm's bin shims point at the + * workspace's hidden hoisted packages). */ function hasReactRouter(clientRoot: string): boolean { - let entry: string; - try { - entry = createRequire( - path.join(clientRoot, "src/design/index.tsx"), - ).resolve("react-router"); - } catch { - return false; - } for ( - let dir = path.dirname(entry); - dir !== path.dirname(dir); + let dir = path.join(clientRoot, "src/design"); + ; dir = path.dirname(dir) ) { - const pkg = path.join(dir, "package.json"); - if (!fs.existsSync(pkg)) continue; - const { name, version } = JSON.parse(fs.readFileSync(pkg, "utf-8")); - if (name !== "react-router") continue; - return Number.parseInt(String(version), 10) >= 7; + const pkg = path.join(dir, "node_modules/react-router/package.json"); + if (fs.existsSync(pkg)) { + const { version } = JSON.parse(fs.readFileSync(pkg, "utf-8")); + return Number.parseInt(String(version), 10) >= 7; + } + if (dir === path.dirname(dir)) return false; } - return false; } /** Browser code for page and app scripts: `settled()`; the includer defines `schedule()`. */ @@ -393,8 +387,13 @@ createRoot(document.getElementById("root")).render( } return `${shared} -import { createBrowserRouter, RouterProvider } from "react-router"; +import { ErrorPage } from "@databricks/appkit-ui/react"; +import { createBrowserRouter, Link, RouterProvider, useRouteError } from "react-router"; +// AppKit's page, not React Router's default, for a page that fails to load or doesn't exist. +// Its home link is the router's, so it stays under /design. +const RouteErrorPage = () => + createElement(ErrorPage, { error: useRouteError(), homeLink: createElement(Link, { to: "/" }, "Back to home") }); const lazyPages = import.meta.glob(${JSON.stringify(PAGE_GLOBS)}); const routes = Object.keys(lazyPages).map((file) => { const name = pageName(file); @@ -403,7 +402,7 @@ const routes = Object.keys(lazyPages).map((file) => { ? { path, Component: withReady(initial, name) } : { path, lazy: async () => ({ Component: withReady(await lazyPages[file](), name) }) }; }); -const router = createBrowserRouter(routes, { basename: "/design" }); +const router = createBrowserRouter([{ ErrorBoundary: RouteErrorPage, children: routes }], { basename: "/design" }); createRoot(document.getElementById("root")).render(createElement(RouterProvider, { router })); `; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6e8bdcb8d..ef924c30e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -622,6 +622,9 @@ importers: react-dom: specifier: 19.2.0 version: 19.2.0(react@19.2.0) + react-router: + specifier: 7.18.0 + version: 7.18.0(react-dom@19.2.0(react@19.2.0))(react@19.2.0) tailwindcss: specifier: 4.1.17 version: 4.1.17 @@ -6719,6 +6722,10 @@ packages: resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} engines: {node: '>= 0.6'} + cookie@1.1.1: + resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} + engines: {node: '>=18'} + copy-webpack-plugin@11.0.0: resolution: {integrity: sha512-fX2MWpamkW0hZxMEg0+mYnA40LTosOSa5TqZ9GYIBzyJa9C3QUaMPSE2xAi/buNr8u89SfD9wHSQVBzrRa/SOQ==} engines: {node: '>= 14.15.0'} @@ -10799,6 +10806,16 @@ packages: peerDependencies: react: '>=15' + react-router@7.18.0: + resolution: {integrity: sha512-pTTGt8J+ji1NOmYnjzT+bAJy/1zD+Jp4ziO6cL7T3ZLvXKtusO7BpFqlRXitqpcPVqllsIXFHRMt+2/k3Xn6HQ==} + engines: {node: '>=20.0.0'} + peerDependencies: + react: '>=18' + react-dom: '>=18' + peerDependenciesMeta: + react-dom: + optional: true + react-style-singleton@2.2.3: resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==} engines: {node: '>=10'} @@ -11251,6 +11268,9 @@ packages: resolution: {integrity: sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==} engines: {node: '>= 0.8.0'} + set-cookie-parser@2.7.3: + resolution: {integrity: sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==} + set-function-length@1.2.2: resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} engines: {node: '>= 0.4'} @@ -19894,6 +19914,8 @@ snapshots: cookie@0.7.2: {} + cookie@1.1.1: {} + copy-webpack-plugin@11.0.0(webpack@5.103.0(esbuild@0.25.10)): dependencies: fast-glob: 3.3.3 @@ -24582,6 +24604,14 @@ snapshots: tiny-invariant: 1.3.3 tiny-warning: 1.0.3 + react-router@7.18.0(react-dom@19.2.0(react@19.2.0))(react@19.2.0): + dependencies: + cookie: 1.1.1 + react: 19.2.0 + set-cookie-parser: 2.7.3 + optionalDependencies: + react-dom: 19.2.0(react@19.2.0) + react-style-singleton@2.2.3(@types/react@19.2.2)(react@19.2.0): dependencies: get-nonce: 1.0.1 @@ -25220,6 +25250,8 @@ snapshots: transitivePeerDependencies: - supports-color + set-cookie-parser@2.7.3: {} + set-function-length@1.2.2: dependencies: define-data-property: 1.1.4 diff --git a/template/client/src/App.tsx b/template/client/src/App.tsx index e0499841e..ec4a92207 100644 --- a/template/client/src/App.tsx +++ b/template/client/src/App.tsx @@ -1,4 +1,13 @@ -import { createBrowserRouter, RouterProvider, Link, NavLink, Outlet, useLocation } from 'react-router'; +import { + createBrowserRouter, + isRouteErrorResponse, + RouterProvider, + Link, + NavLink, + Outlet, + useLocation, + useRouteError, +} from 'react-router'; import { useState } from 'react'; import { Button, @@ -18,7 +27,7 @@ import { SheetTitle, useIsMobile, } from '@databricks/appkit-ui/react'; -import { FileQuestionMark, Menu } from 'lucide-react'; +import { FileQuestionMark, Menu, TriangleAlert } from 'lucide-react'; {{- if .plugins.agents}} import { AgentChat } from './pages/agents/AgentChat'; {{- end}} @@ -149,6 +158,8 @@ function Layout() { const router = createBrowserRouter([ { element: , + // Replaces React Router's default error page; a route's own errorElement wins over it. + errorElement: , children: [ { path: '/', element: }, {{- if .plugins.agents}} @@ -231,6 +242,64 @@ function HomePage() { ); } +// A route that throws, or a route error response such as a loader's 404, renders this instead of the page. +function RouteErrorPage() { + const error = useRouteError(); + const notFound = isNotFound(error); + + return ( + + + {notFound ? : } + {notFound ? 'Page not found' : 'Something went wrong'} + + {notFound + ? 'There is no page at this address.' + : 'An unexpected error occurred. Reload the page, or go back to the home page.'} + + + {/* The error's details help while developing; a deployed app never shows them. */} + {import.meta.env.DEV && ( +
+          {errorDetails(error)}
+        
+ )} + + {/* A reload can recover from a thrown error; on a 404 it repeats the miss. */} + + + +
+ ); +} + +// Runs in production too: a thrown object's getter (e.g. `status`) can throw, then it's a plain error. +function isNotFound(error: unknown): boolean { + try { + return isRouteErrorResponse(error) && error.status === 404; + } catch { + return false; + } +} + +function errorDetails(error: unknown): string { + try { + if (isRouteErrorResponse(error)) { + const data = typeof error.data === 'string' ? `\n${error.data}` : ''; + return `${error.status} ${error.statusText}${data}`; + } + if (error instanceof Error) return error.stack ?? error.message; + return String(error); + } catch { + // String() throws for a value without toString (Object.create(null)), and so can a getter on it. + return "The error can't be shown as text."; + } +} + function NotFoundPage() { const { pathname } = useLocation();