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
25 changes: 25 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: CI

on:
push:
branches: [main]
pull_request:

permissions:
contents: read

jobs:
ci:
name: ci
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: lts/*
cache: npm
- run: npm ci
- run: npm run lint
- run: npm test
- run: npm run build
- run: npm audit --omit=dev --audit-level=high
27 changes: 27 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# CLAUDE.md

WebGPU Groundtruth: a React 19 + Vite single-page map. MapLibre GL basemap (CARTO dark-matter), deck.gl overlay layers for airports, ports, and stress-test points, and WebGPU compute shaders for an airport heatmap and a throughput readout. State lives in a zustand store (`src/store/mapStore.js`); data URLs are in `src/config/sources.js`. See `README.md` for details.

## Gate

Run from the repo root, in order. All must pass before a change is done (CI runs the same steps):

```sh
npm ci
npm run lint
npm test
npm run build
npm audit --omit=dev --audit-level=high
```

## Rules

- JavaScript only (`.js` / `.jsx`). No TypeScript.
- No emojis in code, comments, docs, or commit messages.
- No em dashes; use commas, periods, or colons.
- Keep render pure: no `Math.random`, `performance.now`, or other impure calls during render (`react-hooks/purity` lint rule). Do not add new `eslint-disable` comments or loosen lint rules to get green. The existing ones in `src/components/MapView.jsx` (`react-hooks/purity`) and `src/hooks/useGPUHeatmap.js` (`react-hooks/exhaustive-deps`) are pre-existing.
- Tests use Vitest + Testing Library in jsdom. jsdom has no WebGL or WebGPU, so mock `MapView` and GPU hooks in component tests.

## Git exception

Agents running the /work-issue workflow may commit and push only on their own `issue-<N>-*` branch and open a PR against `main`. Never commit or push to `main`, never force-push, and never merge their own PR or enable auto-merge.
80 changes: 71 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,78 @@
# React + Vite
# WebGPU Groundtruth

This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
A browser map that renders global airports and sea ports over a dark vector basemap and uses WebGPU compute shaders for an airport density heatmap and a live GPU throughput readout. A stress-test slider adds up to 5,000,000 random points so you can watch frame time under load.

Currently, two official plugins are available:
Built with React 19, Vite, MapLibre GL (through `react-map-gl`), deck.gl (`@deck.gl/mapbox` overlay with `ScatterplotLayer` and `BitmapLayer`), and zustand for UI state.

- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## What it does

## React Compiler
- **Basemap:** CARTO dark-matter vector style rendered by MapLibre GL.
- **Airports layer:** every non-closed airport from the OurAirports CSV, drawn as amber points. Click a point to see its properties.
- **Sea ports layer:** the bundled ports GeoJSON, drawn as green points. Click a point to see its properties.
- **Heatmap layer (WebGPU only):** a two-pass compute shader bins airport positions into a 1024 x 512 grid and colorizes it into a bitmap overlay. It runs once, after the airports load. The layer toggle appears only after that compute succeeds, so it is hidden while airports load, when WebGPU is unavailable, and when the airports fetch or the compute fails.
- **Stress test:** a slider from 0 to 5,000,000 points in steps of 100,000. Points are generated on the main thread 150 ms after the slider stops moving, then drawn as a deck.gl binary attribute layer.
- **GPU info panel:** adapter name, render tier (`WebGPU`, `WebGL Fallback`, or `Detecting...`), active point count, frame time with a 60-frame sparkline, compute throughput (a 64 MB storage buffer read and written once per second, reported in GB/s), and heatmap compute time.

The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Requirements

## Expanding the ESLint configuration
- **Node.js:** current LTS (CI uses `lts/*`). Vite 8 needs Node 20.19+ or 22.12+.
- **Browser:** any browser with WebGL 2 for the map and point layers. deck.gl draws through WebGL; WebGPU is used only for compute.
- **WebGPU (optional):** needed for the heatmap and the COMPUTE readout. Use a browser and GPU where `navigator.gpu.requestAdapter()` returns an adapter, for example current Chrome or Edge on desktop. Without it the app still runs: the panel shows `WebGL Fallback`, the heatmap toggle never appears, and COMPUTE shows `--`.
- **Network access:** the basemap style and tiles come from CARTO and the airports CSV comes from GitHub at runtime. The ports data is bundled.

If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
## Setup from a clean clone

```sh
git clone https://github.com/GeoBradDev/WebGPU-Example.git
cd WebGPU-Example
npm ci
npm run dev
```

Open the URL Vite prints (default `http://localhost:5173`). No API keys or environment variables are needed.

## Scripts

| Command | What it does |
| --- | --- |
| `npm run dev` | Start the Vite dev server with hot reload. |
| `npm run build` | Production build into `dist/`. |
| `npm run preview` | Serve the built `dist/` locally (default port 4173). |
| `npm run lint` | ESLint over the repo (`eslint.config.js`, includes `react-hooks` rules). |
| `npm test` | Run the Vitest suite once (jsdom). Includes a real `vite build` that checks the MapLibre worker is bundled. |
| `npm run test:watch` | Vitest in watch mode. |

CI (`.github/workflows/ci.yml`) runs `npm ci`, `npm run lint`, `npm test`, `npm run build`, and `npm audit --omit=dev --audit-level=high` on pushes to `main` and on pull requests.

## Data sources and licenses

| Data | Where it comes from | License |
| --- | --- | --- |
| Airports | [OurAirports](https://ourairports.com/data/) `airports.csv`, fetched at runtime from `https://raw.githubusercontent.com/davidmegginson/ourairports-data/main/airports.csv` (see `src/config/sources.js`). | Public domain. |
| Sea ports | `public/data/ports.geojson`, bundled with the app and served at `/data/ports.geojson`. The file is the Natural Earth `ne_10m_ports` dataset (1,081 points). | [Natural Earth](https://www.naturalearthdata.com/about/terms-of-use/) data is public domain. |
| Basemap | [CARTO](https://carto.com/basemaps) dark-matter GL style, `https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json`, built from OpenStreetMap data. | Map data &copy; [OpenStreetMap contributors](https://www.openstreetmap.org/copyright), ODbL. Map style and tiles &copy; [CARTO](https://carto.com/attributions); use is subject to CARTO's basemap terms, which may require a license for commercial or high-volume use. The MapLibre attribution control shows the required credits; keep it visible. |

Note: the comment in `src/config/sources.js` and the parser in `src/hooks/usePorts.js` refer to the NGA World Port Index (`PORT_NAME`), but the bundled file is Natural Earth and uses `name`. The parser falls back to `name`, so labels still work.

## Project layout

```
src/
App.jsx header, layout, wires hooks to the map
components/ MapView (MapLibre + deck.gl), LayerPanel, GPUInfoPanel, FeaturePopup
config/ data URLs, layer ids, basemap style, MapLibre worker setup
hooks/ data loading (useAirports, usePorts), WebGPU (useGPUCapabilities,
useGPUCompute, useGPUHeatmap), useStressPoints
layers/index.js buildLayers(): visibility and data to deck.gl layers
store/mapStore.js zustand store: viewport, layer visibility, stress count, selection
public/data/ports.geojson bundled ports data
```

## Known limitations

- The airports layer depends on GitHub raw being reachable. Fetch errors are kept in hook state but not shown in the UI, so the layer just stays empty.
- The basemap needs CARTO to be reachable; offline, only the overlays draw.
- The heatmap runs once per page load from the first non-empty airports list and does not update afterwards.
- Stress points are generated on the main thread. Large counts (millions of points) briefly block the UI once the slider settles.
- The COMPUTE throughput benchmark keeps a 64 MB GPU buffer allocated and dispatches every second for as long as the map is mounted.
- Unit tests run in jsdom, which has no WebGL or WebGPU. GPU code paths are covered by mocks and pure helpers only; check rendering in a real browser.
62 changes: 62 additions & 0 deletions docs/plans/2026-11-07-issue-12-ci-lint-tests-readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Plan: No CI; lint fails on main; core hooks and components untested; README is the Vite template (issue #12)

Risk tier: Medium. Mostly additive (CI, tests, docs), but the stress-point generation moves from a render-time `useMemo` to a debounced effect, which changes existing stateful UI behavior that unit tests only partly exercise.

Domain skills:
- vercel-react-best-practices: invoke (React hook refactor for useStressPoints, effect and debounce pattern).
- superpowers:test-driven-development: invoke.
- frontend-design, dataviz, django, fastapi, expo, payments, email: not applicable because no UI design, chart, backend, mobile, payment, or email work is in scope.

## Acceptance criteria

1. `.github/workflows/ci.yml` exists, triggers on `push` to `main` and on `pull_request`, and has a single job with id and name `ci` running on `ubuntu-latest` with Node LTS (`actions/setup-node` `node-version: lts/*`, `cache: npm`) that runs, in order: `npm ci`, `npm run lint`, `npm test`, `npm run build`, `npm audit --omit=dev --audit-level=high`. Actions are pinned to major versions (`actions/checkout@v7`, `actions/setup-node@v7`). The job is green on this PR, including `src/config/maplibreWorker.test.js` (a real `vite build`).
2. `npm run lint` exits 0 with zero errors on this branch. No `eslint-disable` comment and no rule configuration change is added to achieve it.
3. `useStressPoints` calls no impure function during render: points are generated inside a debounced effect timer (default 150 ms) and stored in state. Rapid count changes within the debounce window generate points once, for the last count only. Count 0 clears to the empty object. The returned shape (`{ stressPoints }` with `length` and `attributes.getPosition { value: Float32Array(count*3), size: 3 }`) is unchanged, so `buildLayers` and `MapView` need no change.
4. Tests exist and pass for: `usePorts` (success parse, non-OK response error, network rejection error); `useGPUCapabilities` (no `navigator.gpu`, `requestAdapter` resolves null, plus a success case); `App` render smoke test with `MapView` and WebGPU hooks mocked and `fetch` stubbed; the new `useStressPoints` behavior (debounce, single generation, clear on 0, value ranges).
5. `README.md` replaces the Vite template with: purpose, browser and WebGPU requirements, setup from a clean clone, scripts, data sources and licenses, known limitations.
6. A repo-root `CLAUDE.md` documents the gate commands, JavaScript only (no TypeScript), no emojis, no em dashes, and has a `## Git exception` section scoped to `issue-<N>-*` branches as specified by the user.
7. The workgroup-count overflow from the issue is already fixed on `main` (`src/hooks/useGPUCompute.js` lines 3 to 5 dispatch exactly 65,535 workgroups); no change there.

## Files that change

- `src/hooks/useStressPoints.js`: export a pure-by-argument `generateStressPoints(count, random = Math.random)` helper; the hook holds `stressPoints` in `useState(EMPTY)` and in a `useEffect` keyed on `[count, delayMs]` schedules `setTimeout(() => setStressPoints(count > 0 ? generateStressPoints(count) : EMPTY), delayMs)`, clearing the timer in cleanup. Signature `useStressPoints(count, { delayMs = 150 } = {})`. Setting state only inside the timer callback keeps `react-hooks/set-state-in-effect` quiet.
- `src/hooks/useStressPoints.test.js`: rewrite around fake timers (`vi.useFakeTimers`, `act(() => vi.advanceTimersByTime(...))`).
- `src/hooks/usePorts.test.js` (new).
- `src/hooks/useGPUCapabilities.test.js` (new): stub `navigator.gpu` with `vi.stubGlobal` or `Object.defineProperty` and restore after each test.
- `src/App.test.jsx` (new): `vi.mock('./components/MapView.jsx', ...)` to a stub, mock `./hooks/useGPUHeatmap.js` to return `{ canvas: null, computeMs: 0, supported: false }`, stub `fetch` to resolve empty data for airports CSV and ports GeoJSON; assert header title "WebGPU Groundtruth", the layer panel, and the stub map render. Reset the zustand store between tests if state is touched.
- `.github/workflows/ci.yml` (new).
- `README.md` (rewrite).
- `CLAUDE.md` (new).
- `docs/plans/2026-11-07-issue-12-ci-lint-tests-readme.md` (this file).

## Order of work

1. Red: rewrite `useStressPoints.test.js` to the new debounced contract; run it and confirm failure (the current hook returns points synchronously, so the "empty before debounce" and "single generation" tests fail). Commit the red test alone.
2. Green: change `useStressPoints.js`. Run `npm run lint` and `npm test`.
3. Add `usePorts.test.js`, `useGPUCapabilities.test.js`, `App.test.jsx` (characterization tests of existing behavior; they should pass on first run, so confirm each one can fail by temporarily breaking an assertion locally, not committed).
4. Add `.github/workflows/ci.yml`.
5. Rewrite `README.md`; add `CLAUDE.md`.
6. Full gate, then live drive.

## Risks

- Debounced generation delays points by 150 ms after the slider stops; intended. Slider label still updates immediately from the store.
- Setting the slider back to 0 now clears after the debounce, not instantly. Acceptable; tested.
- A 5M-point generation still blocks the main thread once (about 85 ms) after the user settles. Moving it to a worker is out of scope.
- `App.test.jsx` must not import maplibre or deck.gl (jsdom has no WebGL); mocking `MapView.jsx` prevents that.
- The CI `vite build` inside the test may be slow on runners; it already has a 120 s timeout.
- Chose not to: add a worker for generation, change the slider to commit-on-release, touch `useGPUCompute.js` (issue #11 reworks it), or remove the existing `eslint-disable-next-line react-hooks/purity` in `MapView.jsx` (out of scope; reported).

## Proof

- Criterion 1: workflow file review, plus the CI run on this PR green.
- Criterion 2: `npm run lint` output with zero problems.
- Criterion 3: `useStressPoints.test.js` (debounce, single generation via a `Math.random` spy call count, clear on 0, ranges), and the live drive.
- Criterion 4: the new test files passing in `npm test`.
- Criteria 5 and 6: file review.
- Criterion 7: `grep` of `useGPUCompute.js`.
- Live drive: `npm run build && npx vite preview`; the map renders; moving the stress slider to a non-zero value shows the point count update in the GPU info panel and points draw; moving back to 0 clears them; no console errors from the change.

## Deviations during implementation

- README data sources: the brief named the bundled `public/data/ports.geojson` as the NGA World Port Index, but the file itself is Natural Earth `ne_10m_ports` (1,081 features, `name` property, no `PORT_NAME`). The README documents it as Natural Earth (public domain) and notes the mismatch with the comment in `src/config/sources.js`. The comment is left unchanged here because it is out of scope.
54 changes: 54 additions & 0 deletions src/App.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { useMapStore } from './store/mapStore.js'
import App from './App.jsx'

// jsdom has no WebGL or WebGPU: stub the map and the GPU heatmap hook.
vi.mock('./components/MapView.jsx', () => ({
MapView: ({ layerData }) => (
<div data-testid="map-view">
airports:{layerData.airports.length} ports:{layerData.ports.length}
</div>
),
}))

vi.mock('./hooks/useGPUHeatmap.js', () => ({
useGPUHeatmap: () => ({ canvas: null, computeMs: 0, supported: false }),
}))

const CSV = 'id,ident,type,name,latitude_deg,longitude_deg\n1,KLAX,large_airport,LAX,33.9,-118.4\n'
const GEOJSON = {
type: 'FeatureCollection',
features: [{ type: 'Feature', geometry: { type: 'Point', coordinates: [4.4, 51.9] }, properties: { PORT_NAME: 'Rotterdam' } }],
}

beforeEach(() => {
useMapStore.setState(useMapStore.getInitialState())
vi.stubGlobal('fetch', vi.fn((url) => {
if (String(url).endsWith('.csv')) {
return Promise.resolve({ ok: true, text: () => Promise.resolve(CSV) })
}
return Promise.resolve({ ok: true, json: () => Promise.resolve(GEOJSON) })
}))
})

afterEach(() => {
vi.unstubAllGlobals()
})

describe('App', () => {
it('renders the header title, layer panel, and map', async () => {
render(<App />)

expect(screen.getByText('WebGPU Groundtruth')).toBeInTheDocument()
expect(screen.getByText('SENSOR LAYERS')).toBeInTheDocument()
expect(screen.getByText('STRESS TEST')).toBeInTheDocument()
expect(screen.getByTestId('map-view')).toBeInTheDocument()
// heatmap row hidden because the mocked hook reports unsupported
expect(screen.queryByText('HEATMAP')).not.toBeInTheDocument()

await waitFor(() =>
expect(screen.getByTestId('map-view')).toHaveTextContent('airports:1 ports:1')
)
})
})
49 changes: 49 additions & 0 deletions src/hooks/useGPUCapabilities.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { useGPUCapabilities } from './useGPUCapabilities.js'

function stubGPU(gpu) {
Object.defineProperty(navigator, 'gpu', { value: gpu, configurable: true, writable: true })
}

afterEach(() => {
delete navigator.gpu
})

describe('useGPUCapabilities', () => {
it('starts in the unknown tier', async () => {
stubGPU(undefined)
const { result } = renderHook(() => useGPUCapabilities())
expect(result.current).toEqual({ tier: 'unknown', adapterInfo: {} })
// let detection settle inside act so no state update lands after the test
await waitFor(() => expect(result.current.tier).not.toBe('unknown'))
})

it('reports no-webgpu when navigator.gpu is absent', async () => {
stubGPU(undefined)
const { result } = renderHook(() => useGPUCapabilities())
await waitFor(() => expect(result.current.tier).toBe('no-webgpu'))
expect(result.current.adapterInfo).toEqual({})
})

it('reports no-webgpu when requestAdapter resolves null', async () => {
stubGPU({ requestAdapter: vi.fn().mockResolvedValue(null) })
const { result } = renderHook(() => useGPUCapabilities())
await waitFor(() => expect(result.current.tier).toBe('no-webgpu'))
expect(result.current.adapterInfo).toEqual({})
})

it('reports no-webgpu when requestAdapter rejects', async () => {
stubGPU({ requestAdapter: vi.fn().mockRejectedValue(new Error('denied')) })
const { result } = renderHook(() => useGPUCapabilities())
await waitFor(() => expect(result.current.tier).toBe('no-webgpu'))
})

it('reports webgpu with adapter.info when an adapter is available', async () => {
const info = { vendor: 'acme', architecture: 'rdna3', device: 'Test GPU' }
stubGPU({ requestAdapter: vi.fn().mockResolvedValue({ info }) })
const { result } = renderHook(() => useGPUCapabilities())
await waitFor(() => expect(result.current.tier).toBe('webgpu'))
expect(result.current.adapterInfo).toEqual(info)
})
})
Loading
Loading