Skip to content

Commit bae3b7a

Browse files
Use React Router framework mode + SPA mode (#3400)
https://reactrouter.com/how-to/spa The behavior and basic architecture of the console is unchanged: we're still a fully static SPA served by Nexus. This PR just changes how our route files are hooked up to the router. The point of this is to 1. fix hot reloading, and 2. get more type safety around stuff like path params through RR framework mode's route typegen. Hot reloading was broken because our route modules export `clientLoader` and `handle` next to the component. React Fast Refresh only accepts modules whose exports are all components, so editing any page triggered a full reload. The framework's Vite plugin knows about route exports and hot-updates them itself ([RR docs on supported exports](https://github.com/remix-run/react-router/blob/7ccdcec/docs/explanation/hot-module-replacement.md#L61-L68)). We could have fixed hot reloading without using framework mode, but it would have be just as long of a PR and we wouldn't get the typegen. ### Changes - **Routes move from `app/routes.tsx` (JSX `<Route>` tree with `lazy` + `convert`) to `app/routes.ts`** using the framework route helpers. Routes that had an inline `handle`, an index redirect, or a reused component with a different crumb now point at small modules in `app/routes/`, since in framework mode a route's `handle` and loader have to come from the module. - **Loaders take typed params.** Every `clientLoader` uses the generated `Route.ClientLoaderArgs` and destructures the keys it needs instead of calling a `getXSelector` helper. We destructure these params on purpose in order to pass on only what we need: `params` also holds child-route params, and two query builders (`routeList`, `instanceNetworkInterfaceList`) pass their argument through as the API query, so passing `params` whole would add e.g. `route=x` to the request and the cache key and break the prefetch. AGENTS.md has a line about this. - **`pb` helpers use typed `href()`**, so paths and params are checked against the route config. We could in theory ditch `pb` altogether and just inline the paths, but I think it's still worth keeping. - **`index.html` is gone.** `root.tsx` renders the document, and `npm run build` prerenders it at build time. This requires binding a localhost port during the build (noted in AGENTS.md for sandboxed agents). - **CSP:** Nexus only allows external scripts, but the framework emits inline bootstrap scripts. A `buildEnd` step (`tools/externalize-spa-scripts.ts`) moves each one into a hashed file under `assets/`, and `entry.client.tsx` empties those tags back out after they run so hydration sees the DOM shape React Router expects. - **Build output moves from `dist/` to `build/client/`.** React Router always writes the client build to `<buildDirectory>/client`, so CI, Vercel, `npm run preview`, and the docs now point there. The tarball is built from inside that directory, so the layout Nexus sees is unchanged. Sourcemaps still ship, same as main. - **`routeDiscovery: 'initial'`**: by default, framework mode uses [lazy route discovery](https://github.com/remix-run/react-router/blob/266915e/docs/explanation/lazy-route-discovery.md#L12-L23). The initial page load gets only the route manifest entries for the current URL, and the client fetches the rest from a `/__manifest` server endpoint as you navigate. That's an optimization for apps with a lot of routes. We don't have that many, and Nexus doesn't serve that endpoint anyway, so `initial` mode puts the whole manifest in the initial load (see the bundle comparison below for its size). - **Tailwind's source scan is limited to `app/`** (plus the design system), because watched Markdown elsewhere in the repo was triggering full reloads. This drops only `.shadow`, `.!filter`, and `.[commit:string]`, which were picked up from words in `flake.nix`, an e2e test, and a deno tool. This could be done separately from this PR but it was relevant here because it reduces the number events that trigger reloads. - Deleted the `loader` export in `OxqlMetric.tsx`. It was dead on main too: added in #2654, but nothing ever imported it. - Fixed the `API_MODE` error message, which said the default is `msw` when it's `nexus`. ### How we checked it Opus 5.5 did the following during review: - **Routes:** compared `app/routes.ts` against main's `routes.tsx` route by route: nesting, index redirects, crumbs, IDs on reused modules, and the old `element={null}` routes. Everything matches. - **Pages and forms:** compared every page and form against main. No exports were lost, moved validators are byte-identical, and every re-exported loader gets the params it needs where it's mounted. - **Path builder:** checked every URL. They're all identical to main and the snapshot is unchanged. `path-builder.spec.ts` now builds its routes from the real framework config and module handles instead of the old JSX tree. - **Prod build under CSP:** served the MSW preview build with the same CSP header Nexus sends and loaded deep links in headless Chromium. No CSP violations, hydration errors, or page errors. Index redirects, breadcrumbs, page titles, client-side navigation, and the 404 page all work. - **HMR:** edited `ProjectsPage.tsx`, which exports `clientLoader` and `handle`, with the create form open. It hot-updated without a full reload, and text typed into the form survived. - **Theme test:** the pre-hydration tests in `theme.e2e.ts` check that `theme-init.js` sets the theme before React loads. They do this by blocking the app's entry script, which is now `entry.client.tsx` instead of `main.tsx`. On main, the tests confirmed the block worked by asserting that `#root` was empty, but the framework's document has no `#root`. Now they wait for the blocked request to fail instead. If the entry file is renamed again, the block stops matching and the tests fail, rather than letting React load and passing without testing anything. ### Bundle compared with main (Nexus build) | | main | this PR | | ------------ | ------------------- | ------------------- | | Files | 532 | 832 | | JS files | 258 | 419 | | JS raw | 2.53 MB | 2.83 MB | | JS gzipped | 844 KB | 903 KB | | Initial load | 15 files, 219 KB gz | 41 files, 241 KB gz | - Most of the extra files come from route-module splitting, which is on by default in RR 8.4: 87 `*-client-loader-*` chunks and 24 `*-main-*` chunks, so a route's loader can start fetching before its component code arrives. About 34 more are the tiny route stubs in `app/routes/`. Most are under 1 KB. `splitRouteModules: false` turns splitting off if the file count is a problem. - No module appears in more than one chunk, and the largest chunks are the same as before (SerialConsolePage 350 KB, silo-create 200 KB, DateTimeRangePicker 181 KB). - The one new big file is the route manifest: 260 KB raw, 16.5 KB gzipped, loaded on every page load because of `routeDiscovery: 'initial'`. ### Known dev-only quirk Index routes that re-export a tab's `clientLoader` (`vpc-index`, `sled-index`, `inventory-index`, `alerting-index`, `affinity-create`) keep the old loader after you edit that tab until a full reload. Typechecking breadcrumb params against each route's params will come in a followup PR. --------- Co-authored-by: Joe Thel <[email protected]>
1 parent b950339 commit bae3b7a

132 files changed

Lines changed: 2538 additions & 1530 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/upload-assets.yaml‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,14 @@ jobs:
2323
- name: Build for Nexus
2424
run: SHA=${{ github.sha }} npm run build
2525
- name: Gzip individual files (keep originals)
26-
run: ls dist/assets/*.{js,css,map} | xargs gzip --keep
26+
run: ls build/client/assets/*.{js,css,map} | xargs gzip --keep
2727
- name: add console_version file
28-
run: echo ${{ github.sha }} > dist/VERSION
28+
run: echo ${{ github.sha }} > build/client/VERSION
2929
- name: add API_VERSION file
30-
run: cp app/api/__generated__/API_VERSION dist/API_VERSION
30+
run: cp app/api/__generated__/API_VERSION build/client/API_VERSION
3131
- run: mkdir -p releases/console
3232
- name: Make <sha>.tar.gz
33-
run: tar czf releases/console/${{ github.sha }}.tar.gz --directory=dist .
33+
run: tar czf releases/console/${{ github.sha }}.tar.gz --directory=build/client .
3434
- name: Write sha256sum to file
3535
run: sha256sum releases/console/${{ github.sha }}.tar.gz | awk '{print $1}' > releases/console/${{ github.sha }}.sha256.txt
3636
- name: Upload files to GCP bucket

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,6 @@ playwright-report/
3737
# Visual regression snapshots
3838
test/visual/**/*-snapshots/
3939
test/visual/**/*.png
40+
41+
# React Router build output. build/client is the deployable static site
42+
/build/

‎.oxfmtrc.json‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,12 @@
1919
]
2020
},
2121
"experimentalSortPackageJson": false,
22-
"ignorePatterns": ["dist/**", "coverage/**", "templates/**", "mockServiceWorker.js"]
22+
"ignorePatterns": [
23+
"dist/**",
24+
"build/**",
25+
".react-router/**",
26+
"coverage/**",
27+
"templates/**",
28+
"mockServiceWorker.js"
29+
]
2330
}

