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
1 change: 0 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
VITE_GA_MEASUREMENT_ID='G-XXXXXXXXXX'
VITE_SITE_TITLE='Firefox Public Data Report'
VITE_VALUE_DECIMAL_PLACES=3
20 changes: 19 additions & 1 deletion .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,20 @@ jobs:
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
# Set on each GitHub environment, so stage and prod can report to
# different Plausible sites. The app silently loads no analytics
# without a valid one, so a deploy without one fails here instead.
# The pattern is kept in step with src/lib/measure.js.
env:
VITE_PLAUSIBLE_SCRIPT_URL: ${{ vars.PLAUSIBLE_SCRIPT_URL }}
run: |
set -euo pipefail
if ! printf '%s' "$VITE_PLAUSIBLE_SCRIPT_URL" | grep -Eqx 'https://pa\.firefox\.com/js/pa-[A-Za-z0-9_-]+\.js'; then
echo "PLAUSIBLE_SCRIPT_URL on this environment is \"$VITE_PLAUSIBLE_SCRIPT_URL\", not a https://pa.firefox.com/js/pa-<id>.js script" >&2
exit 1
fi
npm run build
grep -rqF "$VITE_PLAUSIBLE_SCRIPT_URL" build/assets || { echo "the build does not contain the Plausible script URL" >&2; exit 1; }

- name: Authenticate to Google Cloud
uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
Expand Down Expand Up @@ -145,6 +158,7 @@ jobs:
- name: Check the deployed site
env:
URL: ${{ needs.target.outputs.url }}
PLAUSIBLE_SCRIPT_URL: ${{ vars.PLAUSIBLE_SCRIPT_URL }}
run: |
set -euo pipefail
# First, straight from the bucket, bypassing the CDN: did the
Expand Down Expand Up @@ -177,6 +191,10 @@ jobs:
sleep 10
done

# The Plausible script the build loads exists. Fetching it
# doesn't count a visit.
curl -fsS --max-time 20 -o /dev/null -w '%{content_type}' "$PLAUSIBLE_SCRIPT_URL" | grep -q javascript || { echo "$PLAUSIBLE_SCRIPT_URL is not served as JavaScript" >&2; exit 1; }

# Unknown paths still 404, and the transposer's data is untouched.
test "$(curl -s --max-time 20 -o /dev/null -w '%{http_code}' "$URL/no-such-page")" = 404
test "$(curl -s --max-time 20 -o /dev/null -w '%{http_code}' "$URL/datasets/desktop/hardware/index.json")" = 200
Expand Down
13 changes: 7 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ src/
├── setupTests.js Vitest setup: jest-dom matchers, fails on console.error
├── components/
│ ├── containers/ 6 stateful/data-fetching .jsx
│ ├── decorators/ withTracker.jsx (GA4 via react-ga4), withNextButton.jsx
│ ├── decorators/ withNextButton.jsx
│ └── views/ 22 presentational .jsx
│ ├── styl/ Stylus SOURCE (hand-edited); includes/lib.styl
│ ├── css/ GENERATED, GITIGNORED — holds only a README stub
Expand All @@ -43,6 +43,7 @@ src/
│ ├── 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
│ ├── measure.js initPlausible(): loads Plausible's tracker unless GPC or DNT is on
│ ├── withFetch.jsx the data layer: fetches JSON and passes `dataFetch` to containers
│ └── utils.js bumpSort, isFloat, prettifyNumber, getPageTitle
└── tests/
Expand Down Expand Up @@ -94,15 +95,15 @@ npm run size # source-map-explorer on build/assets/index

Run one Vitest file: `npx vitest run src/tests/jest/Dashboard.test.jsx`. Run one Playwright spec: `npx playwright test contact.spec.js`.

**Environment:** `.env` **is checked into git** and holds only public build-time config — `VITE_GA_MEASUREMENT_ID='G-XXXXXXXXXX'` (placeholder; the real GA4 measurement ID is a deploy decision outside this repo), `VITE_SITE_TITLE='Firefox Public Data Report'`, `VITE_VALUE_DECIMAL_PLACES=3`. Consumed through `import.meta.env` by `decorators/withTracker.jsx` and `lib/utils.js`. Override inline: `VITE_SITE_TITLE='…' npm start`.
**Environment:** `.env` **is checked into git** and holds only public build-time config — `VITE_SITE_TITLE='Firefox Public Data Report'`, `VITE_VALUE_DECIMAL_PLACES=3`. Consumed through `import.meta.env` by `lib/utils.js`. Override inline: `VITE_SITE_TITLE='…' npm start`. Plausible's script URL is **not** in `.env`: `deploy.yml` builds with `VITE_PLAUSIBLE_SCRIPT_URL` set from the `PLAUSIBLE_SCRIPT_URL` variable of the `stage` or `prod` GitHub environment (the per-site script on `pa.firefox.com`; events go to `/api/event` on the same origin), and `src/lib/measure.js` loads nothing where it is empty (or, with a console warning, where it is not a `https://pa.firefox.com/js/pa-<id>.js` script, so a setting can't load code from another origin). `deploy.yml` fails the deploy if the variable is unset or doesn't match that pattern. Local runs, CI, and the Playwright dev server (`playwright.config.js` sets a fake one for `measure.spec.js`) never send real events.

