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
14 changes: 8 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
| `containers/MetricOverviewContainer.jsx` | `${dashboardSource}/${activeRegion}/${slug}/index.json` | title, description, `type: 'line'|'table'`, axes, columns, data, annotations |
| `containers/SummaryMetricContainer.jsx` | same per-metric endpoint | buckets populations under 5% into "Other" |

`src/lib/withFetch.jsx` **is the entire data layer** and is used in exactly those three files: `withFetch(props => url)(Container)` passes a `dataFetch` prop (`pending`, `rejected`, `fulfilled`, `value`, `reason`), refetches when the URL changes (back to pending first), rejects on non-2xx, and drops a response that arrives after a newer request started. Each one handles `dataFetch.pending` / `.rejected` / `.fulfilled` itself: `DashboardContainer` renders `views/Spinner.jsx` while pending, the two metric containers render nothing (the chart's own spinner shows instead), and all three render `views/Error.jsx` on rejection. All reshaping is client-side, in the `formatData` of `ChartContainer`, `DataTableContainer`, and `SummaryMetricContainer` (`ChartContainer` sorts populations by max y and drops nulls; `DataTableContainer` sorts rows by value descending).
`src/lib/withFetch.jsx` **is the entire data layer** and is used in exactly those three files: `withFetch(props => url)(Container)` passes a `dataFetch` prop (`pending`, `rejected`, `fulfilled`, `value`, `reason`), refetches when the URL changes (back to pending first), rejects on non-2xx, and drops a response that arrives after a newer request started. Responses are kept in `lib/fetchCache.js` until the page reloads: a URL fetched before is fulfilled from the first render, components asking for one URL at once share a request, and a failed request is forgotten so the next one tries again. Each one handles `dataFetch.pending` / `.rejected` / `.fulfilled` itself: `DashboardContainer` renders `views/Spinner.jsx` while pending, the two metric containers render a same-sized placeholder (`views/MetricOverviewPlaceholder.jsx`, `views/SummaryMetricPlaceholder.jsx`) so nothing moves when the data arrives, and all three render `views/Error.jsx` on rejection. All reshaping is client-side, in the `formatData` of `ChartContainer`, `DataTableContainer`, and `SummaryMetricContainer` (`ChartContainer` sorts populations by max y and drops nulls; `DataTableContainer` sorts rows by value descending).

Metric `description` strings are rendered as inline Markdown through `markdown-it('zero')` with only `link` and `entity` enabled plus the `markdown-it-sup` plugin, via `dangerouslySetInnerHTML`. The dashboard description in `views/Dashboard.jsx` enables only `emphasis`. `src/tests/jest/MetricOverview.test.jsx` exists **specifically to guard that sanitization** — never widen the enabled-rules list without extending that test.

Expand All @@ -34,14 +34,15 @@ src/
├── components/
│ ├── containers/ 6 stateful/data-fetching .jsx
│ ├── decorators/ withTracker.jsx (GA4 via react-ga4), withNextButton.jsx
│ └── views/ 20 presentational .jsx
│ └── views/ 22 presentational .jsx
│ ├── styl/ Stylus SOURCE (hand-edited); includes/lib.styl
│ ├── css/ GENERATED, GITIGNORED — holds only a README stub
│ ├── fonts/FiraSans/ 8 weights/styles of webfonts
│ └── img/ 3 assets
├── lib/
│ ├── lazyLoad.jsx React.lazy wrapper
│ ├── LazyBoundary.jsx error boundary + spinner for lazy-loaded components
│ ├── fetchCache.js withFetch's responses by URL, kept until the page reloads
│ ├── lazyLoad.jsx lazyLoad(() => import(…)): starts loading now, renders loaded code without suspending
│ ├── LazyBoundary.jsx error boundary + spinner for lazy-loaded components; a failed chunk offers a reload
│ ├── withFetch.jsx the data layer: fetches JSON and passes `dataFetch` to containers
│ └── utils.js bumpSort, isFloat, prettifyNumber, getPageTitle
└── tests/
Expand Down Expand Up @@ -101,7 +102,7 @@ Run one Vitest file: `npx vitest run src/tests/jest/Dashboard.test.jsx`. Run one
- **PascalCase filenames matching the default-exported component.** Decorators are camelCase with a `with` prefix; `lib/lazyLoad.jsx` and `lib/withFetch.jsx` are camelCase because they are helpers, not components.
- **One component per file, always `export default`.** There are no named component exports anywhere in the repo; the only named exports at all are the four helpers in `lib/utils.js` and `unregister` in `registerServiceWorker.js`.
- **The container/view split is the organizing principle.** `containers/X.jsx` holds state and fetching and renders `views/X.jsx` with formatted props (`ChartContainer`→`Chart`, `DataTableContainer`→`DataTable`). Keep new state out of `views/`.
- Function components are the default (15 of 20 views), written as anonymous default-exported arrows — `export default props => (...)` — with no `displayName` (hence `react/display-name: off`). The router is react-router 7, imported from `react-router` (not `react-router-dom`), and read with its `useLocation()` hook, in `views/Main.jsx` and both decorators (`withTracker` sends its page view from a `useEffect` on the pathname). Use a class only where state, refs, or lifecycle are genuinely needed: all 6 containers plus `SummaryMetric.jsx` (d3 + `React.createRef`), `ObservablePlot.jsx` (Observable Plot + `React.createRef`), `Spinner.jsx`, `MetricOverview.jsx`, `Footer.jsx`, and `lib/LazyBoundary.jsx` (error boundaries must be classes).
- Function components are the default (17 of 22 views), written as anonymous default-exported arrows — `export default props => (...)` — with no `displayName` (hence `react/display-name: off`). The router is react-router 7, imported from `react-router` (not `react-router-dom`), and read with its `useLocation()` hook, in `views/Main.jsx` and both decorators (`withTracker` sends its page view from a `useEffect` on the pathname). Use a class only where state, refs, or lifecycle are genuinely needed: all 6 containers plus `SummaryMetric.jsx` (d3 + `React.createRef`), `ObservablePlot.jsx` (Observable Plot + `React.createRef`), `Spinner.jsx`, `MetricOverview.jsx`, `Footer.jsx`, and `lib/LazyBoundary.jsx` (error boundaries must be classes).
- Leading underscore for private class-property handlers (`_onRegionChange`, `_drawChart`, `_setChartSize`). Keep using it in new code.
- Locals named `maybeX` hold a JSX fragment **or `null`** (`maybeDescription`, `maybeSummaryMetrics`, `maybeRegion`, `maybeGraphURL`). Keep the idiom.
- Styles attach via a global CSS side-effect import of the **generated** file at the top of the component: `import './css/Dashboard.css';`. Some components import several (`Chart.jsx` pulls `./css/Chart.css` and `./css/Metric.css`). `Metric.css` and `LabelledSelector.css` are shared partials with no component of their own.
Expand Down Expand Up @@ -147,7 +148,7 @@ This applies to everything written for a person to read: ExecPlans, PR descripti

**Vitest + React Testing Library**, configured in the `test` block of `vite.config.mjs` (`jsdom`, `globals: true`, `include: ['src/tests/jest/**/*.test.jsx']`). Files live in `src/tests/jest/`, named after the module under test (`Dashboard.test.jsx`, `withFetch.test.jsx`) — **not colocated, no `__tests__` directories.** JSX uses the automatic runtime, so neither components nor tests import React just for JSX; tests import `render`, `screen`, and `waitFor` from `@testing-library/react`. `src/setupTests.js` registers the jest-dom matchers (`toHaveTextContent`, `toBeInTheDocument`), and **fails any test that calls `console.error` unexpectedly**, so React warnings surface as failures — a test that expects an error replaces `console.error` with `vi.spyOn(console, 'error').mockImplementation(() => {})`. Tests render the real component tree into jsdom and assert on the DOM (`container.querySelector('#dashboard-description')`, or `innerHTML` where the markup itself is the point, as in the sanitization test). Existing style is top-level `it(...)` with long descriptive sentences. No snapshots.

- **Stubbing the network:** `withFetch` calls `window.fetch(new Request(url, …))` each time it fetches. Stub it with `fetchMock = vi.spyOn(window, 'fetch')` in `beforeEach` (`setupTests.js`'s `vi.restoreAllMocks()` undoes it) and read URLs from `fetchMock.mock.calls[n][0].url`. The container tests (`SummaryMetricContainer.test.jsx` is the simplest) show the pattern.
- **Stubbing the network:** `withFetch` calls `window.fetch(new Request(url, …))` once per URL, then answers from `fetchCache`, which `setupTests.js` clears after each test. Stub it with `fetchMock = vi.spyOn(window, 'fetch')` in `beforeEach` (`setupTests.js`'s `vi.restoreAllMocks()` undoes it) and read URLs from `fetchMock.mock.calls[n][0].url`. The container tests (`SummaryMetricContainer.test.jsx` is the simplest) show the pattern.
- **Waiting for lazy routes:** wait with React Testing Library's `waitFor` / `findBy*`, never `vi.waitFor`. RTL turns off React's act() check while it waits, so a `React.lazy` component can resolve. Under `vi.waitFor`, or after a test that returns while a lazy route is still loading, React 18 logs "A suspended resource finished loading inside a test, but the event was not wrapped in act(...)", and the console.error trap turns that into an unhandled error that fails the run.
- **Testing data shaping:** containers that hand formatted props to a view that needs real layout (`views/Chart` → Observable Plot, `views/SummaryMetric` → d3) are tested by replacing the view with `vi.mock('../../components/views/Chart', () => ({ default: vi.fn(() => null) }))` and asserting on the props it was last called with. Views that are plain markup (`views/DataTable`) render for real.
- **Testing chart views:** `Chart.test.jsx` renders the real `views/Chart`, and Observable Plot draws real SVG in jsdom. It asserts on the drawn chart: `svg.scale('y').domain` for bounds, tick and label text, line `stroke`s against legend colors, and the `chart-*` classes on each mark's `<g>`. jsdom can't hover, so it sets `svg.value` and dispatches an `input` event, as Plot does, to check the readout. `SummaryMetric.test.jsx` renders the real d3 summary bar inside `<div id="application"><main>`, with `vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(490)` — jsdom reports 0px, and at 490px the bar draws at its 450px maximum, so segment widths are predictable.
Expand Down Expand Up @@ -179,6 +180,7 @@ In recorded mode, `fixtureData.js`'s `test` answers every `https://data.firefox.
| Gitignored `src/components/views/css/` | Fresh clone cannot resolve the CSS imports until `npm run build:css` runs. Never hand-edit `css/` — edit `styl/`. |
| Renaming a landmark ID | Breaks Playwright selectors silently. |
| `g.chart-line path` in a Playwright locator | A population with one data point, or a point with gaps on both sides, draws a zero-size line piece (shown as a dot, `g.chart-point circle`). A line breaks wherever its population skips a date that another population on the chart has. To check a chart drew, use `g.chart-line path` with `.filter({ visible: true }).first()`. Match a line to its population by its stroke color against the legend entry's color, not by index: a population with no points keeps its legend entry but draws no line. |
| A page heading without `data-page-heading` | After a navigation, `views/Main.jsx` moves focus to the new page's `[data-page-heading]` (which also needs `tabIndex={-1}`). A new page, or an error that stands in for one (`Error`'s `pageHeading` prop), without it leaves focus on `main`. `tests/playwright/specs/fixtures/navigation.spec.js` covers it. |
| Redrawing every chart on every resize event | Across the hardware dashboard's 11 charts, redrawing on each resize event froze the page for about a minute on live data (#409). `containers/ChartContainer.jsx` waits 150 ms after the last resize event; `tests/playwright/specs/fixtures/resize.spec.js` guards it. |
| `build:version.json` | Needs `build/` to already exist and `git` on PATH; must follow `build:app`. |
| `no-shadow` / `no-redeclare` with `builtinGlobals` | Naming a local `name`, `status`, `history`, `event` is a hard error. |
Expand Down
27 changes: 22 additions & 5 deletions docs/architecture/frontend.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,30 @@ and `LazyBoundary`), plus one `sessionStorage` key,
a higher-order component: `withFetch(props => url)(Container)` fetches the URL as JSON and passes
the container a `dataFetch` prop holding `pending`, `rejected`, `fulfilled`, `value`, and `reason`.
It refetches when the URL changes, going back to pending first, treats a non-2xx response as a
rejection, and ignores a response that arrives after a newer request has started. Each container
rejection, and ignores a response that arrives after a newer request has started. Responses are
kept in `src/lib/fetchCache.js` until the page reloads, so a page visited before shows its data on
the first render, and components asking for the same URL at once share one request. A failed
request isn't kept, so the next component to ask tries again. Each container
handles those states itself: `DashboardContainer` renders `views/Spinner.jsx` while pending, the
two metric containers render nothing (the chart's own spinner shows instead), and all three render
two metric containers render a placeholder the size of what will replace it
(`views/MetricOverviewPlaceholder.jsx`, `views/SummaryMetricPlaceholder.jsx`), and all three render
`views/Error.jsx` on rejection. All reshaping of fetched data happens client-side, in the
`formatData` method of `ChartContainer`, `DataTableContainer`, and `SummaryMetricContainer` — `ChartContainer` sorts
its populations by maximum y-value and drops nulls; `DataTableContainer` sorts rows by value,
descending.

## Moving between pages

`views/Main.jsx` does on each client-side navigation what a full page load would. A link
navigation scrolls to the top; Back and Forward keep the position the browser restores. After
every navigation but the first page load, focus moves to the new page's heading, the element
marked `data-page-heading` with `tabIndex={-1}`, so a screen reader reads it and Tab continues
from there. Until the heading renders, `main` holds focus, and the heading takes it on arrival
unless the reader has moved focus by then. Pages with no heading of their own, such as Home,
leave focus on `main`. Only the page-level spinners (route loading and `DashboardContainer`)
announce "Loading" to screen readers, through a `role="status"` region filled when the dots
appear; the metric and summary placeholders are hidden from them.

## Rendering metric descriptions: a real sanitization boundary

Metric `description` strings are rendered as inline Markdown and inserted via
Expand Down Expand Up @@ -108,14 +124,15 @@ these architecture docs.
├── components/
│ ├── containers/ 6 class components; 3 fetch via withFetch (above)
│ ├── decorators/ withTracker.jsx (GA4 via react-ga4), withNextButton.jsx
│ └── views/ 20 presentational .jsx files
│ └── views/ 22 presentational .jsx files
│ ├── styl/ Stylus source, hand-edited; includes/lib.styl holds shared variables
│ ├── css/ generated from styl/, gitignored — see CONTRIBUTING.md
│ ├── fonts/FiraSans/ 8 weights/styles of webfonts
│ └── img/ 3 assets
├── lib/
│ ├── lazyLoad.jsx wraps a dynamic import() in React.lazy
│ ├── LazyBoundary.jsx error boundary + Suspense fallback, paired with lazyLoad.jsx
│ ├── fetchCache.js withFetch's responses by URL, kept until the page reloads
│ ├── lazyLoad.jsx starts a dynamic import() now; renders the loaded code without suspending
│ ├── LazyBoundary.jsx error boundary + Suspense fallback; a failed chunk offers a page reload
│ ├── withFetch.jsx the data layer: fetches JSON and passes `dataFetch` to containers
│ └── utils.js bumpSort, isFloat, prettifyNumber, getPageTitle
└── tests/
Expand Down
3 changes: 2 additions & 1 deletion src/components/containers/DashboardContainer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class DashboardContainer extends React.Component {
const dataFetch = this.props.dataFetch;

if (dataFetch.pending) {
return <Spinner />;
return <Spinner label="Loading dashboard" />;
} else if (dataFetch.rejected) {
if (dataFetch.reason && dataFetch.reason.message) {
// eslint-disable-next-line no-console
Expand All @@ -36,6 +36,7 @@ class DashboardContainer extends React.Component {

return (
<ErrorComponent
pageHeading
id="dashboard-fetch-error"
title="Error fetching dashboard"
/>
Expand Down
28 changes: 6 additions & 22 deletions src/components/containers/MetricOverviewContainer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import withFetch from '../../lib/withFetch';

import ErrorComponent from '../views/Error';
import MetricOverview from '../views/MetricOverview';
import MetricOverviewPlaceholder from '../views/MetricOverviewPlaceholder';


class MetricOverviewContainer extends React.Component {
// If the data is changing, only re-render once the request settles, with
// either the new data or an error. Don't show a spinner while new data is
// being loaded, as that would cause the scrollbar to move.
// either the new data or an error, so that the chart already shown keeps
// its place instead of giving way to a placeholder.
//
// We do want the spinner to be shown on the initial render, but we don't
// need to do anything special here to handle that case because
// shouldComponentUpdate is not run for the initial render.
// shouldComponentUpdate is not run for the initial render, so the
// placeholder still shows while the first data loads.
shouldComponentUpdate(nextProps) {
return nextProps.dataFetch.fulfilled || nextProps.dataFetch.rejected;
}
Expand All @@ -22,23 +22,7 @@ class MetricOverviewContainer extends React.Component {
const dataFetch = props.dataFetch;

if (dataFetch.pending) {

// Metric data loads quickly, even over a bad connection. The
// ChartContainer component, however, is loaded next and can take
// several seconds to load over a bad connection.
//
// If we show both spinners, they should look the same. They should
// be positioned almost identically so that the user doesn't notice
// a difference when the second spinner replaces the first. That can
// be a little tricky. We also don't test against slow connections
// all that often, so that styling is prone to break over time as
// other changes are made.
//
// An easier solution is to not show this Spinner, since it's the
// shorter of the two, and show the ChartContainer spinner as
// normal.

return null;
return <MetricOverviewPlaceholder inSection={props.inSection} />;
} else if (dataFetch.rejected) {
if (dataFetch.reason && dataFetch.reason.message) {
// eslint-disable-next-line no-console
Expand Down
Loading
Loading