‎.oxlintrc.json‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,10 @@
114114
"app/pages/**/*",
115115
"app/layouts/**/*",
116116
"app/forms/**/*",
117+
"app/routes/**/*",
118+
"app/routes.ts",
119+
"app/root.tsx",
120+
"app/entry.server.tsx",
117121
"*.config.ts",
118122
"*.config.mjs",
119123
"test/e2e/compact-reporter.ts"
@@ -125,6 +129,7 @@
125129
{
126130
"files": [
127131
"**/*.spec.ts",
132+
"app/entry.server.tsx",
128133
"**/*.config.ts",
129134
"**/*.config.mjs",
130135
"tools/**/*",
@@ -154,5 +159,5 @@
154159
}
155160
}
156161
],
157-
"ignorePatterns": ["dist/", "node_modules/", ".claude/"]
162+
"ignorePatterns": ["dist/", "build/", ".react-router/", "node_modules/", ".claude/"]
158163
}

‎AGENTS.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
npm run dev
1313
```
1414

15+
- `npm run build` renders `index.html` through a temporary local preview server, so it needs to bind a localhost port. If you're running in a sandbox that blocks local port binding, the build fails at the prerender step with `listen EPERM`; run it outside the sandbox.
16+
1517
# React & TypeScript conventions
1618

1719
- Use `useEffect` as a last resort. Try to find a non-effect version first; see https://react.dev/learn/you-might-not-need-an-effect.md for the hard cases.
@@ -83,8 +85,8 @@
8385

8486
# Routing
8587

86-
- Add routes in `app/routes.tsx`, using `lazy(() => import(...).then(convert))` so loaders become `clientLoader` and components stay tree-shakeable.
87-
- Export navigation helpers via `pb` in `app/util/path-builder.ts`; every new route should get a path-builder entry and appear in `app/util/path-builder.spec.ts`'s snapshot.
88+
- Add routes in `app/routes.ts` with React Router framework route helpers. Route files export a default component, `clientLoader`, and `handle` as needed. Use the local `empty()` helper for outlet-only routes; breadcrumb-bearing routes need a module exporting `handle`. Keep ordinary helper functions out of route exports so Fast Refresh can accept them.
89+
- Export navigation helpers via `pb` in `app/util/path-builder.ts`, using typed `href()` calls. Every new route should get a path-builder entry and appear in `app/util/path-builder.spec.ts`'s snapshot.
8890
- Breadcrumbs come from route `handle.crumb`; use `makeCrumb`/`titleCrumb` and provide a `path` when the parent route redirects (`app/hooks/use-crumbs.ts`). Use `titleCrumb` for side modal forms that should appear in page title but not nav breadcrumbs (check `Crumb.titleOnly` flag).
8991
- When adding tabs or redirects, wire the canonical link in the path builder (e.g., point to the default tab) and update the sidebar/quick actions as needed.
9092
- For tabs synced with the URL, use `QueryParamTabs` (`app/components/QueryParamTabs.tsx`).
@@ -119,7 +121,8 @@
119121

120122
# Route params & loaders
121123

122-
- Wrap `useParams` with the provided selectors (`useProjectSelector`, `useInstanceSelector`, etc.) so required params throw during dev and produce memoized results safe for dependency arrays (`app/hooks/use-params.ts`).
124+
- In route modules, use generated `Route.ClientLoaderArgs` and `Route.ComponentProps` from `./+types/<module>` for typed params. Shared components can keep the selector hooks (`useProjectSelector`, `useInstanceSelector`, etc.) for scoped params and memoized objects. Run `npm run tsc` to regenerate route types after changing the route config.
125+
- In loaders, destructure the params you need (`const { project, vpc } = params`) rather than passing `params` through. It also holds params from child routes, which TypeScript won't flag as extra keys, and a query builder that forwards its argument as the API query would add them to the request and the cache key, so the component's query misses the prefetch.
123126
- Prefer `queryClient.fetchQuery` inside `clientLoader` blocks when the page needs data up front, and throw `trigger404` on real misses so the error boundary renders Not Found.
124127

125128
# UI components & styling

‎README.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ At https://console-preview.oxide.computer, the console is deployed as a static s
2525

2626
![console client-server architecture diagram](docs/architecture-browser-only.svg)
2727

28-
In order to avoid the complexity of server-side rendering (and running JS on the rack), the web console is a fully client-side React app. We use Vite (which uses Rollup internally for production builds) to build a set of assets (`index.html`, JS bundles, CSS, fonts, images) and we serve those assets as static files from a special set of console endpoints in Nexus. From the control plane API server's point of view, the web console simply is:
28+
In order to avoid the complexity of server-side rendering (and running JS on the rack), the web console is a fully client-side React app. We use React Router framework mode with `ssr: false` and Vite to build a set of assets (`index.html`, JS bundles, CSS, fonts, images) and we serve those assets as static files from a special set of console endpoints in Nexus. From the control plane API server's point of view, the web console simply is:
2929

3030
- a directory of static assets and some endpoints that serve them
3131
- a few other endpoints to handle auth actions like login/logout
@@ -46,7 +46,11 @@ The web console has no special privileges as an API consumer. Logging in sets a
4646

4747
## Directory structure
4848

49-
The app is in [`app`](app). You can see the route structure in [`app/routes.tsx`](app/routes.tsx). Also in [`app`](app) we have a [`ui`](app/ui) dir where the low-level components live and an [`api`](app/api) dir where we keep the generated API client and a React Query wrapper for it. The latter is aliased in [`tsconfig.json`](tsconfig.json) for easy import from the main app as `@oxide/api`.
49+
The app is in [`app`](app). You can see the route structure in [`app/routes.ts`](app/routes.ts). Also in [`app`](app) we have a [`ui`](app/ui) dir where the low-level components live and an [`api`](app/api) dir where we keep the generated API client and a React Query wrapper for it. The latter is aliased in [`tsconfig.json`](tsconfig.json) for easy import from the main app as `@oxide/api`.
50+
51+
The framework generates route types in `.react-router/types`. `npm run tsc` regenerates them before checking TypeScript, and the dev server updates them as routes change. Route modules use `Route.ClientLoaderArgs` and `Route.ComponentProps` from their generated `./+types/<module>` import. The `pb` helpers use typed `href()` calls so paths and parameters are checked against the route config.
52+
53+
`npm run build` prerenders the root shell at build time and writes the static site to `build/client/`, with the same flat layout Nexus has always served. The build moves inline framework bootstrap scripts into hashed files under `assets/` to preserve the production CSP. After those scripts execute, `entry.client.tsx` restores their empty DOM shape before React hydrates. `npm run preview` exercises this static output with the same CSP; check for hydration and CSP errors when upgrading React Router. There is no runtime server-rendering service.
5054

5155
## Development
5256

‎app/api/__tests__/safety.spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ it('mock-api is only referenced in test files', () => {
9898
"AGENTS.md",
9999
"README.md",
100100
"app/api/__tests__/client.browser.spec.ts",
101-
"app/main.tsx",
101+
"app/entry.client.tsx",
102102
"app/msw-mock-api.ts",
103103
"docs/mock-api-differences.md",
104104
"docs/update-pinned-api.md",

‎app/components/MswBanner.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ function ExternalLink({ href, children }: { href: string; children: ReactNode })
3636
* is off, the variable stays at its 0px default (set in index.css) and the
3737
* offsets collapse to nothing, so consumers don't need their own conditionals.
3838
*
39-
* Rendered once in main.tsx, outside the router, so the same banner instance
39+
* Rendered once in the root document layout, so the same banner instance
4040
* persists across hydration (skeleton to real page) and error states.
4141
*/
4242
export function PreviewBannerLayout({ children }: { children: ReactNode }) {

‎app/components/oxql-metrics/OxqlMetric.tsx‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,12 @@
1313

1414
import { useQuery } from '@tanstack/react-query'
1515
import { Children, useMemo, useState, type ReactNode } from 'react'
16-
import type { LoaderFunctionArgs } from 'react-router'
1716

18-
import { api, OXQL_GROUP_BY_ERROR, q, queryClient } from '@oxide/api'
17+
import { api, OXQL_GROUP_BY_ERROR, q } from '@oxide/api'
1918

2019
import { CopyCodeModal } from '~/components/CopyCode'
2120
import { MoreActionsMenu } from '~/components/MoreActionsMenu'
22-
import { getInstanceSelector, useProjectSelector } from '~/hooks/use-params'
21+
import { useProjectSelector } from '~/hooks/use-params'
2322
import { LearnMore } from '~/ui/lib/CardBlock'
2423
import * as Dropdown from '~/ui/lib/DropdownMenu'
2524
import { classed } from '~/util/classed'
@@ -40,14 +39,6 @@ import {
4039
type OxqlQuery,
4140
} from './util'
4241

43-
export async function loader({ params }: LoaderFunctionArgs) {
44-
const { project, instance } = getInstanceSelector(params)
45-
await queryClient.prefetchQuery(
46-
q(api.instanceView, { path: { instance }, query: { project } })
47-
)
48-
return null
49-
}
50-
5142
export type OxqlMetricProps = OxqlQuery & {
5243
title: string
5344
description?: string

‎app/entry.client.tsx‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
* This Source Code Form is subject to the terms of the Mozilla Public
3+
* License, v. 2.0. If a copy of the MPL was not distributed with this
4+
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
5+
*
6+
* Copyright Oxide Computer Company
7+
*/
8+
import { StrictMode, startTransition } from 'react'
9+
import { hydrateRoot } from 'react-dom/client'
10+
import { HydratedRouter } from 'react-router/dom'
11+
12+
import { startMockAPI } from './msw-mock-api'
13+
14+
if (process.env.SHA) {
15+
console.info(
16+
'Oxide Web Console version',
17+
`https://github.com/oxidecomputer/console/commits/${process.env.SHA}`
18+
)
19+
}
20+
21+
async function hydrate() {
22+
// Initial route loaders must wait for the worker and its database to be ready.
23+
if (process.env.MSW) await startMockAPI()
24+
if (import.meta.env.PROD) {
25+
// Wait for the parser's blocking bootstrap scripts to finish before hydration.
26+
if (document.readyState === 'loading') {
27+
await new Promise<void>((resolve) => {
28+
document.addEventListener('DOMContentLoaded', () => resolve(), { once: true })
29+
})
30+
}
31+
// The build moves inline script bodies into assets to satisfy CSP. They have
32+
// already run; restore the empty DOM shape expected by React Router's Scripts
33+
// component so it can hydrate normally without executing any inline code.
34+
for (const script of document.querySelectorAll<HTMLScriptElement>(
35+
'script[data-spa-script]'
36+
)) {
37+
script.removeAttribute('src')
38+
script.removeAttribute('data-spa-script')
39+
script.textContent = ' '
40+
}
41+
}
42+
startTransition(() => {
43+
hydrateRoot(
44+
document,
45+
<StrictMode>
46+
<HydratedRouter />
47+
</StrictMode>
48+
)
49+
})
50+
}
51+
52+
hydrate()

0 commit comments

Comments
 (0)