From 8019c1a1bbd9f88280a8332d9e63aa212a8b58c6 Mon Sep 17 00:00:00 2001 From: Stephanie Hobson Date: Mon, 16 Nov 2026 11:33:43 -0700 Subject: [PATCH 1/7] Reserve space for metrics and charts while they load (fix #509) Each metric rendered nothing until its data arrived, then a spinner the height of a few dots until its chart code arrived, so every chart that loaded pushed the rest of the page down. Summary bars also rendered nothing while loading, and collapsed again on every region change. Pending metrics and summary bars now render a placeholder the size of what replaces them, and the spinner while the chart code loads takes the chart's size. Only descriptions and legends, whose height isn't known until the data arrives, still move what's below them. --- AGENTS.md | 6 +- docs/architecture/frontend.md | 5 +- .../containers/MetricOverviewContainer.jsx | 28 ++----- .../containers/SummaryMetricContainer.jsx | 5 +- .../views/MetricOverviewPlaceholder.jsx | 17 ++++ .../views/SummaryMetricPlaceholder.jsx | 12 +++ src/components/views/styl/MetricOverview.styl | 15 ++++ src/components/views/styl/Spinner.styl | 4 - src/components/views/styl/SummaryMetric.styl | 8 ++ .../jest/MetricOverviewContainer.test.jsx | 11 +++ .../jest/SummaryMetricContainer.test.jsx | 11 +++ .../specs/fixtures/placeholders.spec.js | 79 +++++++++++++++++++ 12 files changed, 167 insertions(+), 34 deletions(-) create mode 100644 src/components/views/MetricOverviewPlaceholder.jsx create mode 100644 src/components/views/SummaryMetricPlaceholder.jsx create mode 100644 tests/playwright/specs/fixtures/placeholders.spec.js diff --git a/AGENTS.md b/AGENTS.md index 72941ed7..2e6a81d3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. 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. @@ -34,7 +34,7 @@ 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 @@ -101,7 +101,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. diff --git a/docs/architecture/frontend.md b/docs/architecture/frontend.md index d3be2055..d0e8b595 100644 --- a/docs/architecture/frontend.md +++ b/docs/architecture/frontend.md @@ -41,7 +41,8 @@ the container a `dataFetch` prop holding `pending`, `rejected`, `fulfilled`, `va 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 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, @@ -108,7 +109,7 @@ 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 diff --git a/src/components/containers/MetricOverviewContainer.jsx b/src/components/containers/MetricOverviewContainer.jsx index 07306c38..50ddf079 100644 --- a/src/components/containers/MetricOverviewContainer.jsx +++ b/src/components/containers/MetricOverviewContainer.jsx @@ -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; } @@ -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 ; } else if (dataFetch.rejected) { if (dataFetch.reason && dataFetch.reason.message) { // eslint-disable-next-line no-console diff --git a/src/components/containers/SummaryMetricContainer.jsx b/src/components/containers/SummaryMetricContainer.jsx index 8e988809..f0657729 100644 --- a/src/components/containers/SummaryMetricContainer.jsx +++ b/src/components/containers/SummaryMetricContainer.jsx @@ -2,6 +2,7 @@ import React from 'react'; import withFetch from '../../lib/withFetch'; import SummaryMetric from '../views/SummaryMetric'; +import SummaryMetricPlaceholder from '../views/SummaryMetricPlaceholder'; import ErrorComponent from '../views/Error'; @@ -86,9 +87,7 @@ class SummaryMetricContainer extends React.Component { const dataFetch = this.props.dataFetch; if (dataFetch.pending) { - // Don't show a spinner for the same reason we don't show a spinner - // when metric data is loading. See MetricOverviewContainer.jsx. - return null; + return ; } else if (dataFetch.rejected) { if (dataFetch.reason && dataFetch.reason.message) { // eslint-disable-next-line no-console diff --git a/src/components/views/MetricOverviewPlaceholder.jsx b/src/components/views/MetricOverviewPlaceholder.jsx new file mode 100644 index 00000000..a16424a7 --- /dev/null +++ b/src/components/views/MetricOverviewPlaceholder.jsx @@ -0,0 +1,17 @@ +import Spinner from './Spinner'; +import StripedHeader from './StripedHeader'; + +import './css/MetricOverview.css'; + + +// Holds a metric's place while its data loads, at the height of its title and +// chart, so that the metrics below it don't move when it arrives. The title is +// a non-breaking space so that the header keeps its full height. +export default props => ( + +); diff --git a/src/components/views/SummaryMetricPlaceholder.jsx b/src/components/views/SummaryMetricPlaceholder.jsx new file mode 100644 index 00000000..1c37dd7b --- /dev/null +++ b/src/components/views/SummaryMetricPlaceholder.jsx @@ -0,0 +1,12 @@ +import './css/SummaryMetric.css'; + + +// Holds a summary metric's place while its data loads, at the size of its +// title and bar, so that the others beside it don't move when it arrives. The +// bar is an empty SVG, so that it lines up as the real one does. +export default () => ( + +); diff --git a/src/components/views/styl/MetricOverview.styl b/src/components/views/styl/MetricOverview.styl index eba2c577..8097db1b 100644 --- a/src/components/views/styl/MetricOverview.styl +++ b/src/components/views/styl/MetricOverview.styl @@ -12,11 +12,26 @@ &:last-child { margin-bottom: 0; } + // As wide as main, like the chart, so that the spinner holding the + // chart's place can be as big as the chart. Stretching it instead would + // come too late: its height is settled first, while it is still 0px wide. + .metric-and-legend { + width: 100%; + } .metric-and-legend > div { display: flex; flex-wrap: wrap; justify-content: center; } + // The chart's size, from ChartContainer: as wide as main, and square up + // to 400px tall, below the 20px margin and 28px readout line above it. + .metric-and-legend > .spinner { + align-items: center; + aspect-ratio: 1; // @stylint ignore + margin-top: 48px; + max-height: 400px; + width: 100%; + } .legend { max-width: 1100px; diff --git a/src/components/views/styl/Spinner.styl b/src/components/views/styl/Spinner.styl index 9dc5ebc9..b8792dcc 100644 --- a/src/components/views/styl/Spinner.styl +++ b/src/components/views/styl/Spinner.styl @@ -14,7 +14,3 @@ main > .spinner { // @stylint ignore margin-top: 0; } } - -.metric-overview .spinner { // @stylint ignore - margin: 50px 0; -} diff --git a/src/components/views/styl/SummaryMetric.styl b/src/components/views/styl/SummaryMetric.styl index e241b2a3..ddce6422 100644 --- a/src/components/views/styl/SummaryMetric.styl +++ b/src/components/views/styl/SummaryMetric.styl @@ -2,3 +2,11 @@ .bar-arrow { display: none; } + +// The size SummaryMetric draws its bar at: as wide as main, up to 450px. main +// is only narrower than 450px on small screens, where it is 95vw wide. +.summary-metric-placeholder-bar { + height: 90px; + max-width: 95vw; + width: 450px; +} diff --git a/src/tests/jest/MetricOverviewContainer.test.jsx b/src/tests/jest/MetricOverviewContainer.test.jsx index 26d1536e..f79b27d1 100644 --- a/src/tests/jest/MetricOverviewContainer.test.jsx +++ b/src/tests/jest/MetricOverviewContainer.test.jsx @@ -43,6 +43,17 @@ it('Requests the metric for the dashboard source, region, and slug', async () => expect(fetchMock.mock.calls[0][0].url).toBe('https://data.example/user-activity/Worldwide/daily-usage/index.json'); }); +it('While the first request is in flight, a placeholder hidden from screen readers holds the metric\'s place', async () => { + const { container } = renderForRegion('Worldwide'); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + + const placeholder = container.querySelector('.metric-overview-placeholder'); + expect(placeholder).toHaveAttribute('aria-hidden', 'true'); + expect(placeholder.querySelector('h4.striped')).toBeInTheDocument(); + expect(placeholder.querySelector('.metric-and-legend > .spinner')).toBeInTheDocument(); + expect(container.querySelector('#metric-overview-1')).toBeNull(); +}); + it('When the request succeeds, the metric title is rendered', async () => { renderForRegion('Worldwide'); await waitFor(() => expect(fetchMock).toHaveBeenCalled()); diff --git a/src/tests/jest/SummaryMetricContainer.test.jsx b/src/tests/jest/SummaryMetricContainer.test.jsx index 8f4f0659..291e283c 100644 --- a/src/tests/jest/SummaryMetricContainer.test.jsx +++ b/src/tests/jest/SummaryMetricContainer.test.jsx @@ -46,6 +46,17 @@ it('Requests the summary metric for the active region', async () => { expect(fetchMock.mock.calls[0][0].url).toBe('https://data.example/hardware/Worldwide/gpu-vendor/index.json'); }); +it('While the request is in flight, a placeholder hidden from screen readers holds the summary metric\'s place', async () => { + fetchMock.mockReturnValue(new Promise(() => {})); + + const { container } = renderSummaryMetric(); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + + expect(container.querySelector('.summary-metric')).toHaveAttribute('aria-hidden', 'true'); + expect(container.querySelector('.summary-metric svg.summary-metric-placeholder-bar')).toBeInTheDocument(); + expect(SummaryMetric).not.toHaveBeenCalled(); +}); + it('A single population becomes a True/False split at the active date', async () => { respondWith({ title: 'Has Flash', diff --git a/tests/playwright/specs/fixtures/placeholders.spec.js b/tests/playwright/specs/fixtures/placeholders.spec.js new file mode 100644 index 00000000..a6611469 --- /dev/null +++ b/tests/playwright/specs/fixtures/placeholders.spec.js @@ -0,0 +1,79 @@ +const { test, expect, readFixture } = require('../../fixtureData'); + + +// A request that waits until the test lets it through, so the test can measure +// the page while it is still loading. +async function holdRequests(page, matcher, handler = route => route.fallback()) { + let release; + const released = new Promise(resolve => { + release = resolve; + }); + await page.route(matcher, async route => { + await released; + await handler(route); + }); + return release; +} + +async function box(locator) { + await expect(locator).toBeVisible(); + return locator.boundingBox(); +} + +function expectSameBox(actual, expected) { + for (const side of ['x', 'y', 'width', 'height']) { + expect(Math.abs(actual[side] - expected[side]), side).toBeLessThan(1); + } +} + +for (const width of [375, 1280]) { + test(`A chart's placeholder and spinner take the chart's space at ${width}px`, async ({ page }) => { + const dashboard = readFixture('user-activity/index.json'); + const slug = dashboard.metrics[0]; + const metricPath = `/user-activity/${dashboard.defaultCategory}/${slug}/index.json`; + // One population, so there is no legend, and no description, so the + // chart is all there is below the title. + const metric = readFixture(`user-activity/${dashboard.defaultCategory}/${slug}/index.json`); + delete metric.description; + await page.setViewportSize({ width, height: 900 }); + + const releaseMetric = await holdRequests( + page, + url => decodeURIComponent(url.pathname).endsWith(metricPath), + route => route.fulfill({ json: metric }) + ); + const releaseChartCode = await holdRequests(page, url => url.pathname.includes('ChartContainer')); + await page.goto('/dashboard/user-activity'); + + const placeholder = await box(page.locator('.metric-overview-placeholder').first()); + + releaseMetric(); + const metricOverview = page.locator('#metric-overview-1'); + await expect(metricOverview.locator('.metric-and-legend > .spinner')).toBeAttached(); + expectSameBox(await box(metricOverview), placeholder); + + releaseChartCode(); + await expect(metricOverview.locator('g.chart-line path').filter({ visible: true }).first()).toBeVisible(); + expectSameBox(await box(metricOverview), placeholder); + }); + + test(`A summary metric's placeholder takes the summary metric's space at ${width}px`, async ({ page }) => { + const dashboard = readFixture('hardware/index.json'); + const slug = dashboard.summaryMetrics[0]; + await page.setViewportSize({ width, height: 900 }); + + const releaseSummaryMetric = await holdRequests( + page, + url => decodeURIComponent(url.pathname).endsWith(`/hardware/default/${slug}/index.json`) + ); + await page.goto('/dashboard/hardware'); + + const firstSummaryMetric = page.locator('#summary-metrics .summary-metric').first(); + await expect(firstSummaryMetric).toHaveAttribute('aria-hidden', 'true'); + const placeholder = await box(firstSummaryMetric); + + releaseSummaryMetric(); + await expect(firstSummaryMetric.locator('rect.bar').first()).toBeAttached(); + expectSameBox(await box(firstSummaryMetric), placeholder); + }); +} From dcf3ae01f460eeae483235b77cc35e7be789ddce Mon Sep 17 00:00:00 2001 From: Stephanie Hobson Date: Mon, 16 Nov 2026 11:33:49 -0700 Subject: [PATCH 2/7] Keep the footer at the bottom of the window (#509) On short pages like Contact and Not Found, the footer sat just below the content, part way up the window. The page is now a column at least as tall as the window, with main taking the spare height. While a dashboard loads, main is also at least as tall as the window, so the footer stays out of sight instead of jumping off the screen when the dashboard arrives. That jump was the largest layout shift left on every dashboard. The gap above the header moves from a relative offset to padding, so that it counts toward the page's height instead of making every page scroll by it. --- src/components/views/Main.jsx | 2 +- src/components/views/styl/Application.styl | 19 +++++++++++++++-- .../specs/fixtures/placeholders.spec.js | 13 ++++++++++++ tests/playwright/specs/footer.spec.js | 21 +++++++++++++++---- 4 files changed, 48 insertions(+), 7 deletions(-) diff --git a/src/components/views/Main.jsx b/src/components/views/Main.jsx index 88ba6ad8..3d80f664 100644 --- a/src/components/views/Main.jsx +++ b/src/components/views/Main.jsx @@ -20,7 +20,7 @@ export default () => { const NotFound = withTracker(withNextButton(lazyLoad(import('./NotFound')))); return ( -
+
{/* Keyed on the route so a failed chunk load doesn't brick every later navigation - the key change fully remounts the boundary, resetting its error state, instead of leaving diff --git a/src/components/views/styl/Application.styl b/src/components/views/styl/Application.styl index d8428c07..eaa85651 100644 --- a/src/components/views/styl/Application.styl +++ b/src/components/views/styl/Application.styl @@ -139,9 +139,15 @@ body { background-size: 1920px auto; } +// A column at least as tall as the window, with main taking the spare height, +// so that on a short page the footer sits at the bottom of the window. The gap +// above the header is padding, not an offset, so it counts toward that height. #application { + display: flex; + flex-direction: column; + min-height: 100svh; + padding-top: 10px; position: relative; - top: 10px; } #main-header, main, footer > div { @@ -150,9 +156,18 @@ body { } main { + flex-grow: 1; padding: 12px 0; } +// Until a dashboard loads, keep the footer below the fold, so that it doesn't +// jump off the screen when the dashboard arrives. A loaded dashboard is always +// taller than this. It is the tallest the window can be, unlike the svh above, +// so that the footer stays out of sight on phones too. +main.dashboard-route { + min-height: 100vh; +} + a { color: $link-color-normal; text-decoration: none; @@ -194,7 +209,7 @@ dd { } #application { - top: 40px; + padding-top: 40px; } #main-header, main, footer > div { diff --git a/tests/playwright/specs/fixtures/placeholders.spec.js b/tests/playwright/specs/fixtures/placeholders.spec.js index a6611469..372f9957 100644 --- a/tests/playwright/specs/fixtures/placeholders.spec.js +++ b/tests/playwright/specs/fixtures/placeholders.spec.js @@ -77,3 +77,16 @@ for (const width of [375, 1280]) { expectSameBox(await box(firstSummaryMetric), placeholder); }); } + +test('While a dashboard loads, the footer stays below the window', async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 900 }); + const releaseDashboard = await holdRequests(page, url => decodeURIComponent(url.pathname).endsWith('/hardware/index.json')); + await page.goto('/dashboard/hardware'); + await expect(page.locator('main > .spinner')).toBeAttached(); + + const { y } = await page.locator('footer').boundingBox(); + expect(y).toBeGreaterThanOrEqual(900); + + releaseDashboard(); + await expect(page.locator('#dashboard')).toBeVisible(); +}); diff --git a/tests/playwright/specs/footer.spec.js b/tests/playwright/specs/footer.spec.js index 277ff929..0ed06295 100644 --- a/tests/playwright/specs/footer.spec.js +++ b/tests/playwright/specs/footer.spec.js @@ -1,10 +1,23 @@ const { test, expect } = require('../fixtureData'); -test.beforeEach(async ({ page }) => { - await page.goto('/'); -}); - test('Footer appears', async ({ page }) => { + await page.goto('/'); await expect(page.locator('footer')).toBeVisible(); }); + +// The 375px window is tall enough to fit the header, the page, and the footer, +// which on a phone is taller than many phone screens. +for (const [width, height] of [[1280, 900], [375, 1000]]) { + for (const path of ['/contact', '/this-page-does-not-exist']) { + test(`On a page shorter than the window, the footer sits at the bottom of the window (${path} at ${width}×${height})`, async ({ page }) => { + await page.setViewportSize({ width, height }); + await page.goto(path); + const footer = page.locator('footer'); + await expect(footer).toBeVisible(); + + const { y, height: footerHeight } = await footer.boundingBox(); + expect(Math.abs(y + footerHeight - height)).toBeLessThan(1); + }); + } +} From 6bee72a12e9114de101541048ab5516e3f30ccda Mon Sep 17 00:00:00 2001 From: Stephanie Hobson Date: Mon, 16 Nov 2026 11:33:53 -0700 Subject: [PATCH 3/7] Show a page already visited without loading it again (#509) Moving between pages flickered through spinners and placeholders even on a return visit. Main and MetricOverview created a new React.lazy on every mount, which suspends once even when its code has loaded, and withFetch fetched every response again, with the CDN forcing max-age=0. lazyLoad now renders loaded code straight away, and the lazy components are created once. withFetch keeps responses until the page reloads and shares one request between components asking for the same URL, which hardware's summary bars and metrics do. A chunk that fails to load is no longer loaded again on the next visit. Browsers can keep a failed import() too, so that retry wasn't reliable; the error now offers a page reload instead. --- AGENTS.md | 9 +-- docs/architecture/frontend.md | 10 ++- src/components/views/Main.jsx | 22 +++---- src/components/views/MetricOverview.jsx | 20 +++--- src/lib/LazyBoundary.jsx | 16 +++-- src/lib/fetchCache.js | 3 + src/lib/lazyLoad.jsx | 29 +++++++- src/lib/withFetch.jsx | 46 ++++++++++++- src/setupTests.js | 3 + src/tests/jest/LazyBoundary.test.jsx | 63 ++++++++++++------ .../jest/MetricOverviewContainer.test.jsx | 17 +++++ src/tests/jest/Routes.test.jsx | 19 +++++- src/tests/jest/withFetch.test.jsx | 61 +++++++++++++++++ .../specs/fixtures/navigation.spec.js | 66 +++++++++++++++++++ 14 files changed, 322 insertions(+), 62 deletions(-) create mode 100644 src/lib/fetchCache.js create mode 100644 tests/playwright/specs/fixtures/navigation.spec.js diff --git a/AGENTS.md b/AGENTS.md index 2e6a81d3..f3e4a18b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 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). +`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. @@ -40,8 +40,9 @@ src/ │ ├── 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/ @@ -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 ``. 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 `
`, 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. diff --git a/docs/architecture/frontend.md b/docs/architecture/frontend.md index d0e8b595..80526fd4 100644 --- a/docs/architecture/frontend.md +++ b/docs/architecture/frontend.md @@ -39,7 +39,10 @@ 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 a placeholder the size of what will replace it (`views/MetricOverviewPlaceholder.jsx`, `views/SummaryMetricPlaceholder.jsx`), and all three render @@ -115,8 +118,9 @@ these architecture docs. │ ├── 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/ diff --git a/src/components/views/Main.jsx b/src/components/views/Main.jsx index 3d80f664..6c5f30d3 100644 --- a/src/components/views/Main.jsx +++ b/src/components/views/Main.jsx @@ -8,23 +8,21 @@ import LazyBoundary from '../../lib/LazyBoundary'; import { dashboards } from '../../config.json'; +// Created once, so that a page already visited renders straight away when it +// is visited again. +const Home = withTracker(withNextButton(lazyLoad(() => import('./Home')))); +const Contact = withTracker(lazyLoad(() => import('./Contact'))); +const DashboardContainer = withTracker(withNextButton(lazyLoad(() => import('../containers/DashboardContainer')))); +const NotFound = withTracker(withNextButton(lazyLoad(() => import('./NotFound')))); + export default () => { const { pathname } = useLocation(); - // Created on each render, which only happens on navigation, so a route - // whose chunk failed to load retries the import when it is visited again. - // React.lazy remembers a failed load for good. - const Home = withTracker(withNextButton(lazyLoad(import('./Home')))); - const Contact = withTracker(lazyLoad(import('./Contact'))); - const DashboardContainer = withTracker(withNextButton(lazyLoad(import('../containers/DashboardContainer')))); - const NotFound = withTracker(withNextButton(lazyLoad(import('./NotFound')))); - return (
- {/* Keyed on the route so a failed chunk load doesn't brick every - later navigation - the key change fully remounts the - boundary, resetting its error state, instead of leaving - "Load error" in place until a full page reload. */} + {/* Keyed on the route so that a page whose code failed to load + doesn't leave "Load error" on every other page: the key + change remounts the boundary, resetting its error state. */} } /> diff --git a/src/components/views/MetricOverview.jsx b/src/components/views/MetricOverview.jsx index 15ac3048..802323a6 100644 --- a/src/components/views/MetricOverview.jsx +++ b/src/components/views/MetricOverview.jsx @@ -10,18 +10,14 @@ import StripedHeader from './StripedHeader'; import './css/MetricOverview.css'; +const ChartContainer = lazyLoad(() => import('../containers/ChartContainer')); +const CustomizableDateContainer = lazyLoad(() => import('../containers/CustomizableDateContainer')); +const DataTableContainer = lazyLoad(() => import('../containers/DataTableContainer')); + class MetricOverview extends React.Component { constructor(props) { super(props); - // Lazy-load the proper components - if (props.type === 'line') { - this.ChartContainer = lazyLoad(import('../containers/ChartContainer')); - } else if (props.type === 'table') { - this.CustomizableDateContainer = lazyLoad(import('../containers/CustomizableDateContainer')); - this.DataTableContainer = lazyLoad(import('../containers/DataTableContainer')); - } - this.markdownParser = markdownIt('zero').use(markdownItSup) .enable(['link', 'entity']); } @@ -65,7 +61,7 @@ class MetricOverview extends React.Component { if (props.type === 'line') { const numPopulations = Object.keys(props.data.populations).length; MetricContainer = ( - - - + ); } diff --git a/src/lib/LazyBoundary.jsx b/src/lib/LazyBoundary.jsx index 040faa4e..1565d975 100644 --- a/src/lib/LazyBoundary.jsx +++ b/src/lib/LazyBoundary.jsx @@ -6,7 +6,8 @@ import ErrorComponent from '../components/views/Error'; /** * Wraps children containing a lazyLoad'd component with a loading spinner and - * a fallback for chunk-load failures. React.lazy/Suspense only handles the + * a fallback for chunk-load failures, which offers a reload because only a + * reload loads the code again. React.lazy/Suspense only handles the * loading case; catching the error case requires an error boundary class * component, which is why this can't be a function component. */ @@ -23,10 +24,15 @@ export default class LazyBoundary extends React.Component { render() { if (this.state.hasError) { return ( - + <> + + + ); } diff --git a/src/lib/fetchCache.js b/src/lib/fetchCache.js new file mode 100644 index 00000000..6703a3ce --- /dev/null +++ b/src/lib/fetchCache.js @@ -0,0 +1,3 @@ +// Responses withFetch has fetched or is fetching, by URL, kept until the page +// reloads: { promise, fulfilled, value }. Its own module so tests can clear it. +export default new Map(); diff --git a/src/lib/lazyLoad.jsx b/src/lib/lazyLoad.jsx index 07ed0308..2d586da8 100644 --- a/src/lib/lazyLoad.jsx +++ b/src/lib/lazyLoad.jsx @@ -2,7 +2,30 @@ import React from 'react'; /** - * Return a lazily-loaded component. Pair with LazyBoundary to show a spinner - * while loading and to handle load errors. + * Start loading a component's code now and return a component that renders it. + * Pair with LazyBoundary to show a spinner while loading and to handle load + * errors. + * + * Once the code has loaded, the component renders it straight away. A new + * React.lazy suspends on its first render even when its code is already + * loaded, which would flash the spinner on every visit. + * + * A failed load stays failed until the page is reloaded. Browsers can keep a + * failed import() too, so loading again isn't a reliable retry. */ -export default loader => React.lazy(() => loader); +export default loader => { + let loadedComponent = null; + const loading = loader().then(loadedModule => { + loadedComponent = loadedModule.default; + return loadedModule; + }); + // Nothing may ever render this component, so its failure must not go + // unhandled. React.lazy still sees the rejection. + loading.catch(() => {}); + const LazyComponent = React.lazy(() => loading); + + return props => { + const Component = loadedComponent || LazyComponent; + return ; + }; +}; diff --git a/src/lib/withFetch.jsx b/src/lib/withFetch.jsx index 41b956f0..e01cae78 100644 --- a/src/lib/withFetch.jsx +++ b/src/lib/withFetch.jsx @@ -1,5 +1,7 @@ import React from 'react'; +import fetchCache from './fetchCache'; + const pendingState = { pending: true, rejected: false, fulfilled: false }; @@ -24,17 +26,47 @@ async function fetchJSON(url) { return response.json(); } +// Start fetching url, or join the request already made for it. The entry fills +// in its value when the response arrives, whoever is still waiting for it. A +// failed request is forgotten, so the next component to ask tries again. +function cachedFetch(url) { + if (!fetchCache.has(url)) { + const entry = { fulfilled: false, value: undefined }; + entry.promise = fetchJSON(url).then( + value => { + Object.assign(entry, { fulfilled: true, value }); + return value; + }, + reason => { + fetchCache.delete(url); + throw reason; + } + ); + fetchCache.set(url, entry); + } + return fetchCache.get(url); +} + +function fulfilledState(value) { + return { pending: false, rejected: false, fulfilled: true, value }; +} + /** * Fetch JSON from the URL that mapPropsToUrl returns and pass the request's * state to the wrapped component as `dataFetch`: { pending, rejected, * fulfilled, value, reason }. Refetches whenever the URL changes, going back to * pending first, and ignores any response that arrives after a newer request * has started. + * + * Responses are kept until the page reloads, so a URL fetched before is + * fulfilled from the first render, and components asking for the same URL at + * once share one request. The data changes weekly, so a reload is fresh enough. */ export default mapPropsToUrl => WrappedComponent => class extends React.Component { constructor(props) { super(props); - this.state = { dataFetch: pendingState }; + const cached = fetchCache.get(mapPropsToUrl(props)); + this.state = { dataFetch: cached?.fulfilled ? fulfilledState(cached.value) : pendingState }; this._latestRequest = 0; } @@ -57,15 +89,23 @@ export default mapPropsToUrl => WrappedComponent => class extends React.Componen this._url = url; const request = ++this._latestRequest; const isCurrent = () => request === this._latestRequest; + const entry = cachedFetch(url); + + if (entry.fulfilled) { + if (this.state.dataFetch.value !== entry.value) { + this.setState({ dataFetch: fulfilledState(entry.value) }); + } + return; + } if (this.state.dataFetch !== pendingState) { this.setState({ dataFetch: pendingState }); } - fetchJSON(url).then( + entry.promise.then( value => { if (isCurrent()) { - this.setState({ dataFetch: { pending: false, rejected: false, fulfilled: true, value } }); + this.setState({ dataFetch: fulfilledState(value) }); } }, reason => { diff --git a/src/setupTests.js b/src/setupTests.js index 650b28a0..95213078 100644 --- a/src/setupTests.js +++ b/src/setupTests.js @@ -1,6 +1,8 @@ import { cleanup } from '@testing-library/react'; import '@testing-library/jest-dom/vitest'; +import fetchCache from './lib/fetchCache'; + // React reports deprecations and misuse through console.error, so treat any // unexpected call as a failure. A test that expects an error replaces @@ -20,6 +22,7 @@ afterEach(() => { cleanup(); vi.restoreAllMocks(); sessionStorage.clear(); + fetchCache.clear(); // eslint-disable-next-line no-console console.error = originalConsoleError; }); diff --git a/src/tests/jest/LazyBoundary.test.jsx b/src/tests/jest/LazyBoundary.test.jsx index b92fc5b9..1042633a 100644 --- a/src/tests/jest/LazyBoundary.test.jsx +++ b/src/tests/jest/LazyBoundary.test.jsx @@ -4,40 +4,65 @@ import LazyBoundary from '../../lib/LazyBoundary'; import lazyLoad from '../../lib/lazyLoad'; +function renderInBoundary(ui) { + return render({ui}); +} + it('Shows a spinner while a lazily loaded component is loading', () => { - const NeverLoads = lazyLoad(new Promise(() => {})); + const NeverLoads = lazyLoad(() => new Promise(() => {})); - const { container } = render( - - - - ); + const { container } = renderInBoundary(); expect(container.querySelector('.spinner')).toBeInTheDocument(); }); it('Shows the loaded component once it arrives', async () => { - const Loads = lazyLoad(Promise.resolve({ default: () =>

Loaded

})); + const Loads = lazyLoad(() => Promise.resolve({ default: () =>

Loaded

})); - render( - - - - ); + renderInBoundary(); expect(await screen.findByText('Loaded')).toBeInTheDocument(); }); -it('Shows "Load error" when loading fails', async () => { +it('A component whose code loaded before it is first rendered shows on that first render, with no spinner', async () => { + let resolveLoad; + const LoadsFirst = lazyLoad(() => new Promise(resolve => { + resolveLoad = resolve; + })); + resolveLoad({ default: () =>

Loaded

}); + await Promise.resolve(); + await Promise.resolve(); + + const { container } = renderInBoundary(); + + expect(screen.getByText('Loaded')).toBeInTheDocument(); + expect(container.querySelector('.spinner')).toBeNull(); +}); + +it('A component shown before shows again straight away when it is mounted again', async () => { + const Loads = lazyLoad(() => Promise.resolve({ default: () =>

Loaded

})); + const first = renderInBoundary(); + await screen.findByText('Loaded'); + first.unmount(); + + const { container } = renderInBoundary(); + + expect(screen.getByText('Loaded')).toBeInTheDocument(); + expect(container.querySelector('.spinner')).toBeNull(); +}); + +it('When loading fails, shows "Load error" and a reload button, and never loads again', async () => { // React logs errors caught by an error boundary. vi.spyOn(console, 'error').mockImplementation(() => {}); - const FailsToLoad = lazyLoad(Promise.reject(new Error('Failed to fetch dynamically imported module'))); + const loader = vi.fn(() => Promise.reject(new Error('Failed to fetch dynamically imported module'))); + const FailsToLoad = lazyLoad(loader); - render( - - - - ); + const first = renderInBoundary(<>); + expect(await screen.findByText('Load error')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Reload the page' })).toBeInTheDocument(); + first.unmount(); + renderInBoundary(); expect(await screen.findByText('Load error')).toBeInTheDocument(); + expect(loader).toHaveBeenCalledTimes(1); }); diff --git a/src/tests/jest/MetricOverviewContainer.test.jsx b/src/tests/jest/MetricOverviewContainer.test.jsx index f79b27d1..21f27e28 100644 --- a/src/tests/jest/MetricOverviewContainer.test.jsx +++ b/src/tests/jest/MetricOverviewContainer.test.jsx @@ -100,3 +100,20 @@ it('When the request for a new region fails, #metric-overview-fetch-error replac await waitFor(() => expect(container.querySelector('#metric-overview-fetch-error')).toBeInTheDocument()); expect(screen.queryByText('Daily Usage')).toBeNull(); }); + +it('Going back to a region already loaded shows its metric at once, without another request', async () => { + const { rerender } = renderForRegion('Worldwide'); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + settle('https://data.example/user-activity/Worldwide/daily-usage/index.json', { title: 'Daily Usage' }); + await screen.findByText('Daily Usage'); + + renderForRegion('Germany', rerender); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)); + settle('https://data.example/user-activity/Germany/daily-usage/index.json', { title: 'Tägliche Nutzung' }); + await screen.findByText('Tägliche Nutzung'); + + renderForRegion('Worldwide', rerender); + + expect(screen.getByText('Daily Usage')).toBeInTheDocument(); + expect(fetchMock).toHaveBeenCalledTimes(2); +}); diff --git a/src/tests/jest/Routes.test.jsx b/src/tests/jest/Routes.test.jsx index a9ff3211..10439100 100644 --- a/src/tests/jest/Routes.test.jsx +++ b/src/tests/jest/Routes.test.jsx @@ -1,4 +1,4 @@ -import { render, screen, waitFor } from '@testing-library/react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter } from 'react-router'; import { HelmetProvider } from 'react-helmet-async'; import ReactGA from 'react-ga4'; @@ -72,6 +72,23 @@ it.each([ await waitFor(() => expect(ReactGA.send).toHaveBeenCalledWith({ hitType: 'pageview', page: path })); }); +it('Each navigation sends one pageview, including a return to a page already visited', async () => { + const { container } = renderAt('/contact'); + await screen.findByText(/questions/i, { selector: '#contact' }); + const navigationLink = linkText => [...container.querySelectorAll('#main-navigation a')].find(link => link.textContent === linkText); + + fireEvent.click(navigationLink(dashboards[0].menuTitle)); + await waitFor(() => expect(container.querySelector('#contact')).toBeNull()); + fireEvent.click(navigationLink('Contact')); + await screen.findByText(/questions/i, { selector: '#contact' }); + + expect(ReactGA.send.mock.calls.map(([hit]) => hit.page)).toEqual([ + '/contact', + `/dashboard/${dashboards[0].key}`, + '/contact', + ]); +}); + it('The header links to every dashboard in config.json and the contact page', async () => { const { container } = renderAt('/'); await screen.findByRole('link', { name: 'Proceed to User Activity' }); diff --git a/src/tests/jest/withFetch.test.jsx b/src/tests/jest/withFetch.test.jsx index ffc61930..273a70ff 100644 --- a/src/tests/jest/withFetch.test.jsx +++ b/src/tests/jest/withFetch.test.jsx @@ -103,3 +103,64 @@ it('Ignores a response that arrives after a newer request has started', async () expect(screen.getByText('fulfilled: Fast')).toBeInTheDocument(); }); + +it('A URL fetched before is fulfilled from the first render, without another request', async () => { + const first = render(); + settle('https://data.example/one.json', { title: 'One' }); + await screen.findByText('fulfilled: One'); + first.unmount(); + + render(); + + expect(screen.getByText('fulfilled: One')).toBeInTheDocument(); + expect(fetchMock).toHaveBeenCalledTimes(1); +}); + +it('Components asking for the same URL at once share one request', async () => { + render(<>); + + settle('https://data.example/one.json', { title: 'One' }); + + expect(await screen.findAllByText('fulfilled: One')).toHaveLength(2); + expect(fetchMock).toHaveBeenCalledTimes(1); +}); + +it('A request still in flight when its component unmounts is used by the next component to ask', async () => { + render().unmount(); + + render(); + settle('https://data.example/one.json', { title: 'One' }); + + expect(await screen.findByText('fulfilled: One')).toBeInTheDocument(); + expect(fetchMock).toHaveBeenCalledTimes(1); +}); + +it('A failed URL is requested again by the next component to ask', async () => { + const first = render(); + settle('https://data.example/one.json', { error: 'Internal Server Error' }, 500); + await screen.findByText('rejected: Internal Server Error'); + first.unmount(); + + render(); + expect(screen.getByText('pending')).toBeInTheDocument(); + settle('https://data.example/one.json', { title: 'One' }); + + expect(await screen.findByText('fulfilled: One')).toBeInTheDocument(); + expect(fetchMock).toHaveBeenCalledTimes(2); +}); + +it('Going back to a fetched URL shows it at once, and a request left behind doesn\'t replace it', async () => { + const { rerender } = render(); + settle('https://data.example/one.json', { title: 'One' }); + await screen.findByText('fulfilled: One'); + + rerender(); + expect(await screen.findByText('pending')).toBeInTheDocument(); + rerender(); + expect(screen.getByText('fulfilled: One')).toBeInTheDocument(); + + settle('https://data.example/two.json', { title: 'Two' }); + await new Promise(resolve => setTimeout(resolve, 0)); + + expect(screen.getByText('fulfilled: One')).toBeInTheDocument(); +}); diff --git a/tests/playwright/specs/fixtures/navigation.spec.js b/tests/playwright/specs/fixtures/navigation.spec.js new file mode 100644 index 00000000..fc432f1a --- /dev/null +++ b/tests/playwright/specs/fixtures/navigation.spec.js @@ -0,0 +1,66 @@ +const { test, expect, readFixture } = require('../../fixtureData'); + + +const loadingSelector = '.spinner, .metric-overview-placeholder, .summary-metric[aria-hidden="true"]'; + +const pages = { + 'Hardware': '/dashboard/hardware', + 'User Activity': '/dashboard/user-activity', + 'Contact': '/contact', +}; + +async function waitUntilShown(page, linkText) { + await expect(page).toHaveURL(pages[linkText]); + if (linkText === 'Contact') { + await expect(page.locator('#contact')).toBeVisible(); + return; + } + + const dashboard = readFixture(`${pages[linkText].split('/').at(-1)}/index.json`); + const metricCount = dashboard.sections + ? dashboard.sections.flatMap(section => section.metrics).length + : dashboard.metrics.length; + await expect(page.locator('.metric-and-legend').locator('svg.chart-svg, .customizable-date')).toHaveCount(metricCount); + await expect(page.locator('#summary-metrics .summary-metric:not([aria-hidden]):has(rect.bar)')).toHaveCount((dashboard.summaryMetrics || []).length); + await expect(page.locator(loadingSelector)).toHaveCount(0); +} + +async function navigateTo(page, linkText) { + await page.locator('#main-navigation a', { hasText: linkText }).click(); + await waitUntilShown(page, linkText); +} + +test('Going back to a page already visited shows it without loading anything', async ({ page }) => { + const datasetRequests = []; + page.on('request', request => { + if (request.url().includes('/datasets/')) datasetRequests.push(request.url()); + }); + + await page.goto(pages['Hardware']); + await waitUntilShown(page, 'Hardware'); + await navigateTo(page, 'User Activity'); + await navigateTo(page, 'Contact'); + + // Record every loading state added from here on, including one inside a + // larger piece of the page added at once. + await page.evaluate(selector => { + window.loadingStatesShown = []; + new MutationObserver(records => { + for (const record of records) { + for (const node of record.addedNodes) { + if (node.nodeType !== Node.ELEMENT_NODE) continue; + const shown = [...(node.matches(selector) ? [node] : []), ...node.querySelectorAll(selector)]; + window.loadingStatesShown.push(...shown.map(element => element.className)); + } + } + }).observe(document.querySelector('#application'), { childList: true, subtree: true }); + }, loadingSelector); + datasetRequests.length = 0; + + for (const linkText of ['Hardware', 'Contact', 'User Activity', 'Hardware']) { + await navigateTo(page, linkText); + } + + expect(await page.evaluate(() => window.loadingStatesShown)).toEqual([]); + expect(datasetRequests).toEqual([]); +}); From c3509f848c4c61ae6435859d3ab963dd45fa9bd1 Mon Sep 17 00:00:00 2001 From: Stephanie Hobson Date: Mon, 16 Nov 2026 11:33:54 -0700 Subject: [PATCH 4/7] Open each new page at the top (#509) BrowserRouter leaves the window scrolled where it was. Now that a page visited before renders at full height at once, the Next button opened it part way down in Firefox and Safari. Back and forward still keep the browser's own scroll restoration. --- src/components/views/Main.jsx | 13 +++++++++- src/setupTests.js | 2 ++ .../specs/fixtures/navigation.spec.js | 26 +++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/components/views/Main.jsx b/src/components/views/Main.jsx index 6c5f30d3..f8e61e64 100644 --- a/src/components/views/Main.jsx +++ b/src/components/views/Main.jsx @@ -1,4 +1,5 @@ -import { Routes, Route, useLocation } from 'react-router'; +import { useLayoutEffect } from 'react'; +import { Routes, Route, useLocation, useNavigationType } from 'react-router'; import withTracker from '../decorators/withTracker'; import withNextButton from '../decorators/withNextButton'; @@ -17,6 +18,16 @@ const NotFound = withTracker(withNextButton(lazyLoad(() => import('./NotFound')) export default () => { const { pathname } = useLocation(); + const navigationType = useNavigationType(); + + // BrowserRouter leaves the window scrolled where it was, and a page visited + // before renders at full height at once, so a new page would open part way + // down. Back and forward keep the browser's own scroll restoration. + useLayoutEffect(() => { + if (navigationType !== 'POP') { + window.scrollTo(0, 0); + } + }, [pathname, navigationType]); return (
diff --git a/src/setupTests.js b/src/setupTests.js index 95213078..136dab8d 100644 --- a/src/setupTests.js +++ b/src/setupTests.js @@ -11,6 +11,8 @@ import fetchCache from './lib/fetchCache'; const originalConsoleError = console.error; beforeEach(() => { + // jsdom has no scrolling and reports scrollTo through console.error. + vi.spyOn(window, 'scrollTo').mockImplementation(() => {}); // eslint-disable-next-line no-console console.error = (...args) => { originalConsoleError(...args); diff --git a/tests/playwright/specs/fixtures/navigation.spec.js b/tests/playwright/specs/fixtures/navigation.spec.js index fc432f1a..3c5003f4 100644 --- a/tests/playwright/specs/fixtures/navigation.spec.js +++ b/tests/playwright/specs/fixtures/navigation.spec.js @@ -6,6 +6,7 @@ const loadingSelector = '.spinner, .metric-overview-placeholder, .summary-metric const pages = { 'Hardware': '/dashboard/hardware', 'User Activity': '/dashboard/user-activity', + 'Usage Behavior': '/dashboard/usage-behavior', 'Contact': '/contact', }; @@ -64,3 +65,28 @@ test('Going back to a page already visited shows it without loading anything', a expect(await page.evaluate(() => window.loadingStatesShown)).toEqual([]); expect(datasetRequests).toEqual([]); }); + +test('The Next button opens the next page at the top, even when it was visited before', async ({ page }) => { + await page.goto(pages['Hardware']); + await waitUntilShown(page, 'Hardware'); + await navigateTo(page, 'Usage Behavior'); + + const nextButton = page.getByRole('link', { name: 'Proceed to Hardware' }); + await nextButton.scrollIntoViewIfNeeded(); + expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0); + // Chromium happens to land at the top on its own, but Firefox and Safari + // keep the old position, so also check that the page asks for the top. + await page.evaluate(() => { + window.scrolledTo = []; + const originalScrollTo = window.scrollTo.bind(window); + window.scrollTo = (...position) => { + window.scrolledTo.push(position); + originalScrollTo(...position); + }; + }); + await nextButton.click(); + await waitUntilShown(page, 'Hardware'); + + expect(await page.evaluate(() => window.scrolledTo)).toContainEqual([0, 0]); + expect(await page.evaluate(() => window.scrollY)).toBe(0); +}); From bec3358ca72bcddd4a0dced8c8de9e52601daca4 Mon Sep 17 00:00:00 2001 From: Stephanie Hobson Date: Mon, 16 Nov 2026 11:33:55 -0700 Subject: [PATCH 5/7] Move focus to the new page's heading after navigating (#509) After a client-side navigation, focus stayed on the header link, or fell to the body when the Next button that had it was replaced, and screen readers weren't told that a new page had loaded. Focus now moves to the page's heading, as a full page load would start at the top, so a screen reader reads it and Tab continues from there. Back and forward keep their scroll position. Until a dashboard's heading arrives, main holds focus, and the heading takes it unless the reader has moved on. The route and dashboard spinners now tell screen readers they're loading, once the dots appear, and Not Found has its own title instead of the previous page's. --- AGENTS.md | 1 + docs/architecture/frontend.md | 12 +++ .../containers/DashboardContainer.jsx | 3 +- src/components/views/Contact.jsx | 2 +- src/components/views/Dashboard.jsx | 4 +- src/components/views/Error.jsx | 6 +- src/components/views/Main.jsx | 51 ++++++++-- src/components/views/NotFound.jsx | 4 +- src/components/views/Spinner.jsx | 9 +- src/components/views/styl/Application.styl | 19 ++++ src/components/views/styl/Dashboard.styl | 12 --- src/lib/LazyBoundary.jsx | 2 +- src/tests/jest/Routes.test.jsx | 6 ++ src/tests/jest/Spinner.test.jsx | 29 ++++++ .../specs/fixtures/navigation.spec.js | 92 ++++++++++++++++++- .../specs/fixtures/placeholders.spec.js | 15 +-- tests/playwright/utils.js | 16 ++++ 17 files changed, 242 insertions(+), 41 deletions(-) create mode 100644 src/tests/jest/Spinner.test.jsx diff --git a/AGENTS.md b/AGENTS.md index f3e4a18b..e27c2c6b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,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. | diff --git a/docs/architecture/frontend.md b/docs/architecture/frontend.md index 80526fd4..458fcfe7 100644 --- a/docs/architecture/frontend.md +++ b/docs/architecture/frontend.md @@ -51,6 +51,18 @@ two metric containers render a placeholder the size of what will replace it 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 diff --git a/src/components/containers/DashboardContainer.jsx b/src/components/containers/DashboardContainer.jsx index 01a09409..69db4a0b 100644 --- a/src/components/containers/DashboardContainer.jsx +++ b/src/components/containers/DashboardContainer.jsx @@ -27,7 +27,7 @@ class DashboardContainer extends React.Component { const dataFetch = this.props.dataFetch; if (dataFetch.pending) { - return ; + return ; } else if (dataFetch.rejected) { if (dataFetch.reason && dataFetch.reason.message) { // eslint-disable-next-line no-console @@ -36,6 +36,7 @@ class DashboardContainer extends React.Component { return ( diff --git a/src/components/views/Contact.jsx b/src/components/views/Contact.jsx index 54fd9698..0916e42c 100644 --- a/src/components/views/Contact.jsx +++ b/src/components/views/Contact.jsx @@ -16,7 +16,7 @@ export default () => { -

Contact

+

Contact

Please email us at {' '}fx-public-data@mozilla.com diff --git a/src/components/views/Dashboard.jsx b/src/components/views/Dashboard.jsx index 57e191bb..edbe6d4f 100644 --- a/src/components/views/Dashboard.jsx +++ b/src/components/views/Dashboard.jsx @@ -143,12 +143,12 @@ export default props => {

-

{props.title}

+

{props.title}

{maybeDescription} {maybeRegion}
{maybeSummaryMetrics} -

Metrics

+

Metrics

{body}
diff --git a/src/components/views/Error.jsx b/src/components/views/Error.jsx index a549b7df..0b7d54f3 100644 --- a/src/components/views/Error.jsx +++ b/src/components/views/Error.jsx @@ -5,9 +5,13 @@ export default props => { maybeMessage =

{props.message}

; } + // Only an error that stands in for the whole page takes focus after a + // navigation, as a page's heading does. + const pageHeadingProps = props.pageHeading ? { tabIndex: -1, 'data-page-heading': true } : {}; + return (
-

{props.title}

+

{props.title}

{maybeMessage}
); diff --git a/src/components/views/Main.jsx b/src/components/views/Main.jsx index f8e61e64..0b96fe71 100644 --- a/src/components/views/Main.jsx +++ b/src/components/views/Main.jsx @@ -1,4 +1,4 @@ -import { useLayoutEffect } from 'react'; +import { useLayoutEffect, useRef } from 'react'; import { Routes, Route, useLocation, useNavigationType } from 'react-router'; import withTracker from '../decorators/withTracker'; @@ -16,25 +16,64 @@ const Contact = withTracker(lazyLoad(() => import('./Contact'))); const DashboardContainer = withTracker(withNextButton(lazyLoad(() => import('../containers/DashboardContainer')))); const NotFound = withTracker(withNextButton(lazyLoad(() => import('./NotFound')))); +const pageHeadingSelector = '[data-page-heading]'; + +// After a navigation, do what a full page load would: open the new page at the +// top and start focus there, on its heading, which a screen reader then reads. +// Back and forward keep the scroll position the browser restores. Until the +// heading renders, main holds focus; the heading takes it on arrival unless the +// reader has moved focus elsewhere by then. +function focusPageHeading(main) { + const focusWithoutScrolling = element => element.focus({ preventScroll: true }); + const heading = main.querySelector(pageHeadingSelector); + if (heading) { + focusWithoutScrolling(heading); + return null; + } + + focusWithoutScrolling(main); + const observer = new MutationObserver(() => { + const arrivedHeading = main.querySelector(pageHeadingSelector); + if (!arrivedHeading) return; + if (document.activeElement === main) focusWithoutScrolling(arrivedHeading); + observer.disconnect(); + }); + observer.observe(main, { childList: true, subtree: true }); + return observer; +} + export default () => { const { pathname } = useLocation(); const navigationType = useNavigationType(); + const mainElement = useRef(null); + const isFirstPage = useRef(true); - // BrowserRouter leaves the window scrolled where it was, and a page visited - // before renders at full height at once, so a new page would open part way - // down. Back and forward keep the browser's own scroll restoration. + // BrowserRouter leaves scrolling and focus where they were, and a page + // visited before renders at full height at once, so without this a new + // page would open part way down with focus lost. The first page is left + // to the browser, as on any page load. useLayoutEffect(() => { + if (isFirstPage.current) { + isFirstPage.current = false; + return undefined; + } if (navigationType !== 'POP') { window.scrollTo(0, 0); } + const observer = focusPageHeading(mainElement.current); + return () => observer?.disconnect(); }, [pathname, navigationType]); return ( -
+
{/* Keyed on the route so that a page whose code failed to load doesn't leave "Load error" on every other page: the key change remounts the boundary, resetting its error state. */} - + } /> } /> diff --git a/src/components/views/NotFound.jsx b/src/components/views/NotFound.jsx index ea0595c8..c4723fc6 100644 --- a/src/components/views/NotFound.jsx +++ b/src/components/views/NotFound.jsx @@ -2,13 +2,15 @@ import React from 'react'; import { Helmet } from 'react-helmet-async'; import ErrorComponent from './Error'; +import { getPageTitle } from '../../lib/utils'; export default () => ( + {getPageTitle('Not Found')} - + ); diff --git a/src/components/views/Spinner.jsx b/src/components/views/Spinner.jsx index 0bed4618..433c6be6 100644 --- a/src/components/views/Spinner.jsx +++ b/src/components/views/Spinner.jsx @@ -6,7 +6,9 @@ import './css/Spinner.css'; /** * Simple wrapper for react-spinners that uses some default options and applies - * our custom styles. + * our custom styles. With a label, screen readers announce it when the dots + * appear: the status region is there from the start and its text arrives + * later, because text already in a newly added region often isn't announced. */ export default class extends React.Component { constructor(props) { @@ -33,6 +35,11 @@ export default class extends React.Component { render() { return (
+ {this.props.label ? ( + + {this.state.showSpinner ? this.props.label : null} + + ) : null}