## Coding Style & Naming Conventions

- **`.jsx` for any file containing JSX** — including `src/index.jsx` and `*.test.jsx`. Plain `.js` only for non-JSX modules (`lib/utils.js`, `setupTests.js`, `registerServiceWorker.js`, the Playwright specs and helpers, and the config files at the repository root).
- **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`.
- **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`, `initPlausible` in `lib/measure.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 (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).
- 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 `withNextButton`. 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 @@ -152,7 +153,7 @@ This applies to everything written for a person to read: ExecPlans, PR descripti
- **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.
- **Routing:** `Routes.test.jsx` renders `views/Application` inside `MemoryRouter` through one `renderAt(path)` function — the only place a router upgrade has to touch — wraps it in react-helmet-async's `HelmetProvider` (any test that renders a page with a `<Helmet>` needs one — `render(ui, { wrapper: HelmetProvider })`), and mocks `react-ga4` so no analytics load. Its cases are generated from `config.json`, so adding a dashboard adds a route test.
- **Routing:** `Routes.test.jsx` renders `views/Application` inside `MemoryRouter` through one `renderAt(path)` function — the only place a router upgrade has to touch — wraps it in react-helmet-async's `HelmetProvider` (any test that renders a page with a `<Helmet>` needs one — `render(ui, { wrapper: HelmetProvider })`). Its cases are generated from `config.json`, so adding a dashboard adds a route test.

**Playwright** specs in `tests/playwright/specs/` are **`camelCase.spec.js` or `kebab-case.spec.js`, CommonJS**. Every spec except `jsDisabled.spec.js` imports `test`, `expect` (and, where needed, `readFixture`) from **`tests/playwright/fixtureData.js`**, not `@playwright/test`. `tests/playwright/utils.js` exports `formatPercent`, `linkWorks`, `linksWork`, `metricTitleIsCorrect`, `changeRegionAndWaitForMetrics`, and `flagForUpdate` — which **deliberately fails when an element count changes**, to force a human to look.

Expand All @@ -163,7 +164,7 @@ This applies to everything written for a person to read: ExecPlans, PR descripti
| `chromium` (all but `jsDisabled`) + `chromium-no-js` (`jsDisabled` only, `javaScriptEnabled: false`) | The recording in `tests/playwright/fixtures/` | "End-to-end tests" (`npm run test:playwright:recorded`) | Yes |
| `live-data` (all but `fixtures/` and `jsDisabled`) | The real data.firefox.com | "Live data tests" (`npm run test:playwright:live`) | No |

In recorded mode, `fixtureData.js`'s `test` answers every `https://data.firefox.com/datasets/desktop/**` request from `tests/playwright/fixtures/` (paths mirror the URL), answers other third-party requests (Google Analytics) with an empty 200, and **fails the test on any page error, console error, or dataset request with no recording**. Only the default region and `Germany` are recorded; a metric request for any other region is served the default region's file for the same metric, so specs can pick any region — a missing metric or dashboard still fails. A spec that expects errors sets `test.use({ allowedErrors: /pattern/ })` — a single RegExp, because `test.use()` reads an array as a `[value, options]` pair. Override one response with a later `page.route()`, which takes precedence (`errors.spec.js`, `descriptions.spec.js`). Specs about what a chart draws — `chart-series`, `region-data`, `summary-bars`, `dates`, `boundaries` — serve a small controlled JSON body for one metric this way, so their assertions don't depend on what was recorded. The `fixtures/` specs read expected values from the recording with `readFixture('hardware/index.json')`; the `dashboards/` specs hardcode exact titles and ordering, which matches the recording and is what the live job checks against reality. In `live-data` mode the page is left alone.
In recorded mode, `fixtureData.js`'s `test` answers every `https://data.firefox.com/datasets/desktop/**` request from `tests/playwright/fixtures/` (paths mirror the URL), answers other third-party requests (Plausible) with an empty 200, and **fails the test on any page error, console error, or dataset request with no recording**. Only the default region and `Germany` are recorded; a metric request for any other region is served the default region's file for the same metric, so specs can pick any region — a missing metric or dashboard still fails. A spec that expects errors sets `test.use({ allowedErrors: /pattern/ })` — a single RegExp, because `test.use()` reads an array as a `[value, options]` pair. Override one response with a later `page.route()`, which takes precedence (`errors.spec.js`, `descriptions.spec.js`). Specs about what a chart draws — `chart-series`, `region-data`, `summary-bars`, `dates`, `boundaries` — serve a small controlled JSON body for one metric this way, so their assertions don't depend on what was recorded. The `fixtures/` specs read expected values from the recording with `readFixture('hardware/index.json')`; the `dashboards/` specs hardcode exact titles and ordering, which matches the recording and is what the live job checks against reality. In `live-data` mode the page is left alone, except that it signals Global Privacy Control so the deployed-site smoke test doesn't count as visitors in Plausible.

**The live check breaks by design** when upstream data changes (weekly). A red "Live data tests" means the recording is stale, not that the change is broken: fix it by re-recording in a separate pull request.

Expand Down
Loading
Loading