From 90409979861ceef728d9675c846448639367cc72 Mon Sep 17 00:00:00 2001 From: luen Date: Thu, 12 Nov 2026 11:24:56 +1000 Subject: [PATCH 01/13] feat(routes): shortest water routes between nurseries for move lines and animation (#183) --- AGENTS.md | 10 + drizzle/0006_keen_shaman.sql | 10 + drizzle/meta/0006_snapshot.json | 3284 ++++++++++++++++++++++ drizzle/meta/_journal.json | 7 + e2e/map-routes.spec.ts | 70 + package.json | 1 + scripts/ocean-routes.mjs | 71 + src/lib/components/InteractiveMap.svelte | 46 +- src/lib/components/MooreaMap.svelte | 22 +- src/lib/components/lineGeometry.test.ts | 77 +- src/lib/components/lineGeometry.ts | 121 +- src/lib/server/data.ts | 23 + src/lib/server/db/schema.ts | 14 + src/lib/server/import/index.ts | 21 +- src/lib/server/oceanRoutes.test.ts | 99 + src/lib/server/oceanRoutes.ts | 493 ++++ src/routes/recaptures/+page.server.ts | 32 +- src/routes/recaptures/+page.svelte | 12 +- src/routes/sharks/[id]/+page.server.ts | 10 +- src/routes/sharks/[id]/+page.svelte | 7 +- 20 files changed, 4376 insertions(+), 54 deletions(-) create mode 100644 drizzle/0006_keen_shaman.sql create mode 100644 drizzle/meta/0006_snapshot.json create mode 100644 e2e/map-routes.spec.ts create mode 100644 scripts/ocean-routes.mjs create mode 100644 src/lib/server/oceanRoutes.test.ts create mode 100644 src/lib/server/oceanRoutes.ts diff --git a/AGENTS.md b/AGENTS.md index 0e6fb14..e19f382 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,6 +39,7 @@ src/lib/server/import/ xlsx.ts (reader) · normalize.ts (cell parsers) · colu loggers.ts (HOBO/EnvLogger CSVs, register) · insitu.ts (site, hourly/daily/diel) index.ts (orchestrator: link sets, individuals, env joins, write DB) src/lib/server/db/ schema.ts (Drizzle) · index.ts (fingerprint, rebuild, atomic swap) +src/lib/server/oceanRoutes.ts Moorea water raster grid, A* shortest water routes, GeoJSON (#183) src/lib/server/data.ts loads the whole dataset into memory per import; memo() caches analyses src/lib/server/analytics common.ts (CPUE, Fulton's K, recapture pairs…) · env.ts (per-set variables) findings.ts (live findings) · insitu.ts (logger temperature summaries) @@ -151,6 +152,13 @@ samples/fixture/ synthetic workbooks for tests/CI (committed) - `node scripts/fetch-external.mjs --only=oisst` rewrites just the OISST column of the existing snapshot. `pnpm test` also runs `scripts/erddap.test.mjs` with `node --test`. - Analyses use OISST, else Coral Reef Watch (`oisst ?? crwSst`). Credit it with `SST_SOURCE` from `src/lib/sst.ts`. A snapshot change already rebuilds caches, so no `IMPORTER_VERSION` bump. +### Nursery water routes (#183) + +- `src/lib/server/oceanRoutes.ts`: computes shortest water routes around Moorea between all pairs of nurseries using grid A* routing around the island's coastline (`src/lib/moorea-outline.json`, OpenStreetMap, ODbL 1.0). The 35 m grid rasters Moorea island with a 2 km buffer, calculates chamfer distance-to-land, snaps nursery points to nearby water, searches with an A* penalty near land to avoid hugging rocks, and smooths with raycast string-pulling. +- Precomputed routes are stored in SQLite `nursery_routes` (`cache/` disposable database), bumping `IMPORTER_VERSION` to `'12'`. Never commit nursery coordinates or precomputed routes to git. +- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the traveller dot glides along the water route, scaled with distance (jumping under `prefers-reduced-motion`). +- Standalone CLI `node scripts/ocean-routes.mjs` (or `pnpm routes`, with optional `--geojson`) verifies that 0 routes cross land. + ### Adding a new season Drop the workbook in `data/` named like `Physioshark_Shark Log 2026-2027.xlsx` (the `YYYY-YYYY` in the file name sets the season). Check the Data quality page for unknown sites, unmatched headers ("Sheet not imported") and unit warnings, and extend aliases if needed. Never rename columns in the workbook to make the importer happy. @@ -191,6 +199,7 @@ pnpm build && pnpm test:e2e # Playwright + axe against the production build pnpm db:generate # after editing schema.ts pnpm external # refresh environmental snapshots pnpm fixture # regenerate synthetic workbooks +pnpm routes # compute and verify nursery water routes (scripts/ocean-routes.mjs) pnpm social-preview # re-render static/og-image.png + docs/social-preview.png (Playwright) REAL_DATA_DIR=data pnpm vitest run src/lib/server/import/realData.test.ts # opt-in real-data summary ``` @@ -233,6 +242,7 @@ Questions for the lab go to Dr Jodie Rummer (`@JodieRummer`) on GitHub: label th | 2026-11 | v0.2.6: offshore chlorophyll-a (#23); apparent survival with a Cormack–Jolly–Seber model (#42); nursery month × hour temperature calendars (#127); scar transitions (#126); measurement coverage and the catch model's sample selection (#123); catch-model fit diagnostics (#125); conditions on fieldwork nights vs their months (#124); scrollable tables keyboard-reachable (#150); sitemap, llms.txt, humans.txt (#140, #141, #143); GA4 on production hosts (#145); fixture fits the catch model in CI (#153). IMPORTER_VERSION 9: caches rebuild. | | 2026-11 | v0.2.7: SST is NOAA OISST again, with Coral Reef Watch only where OISST is missing (#154: the old endpoint had left the column empty); ERDDAP failures stop a snapshot instead of blanking it; patched esbuild and minimatch, and map tooltips rendered as text (#144). | | 2026-11 | v0.2.10: pressure scores from the Bouyoucos et al. (2024) dataset (#131); year-off recaptures take their set's date (#133); lab statistics conventions (#132) and sex-ratio wording (#130); capture numbers that disagree with the tags go on the Data quality page (#168). | +| 2026-11 | v0.2.11: shortest water routes between Moorea nurseries precomputed via grid A* routing around the island coastline (#183); move lines follow water paths, offset rightwards when reversed, with water distance; shark player animation glides along the water route; IMPORTER_VERSION 12. | - Security scans (#144): use Snyk CLI >=1.1308.3 with `test --all-projects --dev` for the pnpm 12 multi-document lockfile. Remaining upstream advisories and mitigations are tracked in docs/dev/SNYK-144.md. - Leaflet treats string tooltips as HTML. Pass a DOM element populated with `textContent` for workbook-derived point and move labels, including when rebuilding overlays. diff --git a/drizzle/0006_keen_shaman.sql b/drizzle/0006_keen_shaman.sql new file mode 100644 index 0000000..7adfe98 --- /dev/null +++ b/drizzle/0006_keen_shaman.sql @@ -0,0 +1,10 @@ +CREATE TABLE `nursery_routes` ( + `id` integer PRIMARY KEY NOT NULL, + `from_site_id` text NOT NULL, + `to_site_id` text NOT NULL, + `km` real NOT NULL, + `straight_km` real NOT NULL, + `coordinates` text NOT NULL +); +--> statement-breakpoint +CREATE INDEX `nursery_routes_pair` ON `nursery_routes` (`from_site_id`,`to_site_id`); \ No newline at end of file diff --git a/drizzle/meta/0006_snapshot.json b/drizzle/meta/0006_snapshot.json new file mode 100644 index 0000000..6b4b492 --- /dev/null +++ b/drizzle/meta/0006_snapshot.json @@ -0,0 +1,3284 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "976d4066-25fc-43d5-9ccc-45ac7d9f4dba", + "prevId": "6ad99c8e-03ff-43bd-8102-508420761a19", + "tables": { + "adult_captures": { + "name": "adult_captures", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "shark_id": { + "name": "shark_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hooked_min": { + "name": "hooked_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "boat_min": { + "name": "boat_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "released_min": { + "name": "released_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fight_min": { + "name": "fight_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "handling_min": { + "name": "handling_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lat": { + "name": "lat", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lon": { + "name": "lon", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site": { + "name": "site", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sex": { + "name": "sex", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "maturity": { + "name": "maturity", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "repro_code": { + "name": "repro_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pcl_mm": { + "name": "pcl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fl_mm": { + "name": "fl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tl_mm": { + "name": "tl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pec_girth_mm": { + "name": "pec_girth_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dors_girth_mm": { + "name": "dors_girth_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "caud_girth_mm": { + "name": "caud_girth_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "clasper_inner": { + "name": "clasper_inner", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "clasper_outer": { + "name": "clasper_outer", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sperm": { + "name": "sperm", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ultrasound": { + "name": "ultrasound", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pregnant": { + "name": "pregnant", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "blood1_min": { + "name": "blood1_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lact1": { + "name": "lact1", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gluc1": { + "name": "gluc1", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bhb1": { + "name": "bhb1", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "blood2_min": { + "name": "blood2_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lact2": { + "name": "lact2", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gluc2": { + "name": "gluc2", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bhb2": { + "name": "bhb2", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tagged": { + "name": "tagged", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bait": { + "name": "bait", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "comments": { + "name": "comments", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_file": { + "name": "source_file", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_sheet": { + "name": "source_sheet", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_row": { + "name": "source_row", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "adult_effort": { + "name": "adult_effort", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session": { + "name": "session", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bait_in_min": { + "name": "bait_in_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bait_out_min": { + "name": "bait_out_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "soak_min": { + "name": "soak_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "shark_times": { + "name": "shark_times", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "n_sharks": { + "name": "n_sharks", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "comments": { + "name": "comments", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "adult_samples": { + "name": "adult_samples", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "sample": { + "name": "sample", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "size_cm": { + "name": "size_cm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sex": { + "name": "sex", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "island": { + "name": "island", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "year": { + "name": "year", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "blood": { + "name": "blood", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "species": { + "name": "species", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "experiment": { + "name": "experiment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "shark_no": { + "name": "shark_no", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hct": { + "name": "hct", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hb": { + "name": "hb", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cholesterol": { + "name": "cholesterol", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ffa": { + "name": "ffa", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "triglycerides": { + "name": "triglycerides", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "captures": { + "name": "captures", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "species": { + "name": "species", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site_raw": { + "name": "site_raw", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "set_id": { + "name": "set_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "set_no": { + "name": "set_no", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "shark_no": { + "name": "shark_no", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capture_no": { + "name": "capture_no", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tags": { + "name": "tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "individual_id": { + "name": "individual_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sex": { + "name": "sex", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "age_class": { + "name": "age_class", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "umbilical": { + "name": "umbilical", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "uss": { + "name": "uss", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pcl_mm": { + "name": "pcl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fl_mm": { + "name": "fl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tl_mm": { + "name": "tl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pec_girth_mm": { + "name": "pec_girth_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dors_girth_mm": { + "name": "dors_girth_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "caud_girth_mm": { + "name": "caud_girth_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mass_kg": { + "name": "mass_kg", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "clasper_l": { + "name": "clasper_l", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "clasper_r": { + "name": "clasper_r", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capture_min": { + "name": "capture_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "landing_min": { + "name": "landing_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "release_min": { + "name": "release_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workup_min": { + "name": "workup_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "to_lab": { + "name": "to_lab", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "died": { + "name": "died", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "blood": { + "name": "blood", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dna": { + "name": "dna", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "us_area": { + "name": "us_area", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "us_perimeter": { + "name": "us_perimeter", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "habitat": { + "name": "habitat", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tide_raw": { + "name": "tide_raw", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lavage": { + "name": "lavage", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stomach": { + "name": "stomach", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stomach_contents": { + "name": "stomach_contents", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "min_after_sunset": { + "name": "min_after_sunset", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "min_after_net_in": { + "name": "min_after_net_in", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tide_mm": { + "name": "tide_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tide_trend": { + "name": "tide_trend", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "moon_illum": { + "name": "moon_illum", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "moon_phase": { + "name": "moon_phase", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sst": { + "name": "sst", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dhw": { + "name": "dhw", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_file": { + "name": "source_file", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_sheet": { + "name": "source_sheet", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_row": { + "name": "source_row", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "captures_season": { + "name": "captures_season", + "columns": [ + "season" + ], + "isUnique": false + }, + "captures_site": { + "name": "captures_site", + "columns": [ + "site_id" + ], + "isUnique": false + }, + "captures_individual": { + "name": "captures_individual", + "columns": [ + "individual_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chlorophyll_weekly": { + "name": "chlorophyll_weekly", + "columns": { + "date": { + "name": "date", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "chl": { + "name": "chl", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pixels": { + "name": "pixels", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "climate_monthly": { + "name": "climate_monthly", + "columns": { + "ym": { + "name": "ym", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "oni": { + "name": "oni", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "soi": { + "name": "soi", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "cyclone_points": { + "name": "cyclone_points", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "sid": { + "name": "sid", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ts": { + "name": "ts", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lat": { + "name": "lat", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lon": { + "name": "lon", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "wind_kt": { + "name": "wind_kt", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pres_hpa": { + "name": "pres_hpa", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dist_km": { + "name": "dist_km", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "data_issues": { + "name": "data_issues", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sheet": { + "name": "sheet", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "row": { + "name": "row", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "column": { + "name": "column", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "field_notes": { + "name": "field_notes", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ref_id": { + "name": "ref_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "species": { + "name": "species", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "field_wq": { + "name": "field_wq", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "time_min": { + "name": "time_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "depth_cm": { + "name": "depth_cm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "salinity": { + "name": "salinity", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "do_mg": { + "name": "do_mg", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "do_pct": { + "name": "do_pct", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "temp": { + "name": "temp", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ph": { + "name": "ph", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "hobo": { + "name": "hobo", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site_raw": { + "name": "site_raw", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "logger": { + "name": "logger", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deployed": { + "name": "deployed", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "retrieved": { + "name": "retrieved", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "individuals": { + "name": "individuals", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "species": { + "name": "species", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sex": { + "name": "sex", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_date": { + "name": "first_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_date": { + "name": "last_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "n_captures": { + "name": "n_captures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "n_seasons": { + "name": "n_seasons", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sites": { + "name": "sites", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_tl_mm": { + "name": "first_tl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_tl_mm": { + "name": "last_tl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tags": { + "name": "tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "conflict": { + "name": "conflict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "lab_feeding": { + "name": "lab_feeding", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tank": { + "name": "tank", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "shark": { + "name": "shark", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "food_g": { + "name": "food_g", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rejected_g": { + "name": "rejected_g", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pct": { + "name": "pct", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "lab_sharks": { + "name": "lab_sharks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "shark_no": { + "name": "shark_no", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "individual_id": { + "name": "individual_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "species": { + "name": "species", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sex": { + "name": "sex", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "arrival_date": { + "name": "arrival_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "release_date": { + "name": "release_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "days": { + "name": "days", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "arr_tl_mm": { + "name": "arr_tl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "arr_fl_mm": { + "name": "arr_fl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "arr_mass_kg": { + "name": "arr_mass_kg", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rel_tl_mm": { + "name": "rel_tl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rel_fl_mm": { + "name": "rel_fl_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rel_mass_kg": { + "name": "rel_mass_kg", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tank": { + "name": "tank", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "project": { + "name": "project", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "died": { + "name": "died", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_file": { + "name": "source_file", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_sheet": { + "name": "source_sheet", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_row": { + "name": "source_row", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "lab_wq": { + "name": "lab_wq", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "time_min": { + "name": "time_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tank": { + "name": "tank", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "temp": { + "name": "temp", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ph": { + "name": "ph", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "do_mg": { + "name": "do_mg", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "do_pct": { + "name": "do_pct", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "salinity": { + "name": "salinity", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "recorder": { + "name": "recorder", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "logger_daily": { + "name": "logger_daily", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mean": { + "name": "mean", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "min": { + "name": "min", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "max": { + "name": "max", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hours": { + "name": "hours", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "loggers": { + "name": "loggers", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "logger_daily_site": { + "name": "logger_daily_site", + "columns": [ + "site_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "logger_diel": { + "name": "logger_diel", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "month": { + "name": "month", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hour": { + "name": "hour", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "temp": { + "name": "temp", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "n": { + "name": "n", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "logger_files": { + "name": "logger_files", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "system": { + "name": "system", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logger": { + "name": "logger", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "serial": { + "name": "serial", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site_basis": { + "name": "site_basis", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "start": { + "name": "start", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "end": { + "name": "end", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "samples": { + "name": "samples", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kept": { + "name": "kept", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lat": { + "name": "lat", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lon": { + "name": "lon", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "excluded": { + "name": "excluded", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "meta": { + "name": "meta", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "mouth": { + "name": "mouth", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "shark_no": { + "name": "shark_no", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "species": { + "name": "species", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sex": { + "name": "sex", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mol": { + "name": "mol", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mow": { + "name": "mow", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "nursery_routes": { + "name": "nursery_routes", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "from_site_id": { + "name": "from_site_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "to_site_id": { + "name": "to_site_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "km": { + "name": "km", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "straight_km": { + "name": "straight_km", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "coordinates": { + "name": "coordinates", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "nursery_routes_pair": { + "name": "nursery_routes_pair", + "columns": [ + "from_site_id", + "to_site_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ocean_daily": { + "name": "ocean_daily", + "columns": { + "date": { + "name": "date", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "oisst": { + "name": "oisst", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "crw_sst": { + "name": "crw_sst", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "crw_anom": { + "name": "crw_anom", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "crw_hotspot": { + "name": "crw_hotspot", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "crw_dhw": { + "name": "crw_dhw", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "crw_baa": { + "name": "crw_baa", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wave_max": { + "name": "wave_max", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wave_period": { + "name": "wave_period", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wave_dir": { + "name": "wave_dir", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "swell_max": { + "name": "swell_max", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "prey": { + "name": "prey", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "school_holidays": { + "name": "school_holidays", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "school_year": { + "name": "school_year", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "start": { + "name": "start", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "end": { + "name": "end", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "set_crew": { + "name": "set_crew", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "set_id": { + "name": "set_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "person": { + "name": "person", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "set_crew_set": { + "name": "set_crew_set", + "columns": [ + "set_id" + ], + "isUnique": false + }, + "set_crew_person": { + "name": "set_crew_person", + "columns": [ + "person" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sets": { + "name": "sets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "season": { + "name": "season", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "set_no": { + "name": "set_no", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site_id": { + "name": "site_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "site_raw": { + "name": "site_raw", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "weekday": { + "name": "weekday", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gear": { + "name": "gear", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visit": { + "name": "visit", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "crew_raw": { + "name": "crew_raw", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "crew_size": { + "name": "crew_size", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "start_min": { + "name": "start_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "end_min": { + "name": "end_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_min": { + "name": "duration_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "n_cm": { + "name": "n_cm", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "n_na": { + "name": "n_na", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "n_nf": { + "name": "n_nf", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "n_total": { + "name": "n_total", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "n_linked": { + "name": "n_linked", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpue": { + "name": "cpue", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpue_cm": { + "name": "cpue_cm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpue_na": { + "name": "cpue_na", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpue_sheet": { + "name": "cpue_sheet", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tide_raw": { + "name": "tide_raw", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "moon_raw": { + "name": "moon_raw", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "weather_raw": { + "name": "weather_raw", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cloud_cover": { + "name": "cloud_cover", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "water_temp": { + "name": "water_temp", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ph": { + "name": "ph", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "do_mg": { + "name": "do_mg", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "do_pct": { + "name": "do_pct", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "salinity": { + "name": "salinity", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "depth_cm": { + "name": "depth_cm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sunset_min": { + "name": "sunset_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "civil_dusk_min": { + "name": "civil_dusk_min", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "moon_phase": { + "name": "moon_phase", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "moon_illum": { + "name": "moon_illum", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "moon_alt_mid": { + "name": "moon_alt_mid", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tide_start_mm": { + "name": "tide_start_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tide_mid_mm": { + "name": "tide_mid_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tide_trend": { + "name": "tide_trend", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tide_range_mm": { + "name": "tide_range_mm", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "air_temp": { + "name": "air_temp", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wind_speed": { + "name": "wind_speed", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wind_dir": { + "name": "wind_dir", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gusts": { + "name": "gusts", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rain_24h": { + "name": "rain_24h", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rain_evening": { + "name": "rain_evening", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cloud_evening": { + "name": "cloud_evening", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pressure": { + "name": "pressure", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sst": { + "name": "sst", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sst_anom": { + "name": "sst_anom", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dhw": { + "name": "dhw", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chl": { + "name": "chl", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wave_height": { + "name": "wave_height", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "swell_height": { + "name": "swell_height", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "oni": { + "name": "oni", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "insitu_temp": { + "name": "insitu_temp", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_file": { + "name": "source_file", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_sheet": { + "name": "source_sheet", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_row": { + "name": "source_row", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sets_season": { + "name": "sets_season", + "columns": [ + "season" + ], + "isUnique": false + }, + "sets_site": { + "name": "sets_site", + "columns": [ + "site_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sites": { + "name": "sites", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "island": { + "name": "island", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lat": { + "name": "lat", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lon": { + "name": "lon", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "coord_source": { + "name": "coord_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "retired": { + "name": "retired", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fishing_effort": { + "name": "fishing_effort", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "human_impact": { + "name": "human_impact", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "artificialisation": { + "name": "artificialisation", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pressure_composite": { + "name": "pressure_composite", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pressure_tier": { + "name": "pressure_tier", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "directions": { + "name": "directions", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "habitat": { + "name": "habitat", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "aliases": { + "name": "aliases", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tide_extrema": { + "name": "tide_extrema", + "columns": { + "ts": { + "name": "ts", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mm": { + "name": "mm", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tide_hourly": { + "name": "tide_hourly", + "columns": { + "ts": { + "name": "ts", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "mm": { + "name": "mm", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "weather_daily": { + "name": "weather_daily", + "columns": { + "date": { + "name": "date", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "tmax": { + "name": "tmax", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmin": { + "name": "tmin", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmean": { + "name": "tmean", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "precip": { + "name": "precip", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wind_max": { + "name": "wind_max", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gust_max": { + "name": "gust_max", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wind_dir": { + "name": "wind_dir", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "radiation": { + "name": "radiation", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cloud": { + "name": "cloud", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pressure": { + "name": "pressure", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "humidity": { + "name": "humidity", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sunshine_h": { + "name": "sunshine_h", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "weather_hourly": { + "name": "weather_hourly", + "columns": { + "ts": { + "name": "ts", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "temp": { + "name": "temp", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "precip": { + "name": "precip", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cloud": { + "name": "cloud", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wind": { + "name": "wind", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wind_dir": { + "name": "wind_dir", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gust": { + "name": "gust", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pressure": { + "name": "pressure", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 8836709..db31ec2 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1793749487724, "tag": "0005_melted_fat_cobra", "breakpoints": true + }, + { + "idx": 6, + "version": "6", + "when": 1794445415461, + "tag": "0006_keen_shaman", + "breakpoints": true } ] } \ No newline at end of file diff --git a/e2e/map-routes.spec.ts b/e2e/map-routes.spec.ts new file mode 100644 index 0000000..133b5db --- /dev/null +++ b/e2e/map-routes.spec.ts @@ -0,0 +1,70 @@ +import { expect, test } from '@playwright/test'; + +test.beforeEach(async ({ page }) => { + await page.route(/server\.arcgisonline\.com|tile\.openstreetmap\.org/, (route) => route.abort()); +}); + +test('recaptures map renders routed water lines with water and direct km (#183)', async ({ + page +}) => { + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.goto('/recaptures'); + + const map = page.getByRole('region', { + name: "Map of recaptured sharks' moves between nurseries" + }); + await expect(map).toBeVisible(); + + // Line follows multi-point routed path around the island + const line = map.locator('.ps-line-0[role="button"]').first(); + await expect(line).toBeVisible(); + const d = await line.getAttribute('d'); + expect(d).not.toBeNull(); + // Multi-segment water route has multiple M/L coordinates + expect(d!.match(/[ML]/g)!.length).toBeGreaterThanOrEqual(4); + + // Line tooltip or popup reflects water km + await line.focus(); + await line.press('Enter'); + const popup = map.locator('.leaflet-popup-content'); + await expect(popup).toBeVisible(); + await expect(popup).toContainText('km by water'); + + // Note credits OpenStreetMap coastline data + await expect(page.getByText('OpenStreetMap coastline data')).toBeVisible(); + + // Longest moves table displays both water km and direct km + const table = page.locator('table').first(); + await expect(table.getByRole('columnheader', { name: 'km (water)' })).toBeVisible(); + await expect(table.getByRole('columnheader', { name: 'km (direct)' })).toBeVisible(); +}); + +test('shark detail page plays moves along the water route with distance (#183)', async ({ + page +}) => { + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.goto('/recaptures'); + + // Navigate to the first shark with a move from the table + const sharkLink = page.locator('table a[href^="/sharks/"]').first(); + await expect(sharkLink).toBeVisible(); + await sharkLink.click(); + + await expect(page.locator('h1')).toBeVisible(); + + // Subtitle explains water route estimate + await expect(page.getByText('along the shortest water route')).toBeVisible(); + + // Play button and slider exist + const slider = page.locator('#capture-slider'); + if ((await slider.count()) > 0) { + // Advance slider to step 1 (second capture) + await slider.fill('1'); + const output = page.locator('output[for="capture-slider"]'); + await expect(output).toContainText('km by water'); + + // Traveller dot exists on map + const traveller = page.locator('.ps-traveller'); + await expect(traveller).toBeVisible(); + } +}); diff --git a/package.json b/package.json index 9568f0a..5d95694 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "social-preview": "node scripts/make-social-preview.mjs", "external": "node scripts/fetch-external.mjs", "import": "node scripts/import.mjs", + "routes": "node scripts/ocean-routes.mjs", "start": "node scripts/server.mjs" }, "devDependencies": { diff --git a/scripts/ocean-routes.mjs b/scripts/ocean-routes.mjs new file mode 100644 index 0000000..e5d9089 --- /dev/null +++ b/scripts/ocean-routes.mjs @@ -0,0 +1,71 @@ +#!/usr/bin/env node +/** + * Compute and verify shortest water routes between Moorea nurseries (#183). + * + * Usage: + * node scripts/ocean-routes.mjs + * node scripts/ocean-routes.mjs --geojson + * + * Uses Moorea coastline polygon from src/lib/moorea-outline.json (ODbL 1.0). + */ +import { SITE_DEFS } from '../src/lib/server/import/sites.ts'; +import { + buildMooreaWaterGrid, + computeAllNurseryRoutes, + crossesLand, + routeToGeoJson +} from '../src/lib/server/oceanRoutes.ts'; + +const args = process.argv.slice(2); +const asGeoJson = args.includes('--geojson'); + +const nurseries = SITE_DEFS.filter( + (s) => s.island === 'Moorea' && s.kind === 'nursery' && s.lat != null && s.lon != null +).map((s) => ({ id: s.id, name: s.name, lat: s.lat, lon: s.lon })); + +const t0 = performance.now(); +const grid = buildMooreaWaterGrid({ cell: 35, padM: 2000 }); +const routes = computeAllNurseryRoutes(nurseries, grid); +const elapsedMs = Math.round(performance.now() - t0); + +if (asGeoJson) { + const fc = { + type: 'FeatureCollection', + features: routes.map((r) => routeToGeoJson(r)) + }; + process.stdout.write(JSON.stringify(fc, null, 2) + '\n'); + process.exit(0); +} + +let landCrossings = 0; +for (const r of routes) { + if (crossesLand(grid, r.coordinates)) { + landCrossings++; + console.error(`Warning: route ${r.fromId} -> ${r.toId} intersects land`); + } +} + +console.log( + `Computed ${routes.length} water routes across ${nurseries.length} nurseries in ${elapsedMs} ms:\n` +); +console.log( + `${'From'.padEnd(14)} ${'To'.padEnd(14)} ${'Water km'.padStart(10)} ${'Direct km'.padStart(10)} ${'Ratio'.padStart(8)} ${'Vertices'.padStart(10)}` +); +console.log('-'.repeat(72)); + +for (const r of routes) { + const ratio = r.straightKm > 0 ? (r.km / r.straightKm).toFixed(2) : '-'; + console.log( + `${r.fromId.padEnd(14)} ${r.toId.padEnd(14)} ${r.km.toFixed(1).padStart(10)} ${r.straightKm.toFixed(1).padStart(10)} ${ratio.padStart(8)} ${String(r.coordinates.length).padStart(10)}` + ); +} + +console.log('-'.repeat(72)); +console.log(`Total pairs: ${routes.length}`); +console.log(`Land crossings: ${landCrossings}`); +if (landCrossings === 0) { + console.log('✓ All routes stay entirely on water (no land intersections).'); +} else { + console.error(`✗ ${landCrossings} route(s) intersect land.`); + process.exit(1); +} diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index f4b70cc..3fda073 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -53,7 +53,7 @@ import { onMount, tick } from 'svelte'; import MooreaMap from './MooreaMap.svelte'; import { registerCsv } from './charts/csv'; - import { directedPoints, lineWidth, reversed, shiftFor } from './lineGeometry'; + import { lineWidth, offsetPolyline, pointAlongPath, reversed, shiftFor } from './lineGeometry'; let { layers, @@ -77,11 +77,13 @@ density?: MapDensity; /** Value that gets the widest line; fix it so widths don't jump as lines are added. */ lineMax?: number; - /** A dot that glides from `from` to `to` whenever `key` changes (a Play button). */ + /** A dot that glides from `from` to `to` along the water route whenever `key` changes (a Play button). */ traveller?: { key: string | number; from: { lat: number; lon: number }; to: { lat: number; lon: number }; + path?: [number, number][]; + km?: number | null; color: string; }; /** Accessible name of the map region. */ @@ -290,16 +292,27 @@ const group = L.layerGroup(); for (const l of g.lines) { const weight = lineWidth(l.value, lineMax); - const a = m.latLngToLayerPoint([l.from.lat, l.from.lon]); - const b = m.latLngToLayerPoint([l.to.lat, l.to.lon]); - const pts = directedPoints(a.x, a.y, b.x, b.y, back[n++] ? shiftFor(weight) : 0).map( - ([x, y]) => m.layerPointToLatLng([x, y]) - ); - const line = L.polyline(pts, { + const rawPts: [number, number][] = l.path + ? l.path.map(([lat, lon]) => { + const pt = m.latLngToLayerPoint([lat, lon]); + return [pt.x, pt.y]; + }) + : [ + (() => { + const pt = m.latLngToLayerPoint([l.from.lat, l.from.lon]); + return [pt.x, pt.y]; + })(), + (() => { + const pt = m.latLngToLayerPoint([l.to.lat, l.to.lon]); + return [pt.x, pt.y]; + })() + ]; + const shiftedPts = offsetPolyline(rawPts, back[n++] ? shiftFor(weight) : 0); + const latLngs = shiftedPts.map(([x, y]) => m.layerPointToLatLng([x, y])); + const line = L.polyline(latLngs, { weight, className: `ps-line ps-line-${i}`, lineCap: 'round', - // Keep the midpoint the arrow marker hangs on (Leaflet would simplify it away). smoothFactor: 0 }); line.on('add', () => @@ -364,10 +377,14 @@ dot = undefined; if (!t) return; const still = matchMedia('(prefers-reduced-motion: reduce)').matches; - const at = (f: number): [number, number] => [ - t.from.lat + (t.to.lat - t.from.lat) * f, - t.from.lon + (t.to.lon - t.from.lon) * f - ]; + const path: [number, number][] = + t.path && t.path.length >= 2 + ? t.path + : [ + [t.from.lat, t.from.lon], + [t.to.lat, t.to.lon] + ]; + const at = (f: number): [number, number] => pointAlongPath(path, f); const marker = L.circleMarker(at(still ? 1 : 0), { radius: 7, className: 'ps-traveller', @@ -378,8 +395,9 @@ if (still) return; const start = performance.now(); let frame = 0; + const duration = t.km != null ? Math.min(2500, Math.max(800, 500 + t.km * 60)) : 800; const step = (now: number) => { - const f = Math.min(1, (now - start) / 800); + const f = Math.min(1, (now - start) / duration); const eased = f < 0.5 ? 2 * f * f : 1 - (-2 * f + 2) ** 2 / 2; marker.setLatLng(at(eased)); if (f < 1) frame = requestAnimationFrame(step); diff --git a/src/lib/components/MooreaMap.svelte b/src/lib/components/MooreaMap.svelte index 57a9f0e..fc0bb97 100644 --- a/src/lib/components/MooreaMap.svelte +++ b/src/lib/components/MooreaMap.svelte @@ -10,12 +10,14 @@ sub?: string; } - /** A straight line between two places, e.g. a shark's move between nurseries. */ + /** A straight or routed water line between two places, e.g. a shark's move between nurseries. */ export interface MapLine { id: string; label: string; from: { lat: number; lon: number }; to: { lat: number; lon: number }; + /** Optional multi-point routed water path [lat, lon][]. */ + path?: [number, number][]; /** Sets the line width (relative to the largest). */ value?: number; color?: string; @@ -28,7 +30,7 @@ import Tip, { type TipState } from './charts/Tip.svelte'; import { registerCsv } from './charts/csv'; import { KEYS_HINT, markAt, markKeys, pointerIn } from './charts/marks'; - import { directedPoints, lineWidth, reversed, shiftFor } from './lineGeometry'; + import { lineWidth, offsetPolyline, reversed, shiftFor } from './lineGeometry'; let { points, @@ -124,17 +126,17 @@ const back = reversed(lines); return lines.map((l, i) => { const w = lineWidth(l.value, lineMax); - const pts = directedPoints( - px(l.from.lon), - py(l.from.lat), - px(l.to.lon), - py(l.to.lat), - back[i] ? shiftFor(w) : 0 - ); + const rawPts: [number, number][] = l.path + ? l.path.map(([lat, lon]) => [px(lon), py(lat)]) + : [ + [px(l.from.lon), py(l.from.lat)], + [px(l.to.lon), py(l.to.lat)] + ]; + const shiftedPts = offsetPolyline(rawPts, back[i] ? shiftFor(w) : 0); return { line: l, w, - points: pts.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' '), + points: shiftedPts.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' '), arrow: colours.indexOf(l.color ?? 'var(--series-1)') }; }); diff --git a/src/lib/components/lineGeometry.test.ts b/src/lib/components/lineGeometry.test.ts index 53af6d3..60b295b 100644 --- a/src/lib/components/lineGeometry.test.ts +++ b/src/lib/components/lineGeometry.test.ts @@ -1,5 +1,12 @@ import { describe, expect, it } from 'vitest'; -import { directedPoints, reversed, shiftFor } from './lineGeometry'; +import { + directedPoints, + offsetPolyline, + pointAlongPath, + polylineArrow, + reversed, + shiftFor +} from './lineGeometry'; const A = { lat: -17.5, lon: -149.9 }; const B = { lat: -17.6, lon: -149.8 }; @@ -40,3 +47,71 @@ describe('directedPoints', () => { expect(2 * shiftFor(w)).toBeGreaterThan(w); }); }); + +describe('offsetPolyline', () => { + it('returns original points when shift is 0', () => { + const pts: [number, number][] = [ + [0, 0], + [10, 0], + [10, 10] + ]; + expect(offsetPolyline(pts, 0)).toEqual(pts); + }); + + it('shifts 2-point and multi-point polylines rightward', () => { + const pts2: [number, number][] = [ + [0, 0], + [10, 0] + ]; + const rev2: [number, number][] = [ + [10, 0], + [0, 0] + ]; + const off = offsetPolyline(pts2, 4); + const offRev = offsetPolyline(rev2, 4); + expect(off).toEqual([ + [0, 4], + [6, 4], + [10, 4] + ]); + expect(offRev).toEqual([ + [10, -4], + [4, -4], + [0, -4] + ]); + }); +}); + +describe('polylineArrow', () => { + it('places arrow at 60% of total length along multi-segment line', () => { + // Total length 20 (0 to 10 on x, then 0 to 10 on y). 60% is distance 12 -> at [10, 2] + const pts: [number, number][] = [ + [0, 0], + [10, 0], + [10, 10] + ]; + const arrow = polylineArrow(pts); + expect(arrow[1][0]).toBeCloseTo(10, 4); + expect(arrow[1][1]).toBeCloseTo(2, 4); + // Orientation points along y axis + expect(arrow[0][0]).toBeCloseTo(10, 4); + expect(arrow[2][0]).toBeCloseTo(10, 4); + expect(arrow[2][1]).toBeGreaterThan(arrow[0][1]); + }); +}); + +describe('pointAlongPath', () => { + const path: [number, number][] = [ + [0, 0], + [10, 0], + [10, 10] + ]; + + it('interpolates along vertices', () => { + expect(pointAlongPath(path, 0)).toEqual([0, 0]); + expect(pointAlongPath(path, 0.25)).toEqual([5, 0]); + expect(pointAlongPath(path, 0.5)).toEqual([10, 0]); + expect(pointAlongPath(path, 0.75)).toEqual([10, 5]); + expect(pointAlongPath(path, 1)).toEqual([10, 10]); + }); +}); diff --git a/src/lib/components/lineGeometry.ts b/src/lib/components/lineGeometry.ts index 413b9a5..a7f6901 100644 --- a/src/lib/components/lineGeometry.ts +++ b/src/lib/components/lineGeometry.ts @@ -1,11 +1,9 @@ /** - * Directed move lines (#182): shared by MooreaMap (SVG) and InteractiveMap (Leaflet). + * Directed move lines (#182, #183): shared by MooreaMap (SVG) and InteractiveMap (Leaflet). * - * A line is drawn as three points (start, arrow point, end) so an SVG `marker-mid` arrow sits - * 60% of the way along, clear of the circles at either end; the arrows of A → B and B → A then - * land at different places instead of side by side. When the reverse move is also drawn, both lines - * shift sideways to the right of their direction of travel, so A → B and B → A sit side by side - * instead of on top of each other. + * For straight lines or multi-segment water routes, lines are drawn with a directional arrow + * sitting 60% of the way along. When the reverse move is also drawn, both lines shift sideways + * to the right of their direction of travel, so A → B and B → A sit side by side without overlapping. */ interface Ends { @@ -22,7 +20,7 @@ export function reversed(lines: Ends[]): boolean[] { return lines.map((l) => all.has(key(l.to, l.from))); } -const ARROW_AT = 0.6; +export const ARROW_AT = 0.6; /** Screen points of a line, shifted `shift` px to the right of travel, with its arrow point. */ export function directedPoints( @@ -47,3 +45,112 @@ export const lineWidth = (value: number | undefined, max: number) => /** Sideways shift for a line of this width when its reverse is drawn too. */ export const shiftFor = (width: number) => width / 2 + 4; + +/** + * Shift a multi-point polyline in screen coordinates to the right of travel by `shift` px. + * For 2-point lines, delegates to directedPoints so the line includes its 60% arrow point. + */ +export function offsetPolyline(pts: [number, number][], shift: number): [number, number][] { + if (pts.length < 2) return pts.map(([x, y]) => [x, y]); + const n = pts.length; + if (n === 2) { + return directedPoints(pts[0][0], pts[0][1], pts[1][0], pts[1][1], shift); + } + if (!shift) return pts.map(([x, y]) => [x, y]); + const normals: [number, number][] = []; + for (let i = 0; i < n - 1; i++) { + const dx = pts[i + 1][0] - pts[i][0]; + const dy = pts[i + 1][1] - pts[i][1]; + const len = Math.hypot(dx, dy) || 1; + normals.push([(-dy / len) * shift, (dx / len) * shift]); + } + const out: [number, number][] = []; + out.push([pts[0][0] + normals[0][0], pts[0][1] + normals[0][1]]); + for (let i = 1; i < n - 1; i++) { + const mx = (normals[i - 1][0] + normals[i][0]) / 2; + const my = (normals[i - 1][1] + normals[i][1]) / 2; + const mLen = Math.hypot(mx, my); + if (mLen > 1e-6) { + out.push([ + pts[i][0] + (mx / mLen) * Math.abs(shift), + pts[i][1] + (my / mLen) * Math.abs(shift) + ]); + } else { + out.push([pts[i][0] + normals[i][0], pts[i][1] + normals[i][1]]); + } + } + out.push([pts[n - 1][0] + normals[n - 2][0], pts[n - 1][1] + normals[n - 2][1]]); + return out; +} + +/** + * Returns a 3-point segment around the 60% cumulative-length point of a polyline, + * oriented in the direction of travel, for SVG marker-mid arrow rendering. + */ +export function polylineArrow(pts: [number, number][], arrowAt = ARROW_AT): [number, number][] { + if (pts.length < 2) return [pts[0] ?? [0, 0], pts[0] ?? [0, 0], pts[0] ?? [0, 0]]; + let total = 0; + const lens: number[] = []; + for (let i = 0; i < pts.length - 1; i++) { + const d = Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]); + lens.push(d); + total += d; + } + if (total === 0) return [pts[0], pts[0], pts[0]]; + const target = total * arrowAt; + let acc = 0; + for (let i = 0; i < pts.length - 1; i++) { + if (acc + lens[i] >= target || i === pts.length - 2) { + const segLen = lens[i] || 1; + const rem = Math.max(0, target - acc); + const t = Math.min(1, rem / segLen); + const x0 = pts[i][0]; + const y0 = pts[i][1]; + const x1 = pts[i + 1][0]; + const y1 = pts[i + 1][1]; + const ax = x0 + t * (x1 - x0); + const ay = y0 + t * (y1 - y0); + const ux = (x1 - x0) / segLen; + const uy = (y1 - y0) / segLen; + return [ + [ax - ux * 0.1, ay - uy * 0.1], + [ax, ay], + [ax + ux * 0.1, ay + uy * 0.1] + ]; + } + acc += lens[i]; + } + return [pts[0], pts[0], pts[0]]; +} + +/** + * Interpolate a position along a multi-point path at fraction f in [0, 1]. + */ +export function pointAlongPath(path: [number, number][], f: number): [number, number] { + if (path.length === 0) return [0, 0]; + if (path.length === 1 || f <= 0) return path[0]; + if (f >= 1) return path[path.length - 1]; + let total = 0; + const lens: number[] = []; + for (let i = 0; i < path.length - 1; i++) { + const d = Math.hypot(path[i + 1][0] - path[i][0], path[i + 1][1] - path[i][1]); + lens.push(d); + total += d; + } + if (total === 0) return path[0]; + const target = total * f; + let acc = 0; + for (let i = 0; i < path.length - 1; i++) { + if (acc + lens[i] >= target || i === path.length - 2) { + const segLen = lens[i] || 1; + const rem = Math.max(0, target - acc); + const t = Math.min(1, rem / segLen); + return [ + path[i][0] + t * (path[i + 1][0] - path[i][0]), + path[i][1] + t * (path[i + 1][1] - path[i][1]) + ]; + } + acc += lens[i]; + } + return path[path.length - 1]; +} diff --git a/src/lib/server/data.ts b/src/lib/server/data.ts index 4d04033..1e98b0f 100644 --- a/src/lib/server/data.ts +++ b/src/lib/server/data.ts @@ -16,12 +16,14 @@ export type WeatherDay = typeof schema.weatherDaily.$inferSelect; export type OceanDay = typeof schema.oceanDaily.$inferSelect; export type DataIssue = typeof schema.dataIssues.$inferSelect; export type LoggerDay = typeof schema.loggerDaily.$inferSelect; +export type NurseryRoute = typeof schema.nurseryRoutes.$inferSelect; export interface Dataset { version: number; meta: Record; sites: Site[]; siteById: Map; + nurseryRoutes: NurseryRoute[]; sets: SetRow[]; setById: Map; crew: { setId: number; person: string }[]; @@ -76,6 +78,7 @@ export function dataset(): Dataset { ), sites, siteById: new Map(sites.map((s) => [s.id, s])), + nurseryRoutes: db.select().from(schema.nurseryRoutes).all(), sets, setById: new Map(sets.map((s) => [s.id, s])), crew: db.select().from(schema.setCrew).all(), @@ -151,3 +154,23 @@ export function weatherHourlyAll() { /** Field (nursery gillnet) captures only: excludes hook-and-line adults and lab releases. */ export const isNursery = (c: Capture) => c.kind === 'field'; export const isGillnet = (s: SetRow) => s.gear === 'Gillnet'; + +/** + * Retrieve the shortest water route between two nurseries, in the direction from `fromId` to `toId`. + */ +export function nurseryRoute( + d: Dataset, + fromId: string, + toId: string +): { km: number; straightKm: number; coordinates: [number, number][] } | null { + if (!fromId || !toId || fromId === toId) return null; + const [a, b] = fromId < toId ? [fromId, toId] : [toId, fromId]; + const r = d.nurseryRoutes.find((r) => r.fromId === a && r.toId === b); + if (!r) return null; + const coords = JSON.parse(r.coordinates) as [number, number][]; + return { + km: r.km, + straightKm: r.straightKm, + coordinates: fromId < toId ? coords : [...coords].reverse() + }; +} diff --git a/src/lib/server/db/schema.ts b/src/lib/server/db/schema.ts index 3ed1aee..1713994 100644 --- a/src/lib/server/db/schema.ts +++ b/src/lib/server/db/schema.ts @@ -534,3 +534,17 @@ export const dataIssues = sqliteTable('data_issues', { column: text('column'), value: text('value') }); + +/** Shortest water routes between Moorea nurseries (#183). Coordinates are JSON [lat, lon][]. */ +export const nurseryRoutes = sqliteTable( + 'nursery_routes', + { + id: integer('id').primaryKey(), + fromId: text('from_site_id').notNull(), + toId: text('to_site_id').notNull(), + km: real('km').notNull(), + straightKm: real('straight_km').notNull(), + coordinates: text('coordinates').notNull() + }, + (t) => [index('nursery_routes_pair').on(t.fromId, t.toId)] +); diff --git a/src/lib/server/import/index.ts b/src/lib/server/import/index.ts index c66c23d..ad3634e 100644 --- a/src/lib/server/import/index.ts +++ b/src/lib/server/import/index.ts @@ -73,10 +73,11 @@ import { import { buildLoggerTables } from './insitu'; import { checkRecaptures } from './recaptures'; import { SITE_DEFS } from './sites'; +import { computeAllNurseryRoutes } from '../oceanRoutes'; import { readWorkbook } from './xlsx'; /** Bump when import logic changes so existing caches rebuild on the next start. */ -export const IMPORTER_VERSION = '11'; +export const IMPORTER_VERSION = '12'; const MIGRATIONS = import.meta.glob('/drizzle/*.sql', { query: '?raw', @@ -828,6 +829,20 @@ export function runImport( }; }); + // --- nursery water routes (#183) ------------------------------------------------------------ + const mooreaNurseries = siteRows + .filter((s) => s.island === 'Moorea' && s.kind === 'nursery' && s.lat != null && s.lon != null) + .map((s) => ({ id: s.id, lat: s.lat!, lon: s.lon! })); + const routes = computeAllNurseryRoutes(mooreaNurseries); + const routeRows: (typeof schema.nurseryRoutes.$inferInsert)[] = routes.map((r, i) => ({ + id: i + 1, + fromId: r.fromId, + toId: r.toId, + km: r.km, + straightKm: r.straightKm, + coordinates: JSON.stringify(r.coordinates) + })); + // --- lab sharks: link to individuals ------------------------------------------------------- const labRows: (typeof schema.labSharks.$inferInsert)[] = p.labSharks.map((l, i) => ({ id: i + 1, @@ -962,11 +977,13 @@ export function runImport( labSharks: labRows.length, adultCaptures: p.adults.length, loggerFiles: insitu.files.length, - loggerDays: insitu.daily.length + loggerDays: insitu.daily.length, + nurseryRoutes: routeRows.length }; sqlite.transaction(() => { insert(schema.sites, siteRows); + insert(schema.nurseryRoutes, routeRows); insert(schema.sets, setRows); insert( schema.setCrew, diff --git a/src/lib/server/oceanRoutes.test.ts b/src/lib/server/oceanRoutes.test.ts new file mode 100644 index 0000000..cea2c14 --- /dev/null +++ b/src/lib/server/oceanRoutes.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from 'vitest'; +import { SITE_DEFS } from './import/sites'; +import { + buildMooreaWaterGrid, + computeAllNurseryRoutes, + crossesLand, + routeToGeoJson, + routeWater, + snapToWater +} from './oceanRoutes'; + +describe('oceanRoutes', () => { + const grid = buildMooreaWaterGrid({ cell: 35, padM: 2000 }); + + it('builds a valid Moorea water raster grid', () => { + expect(grid.width).toBeGreaterThan(400); + expect(grid.height).toBeGreaterThan(300); + expect(grid.water.length).toBe(grid.width * grid.height); + expect(grid.distance.length).toBe(grid.width * grid.height); + // More water than land in the padded bbox + let waterCount = 0; + for (let i = 0; i < grid.water.length; i++) { + if (grid.water[i] === 1) waterCount++; + } + expect(waterCount).toBeGreaterThan(grid.water.length / 2); + }); + + it('snaps coastal points to water cells', () => { + const haapiti = SITE_DEFS.find((s) => s.id === 'haapiti')!; + const cellIdx = snapToWater(grid, haapiti.lon!, haapiti.lat!); + expect(cellIdx).toBeGreaterThanOrEqual(0); + expect(grid.water[cellIdx]).toBe(1); + }); + + it('computes shortest water route avoiding land', () => { + const haapiti = SITE_DEFS.find((s) => s.id === 'haapiti')!; + const vaiane = SITE_DEFS.find((s) => s.id === 'vaiane')!; + const route = routeWater( + grid, + { id: haapiti.id, lat: haapiti.lat!, lon: haapiti.lon! }, + { id: vaiane.id, lat: vaiane.lat!, lon: vaiane.lon! } + ); + expect(route).not.toBeNull(); + if (!route) return; + expect(route.fromId).toBe('haapiti'); + expect(route.toId).toBe('vaiane'); + expect(route.km).toBeGreaterThanOrEqual(route.straightKm); + expect(route.coordinates[0]).toEqual([haapiti.lat, haapiti.lon]); + expect(route.coordinates[route.coordinates.length - 1]).toEqual([vaiane.lat, vaiane.lon]); + expect(crossesLand(grid, route.coordinates)).toBe(false); + }); + + it('computes long-distance routes around Moorea', () => { + const apaura = SITE_DEFS.find((s) => s.id === 'apaura')!; + const maharepa = SITE_DEFS.find((s) => s.id === 'maharepa')!; + const route = routeWater( + grid, + { id: apaura.id, lat: apaura.lat!, lon: apaura.lon! }, + { id: maharepa.id, lat: maharepa.lat!, lon: maharepa.lon! } + ); + expect(route).not.toBeNull(); + if (!route) return; + // Straight line is ~11 km across mountain, water route around coast is ~22 km + expect(route.straightKm).toBeLessThan(15); + expect(route.km).toBeGreaterThan(20); + expect(crossesLand(grid, route.coordinates)).toBe(false); + }); + + it('computes all nursery routes without crossing land', () => { + const nurseries = SITE_DEFS.filter( + (s) => s.island === 'Moorea' && s.kind === 'nursery' && s.lat != null && s.lon != null + ).map((s) => ({ id: s.id, lat: s.lat!, lon: s.lon! })); + const routes = computeAllNurseryRoutes(nurseries, grid); + const expectedPairs = (nurseries.length * (nurseries.length - 1)) / 2; + expect(routes.length).toBe(expectedPairs); + for (const r of routes) { + expect(r.km).toBeGreaterThanOrEqual(r.straightKm * 0.99); + expect(crossesLand(grid, r.coordinates)).toBe(false); + } + }); + + it('exports valid GeoJSON LineString Feature', () => { + const haapiti = SITE_DEFS.find((s) => s.id === 'haapiti')!; + const vaiane = SITE_DEFS.find((s) => s.id === 'vaiane')!; + const route = routeWater( + grid, + { id: haapiti.id, lat: haapiti.lat!, lon: haapiti.lon! }, + { id: vaiane.id, lat: vaiane.lat!, lon: vaiane.lon! } + )!; + const gj = routeToGeoJson(route); + expect(gj.type).toBe('Feature'); + expect(gj.geometry.type).toBe('LineString'); + expect(gj.geometry.coordinates[0]).toEqual([haapiti.lon, haapiti.lat]); + expect(gj.geometry.coordinates[gj.geometry.coordinates.length - 1]).toEqual([ + vaiane.lon, + vaiane.lat + ]); + }); +}); diff --git a/src/lib/server/oceanRoutes.ts b/src/lib/server/oceanRoutes.ts new file mode 100644 index 0000000..25d4cd4 --- /dev/null +++ b/src/lib/server/oceanRoutes.ts @@ -0,0 +1,493 @@ +/** + * Shortest water routes between Moorea nurseries (#183). + * + * Adapted from water routing in hikeandexplore (#1661): rasterises Moorea's coastline + * (src/lib/moorea-outline.json, OpenStreetMap ODbL 1.0) on a 35 m grid, runs A* over + * water cells with a cost penalty near land, and pulls strings (straightens) where a + * direct line stays entirely on water without crossing land. + */ +import outline from '../moorea-outline.json' with { type: 'json' }; + +const SQRT2 = Math.SQRT2; + +export interface Bbox { + minLon: number; + minLat: number; + maxLon: number; + maxLat: number; +} + +export interface WaterGrid { + width: number; + height: number; + cell: number; + bbox: Bbox; + kx: number; + ky: number; + water: Uint8Array; + distance: Float32Array; +} + +export interface RouteResult { + fromId: string; + toId: string; + km: number; + straightKm: number; + /** Ordered array of [lat, lon] coordinates from start site to destination site. */ + coordinates: [number, number][]; +} + +/** Binary min-heap of (priority, index) on typed arrays with dynamic resizing. */ +class Heap { + keys: Float64Array; + values: Int32Array; + size: number; + + constructor(capacity = 1024) { + this.keys = new Float64Array(capacity); + this.values = new Int32Array(capacity); + this.size = 0; + } + + push(key: number, value: number) { + if (this.size === this.keys.length) { + const keys = new Float64Array(this.size * 2); + keys.set(this.keys); + const values = new Int32Array(this.size * 2); + values.set(this.values); + this.keys = keys; + this.values = values; + } + let i = this.size++; + while (i > 0) { + const parent = (i - 1) >> 1; + if (this.keys[parent] <= key) break; + this.keys[i] = this.keys[parent]; + this.values[i] = this.values[parent]; + i = parent; + } + this.keys[i] = key; + this.values[i] = value; + } + + pop(): number { + const top = this.values[0]; + const key = this.keys[--this.size]; + const value = this.values[this.size]; + let i = 0; + for (;;) { + let child = 2 * i + 1; + if (child >= this.size) break; + if (child + 1 < this.size && this.keys[child + 1] < this.keys[child]) child++; + if (this.keys[child] >= key) break; + this.keys[i] = this.keys[child]; + this.values[i] = this.values[child]; + i = child; + } + this.keys[i] = key; + this.values[i] = value; + return top; + } +} + +/** + * Visit every cell a segment touches (4-connected supercover). Stops early when visit returns false. + */ +export function traverse( + x0: number, + y0: number, + x1: number, + y1: number, + visit: (x: number, y: number) => boolean | void +): boolean { + let cx = Math.floor(x0); + let cy = Math.floor(y0); + const ex = Math.floor(x1); + const ey = Math.floor(y1); + const dx = x1 - x0; + const dy = y1 - y0; + const stepX = dx > 0 ? 1 : -1; + const stepY = dy > 0 ? 1 : -1; + const tDeltaX = dx !== 0 ? Math.abs(1 / dx) : Infinity; + const tDeltaY = dy !== 0 ? Math.abs(1 / dy) : Infinity; + let tMaxX = dx !== 0 ? (dx > 0 ? cx + 1 - x0 : x0 - cx) * tDeltaX : Infinity; + let tMaxY = dy !== 0 ? (dy > 0 ? cy + 1 - y0 : y0 - cy) * tDeltaY : Infinity; + if (visit(cx, cy) === false) return false; + let n = Math.abs(ex - cx) + Math.abs(ey - cy); + while (n > 0) { + if (Math.abs(tMaxX - tMaxY) < 1e-9 && n >= 2) { + if (visit(cx + stepX, cy) === false || visit(cx, cy + stepY) === false) return false; + tMaxX += tDeltaX; + tMaxY += tDeltaY; + cx += stepX; + cy += stepY; + n -= 2; + } else if (tMaxX < tMaxY) { + tMaxX += tDeltaX; + cx += stepX; + n--; + } else { + tMaxY += tDeltaY; + cy += stepY; + n--; + } + if (visit(cx, cy) === false) return false; + } + return true; +} + +/** Two-pass chamfer distance (m) from each water cell to the nearest land cell. */ +export function distanceToLand( + water: Uint8Array, + width: number, + height: number, + cell: number +): Float32Array { + const d = new Float32Array(width * height); + const diag = cell * SQRT2; + for (let i = 0; i < d.length; i++) d[i] = water[i] ? Infinity : 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const i = y * width + x; + if (!d[i]) continue; + let v = d[i]; + if (x > 0) v = Math.min(v, d[i - 1] + cell); + if (y > 0) { + v = Math.min(v, d[i - width] + cell); + if (x > 0) v = Math.min(v, d[i - width - 1] + diag); + if (x < width - 1) v = Math.min(v, d[i - width + 1] + diag); + } + d[i] = v; + } + } + for (let y = height - 1; y >= 0; y--) { + for (let x = width - 1; x >= 0; x--) { + const i = y * width + x; + if (!d[i]) continue; + let v = d[i]; + if (x < width - 1) v = Math.min(v, d[i + 1] + cell); + if (y < height - 1) { + v = Math.min(v, d[i + width] + cell); + if (x < width - 1) v = Math.min(v, d[i + width + 1] + diag); + if (x > 0) v = Math.min(v, d[i + width - 1] + diag); + } + d[i] = v; + } + } + return d; +} + +/** + * Build the Moorea water raster grid from the simplified island coastline. + * Everything inside the Moorea ring is land (0); the surrounding ocean is water (1). + */ +export function buildMooreaWaterGrid({ + cell = 35, + padM = 2000 +}: { cell?: number; padM?: number } = {}): WaterGrid { + const ring = outline.ring as [number, number][]; + let minLon = Infinity; + let maxLon = -Infinity; + let minLat = Infinity; + let maxLat = -Infinity; + for (const [lon, lat] of ring) { + minLon = Math.min(minLon, lon); + maxLon = Math.max(maxLon, lon); + minLat = Math.min(minLat, lat); + maxLat = Math.max(maxLat, lat); + } + const midLat = (minLat + maxLat) / 2; + const kx = 111320 * Math.cos((midLat * Math.PI) / 180); + const ky = 110540; + const dLat = padM / ky; + const dLon = padM / kx; + const bbox: Bbox = { + minLon: minLon - dLon, + maxLon: maxLon + dLon, + minLat: minLat - dLat, + maxLat: maxLat + dLat + }; + + const width = Math.ceil(((bbox.maxLon - bbox.minLon) * kx) / cell); + const height = Math.ceil(((bbox.maxLat - bbox.minLat) * ky) / cell); + + const toCell = ([lon, lat]: [number, number]): [number, number] => [ + ((lon - bbox.minLon) * kx) / cell, + ((lat - bbox.minLat) * ky) / cell + ]; + const pts = ring.map(toCell); + + const rows = new Map(); + for (let i = 1; i < pts.length; i++) { + const [x0, y0] = pts[i - 1]; + const [x1, y1] = pts[i]; + if (y0 === y1) continue; + const lo = Math.max(0, Math.ceil(Math.min(y0, y1) - 0.5)); + const hi = Math.min(height - 1, Math.floor(Math.max(y0, y1) - 0.5)); + for (let row = lo; row <= hi; row++) { + const yc = row + 0.5; + if (yc < Math.min(y0, y1) || yc >= Math.max(y0, y1)) continue; + const x = x0 + ((yc - y0) / (y1 - y0)) * (x1 - x0); + let list = rows.get(row); + if (!list) rows.set(row, (list = [])); + list.push(x); + } + } + + const water = new Uint8Array(width * height).fill(1); // default water + for (const [row, xs] of rows) { + xs.sort((a, b) => a - b); + for (let i = 0; i + 1 < xs.length; i += 2) { + const from = Math.max(0, Math.ceil(xs[i] - 0.5)); + const to = Math.min(width - 1, Math.floor(xs[i + 1] - 0.5)); + for (let x = from; x <= to; x++) water[row * width + x] = 0; // land + } + } + + const distance = distanceToLand(water, width, height, cell); + return { width, height, cell, bbox, kx, ky, water, distance }; +} + +/** Lon/lat of a cell centre. */ +export function cellCentre(grid: WaterGrid, index: number): [lon: number, lat: number] { + const x = index % grid.width; + const y = Math.floor(index / grid.width); + return [ + grid.bbox.minLon + ((x + 0.5) * grid.cell) / grid.kx, + grid.bbox.minLat + ((y + 0.5) * grid.cell) / grid.ky + ]; +} + +/** + * Snap a point (lon, lat) to the nearest water cell within maxM metres. + */ +export function snapToWater(grid: WaterGrid, lon: number, lat: number, maxM = 3000): number { + const cx = ((lon - grid.bbox.minLon) * grid.kx) / grid.cell; + const cy = ((lat - grid.bbox.minLat) * grid.ky) / grid.cell; + const sx = Math.floor(cx); + const sy = Math.floor(cy); + const reach = Math.ceil(maxM / grid.cell); + let bestDist = Infinity; + let bestIdx = -1; + for (let dy = -reach; dy <= reach; dy++) { + for (let dx = -reach; dx <= reach; dx++) { + const x = sx + dx; + const y = sy + dy; + if (x < 0 || y < 0 || x >= grid.width || y >= grid.height) continue; + const idx = y * grid.width + x; + if (grid.water[idx] !== 1) continue; + const d = Math.hypot(dx, dy); + if (d < bestDist) { + bestDist = d; + bestIdx = idx; + } + } + } + return bestIdx; +} + +/** + * A* search over water cells from start to goal with distance-to-land penalty. + */ +export function findWaterPath( + grid: WaterGrid, + start: number, + goal: number, + { clearanceM = 50, penalty = 2 }: { clearanceM?: number; penalty?: number } = {} +): number[] | null { + const { width, height, water, distance, cell } = grid; + const size = width * height; + const cost = (i: number) => 1 + penalty * Math.max(0, (clearanceM - distance[i]) / clearanceM); + const g = new Float32Array(size).fill(Infinity); + const from = new Int32Array(size).fill(-1); + const closed = new Uint8Array(size); + const gx = goal % width; + const gy = Math.floor(goal / width); + const h = (i: number) => { + const x = i % width; + return Math.hypot(x - gx, Math.floor(i / width) - gy) * cell; + }; + const heap = new Heap(); + g[start] = 0; + heap.push(h(start), start); + while (heap.size) { + const current = heap.pop(); + if (closed[current]) continue; + if (current === goal) break; + closed[current] = 1; + const x = current % width; + const y = Math.floor(current / width); + const cCost = cost(current); + for (let dy = -1; dy <= 1; dy++) { + for (let dx = -1; dx <= 1; dx++) { + if (!dx && !dy) continue; + const nx = x + dx; + const ny = y + dy; + if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue; + const next = ny * width + nx; + if (!water[next] || closed[next]) continue; + // Do not cut land corners on diagonal steps. + if (dx && dy && (!water[y * width + nx] || !water[ny * width + x])) continue; + const step = (dx && dy ? SQRT2 : 1) * cell * ((cCost + cost(next)) / 2); + const tentative = g[current] + step; + if (tentative < g[next]) { + g[next] = tentative; + from[next] = current; + heap.push(tentative + h(next), next); + } + } + } + } + if (start !== goal && from[goal] < 0) return null; + const path = [goal]; + for (let i = goal; i !== start; i = from[i]) path.push(from[i]); + return path.reverse(); +} + +/** + * Straighten a path using raycast string-pulling, ensuring every direct segment stays on water. + */ +export function straightenPath( + grid: WaterGrid, + path: number[], + { clearanceM = 50 }: { clearanceM?: number } = {} +): number[] { + if (path.length <= 2) return path.slice(); + const { width, water, distance } = grid; + const centre = (i: number): [number, number] => [(i % width) + 0.5, Math.floor(i / width) + 0.5]; + const clear = (a: number, b: number, need: number) => { + const [x0, y0] = centre(a); + const [x1, y1] = centre(b); + return traverse(x0, y0, x1, y1, (x, y) => { + const i = y * width + x; + return water[i] === 1 && distance[i] >= need; + }); + }; + const out = [path[0]]; + let anchor = 0; + while (anchor < path.length - 1) { + let need = Math.min(clearanceM, distance[path[anchor]]); + let best = anchor + 1; + for (let j = anchor + 1; j < path.length; j++) { + need = Math.min(need, distance[path[j]]); + if (clear(path[anchor], path[j], need)) best = j; + else if (j - best > 64) break; + } + out.push(path[best]); + anchor = best; + } + return out; +} + +/** + * Compute the shortest water route between two locations. + * Returns coordinates as an ordered array of [lat, lon] tuples. + */ +export function routeWater( + grid: WaterGrid, + from: { id?: string; lat: number; lon: number }, + to: { id?: string; lat: number; lon: number }, + { clearanceM = 50, penalty = 2 }: { clearanceM?: number; penalty?: number } = {} +): RouteResult | null { + const s1 = snapToWater(grid, from.lon, from.lat); + const s2 = snapToWater(grid, to.lon, to.lat); + if (s1 < 0 || s2 < 0) return null; + + const rawPath = findWaterPath(grid, s1, s2, { clearanceM, penalty }); + if (!rawPath) return null; + + const smoothed = straightenPath(grid, rawPath, { clearanceM }); + const coordinates: [number, number][] = [[from.lat, from.lon]]; + for (const idx of smoothed) { + const [lon, lat] = cellCentre(grid, idx); + coordinates.push([lat, lon]); + } + coordinates.push([to.lat, to.lon]); + + // Filter out zero-length steps if start/end coincided with snapped cell + const cleaned = coordinates.filter( + (pt, i) => + i === 0 || Math.hypot(pt[0] - coordinates[i - 1][0], pt[1] - coordinates[i - 1][1]) > 1e-7 + ); + + let km = 0; + for (let i = 1; i < cleaned.length; i++) { + const dX = (cleaned[i][1] - cleaned[i - 1][1]) * grid.kx; + const dY = (cleaned[i][0] - cleaned[i - 1][0]) * grid.ky; + km += Math.hypot(dX, dY) / 1000; + } + + const straightKm = + Math.hypot((to.lon - from.lon) * grid.kx, (to.lat - from.lat) * grid.ky) / 1000; + + return { + fromId: from.id ?? '', + toId: to.id ?? '', + km: Math.round(km * 100) / 100, + straightKm: Math.round(straightKm * 100) / 100, + coordinates: cleaned + }; +} + +/** + * Check whether any segment of coordinates (excluding the short landing legs) crosses land. + */ +export function crossesLand(grid: WaterGrid, coordinates: [number, number][]): boolean { + const toCell = ([lat, lon]: [number, number]): [number, number] => [ + ((lon - grid.bbox.minLon) * grid.kx) / grid.cell, + ((lat - grid.bbox.minLat) * grid.ky) / grid.cell + ]; + // Only test intermediate water segments (skip indices 0->1 and (N-2)->(N-1) which are shore landings). + if (coordinates.length <= 3) return false; + for (let i = 2; i < coordinates.length - 1; i++) { + const [x0, y0] = toCell(coordinates[i - 1]); + const [x1, y1] = toCell(coordinates[i]); + const ok = traverse(x0, y0, x1, y1, (x, y) => { + if (x < 0 || y < 0 || x >= grid.width || y >= grid.height) return true; + return grid.water[y * grid.width + x] === 1; + }); + if (!ok) return true; + } + return false; +} + +/** + * Precompute shortest water routes for all pairs of Moorea nurseries. + * Generates an unordered pair (a, b) where a.id < b.id. + */ +export function computeAllNurseryRoutes( + nurseries: { id: string; lat: number; lon: number }[], + grid?: WaterGrid +): RouteResult[] { + const g = grid ?? buildMooreaWaterGrid(); + const results: RouteResult[] = []; + const sorted = [...nurseries].sort((a, b) => a.id.localeCompare(b.id)); + for (let i = 0; i < sorted.length; i++) { + for (let j = i + 1; j < sorted.length; j++) { + const route = routeWater(g, sorted[i], sorted[j]); + if (route) { + results.push(route); + } + } + } + return results; +} + +/** + * Export a route as standard GeoJSON Feature (RFC 7946, [lon, lat] coordinates). + */ +export function routeToGeoJson(route: RouteResult) { + return { + type: 'Feature' as const, + properties: { + from: route.fromId, + to: route.toId, + km: route.km, + straightKm: route.straightKm + }, + geometry: { + type: 'LineString' as const, + coordinates: route.coordinates.map(([lat, lon]) => [lon, lat]) + } + }; +} diff --git a/src/routes/recaptures/+page.server.ts b/src/routes/recaptures/+page.server.ts index b4337b9..3c0c973 100644 --- a/src/routes/recaptures/+page.server.ts +++ b/src/routes/recaptures/+page.server.ts @@ -1,4 +1,4 @@ -import { memo } from '#lib/server/data'; +import { memo, nurseryRoute } from '#lib/server/data'; import { activeNurseries, fieldCaptures, @@ -63,14 +63,18 @@ export const load: PageServerLoad = () => const to = place(e.b); if (!from || !to) return []; const [na, nb] = [siteName(d, e.a), siteName(d, e.b)]; + const route = nurseryRoute(d, e.a, e.b); + const km = route?.km ?? dist(e.a, e.b); + const straightKm = route?.straightKm ?? dist(e.a, e.b); return [ { id: `${sp}-${e.a}-${e.b}`, label: `${na} → ${nb}`, from, to, + path: route?.coordinates, value: e.n, - sub: `${e.n} move${e.n === 1 ? '' : 's'} · ${round(dist(e.a, e.b), 1)} km` + sub: `${e.n} move${e.n === 1 ? '' : 's'} · ${round(km, 1)} km by water${straightKm != null && km != null && Math.abs(km - straightKm) > 0.5 ? ` (${round(straightKm, 1)} km straight line)` : ''}` } ]; }) @@ -95,15 +99,21 @@ export const load: PageServerLoad = () => ]; }); const longest = moved - .map((p) => ({ - id: p.id, - species: p.species, - from: siteName(d, p.a.siteId), - to: siteName(d, p.b.siteId), - km: round(dist(p.a.siteId, p.b.siteId), 1), - days: p.days, - date: p.b.date - })) + .map((p) => { + const route = p.a.siteId && p.b.siteId ? nurseryRoute(d, p.a.siteId, p.b.siteId) : null; + const km = route?.km ?? dist(p.a.siteId, p.b.siteId); + const straightKm = route?.straightKm ?? dist(p.a.siteId, p.b.siteId); + return { + id: p.id, + species: p.species, + from: siteName(d, p.a.siteId), + to: siteName(d, p.b.siteId), + km: round(km, 1), + straightKm: round(straightKm, 1), + days: p.days, + date: p.b.date + }; + }) .sort((a, b) => (b.km ?? 0) - (a.km ?? 0)) .slice(0, 15); diff --git a/src/routes/recaptures/+page.svelte b/src/routes/recaptures/+page.svelte index ba938dd..ca554c8 100644 --- a/src/routes/recaptures/+page.svelte +++ b/src/routes/recaptures/+page.svelte @@ -100,8 +100,8 @@ ({ @@ -225,7 +226,10 @@ href: `/sharks/${encodeURIComponent(r.id)}` }))} /> -

Straight-line distance between nursery coordinates.

+

+ Shortest water route around Moorea between nurseries, alongside direct straight-line + distance. Routes are an estimate and not the actual path swum. +

Most-caught sharks

diff --git a/src/routes/sharks/[id]/+page.server.ts b/src/routes/sharks/[id]/+page.server.ts index 85d8bec..0a2fac4 100644 --- a/src/routes/sharks/[id]/+page.server.ts +++ b/src/routes/sharks/[id]/+page.server.ts @@ -1,5 +1,5 @@ import { error } from '@sveltejs/kit'; -import { dataset } from '#lib/server/data'; +import { dataset, nurseryRoute } from '#lib/server/data'; import { fulton, round, siteName } from '#lib/server/analytics/common'; import type { PageServerLoad } from './$types'; @@ -43,13 +43,15 @@ export const load: PageServerLoad = ({ params }) => { relMass: l.relMassKg, notes: l.notes })), - // Consecutive captures at different nurseries, in order (#173). + // Consecutive captures at different nurseries, in order (#173, #183). moves: caps.flatMap((c, i) => { const prev = caps[i - 1]; if (!prev || !prev.siteId || !c.siteId || prev.siteId === c.siteId) return []; const a = d.siteById.get(prev.siteId); const b = d.siteById.get(c.siteId); if (a?.lat == null || a.lon == null || b?.lat == null || b.lon == null) return []; + const route = nurseryRoute(d, prev.siteId, c.siteId); + const km = route?.km; return [ { id: `move-${i}`, @@ -57,7 +59,9 @@ export const load: PageServerLoad = ({ params }) => { label: `${a.name} → ${b.name}`, from: { lat: a.lat, lon: a.lon }, to: { lat: b.lat, lon: b.lon }, - sub: `Capture ${i} to ${i + 1}: ${prev.date ?? '?'} → ${c.date ?? '?'}` + path: route?.coordinates, + km: km != null ? round(km, 1) : null, + sub: `Capture ${i} to ${i + 1}: ${prev.date ?? '?'} → ${c.date ?? '?'}${km != null ? ` · ≥ ${round(km, 1)} km by water` : ''}` } ]; }), diff --git a/src/routes/sharks/[id]/+page.svelte b/src/routes/sharks/[id]/+page.svelte index aac08d8..c946af0 100644 --- a/src/routes/sharks/[id]/+page.svelte +++ b/src/routes/sharks/[id]/+page.svelte @@ -26,6 +26,7 @@ const shownMoves = $derived( current ? data.moves.filter((m) => m.at + 1 <= current.n) : data.moves ); + const currentMove = $derived(current ? data.moves.find((m) => m.at + 1 === current.n) : null); let timer: ReturnType | undefined; let playing = $state(false); function stop() { @@ -86,7 +87,7 @@ {#if data.moves.length} @@ -116,7 +117,7 @@ · {date(current.date)} · {current.site}{current.tl != null ? ` · ${num(current.tl)} mm` : ''}{previous && previous.site !== current.site - ? ` (moved from ${previous.site})` + ? ` (moved from ${previous.site}${currentMove?.km ? ` · ≥ ${num(currentMove.km)} km by water` : ''})` : ''} {:else} All captures @@ -137,6 +138,8 @@ key: at, from: previous ?? current, to: current, + path: currentMove?.path, + km: currentMove?.km, color } : undefined} From 8086fe350b718926fd3a3c21dad0dd5893bb6f52 Mon Sep 17 00:00:00 2001 From: luen Date: Thu, 12 Nov 2026 11:44:47 +1000 Subject: [PATCH 02/13] fix(a11y): focus popup content on non-linked map controls and omit unlabeled values --- e2e/map-keyboard.spec.ts | 14 +++++++++-- src/lib/components/InteractiveMap.svelte | 30 +++++++++++++++--------- 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/e2e/map-keyboard.spec.ts b/e2e/map-keyboard.spec.ts index abc1af1..5174d0b 100644 --- a/e2e/map-keyboard.spec.ts +++ b/e2e/map-keyboard.spec.ts @@ -182,9 +182,19 @@ test('adult capture circles are keyboard reachable and survive zoom and overlay await circle.focus(); await expect(map.locator('.leaflet-tooltip').last()).toBeVisible(); await circle.press('Enter'); - await expect(map.locator('.leaflet-popup-content')).toContainText('Adult blacktip “Synthetic”'); + const popupContent = map.locator('.leaflet-popup-content'); + await expect(popupContent).toContainText('Adult blacktip “Synthetic”'); + await expect(popupContent).toBeFocused(); await page.keyboard.press('Escape'); - await expect(map.locator('.leaflet-popup-content')).toHaveCount(0); + await expect(popupContent).toHaveCount(0); + await expect(circle).toBeFocused(); + // Close button also restores focus to the circle marker + await circle.press('Enter'); + await expect(popupContent).toBeVisible(); + const closeBtn = map.locator('.leaflet-popup-close-button'); + await closeBtn.focus(); + await closeBtn.press('Space'); + await expect(popupContent).toHaveCount(0); await expect(circle).toBeFocused(); // Controls survive zoom redraws await map.getByRole('button', { name: 'Zoom in', exact: true }).click(); diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index f4b70cc..0b61a22 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -148,19 +148,28 @@ layer.on('popupopen', (e) => { const popupEl = (e as unknown as { popup?: import('leaflet').Popup })?.popup?.getElement(); if (!popupEl) return; - const focusable = popupEl.querySelector('a[href], button'); + const contentEl = popupEl.querySelector('.leaflet-popup-content'); + const focusable = contentEl?.querySelector('a[href], button'); if (focusable) focusable.focus(); - else { - popupEl.setAttribute('tabindex', '-1'); - popupEl.focus(); + else if (contentEl) { + contentEl.setAttribute('tabindex', '-1'); + contentEl.focus(); + } + const dismiss = (ev: Event) => { + ev.preventDefault(); + ev.stopPropagation(); + layer.closePopup(); + (layer.getElement() as HTMLElement | undefined)?.focus(); + }; + const closeBtn = popupEl.querySelector('.leaflet-popup-close-button'); + if (closeBtn) { + closeBtn.onclick = dismiss; + closeBtn.onkeydown = (ev: KeyboardEvent) => { + if (ev.key === 'Enter' || ev.key === ' ') dismiss(ev); + }; } popupEl.onkeydown = (ev: KeyboardEvent) => { - if (ev.key === 'Escape') { - ev.preventDefault(); - ev.stopPropagation(); - layer.closePopup(); - (layer.getElement() as HTMLElement | undefined)?.focus(); - } + if (ev.key === 'Escape') dismiss(ev); }; }); return layer; @@ -169,7 +178,6 @@ function pointLabel(p: MapPoint, unit = valueLabel) { const parts = [p.label]; if (p.value != null && unit) parts.push(`${unit}: ${format(p.value)}`); - else if (p.value != null && !unit) parts.push(format(p.value)); if (p.sub) parts.push(p.sub); return parts.join(' · '); } From b6c5efa4ceaeb7f13a84818e6bf15180ff1ccd97 Mon Sep 17 00:00:00 2001 From: luen Date: Thu, 12 Nov 2026 14:01:13 +1000 Subject: [PATCH 03/13] fix(routes): rasterize coastline boundary, fix 3-point crossesLand check, single arrowhead on water polylines, and scale move duration --- AGENTS.md | 4 +- e2e/map-keyboard.spec.ts | 28 ++++++++++--- src/lib/components/InteractiveMap.svelte | 37 +++++++++++------ src/lib/components/MooreaMap.svelte | 13 +++++- src/lib/components/lineGeometry.test.ts | 14 +++++++ src/lib/components/lineGeometry.ts | 42 ++++++++++++++----- src/lib/server/import/index.ts | 2 +- src/lib/server/oceanRoutes.test.ts | 6 +++ src/lib/server/oceanRoutes.ts | 53 ++++++++++++++++++++---- src/routes/recaptures/+page.server.ts | 2 +- src/routes/sharks/[id]/+page.svelte | 19 +++++---- 11 files changed, 170 insertions(+), 50 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6ebaebd..cc4cc42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -155,7 +155,7 @@ samples/fixture/ synthetic workbooks for tests/CI (committed) ### Nursery water routes (#183) - `src/lib/server/oceanRoutes.ts`: computes shortest water routes around Moorea between all pairs of nurseries using grid A* routing around the island's coastline (`src/lib/moorea-outline.json`, OpenStreetMap, ODbL 1.0). The 35 m grid rasters Moorea island with a 2 km buffer, calculates chamfer distance-to-land, snaps nursery points to nearby water, searches with an A* penalty near land to avoid hugging rocks, and smooths with raycast string-pulling. -- Precomputed routes are stored in SQLite `nursery_routes` (`cache/` disposable database), bumping `IMPORTER_VERSION` to `'12'`. Never commit nursery coordinates or precomputed routes to git. +- Precomputed routes are stored in SQLite `nursery_routes` (`cache/` disposable database), bumping `IMPORTER_VERSION` to `'13'`. Never commit nursery coordinates or precomputed routes to git. - Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the traveller dot glides along the water route, scaled with distance (jumping under `prefers-reduced-motion`). - Standalone CLI `node scripts/ocean-routes.mjs` (or `pnpm routes`, with optional `--geojson`) verifies that 0 routes cross land. @@ -242,7 +242,7 @@ Questions for the lab go to Dr Jodie Rummer (`@JodieRummer`) on GitHub: label th | 2026-11 | v0.2.6: offshore chlorophyll-a (#23); apparent survival with a Cormack–Jolly–Seber model (#42); nursery month × hour temperature calendars (#127); scar transitions (#126); measurement coverage and the catch model's sample selection (#123); catch-model fit diagnostics (#125); conditions on fieldwork nights vs their months (#124); scrollable tables keyboard-reachable (#150); sitemap, llms.txt, humans.txt (#140, #141, #143); GA4 on production hosts (#145); fixture fits the catch model in CI (#153). IMPORTER_VERSION 9: caches rebuild. | | 2026-11 | v0.2.7: SST is NOAA OISST again, with Coral Reef Watch only where OISST is missing (#154: the old endpoint had left the column empty); ERDDAP failures stop a snapshot instead of blanking it; patched esbuild and minimatch, and map tooltips rendered as text (#144). | | 2026-11 | v0.2.10: pressure scores from the Bouyoucos et al. (2024) dataset (#131); year-off recaptures take their set's date (#133); lab statistics conventions (#132) and sex-ratio wording (#130); capture numbers that disagree with the tags go on the Data quality page (#168). | -| 2026-11 | v0.2.11: shortest water routes between Moorea nurseries precomputed via grid A* routing around the island coastline (#183); move lines follow water paths, offset rightwards when reversed, with water distance; shark player animation glides along the water route; IMPORTER_VERSION 12. | +| 2026-11 | v0.2.13: shortest water routes between Moorea nurseries precomputed via grid A* routing around the island coastline (#183); move lines follow water paths, offset rightwards when reversed, with water distance; shark player animation glides along the water route; IMPORTER_VERSION 13. | - Security scans (#144): use Snyk CLI >=1.1308.3 with `test --all-projects --dev` for the pnpm 12 multi-document lockfile. Remaining upstream advisories and mitigations are tracked in docs/dev/SNYK-144.md. - Seasonal comparisons must report dates from their eligible sets, not an assumed October–February window (2020–21 starts in September). ISPF's Moorea hotel-room sales are a visitor proxy, not a count of people on the water. diff --git a/e2e/map-keyboard.spec.ts b/e2e/map-keyboard.spec.ts index 5174d0b..b8aae11 100644 --- a/e2e/map-keyboard.spec.ts +++ b/e2e/map-keyboard.spec.ts @@ -57,16 +57,33 @@ test('directed move markers and keyboard controls survive a zoom redraw', async const line = map.locator('.ps-line-0[role="button"]').first(); await expect(line).toBeVisible(); const before = await line.getAttribute('d'); - // marker-mid needs an interior vertex, not just the two endpoints. expect(before!.match(/[ML]/g)!.length).toBeGreaterThanOrEqual(3); await map.getByRole('button', { name: 'Zoom in', exact: true }).click(); await expect.poll(() => line.getAttribute('d')).not.toBe(before); - for (const path of await map.locator('.ps-line').all()) { - const ref = await path.getAttribute('marker-mid'); + const lines = await map.locator('.ps-line').all(); + const arrows = await map.locator('.ps-arrow').all(); + expect(arrows.length).toBe(lines.length); + for (const path of lines) { + expect(await path.getAttribute('marker-mid')).toBeNull(); + } + let inView = 0; + for (const arrow of arrows) { + // Each arrow carrier is a 3-point segment so marker-mid renders a single arrowhead at 60%. + // Polylines clipped out of the current viewport by Leaflet collapse to M0 0. + const d = await arrow.getAttribute('d'); + const points = d!.match(/[ML]/g)!.length; + if (d !== 'M0 0') { + expect(points).toBe(3); + inView++; + } else { + expect(points).toBe(1); + } + const ref = await arrow.getAttribute('marker-mid'); expect(ref).toMatch(/^url\(#.+\)$/); const id = ref!.slice(5, -1); expect(await page.evaluate((id) => document.getElementById(id)?.tagName, id)).toBe('marker'); } + expect(inView).toBeGreaterThan(0); await line.focus(); await line.press('Enter'); await expect(map.locator('.leaflet-popup-content')).toContainText( @@ -184,16 +201,15 @@ test('adult capture circles are keyboard reachable and survive zoom and overlay await circle.press('Enter'); const popupContent = map.locator('.leaflet-popup-content'); await expect(popupContent).toContainText('Adult blacktip “Synthetic”'); - await expect(popupContent).toBeFocused(); await page.keyboard.press('Escape'); await expect(popupContent).toHaveCount(0); await expect(circle).toBeFocused(); - // Close button also restores focus to the circle marker + // Close button also restores focus to the circle marker when activated await circle.press('Enter'); await expect(popupContent).toBeVisible(); const closeBtn = map.locator('.leaflet-popup-close-button'); await closeBtn.focus(); - await closeBtn.press('Space'); + await closeBtn.press('Enter'); await expect(popupContent).toHaveCount(0); await expect(circle).toBeFocused(); // Controls survive zoom redraws diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index 4b8c957..6fa9fc1 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -53,7 +53,15 @@ import { onMount, tick } from 'svelte'; import MooreaMap from './MooreaMap.svelte'; import { registerCsv } from './charts/csv'; - import { lineWidth, offsetPolyline, pointAlongPath, reversed, shiftFor } from './lineGeometry'; + import { + lineWidth, + moveDuration, + offsetPolyline, + pointAlongPath, + polylineArrow, + reversed, + shiftFor + } from './lineGeometry'; let { layers, @@ -150,13 +158,7 @@ layer.on('popupopen', (e) => { const popupEl = (e as unknown as { popup?: import('leaflet').Popup })?.popup?.getElement(); if (!popupEl) return; - const contentEl = popupEl.querySelector('.leaflet-popup-content'); - const focusable = contentEl?.querySelector('a[href], button'); - if (focusable) focusable.focus(); - else if (contentEl) { - contentEl.setAttribute('tabindex', '-1'); - contentEl.focus(); - } + popupEl.querySelector('a[href], button')?.focus(); const dismiss = (ev: Event) => { ev.preventDefault(); ev.stopPropagation(); @@ -323,13 +325,24 @@ lineCap: 'round', smoothFactor: 0 }); - line.on('add', () => - line.getElement()?.setAttribute('marker-mid', `url(#${uid}-arrow-${i})`) - ); keyboardInteractive(line, l.label) .bindTooltip(tooltip(l.label)) .bindPopup(() => popup(l, lineLabel)) .addTo(group); + const arrowLatLngs = polylineArrow(shiftedPts).map(([x, y]) => + m.layerPointToLatLng([x, y]) + ); + const arrow = L.polyline(arrowLatLngs, { + stroke: false, + interactive: false, + className: `ps-arrow ps-arrow-${i}`, + smoothFactor: 0, + noClip: true + }); + arrow.on('add', () => + arrow.getElement()?.setAttribute('marker-mid', `url(#${uid}-arrow-${i})`) + ); + arrow.addTo(group); } const key = `line:${i}`; if (!hidden.has(key)) group.addTo(m); @@ -403,7 +416,7 @@ if (still) return; const start = performance.now(); let frame = 0; - const duration = t.km != null ? Math.min(2500, Math.max(800, 500 + t.km * 60)) : 800; + const duration = moveDuration(t.km); const step = (now: number) => { const f = Math.min(1, (now - start) / duration); const eased = f < 0.5 ? 2 * f * f : 1 - (-2 * f + 2) ** 2 / 2; diff --git a/src/lib/components/MooreaMap.svelte b/src/lib/components/MooreaMap.svelte index fc0bb97..da8829c 100644 --- a/src/lib/components/MooreaMap.svelte +++ b/src/lib/components/MooreaMap.svelte @@ -30,7 +30,7 @@ import Tip, { type TipState } from './charts/Tip.svelte'; import { registerCsv } from './charts/csv'; import { KEYS_HINT, markAt, markKeys, pointerIn } from './charts/marks'; - import { lineWidth, offsetPolyline, reversed, shiftFor } from './lineGeometry'; + import { lineWidth, offsetPolyline, polylineArrow, reversed, shiftFor } from './lineGeometry'; let { points, @@ -133,10 +133,12 @@ [px(l.to.lon), py(l.to.lat)] ]; const shiftedPts = offsetPolyline(rawPts, back[i] ? shiftFor(w) : 0); + const arrowPts = polylineArrow(shiftedPts); return { line: l, w, points: shiftedPts.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' '), + arrowPoints: arrowPts.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' '), arrow: colours.indexOf(l.color ?? 'var(--series-1)') }; }); @@ -215,11 +217,18 @@ stroke-width={d.w} stroke-linecap="round" stroke-opacity="0.75" - marker-mid={`url(#${uid}-arrow-${d.arrow})`} role="presentation" data-mark={i} onpointermove={(e) => showLine(pointerIn(e), d.line)} /> + {/each} {#each sorted as p, i (p.id)} {@const x = px(p.lon)} diff --git a/src/lib/components/lineGeometry.test.ts b/src/lib/components/lineGeometry.test.ts index 60b295b..e611bab 100644 --- a/src/lib/components/lineGeometry.test.ts +++ b/src/lib/components/lineGeometry.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest'; import { directedPoints, + moveDuration, offsetPolyline, pointAlongPath, polylineArrow, @@ -97,6 +98,10 @@ describe('polylineArrow', () => { expect(arrow[0][0]).toBeCloseTo(10, 4); expect(arrow[2][0]).toBeCloseTo(10, 4); expect(arrow[2][1]).toBeGreaterThan(arrow[0][1]); + // Flanking vertices stay distinct after integer pixel rounding (Leaflet layer points). + expect( + new Set(arrow.map(([x, y]) => `${Math.round(x)},${Math.round(y)}`)).size + ).toBe(3); }); }); @@ -115,3 +120,12 @@ describe('pointAlongPath', () => { expect(pointAlongPath(path, 1)).toEqual([10, 10]); }); }); + +describe('moveDuration', () => { + it('scales with distance within [800, 2500] ms bounds', () => { + expect(moveDuration(null)).toBe(800); + expect(moveDuration(0.5)).toBe(800); + expect(moveDuration(15)).toBe(1400); + expect(moveDuration(50)).toBe(2500); + }); +}); diff --git a/src/lib/components/lineGeometry.ts b/src/lib/components/lineGeometry.ts index a7f6901..73700c4 100644 --- a/src/lib/components/lineGeometry.ts +++ b/src/lib/components/lineGeometry.ts @@ -46,40 +46,60 @@ export const lineWidth = (value: number | undefined, max: number) => /** Sideways shift for a line of this width when its reverse is drawn too. */ export const shiftFor = (width: number) => width / 2 + 4; +/** Animation duration in ms for a move of `km` water distance, clamped to [800, 2500]. */ +export const moveDuration = (km: number | null | undefined) => + km != null && km > 0 ? Math.min(2500, Math.max(800, Math.round(500 + km * 60))) : 800; + /** * Shift a multi-point polyline in screen coordinates to the right of travel by `shift` px. * For 2-point lines, delegates to directedPoints so the line includes its 60% arrow point. */ export function offsetPolyline(pts: [number, number][], shift: number): [number, number][] { if (pts.length < 2) return pts.map(([x, y]) => [x, y]); - const n = pts.length; - if (n === 2) { + if (pts.length === 2) { return directedPoints(pts[0][0], pts[0][1], pts[1][0], pts[1][1], shift); } if (!shift) return pts.map(([x, y]) => [x, y]); + // Drop sub-2px interior stubs (such as shore-snapping steps) so endpoint normals follow the coast. + const last = pts[pts.length - 1]; + const clean: [number, number][] = [pts[0]]; + for (let i = 1; i < pts.length - 1; i++) { + const prev = clean[clean.length - 1]; + if ( + Math.hypot(pts[i][0] - prev[0], pts[i][1] - prev[1]) >= 2 && + Math.hypot(last[0] - pts[i][0], last[1] - pts[i][1]) >= 2 + ) { + clean.push(pts[i]); + } + } + clean.push(last); + const n = clean.length; + if (n === 2) { + return directedPoints(clean[0][0], clean[0][1], clean[1][0], clean[1][1], shift); + } const normals: [number, number][] = []; for (let i = 0; i < n - 1; i++) { - const dx = pts[i + 1][0] - pts[i][0]; - const dy = pts[i + 1][1] - pts[i][1]; + const dx = clean[i + 1][0] - clean[i][0]; + const dy = clean[i + 1][1] - clean[i][1]; const len = Math.hypot(dx, dy) || 1; normals.push([(-dy / len) * shift, (dx / len) * shift]); } const out: [number, number][] = []; - out.push([pts[0][0] + normals[0][0], pts[0][1] + normals[0][1]]); + out.push([clean[0][0] + normals[0][0], clean[0][1] + normals[0][1]]); for (let i = 1; i < n - 1; i++) { const mx = (normals[i - 1][0] + normals[i][0]) / 2; const my = (normals[i - 1][1] + normals[i][1]) / 2; const mLen = Math.hypot(mx, my); if (mLen > 1e-6) { out.push([ - pts[i][0] + (mx / mLen) * Math.abs(shift), - pts[i][1] + (my / mLen) * Math.abs(shift) + clean[i][0] + (mx / mLen) * Math.abs(shift), + clean[i][1] + (my / mLen) * Math.abs(shift) ]); } else { - out.push([pts[i][0] + normals[i][0], pts[i][1] + normals[i][1]]); + out.push([clean[i][0] + normals[i][0], clean[i][1] + normals[i][1]]); } } - out.push([pts[n - 1][0] + normals[n - 2][0], pts[n - 1][1] + normals[n - 2][1]]); + out.push([clean[n - 1][0] + normals[n - 2][0], clean[n - 1][1] + normals[n - 2][1]]); return out; } @@ -113,9 +133,9 @@ export function polylineArrow(pts: [number, number][], arrowAt = ARROW_AT): [num const ux = (x1 - x0) / segLen; const uy = (y1 - y0) / segLen; return [ - [ax - ux * 0.1, ay - uy * 0.1], + [ax - ux * 2, ay - uy * 2], [ax, ay], - [ax + ux * 0.1, ay + uy * 0.1] + [ax + ux * 2, ay + uy * 2] ]; } acc += lens[i]; diff --git a/src/lib/server/import/index.ts b/src/lib/server/import/index.ts index ad3634e..fef23eb 100644 --- a/src/lib/server/import/index.ts +++ b/src/lib/server/import/index.ts @@ -77,7 +77,7 @@ import { computeAllNurseryRoutes } from '../oceanRoutes'; import { readWorkbook } from './xlsx'; /** Bump when import logic changes so existing caches rebuild on the next start. */ -export const IMPORTER_VERSION = '12'; +export const IMPORTER_VERSION = '13'; const MIGRATIONS = import.meta.glob('/drizzle/*.sql', { query: '?raw', diff --git a/src/lib/server/oceanRoutes.test.ts b/src/lib/server/oceanRoutes.test.ts index cea2c14..9f22d94 100644 --- a/src/lib/server/oceanRoutes.test.ts +++ b/src/lib/server/oceanRoutes.test.ts @@ -64,6 +64,12 @@ describe('oceanRoutes', () => { expect(route.straightKm).toBeLessThan(15); expect(route.km).toBeGreaterThan(20); expect(crossesLand(grid, route.coordinates)).toBe(false); + expect( + crossesLand(grid, [ + [apaura.lat!, apaura.lon!], + [maharepa.lat!, maharepa.lon!] + ]) + ).toBe(true); }); it('computes all nursery routes without crossing land', () => { diff --git a/src/lib/server/oceanRoutes.ts b/src/lib/server/oceanRoutes.ts index 25d4cd4..aa312fc 100644 --- a/src/lib/server/oceanRoutes.ts +++ b/src/lib/server/oceanRoutes.ts @@ -243,18 +243,28 @@ export function buildMooreaWaterGrid({ for (let x = from; x <= to; x++) water[row * width + x] = 0; // land } } + // Mark every cell touched by the coastline boundary itself as land so chords never clip headlands. + for (let i = 1; i < pts.length; i++) { + const [x0, y0] = pts[i - 1]; + const [x1, y1] = pts[i]; + traverse(x0, y0, x1, y1, (x, y) => { + if (x >= 0 && y >= 0 && x < width && y < height) water[y * width + x] = 0; + }); + } const distance = distanceToLand(water, width, height, cell); return { width, height, cell, bbox, kx, ky, water, distance }; } -/** Lon/lat of a cell centre. */ +const roundCoord = (v: number) => Math.round(v * 1e5) / 1e5; + +/** Lon/lat of a cell centre (~1.1 m precision). */ export function cellCentre(grid: WaterGrid, index: number): [lon: number, lat: number] { const x = index % grid.width; const y = Math.floor(index / grid.width); return [ - grid.bbox.minLon + ((x + 0.5) * grid.cell) / grid.kx, - grid.bbox.minLat + ((y + 0.5) * grid.cell) / grid.ky + roundCoord(grid.bbox.minLon + ((x + 0.5) * grid.cell) / grid.kx), + roundCoord(grid.bbox.minLat + ((y + 0.5) * grid.cell) / grid.ky) ]; } @@ -429,17 +439,41 @@ export function routeWater( }; } +const ccw = (ax: number, ay: number, bx: number, by: number, cx: number, cy: number) => + (cy - ay) * (bx - ax) > (by - ay) * (cx - ax); + +const segmentsIntersect = ( + ax: number, + ay: number, + bx: number, + by: number, + cx: number, + cy: number, + dx: number, + dy: number +) => + ccw(ax, ay, cx, cy, dx, dy) !== ccw(bx, by, cx, cy, dx, dy) && + ccw(ax, ay, bx, by, cx, cy) !== ccw(ax, ay, bx, by, dx, dy); + /** - * Check whether any segment of coordinates (excluding the short landing legs) crosses land. + * Check whether any water segment of coordinates crosses land cells or the coastline polygon. + * Short shore-landing steps (<= 150 m at the first/last segment of a multi-segment route) are allowed + * because beach GPS pins can sit slightly inside the simplified coastline ring. */ export function crossesLand(grid: WaterGrid, coordinates: [number, number][]): boolean { + if (coordinates.length < 2) return false; + const ring = outline.ring as [number, number][]; const toCell = ([lat, lon]: [number, number]): [number, number] => [ ((lon - grid.bbox.minLon) * grid.kx) / grid.cell, ((lat - grid.bbox.minLat) * grid.ky) / grid.cell ]; - // Only test intermediate water segments (skip indices 0->1 and (N-2)->(N-1) which are shore landings). - if (coordinates.length <= 3) return false; - for (let i = 2; i < coordinates.length - 1; i++) { + for (let i = 1; i < coordinates.length; i++) { + const [lat0, lon0] = coordinates[i - 1]; + const [lat1, lon1] = coordinates[i]; + const segM = Math.hypot((lon1 - lon0) * grid.kx, (lat1 - lat0) * grid.ky); + const isShoreLanding = + coordinates.length > 2 && (i === 1 || i === coordinates.length - 1) && segM <= 150; + if (isShoreLanding) continue; const [x0, y0] = toCell(coordinates[i - 1]); const [x1, y1] = toCell(coordinates[i]); const ok = traverse(x0, y0, x1, y1, (x, y) => { @@ -447,6 +481,11 @@ export function crossesLand(grid: WaterGrid, coordinates: [number, number][]): b return grid.water[y * grid.width + x] === 1; }); if (!ok) return true; + for (let j = 1; j < ring.length; j++) { + const [rlon0, rlat0] = ring[j - 1]; + const [rlon1, rlat1] = ring[j]; + if (segmentsIntersect(lon0, lat0, lon1, lat1, rlon0, rlat0, rlon1, rlat1)) return true; + } } return false; } diff --git a/src/routes/recaptures/+page.server.ts b/src/routes/recaptures/+page.server.ts index 3c0c973..85e5b1d 100644 --- a/src/routes/recaptures/+page.server.ts +++ b/src/routes/recaptures/+page.server.ts @@ -74,7 +74,7 @@ export const load: PageServerLoad = () => to, path: route?.coordinates, value: e.n, - sub: `${e.n} move${e.n === 1 ? '' : 's'} · ${round(km, 1)} km by water${straightKm != null && km != null && Math.abs(km - straightKm) > 0.5 ? ` (${round(straightKm, 1)} km straight line)` : ''}` + sub: `${e.n} move${e.n === 1 ? '' : 's'} · ${round(km, 1)} km by water${straightKm != null ? ` (${round(straightKm, 1)} km straight line)` : ''}` } ]; }) diff --git a/src/routes/sharks/[id]/+page.svelte b/src/routes/sharks/[id]/+page.svelte index c946af0..a020aed 100644 --- a/src/routes/sharks/[id]/+page.svelte +++ b/src/routes/sharks/[id]/+page.svelte @@ -3,6 +3,7 @@ import DataTable from '#lib/components/DataTable.svelte'; import InteractiveMap from '#lib/components/InteractiveMap.svelte'; import MooreaMap from '#lib/components/MooreaMap.svelte'; + import { moveDuration } from '#lib/components/lineGeometry'; import LineChart from '#lib/components/charts/LineChart.svelte'; import { toDay } from '#lib/components/charts/scale'; import { clock, date, num } from '#lib/format'; @@ -27,22 +28,24 @@ current ? data.moves.filter((m) => m.at + 1 <= current.n) : data.moves ); const currentMove = $derived(current ? data.moves.find((m) => m.at + 1 === current.n) : null); - let timer: ReturnType | undefined; let playing = $state(false); function stop() { - clearInterval(timer); playing = false; } function play() { if (playing) return stop(); if (at >= stops - 1) step = 0; playing = true; - timer = setInterval(() => { - if (step >= stops - 1) stop(); - else step = Math.min(step, stops) + 1; - }, 1400); } - $effect(() => stop); + $effect(() => { + if (!playing) return; + const delay = moveDuration(currentMove?.km) + 350; + const timer = setTimeout(() => { + if (step >= stops - 1) playing = false; + else step = Math.min(step, stops) + 1; + }, delay); + return () => clearTimeout(timer); + });
@@ -117,7 +120,7 @@ · {date(current.date)} · {current.site}{current.tl != null ? ` · ${num(current.tl)} mm` : ''}{previous && previous.site !== current.site - ? ` (moved from ${previous.site}${currentMove?.km ? ` · ≥ ${num(currentMove.km)} km by water` : ''})` + ? ` (moved from ${previous.site}${currentMove?.km ? ` · ≥ ${num(currentMove.km, 1)} km by water` : ''})` : ''} {:else} All captures From da8c358594777356da2f903136efa144677c967e Mon Sep 17 00:00:00 2001 From: luen Date: Thu, 12 Nov 2026 14:10:28 +1000 Subject: [PATCH 04/13] test: format polylineArrow test assertion --- src/lib/components/lineGeometry.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/lib/components/lineGeometry.test.ts b/src/lib/components/lineGeometry.test.ts index e611bab..82d7e94 100644 --- a/src/lib/components/lineGeometry.test.ts +++ b/src/lib/components/lineGeometry.test.ts @@ -99,9 +99,7 @@ describe('polylineArrow', () => { expect(arrow[2][0]).toBeCloseTo(10, 4); expect(arrow[2][1]).toBeGreaterThan(arrow[0][1]); // Flanking vertices stay distinct after integer pixel rounding (Leaflet layer points). - expect( - new Set(arrow.map(([x, y]) => `${Math.round(x)},${Math.round(y)}`)).size - ).toBe(3); + expect(new Set(arrow.map(([x, y]) => `${Math.round(x)},${Math.round(y)}`)).size).toBe(3); }); }); From 6608835daa93c970f4850ac7122af25ea534c4e8 Mon Sep 17 00:00:00 2001 From: luen Date: Thu, 12 Nov 2026 14:32:34 +1000 Subject: [PATCH 05/13] feat(map): progressively animate move line along water route during playback (#183) --- AGENTS.md | 2 +- e2e/map-routes.spec.ts | 44 +++++++++++++ src/lib/components/InteractiveMap.svelte | 84 ++++++++++++++++++++++-- src/routes/sharks/[id]/+page.svelte | 3 +- 4 files changed, 127 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cc4cc42..c5de5f6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -156,7 +156,7 @@ samples/fixture/ synthetic workbooks for tests/CI (committed) - `src/lib/server/oceanRoutes.ts`: computes shortest water routes around Moorea between all pairs of nurseries using grid A* routing around the island's coastline (`src/lib/moorea-outline.json`, OpenStreetMap, ODbL 1.0). The 35 m grid rasters Moorea island with a 2 km buffer, calculates chamfer distance-to-land, snaps nursery points to nearby water, searches with an A* penalty near land to avoid hugging rocks, and smooths with raycast string-pulling. - Precomputed routes are stored in SQLite `nursery_routes` (`cache/` disposable database), bumping `IMPORTER_VERSION` to `'13'`. Never commit nursery coordinates or precomputed routes to git. -- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the traveller dot glides along the water route, scaled with distance (jumping under `prefers-reduced-motion`). +- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the move line draws progressively along the water route while the traveller dot glides at its tip, scaled with distance (jumping under `prefers-reduced-motion`). - Standalone CLI `node scripts/ocean-routes.mjs` (or `pnpm routes`, with optional `--geojson`) verifies that 0 routes cross land. ### Adding a new season diff --git a/e2e/map-routes.spec.ts b/e2e/map-routes.spec.ts index 133b5db..9cd3529 100644 --- a/e2e/map-routes.spec.ts +++ b/e2e/map-routes.spec.ts @@ -68,3 +68,47 @@ test('shark detail page plays moves along the water route with distance (#183)', await expect(traveller).toBeVisible(); } }); + +test('shark detail page animates move line and traveller dot along water route (#183)', async ({ + page +}) => { + await page.goto('/recaptures'); + + const sharkLink = page.locator('table a[href^="/sharks/"]').first(); + await expect(sharkLink).toBeVisible(); + await sharkLink.click(); + + await expect(page.locator('h1')).toBeVisible(); + + const playBtn = page.locator('button.play'); + const slider = page.locator('#capture-slider'); + if ((await slider.count()) > 0) { + // Start playback + await playBtn.click(); + // While stepping from capture 1 to capture 2, the line animates along the water route + await expect(async () => { + const animating = await page.evaluate(() => { + const line = document.querySelector('.ps-line'); + return ( + line instanceof SVGElement && + line.style.strokeDasharray !== '' && + parseFloat(line.style.strokeDashoffset || '0') > 0 + ); + }); + expect(animating).toBe(true); + }).toPass({ timeout: 4000 }); + + // Traveller dot exists and glides along the water route + const traveller = page.locator('.ps-traveller'); + await expect(traveller).toBeVisible(); + + // Eventually animation finishes and stroke properties reset to normal + await expect(async () => { + const finished = await page.evaluate(() => { + const line = document.querySelector('.ps-line'); + return line instanceof SVGElement && line.style.strokeDasharray === ''; + }); + expect(finished).toBe(true); + }).toPass({ timeout: 5000 }); + } +}); diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index 6fa9fc1..67255b1 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -54,6 +54,7 @@ import MooreaMap from './MooreaMap.svelte'; import { registerCsv } from './charts/csv'; import { + ARROW_AT, lineWidth, moveDuration, offsetPolyline, @@ -93,6 +94,7 @@ path?: [number, number][]; km?: number | null; color: string; + lineId?: string; }; /** Accessible name of the map region. */ label: string; @@ -298,6 +300,11 @@ // Direction (#182): an arrow mid-line; a move drawn both ways splits into two parallel lines. const back = reversed(currentLines.flatMap((g) => g.lines)); let n = 0; + const lineEntries: { + l: MapLine; + line: import('leaflet').Polyline; + arrow: import('leaflet').Polyline; + }[] = []; const lineGroups = currentLines.map((g, i) => { const group = L.layerGroup(); for (const l of g.lines) { @@ -343,12 +350,14 @@ arrow.getElement()?.setAttribute('marker-mid', `url(#${uid}-arrow-${i})`) ); arrow.addTo(group); + lineEntries.push({ l, line, arrow }); } const key = `line:${i}`; if (!hidden.has(key)) group.addTo(m); overlays[`${g.name}`] = group; return { key, group }; }); + currentLineEntries = lineEntries; const groups = current.map((layer, i) => { const max = layer.max ?? Math.max(1e-9, ...layer.points.map((p) => p.value ?? 0)); const group = L.layerGroup(); @@ -387,8 +396,13 @@ drawn = [{ groups: [...densityGroups, ...lineGroups, ...groups], control }]; }); - // Glide a dot along the traveller's line; reduced motion (#32) just places it at the end. + // Glide a dot and animate the move line along the water route; reduced motion (#32) just places it at the end. let dot: import('leaflet').CircleMarker | undefined; + let currentLineEntries: { + l: MapLine; + line: import('leaflet').Polyline; + arrow: import('leaflet').Polyline; + }[] = []; $effect(() => { const m = map; const L = leaflet; @@ -406,6 +420,20 @@ [t.to.lat, t.to.lon] ]; const at = (f: number): [number, number] => pointAlongPath(path, f); + + // Locate the move line matching this traveller step to progressively draw its stroke. + const target = currentLineEntries.find( + (e) => + (t.lineId && (e.l as { id?: string }).id === t.lineId) || + (Math.abs(e.l.from.lat - t.from.lat) < 1e-4 && + Math.abs(e.l.from.lon - t.from.lon) < 1e-4 && + Math.abs(e.l.to.lat - t.to.lat) < 1e-4 && + Math.abs(e.l.to.lon - t.to.lon) < 1e-4) + ); + let lineEl = target?.line.getElement() as SVGPathElement | undefined; + let arrowEl = target?.arrow.getElement() as SVGPathElement | undefined; + let totalLen = lineEl?.getTotalLength ? lineEl.getTotalLength() : 0; + const marker = L.circleMarker(at(still ? 1 : 0), { radius: 7, className: 'ps-traveller', @@ -414,17 +442,65 @@ (marker.getElement() as SVGElement | undefined)?.style.setProperty('fill', t.color); dot = marker; if (still) return; + + // Progressive stroke animation along the water route polyline. + if (lineEl && totalLen > 0) { + lineEl.style.strokeDasharray = `${totalLen} ${totalLen}`; + lineEl.style.strokeDashoffset = `${totalLen}`; + if (arrowEl) arrowEl.style.opacity = '0'; + } + const start = performance.now(); let frame = 0; const duration = moveDuration(t.km); const step = (now: number) => { const f = Math.min(1, (now - start) / duration); const eased = f < 0.5 ? 2 * f * f : 1 - (-2 * f + 2) ** 2 / 2; - marker.setLatLng(at(eased)); - if (f < 1) frame = requestAnimationFrame(step); + + // Re-anchor if zoom redraw replaced elements during animation. + if (target && (!lineEl || !lineEl.isConnected)) { + lineEl = target.line.getElement() as SVGPathElement | undefined; + arrowEl = target.arrow.getElement() as SVGPathElement | undefined; + totalLen = lineEl?.getTotalLength ? lineEl.getTotalLength() : 0; + if (lineEl && totalLen > 0) { + lineEl.style.strokeDasharray = `${totalLen} ${totalLen}`; + } + } + + if (lineEl && totalLen > 0) { + lineEl.style.strokeDashoffset = `${totalLen * (1 - eased)}`; + if (arrowEl) arrowEl.style.opacity = f >= ARROW_AT ? '1' : '0'; + if (lineEl.getPointAtLength) { + const pt = lineEl.getPointAtLength(totalLen * eased); + marker.setLatLng(m.layerPointToLatLng([pt.x, pt.y])); + } else { + marker.setLatLng(at(eased)); + } + } else { + marker.setLatLng(at(eased)); + } + + if (f < 1) { + frame = requestAnimationFrame(step); + } else { + if (lineEl) { + lineEl.style.strokeDasharray = ''; + lineEl.style.strokeDashoffset = ''; + } + if (arrowEl) arrowEl.style.opacity = ''; + } }; frame = requestAnimationFrame(step); - return () => cancelAnimationFrame(frame); + return () => { + cancelAnimationFrame(frame); + if (lineEl) { + lineEl.style.strokeDasharray = ''; + lineEl.style.strokeDashoffset = ''; + } + if (arrowEl) { + arrowEl.style.opacity = ''; + } + }; }); const style = $derived( diff --git a/src/routes/sharks/[id]/+page.svelte b/src/routes/sharks/[id]/+page.svelte index a020aed..977d90e 100644 --- a/src/routes/sharks/[id]/+page.svelte +++ b/src/routes/sharks/[id]/+page.svelte @@ -143,7 +143,8 @@ to: current, path: currentMove?.path, km: currentMove?.km, - color + color, + lineId: currentMove?.id } : undefined} /> From c0ea01214071c00d11f22841355096c0de42fbbd Mon Sep 17 00:00:00 2001 From: luen Date: Thu, 12 Nov 2026 14:45:18 +1000 Subject: [PATCH 06/13] fix(map): include polyline coordinates in autozoom bounds and deduplicate recaptures copy --- src/lib/components/InteractiveMap.svelte | 16 ++++++++++++++-- src/routes/recaptures/+page.svelte | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index 67255b1..160a555 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -243,9 +243,21 @@ ]) ); bases[BASEMAPS[0].name].addTo(m); - const all = layers.flatMap((l) => l.points.map((p) => [p.lat, p.lon] as [number, number])); + const all: [number, number][] = [ + ...layers.flatMap((l) => l.points.map((p) => [p.lat, p.lon] as [number, number])), + ...lineLayers.flatMap((g) => + g.lines.flatMap((l) => + l.path && l.path.length > 0 + ? l.path + : ([ + [l.from.lat, l.from.lon], + [l.to.lat, l.to.lon] + ] as [number, number][]) + ) + ) + ]; if (focus) m.setView([focus.lat, focus.lon], focus.zoom ?? 14); - else if (all.length) m.fitBounds(L.latLngBounds(all), { padding: [24, 24], maxZoom: 14 }); + else if (all.length) m.fitBounds(L.latLngBounds(all), { padding: [36, 36], maxZoom: 14 }); else m.setView([-17.53, -149.83], 12); // Line offsets are in screen pixels, so redraw them at each zoom (#182). m.on('zoomend', () => (zoom = m.getZoom())); diff --git a/src/routes/recaptures/+page.svelte b/src/routes/recaptures/+page.svelte index ca554c8..c0890db 100644 --- a/src/routes/recaptures/+page.svelte +++ b/src/routes/recaptures/+page.svelte @@ -100,7 +100,7 @@ Date: Thu, 12 Nov 2026 15:16:06 +1000 Subject: [PATCH 07/13] feat(sharks): animate bird's-eye view swimming shark along water route --- AGENTS.md | 2 +- e2e/map-routes.spec.ts | 3 +- src/lib/components/InteractiveMap.svelte | 126 ++++++++++++++++++++--- src/routes/sharks/[id]/+page.svelte | 39 +++++-- 4 files changed, 144 insertions(+), 26 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c5de5f6..e536e3b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -156,7 +156,7 @@ samples/fixture/ synthetic workbooks for tests/CI (committed) - `src/lib/server/oceanRoutes.ts`: computes shortest water routes around Moorea between all pairs of nurseries using grid A* routing around the island's coastline (`src/lib/moorea-outline.json`, OpenStreetMap, ODbL 1.0). The 35 m grid rasters Moorea island with a 2 km buffer, calculates chamfer distance-to-land, snaps nursery points to nearby water, searches with an A* penalty near land to avoid hugging rocks, and smooths with raycast string-pulling. - Precomputed routes are stored in SQLite `nursery_routes` (`cache/` disposable database), bumping `IMPORTER_VERSION` to `'13'`. Never commit nursery coordinates or precomputed routes to git. -- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the move line draws progressively along the water route while the traveller dot glides at its tip, scaled with distance (jumping under `prefers-reduced-motion`). +- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the move line draws progressively along the water route while an animated bird's-eye view shark swims at its tip (rotating along the route with tail waggle, jumping under `prefers-reduced-motion`). - Standalone CLI `node scripts/ocean-routes.mjs` (or `pnpm routes`, with optional `--geojson`) verifies that 0 routes cross land. ### Adding a new season diff --git a/e2e/map-routes.spec.ts b/e2e/map-routes.spec.ts index 9cd3529..8c65697 100644 --- a/e2e/map-routes.spec.ts +++ b/e2e/map-routes.spec.ts @@ -98,9 +98,10 @@ test('shark detail page animates move line and traveller dot along water route ( expect(animating).toBe(true); }).toPass({ timeout: 4000 }); - // Traveller dot exists and glides along the water route + // Traveller shark icon exists and glides along the water route const traveller = page.locator('.ps-traveller'); await expect(traveller).toBeVisible(); + await expect(page.locator('.ps-traveller .ps-shark-svg')).toBeVisible(); // Eventually animation finishes and stroke properties reset to normal await expect(async () => { diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index 160a555..99fbf99 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -76,6 +76,7 @@ format = (v: number) => String(Math.round(v)), focus, height = 440, + bounds, fallback }: { layers: MapLayer[]; @@ -86,7 +87,7 @@ density?: MapDensity; /** Value that gets the widest line; fix it so widths don't jump as lines are added. */ lineMax?: number; - /** A dot that glides from `from` to `to` along the water route whenever `key` changes (a Play button). */ + /** A bird's-eye view shark that glides from `from` to `to` along the water route whenever `key` changes (a Play button). */ traveller?: { key: string | number; from: { lat: number; lon: number }; @@ -94,7 +95,9 @@ path?: [number, number][]; km?: number | null; color: string; + species?: string; lineId?: string; + still?: boolean; }; /** Accessible name of the map region. */ label: string; @@ -103,6 +106,8 @@ /** Open zoomed on this point instead of fitting all points. */ focus?: { lat: number; lon: number; zoom?: number }; height?: number; + /** Extra coordinates to include in initial fitBounds (e.g. future moves on a stepped shark map). */ + bounds?: [number, number][]; /** Points for the server-rendered SVG map shown before Leaflet loads (default: first layer). */ fallback?: MapPoint[]; } = $props(); @@ -254,7 +259,8 @@ [l.to.lat, l.to.lon] ] as [number, number][]) ) - ) + ), + ...(bounds ?? []) ]; if (focus) m.setView([focus.lat, focus.lon], focus.zoom ?? 14); else if (all.length) m.fitBounds(L.latLngBounds(all), { padding: [36, 36], maxZoom: 14 }); @@ -408,8 +414,8 @@ drawn = [{ groups: [...densityGroups, ...lineGroups, ...groups], control }]; }); - // Glide a dot and animate the move line along the water route; reduced motion (#32) just places it at the end. - let dot: import('leaflet').CircleMarker | undefined; + // Glide a bird's-eye view shark and animate the move line along the water route (#183). + let dot: import('leaflet').Marker | undefined; let currentLineEntries: { l: MapLine; line: import('leaflet').Polyline; @@ -423,7 +429,8 @@ dot?.remove(); dot = undefined; if (!t) return; - const still = matchMedia('(prefers-reduced-motion: reduce)').matches; + const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches; + const still = reducedMotion || Boolean(t.still); const path: [number, number][] = t.path && t.path.length >= 2 ? t.path @@ -433,6 +440,63 @@ ]; const at = (f: number): [number, number] => pointAlongPath(path, f); + // Compute initial heading angle (degrees clockwise from North). + let initialHeading = 0; + if (path.length >= 2) { + const refIdx = still ? path.length - 1 : 0; + const p1 = m.latLngToLayerPoint(still ? path[Math.max(0, refIdx - 1)] : path[0]); + const p2 = m.latLngToLayerPoint(still ? path[refIdx] : path[Math.min(path.length - 1, 1)]); + const dx = p2.x - p1.x; + const dy = p2.y - p1.y; + if (dx !== 0 || dy !== 0) { + initialHeading = Math.atan2(dx, -dy) * (180 / Math.PI); + } + } + + const isBlacktip = t.species !== 'Na'; + const tipColor = isBlacktip ? '#0f172a' : '#92400e'; + const sharkHtml = ` +
+ + + + ${ + isBlacktip + ? ` + + + ` + : '' + } + + + + + + + + + + ${isBlacktip ? `` : ''} + + +
+ `; + + const marker = L.marker(at(still ? 1 : 0), { + icon: L.divIcon({ + className: 'ps-traveller ps-shark-marker', + html: sharkHtml, + iconSize: [32, 46], + iconAnchor: [16, 23] + }), + interactive: false + }).addTo(m); + dot = marker; + if (still) return; + // Locate the move line matching this traveller step to progressively draw its stroke. const target = currentLineEntries.find( (e) => @@ -446,15 +510,6 @@ let arrowEl = target?.arrow.getElement() as SVGPathElement | undefined; let totalLen = lineEl?.getTotalLength ? lineEl.getTotalLength() : 0; - const marker = L.circleMarker(at(still ? 1 : 0), { - radius: 7, - className: 'ps-traveller', - interactive: false - }).addTo(m); - (marker.getElement() as SVGElement | undefined)?.style.setProperty('fill', t.color); - dot = marker; - if (still) return; - // Progressive stroke animation along the water route polyline. if (lineEl && totalLen > 0) { lineEl.style.strokeDasharray = `${totalLen} ${totalLen}`; @@ -479,12 +534,22 @@ } } + let heading = initialHeading; if (lineEl && totalLen > 0) { lineEl.style.strokeDashoffset = `${totalLen * (1 - eased)}`; if (arrowEl) arrowEl.style.opacity = f >= ARROW_AT ? '1' : '0'; if (lineEl.getPointAtLength) { - const pt = lineEl.getPointAtLength(totalLen * eased); + const curLen = totalLen * eased; + const pt = lineEl.getPointAtLength(curLen); marker.setLatLng(m.layerPointToLatLng([pt.x, pt.y])); + + const ahead = lineEl.getPointAtLength(Math.min(totalLen, curLen + 3)); + const behind = lineEl.getPointAtLength(Math.max(0, curLen - 3)); + const dx = ahead.x - behind.x; + const dy = ahead.y - behind.y; + if (dx !== 0 || dy !== 0) { + heading = Math.atan2(dx, -dy) * (180 / Math.PI); + } } else { marker.setLatLng(at(eased)); } @@ -492,6 +557,21 @@ marker.setLatLng(at(eased)); } + const wrapEl = (marker.getElement() as HTMLElement | undefined)?.querySelector( + '.ps-shark-wrap' + ) as HTMLElement | null; + const tailEl = (marker.getElement() as HTMLElement | undefined)?.querySelector( + '.ps-shark-tail' + ) as HTMLElement | null; + if (wrapEl) { + const bodyWiggle = f < 1 ? Math.sin((now - start) * 0.018) * 4 : 0; + wrapEl.style.transform = `rotate(${heading + bodyWiggle}deg)`; + } + if (tailEl) { + const tailWiggle = f < 1 ? Math.sin((now - start) * 0.018 - 1.2) * 12 : 0; + tailEl.style.transform = `rotate(${tailWiggle}deg)`; + } + if (f < 1) { frame = requestAnimationFrame(step); } else { @@ -650,6 +730,22 @@ stroke-width: 2px; fill-opacity: 1; } + .map :global(.ps-shark-marker) { + background: transparent !important; + border: none !important; + } + .map :global(.ps-shark-wrap) { + width: 32px; + height: 46px; + transform-origin: 16px 23px; + filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.7)); + pointer-events: none; + will-change: transform; + } + .map :global(.ps-shark-tail) { + transform-origin: 16px 33px; + will-change: transform; + } .map :global(.leaflet-interactive.ps-line) { stroke-opacity: 0.75; } diff --git a/src/routes/sharks/[id]/+page.svelte b/src/routes/sharks/[id]/+page.svelte index 977d90e..7dbff28 100644 --- a/src/routes/sharks/[id]/+page.svelte +++ b/src/routes/sharks/[id]/+page.svelte @@ -14,9 +14,9 @@ const ind = $derived(data.ind); const growth = $derived(data.captures.filter((c) => c.date && c.tl != null)); - // Play this shark's captures in order (#173): lines appear as it moves, a dot glides along. + // Play this shark's captures in order (#173, #183): lines appear as it moves, a shark swims along. const stops = $derived(data.track.length); - let step = $state(Number.MAX_SAFE_INTEGER); + let step = $state(0); const at = $derived(Math.min(step, stops)); const current = $derived(at < stops ? data.track[at] : null); // An unlocated capture breaks the path: do not animate across that unknown stop. @@ -34,7 +34,16 @@ } function play() { if (playing) return stop(); - if (at >= stops - 1) step = 0; + if (at >= stops - 1) { + step = 0; + playing = true; + return; + } + if (at === 0) { + step = 1; + playing = true; + return; + } playing = true; } $effect(() => { @@ -96,7 +105,7 @@ {#if data.moves.length}
+ m.path && m.path.length > 0 + ? m.path + : [ + [m.from.lat, m.from.lon], + [m.to.lat, m.to.lon] + ] + )} layers={[ { name: 'Capture sites', color, sized: true, maxRadius: 12, points: data.map } ]} lineLayers={[{ name: 'Moves', color, lines: shownMoves }]} lineMax={4} - traveller={current + traveller={data.track.length ? { key: at, - from: previous ?? current, - to: current, - path: currentMove?.path, + from: previous ?? current ?? data.track[0], + to: current ?? data.track[stops - 1], + path: + currentMove?.path ?? + (at >= stops ? data.moves[data.moves.length - 1]?.path : undefined), km: currentMove?.km, color, - lineId: currentMove?.id + species: ind.species, + lineId: currentMove?.id, + still: !currentMove } : undefined} /> From 3152c36ad9dafadeaeb8e9347bbf1f32ee964f98 Mon Sep 17 00:00:00 2001 From: luen Date: Thu, 12 Nov 2026 15:42:25 +1000 Subject: [PATCH 08/13] feat(sharks): continuous water route scrubbing and smooth swim animation (#183) --- AGENTS.md | 2 +- src/lib/components/InteractiveMap.svelte | 119 +++++++++++-- src/routes/sharks/[id]/+page.svelte | 210 +++++++++++++++++------ 3 files changed, 264 insertions(+), 67 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e536e3b..62b8260 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -156,7 +156,7 @@ samples/fixture/ synthetic workbooks for tests/CI (committed) - `src/lib/server/oceanRoutes.ts`: computes shortest water routes around Moorea between all pairs of nurseries using grid A* routing around the island's coastline (`src/lib/moorea-outline.json`, OpenStreetMap, ODbL 1.0). The 35 m grid rasters Moorea island with a 2 km buffer, calculates chamfer distance-to-land, snaps nursery points to nearby water, searches with an A* penalty near land to avoid hugging rocks, and smooths with raycast string-pulling. - Precomputed routes are stored in SQLite `nursery_routes` (`cache/` disposable database), bumping `IMPORTER_VERSION` to `'13'`. Never commit nursery coordinates or precomputed routes to git. -- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the move line draws progressively along the water route while an animated bird's-eye view shark swims at its tip (rotating along the route with tail waggle, jumping under `prefers-reduced-motion`). +- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the slider scrubs continuously (`step="0.002"`) across all intermediate points with live line drawing, real-time distance and capture stop quick-jump pills; playback smoothly animates a bird's-eye view shark swimming along the water route at the tip of the line (rotating along the route with tail waggle, jumping under `prefers-reduced-motion`). - Standalone CLI `node scripts/ocean-routes.mjs` (or `pnpm routes`, with optional `--geojson`) verifies that 0 routes cross land. ### Adding a new season diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index 99fbf99..9bafca2 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -98,6 +98,8 @@ species?: string; lineId?: string; still?: boolean; + fraction?: number; + playing?: boolean; }; /** Accessible name of the map region. */ label: string; @@ -416,6 +418,9 @@ // Glide a bird's-eye view shark and animate the move line along the water route (#183). let dot: import('leaflet').Marker | undefined; + let dotKey: string | undefined; + let lastLineEl: SVGPathElement | undefined; + let lastArrowEl: SVGPathElement | undefined; let currentLineEntries: { l: MapLine; line: import('leaflet').Polyline; @@ -426,9 +431,19 @@ const L = leaflet; const t = traveller; if (!m || !L) return; - dot?.remove(); - dot = undefined; - if (!t) return; + if (!t) { + dot?.remove(); + dot = undefined; + dotKey = undefined; + if (lastLineEl) { + lastLineEl.style.strokeDasharray = ''; + lastLineEl.style.strokeDashoffset = ''; + } + if (lastArrowEl) lastArrowEl.style.opacity = ''; + lastLineEl = undefined; + lastArrowEl = undefined; + return; + } const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches; const still = reducedMotion || Boolean(t.still); const path: [number, number][] = @@ -485,17 +500,20 @@
`; - const marker = L.marker(at(still ? 1 : 0), { - icon: L.divIcon({ - className: 'ps-traveller ps-shark-marker', - html: sharkHtml, - iconSize: [32, 46], - iconAnchor: [16, 23] - }), - interactive: false - }).addTo(m); - dot = marker; - if (still) return; + const neededKey = `${t.species ?? ''}-${t.color}`; + if (!dot || dotKey !== neededKey) { + dot?.remove(); + dot = L.marker(at(still ? 1 : 0), { + icon: L.divIcon({ + className: 'ps-traveller ps-shark-marker', + html: sharkHtml, + iconSize: [32, 46], + iconAnchor: [16, 23] + }), + interactive: false + }).addTo(m); + dotKey = neededKey; + } // Locate the move line matching this traveller step to progressively draw its stroke. const target = currentLineEntries.find( @@ -508,9 +526,79 @@ ); let lineEl = target?.line.getElement() as SVGPathElement | undefined; let arrowEl = target?.arrow.getElement() as SVGPathElement | undefined; + if (lastLineEl && lastLineEl !== lineEl) { + lastLineEl.style.strokeDasharray = ''; + lastLineEl.style.strokeDashoffset = ''; + } + if (lastArrowEl && lastArrowEl !== arrowEl) { + lastArrowEl.style.opacity = ''; + } + lastLineEl = lineEl; + lastArrowEl = arrowEl; let totalLen = lineEl?.getTotalLength ? lineEl.getTotalLength() : 0; - // Progressive stroke animation along the water route polyline. + // When fraction is explicitly passed (continuous scrubbing or smooth external RAF loop): + if (t.fraction != null) { + const f = still ? 1 : Math.max(0, Math.min(1, t.fraction)); + if (lineEl && totalLen > 0) { + if (f >= 1) { + lineEl.style.strokeDasharray = ''; + lineEl.style.strokeDashoffset = ''; + } else { + lineEl.style.strokeDasharray = `${totalLen} ${totalLen}`; + lineEl.style.strokeDashoffset = `${totalLen * (1 - f)}`; + } + if (arrowEl) arrowEl.style.opacity = f >= ARROW_AT ? '1' : '0'; + } + + let heading = initialHeading; + if (lineEl && totalLen > 0 && lineEl.getPointAtLength) { + const curLen = totalLen * f; + const pt = lineEl.getPointAtLength(curLen); + dot.setLatLng(m.layerPointToLatLng([pt.x, pt.y])); + + const ahead = lineEl.getPointAtLength(Math.min(totalLen, curLen + 3)); + const behind = lineEl.getPointAtLength(Math.max(0, curLen - 3)); + const dx = ahead.x - behind.x; + const dy = ahead.y - behind.y; + if (dx !== 0 || dy !== 0) { + heading = Math.atan2(dx, -dy) * (180 / Math.PI); + } + } else { + dot.setLatLng(at(f)); + if (path.length >= 2) { + const fAhead = Math.min(1, f + 0.02); + const fBehind = Math.max(0, f - 0.02); + const pAhead = m.latLngToLayerPoint(at(fAhead)); + const pBehind = m.latLngToLayerPoint(at(fBehind)); + const dx = pAhead.x - pBehind.x; + const dy = pAhead.y - pBehind.y; + if (dx !== 0 || dy !== 0) { + heading = Math.atan2(dx, -dy) * (180 / Math.PI); + } + } + } + + const wrapEl = (dot.getElement() as HTMLElement | undefined)?.querySelector( + '.ps-shark-wrap' + ) as HTMLElement | null; + const tailEl = (dot.getElement() as HTMLElement | undefined)?.querySelector( + '.ps-shark-tail' + ) as HTMLElement | null; + if (wrapEl) { + const bodyWiggle = t.playing && f < 1 ? Math.sin(performance.now() * 0.018) * 4 : 0; + wrapEl.style.transform = `rotate(${heading + bodyWiggle}deg)`; + } + if (tailEl) { + const tailWiggle = t.playing && f < 1 ? Math.sin(performance.now() * 0.018 - 1.2) * 12 : 0; + tailEl.style.transform = `rotate(${tailWiggle}deg)`; + } + return; + } + + // Fallback self-driven RAF animation when fraction is omitted: + if (still) return; + if (lineEl && totalLen > 0) { lineEl.style.strokeDasharray = `${totalLen} ${totalLen}`; lineEl.style.strokeDashoffset = `${totalLen}`; @@ -520,6 +608,7 @@ const start = performance.now(); let frame = 0; const duration = moveDuration(t.km); + const marker = dot; const step = (now: number) => { const f = Math.min(1, (now - start) / duration); const eased = f < 0.5 ? 2 * f * f : 1 - (-2 * f + 2) ** 2 / 2; diff --git a/src/routes/sharks/[id]/+page.svelte b/src/routes/sharks/[id]/+page.svelte index 7dbff28..4165a9c 100644 --- a/src/routes/sharks/[id]/+page.svelte +++ b/src/routes/sharks/[id]/+page.svelte @@ -14,47 +14,91 @@ const ind = $derived(data.ind); const growth = $derived(data.captures.filter((c) => c.date && c.tl != null)); - // Play this shark's captures in order (#173, #183): lines appear as it moves, a shark swims along. + // Play this shark's captures in order (#173, #183): continuous slider scrubbing and animated water routes. const stops = $derived(data.track.length); - let step = $state(0); - const at = $derived(Math.min(step, stops)); - const current = $derived(at < stops ? data.track[at] : null); - // An unlocated capture breaks the path: do not animate across that unknown stop. - const previous = $derived( - current && at > 0 && data.track[at - 1].n === current.n - 1 ? data.track[at - 1] : null - ); + const totalMoves = $derived(Math.max(1, stops - 1)); + let progress = $state(0); + let playing = $state(false); + let showAll = $state(false); + + // Which leg of the track is active (0 to totalMoves - 1): + const activeLeg = $derived(Math.min(totalMoves - 1, Math.floor(progress))); + const legFraction = $derived(progress >= totalMoves ? 1 : Math.max(0, progress - activeLeg)); + const fromStop = $derived(data.track[activeLeg] ?? data.track[0]); + const toStop = $derived(data.track[activeLeg + 1] ?? data.track[stops - 1]); + // The move between consecutive captures (m.at is the destination capture index in +page.server.ts): + const activeMove = $derived(data.moves.find((m) => m.at === activeLeg + 1)); const color = $derived(speciesColor(ind.species)); + const shownMoves = $derived( - current ? data.moves.filter((m) => m.at + 1 <= current.n) : data.moves + showAll ? data.moves : data.moves.filter((m) => m.at <= activeLeg + 1) ); - const currentMove = $derived(current ? data.moves.find((m) => m.at + 1 === current.n) : null); - let playing = $state(false); + function stop() { playing = false; } + function play() { if (playing) return stop(); - if (at >= stops - 1) { - step = 0; - playing = true; - return; - } - if (at === 0) { - step = 1; - playing = true; - return; + showAll = false; + if (progress >= totalMoves - 0.001) { + progress = 0; } playing = true; } + + function jumpTo(idx: number) { + stop(); + showAll = false; + progress = idx; + } + + function toggleAll() { + stop(); + showAll = true; + progress = totalMoves; + } + $effect(() => { if (!playing) return; - const delay = moveDuration(currentMove?.km) + 350; - const timer = setTimeout(() => { - if (step >= stops - 1) playing = false; - else step = Math.min(step, stops) + 1; - }, delay); - return () => clearTimeout(timer); + let lastTime: number | null = null; + let raf: number; + const tick = (now: number) => { + if (!playing) return; + if (lastTime == null) { + lastTime = now; + raf = requestAnimationFrame(tick); + return; + } + const dt = now - lastTime; + lastTime = now; + + const leg = Math.min(totalMoves - 1, Math.floor(progress)); + const move = data.moves.find((m) => m.at === leg + 1); + const duration = moveDuration(move?.km); + const next = progress + dt / Math.max(800, duration); + + if (next >= totalMoves) { + progress = totalMoves; + playing = false; + return; + } + progress = next; + raf = requestAnimationFrame(tick); + }; + raf = requestAnimationFrame(tick); + return () => cancelAnimationFrame(raf); }); + + const sliderAriaText = $derived( + showAll + ? 'All captures' + : activeMove && legFraction > 0.01 && legFraction < 0.99 + ? `Swimming from ${fromStop.site} to ${toStop.site}, ${Math.round(legFraction * 100)}%` + : progress >= 0.99 + ? `Capture ${toStop.n}: ${toStop.site}, ${date(toStop.date)}` + : `Capture 1: ${data.track[0].site}, ${date(data.track[0].date)}` + );
@@ -105,36 +149,69 @@ {#if data.moves.length}
{ stop(); - step = Number(e.currentTarget.value); + showAll = false; + progress = Number(e.currentTarget.value); }} - aria-valuetext={current - ? `Capture ${current.n}: ${current.site}, ${date(current.date)}` - : 'All captures'} + aria-valuetext={sliderAriaText} /> - {#if current} - Capture {current.n} of {ind.nCaptures} - · {date(current.date)} · {current.site}{current.tl != null - ? ` · ${num(current.tl)} mm` - : ''}{previous && previous.site !== current.site - ? ` (moved from ${previous.site}${currentMove?.km ? ` · ≥ ${num(currentMove.km, 1)} km by water` : ''})` - : ''} + {#if showAll} + All captures ({data.track.length} captures, {data.moves.length} moves) + {:else if activeMove && legFraction > 0.01 && legFraction < 0.99} + Swimming: + {fromStop.site} → {toStop.site} + {#if activeMove.km != null} + · {num(activeMove.km * legFraction, 1)} of {num(activeMove.km, 1)} km by water + ({Math.round(legFraction * 100)}%) + {/if} + {:else if progress >= 0.99} + {@const arrivedStop = toStop} + {@const prevStop = fromStop} + Capture {arrivedStop.n} of {ind.nCaptures} + · {date(arrivedStop.date)} · {arrivedStop.site}{arrivedStop.tl != null + ? ` · ${num(arrivedStop.tl)} mm` + : ''}{prevStop && prevStop.site !== arrivedStop.site + ? ` (moved from ${prevStop.site}${activeMove?.km ? ` · ≥ ${num(activeMove.km, 1)} km by water` : ''})` + : prevStop + ? ` (recaptured at ${arrivedStop.site})` + : ''} {:else} - All captures + {@const firstStop = data.track[0]} + Capture 1 of {ind.nCaptures} + · {date(firstStop.date)} · {firstStop.site}{firstStop.tl != null + ? ` · ${num(firstStop.tl)} mm` + : ''} (starting nursery) {/if} +
+ {#each data.track as t, i (t.n)} + + {/each} + +
= stops ? data.moves[data.moves.length - 1]?.path : undefined), - km: currentMove?.km, + key: activeLeg, + from: fromStop, + to: toStop, + path: activeMove?.path, + km: activeMove?.km, color, species: ind.species, - lineId: currentMove?.id, - still: !currentMove + lineId: activeMove?.id, + still: !activeMove, + fraction: showAll ? 1 : legFraction, + playing } : undefined} /> @@ -243,6 +320,37 @@ color: var(--ink); cursor: pointer; } + .stops-nav { + display: flex; + flex-wrap: wrap; + gap: 6px; + width: 100%; + margin-top: 2px; + } + .stop-btn { + font: inherit; + font-size: 0.78rem; + padding: 2px 9px; + border-radius: 999px; + border: 1px solid var(--hairline); + background: var(--surface-2); + color: var(--ink-2); + cursor: pointer; + transition: + background 0.15s, + color 0.15s, + border-color 0.15s; + } + .stop-btn:hover { + color: var(--ink); + border-color: var(--ink-2); + } + .stop-btn.active { + background: var(--series-1); + color: #ffffff; + border-color: var(--series-1); + font-weight: 600; + } .id { font-weight: 400; color: var(--ink-2); From 9d108ee23fd621d7c49930452aeb93c27d38a780 Mon Sep 17 00:00:00 2001 From: luen Date: Thu, 12 Nov 2026 16:18:49 +1000 Subject: [PATCH 09/13] fix(sharks): synchronize slider scrubbing with shark marker and water route stroke (#183) --- src/lib/components/InteractiveMap.svelte | 33 ++++++++++++++++++++---- src/routes/sharks/[id]/+page.svelte | 8 +++--- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index 9bafca2..fb9c571 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -279,6 +279,7 @@ }); // Redraw the overlays whenever the layers change (e.g. a season slider), keeping the view. + let lastLayerKey = ''; $effect(() => { const m = map; const L = leaflet; @@ -287,6 +288,11 @@ const currentDensity = density; void zoom; if (!m || !L || !el) return; + + const layerKey = `${current.map((l) => `${l.name}:${l.points.length}`).join('|')}_${currentLines.map((g) => `${g.name}:${g.lines.map((l) => (l as { id?: string }).id ?? l.label).join(',')}`).join('|')}_${currentDensity?.name ?? ''}_${zoom}`; + if (drawn.length && layerKey === lastLayerKey) return; + lastLayerKey = layerKey; + const hidden = new Set( drawn.flatMap((d) => d.groups.filter((g) => !m.hasLayer(g.group)).map((g) => g.key)) ); @@ -346,6 +352,12 @@ ]; const shiftedPts = offsetPolyline(rawPts, back[n++] ? shiftFor(weight) : 0); const latLngs = shiftedPts.map(([x, y]) => m.layerPointToLatLng([x, y])); + L.polyline(latLngs, { + weight: Math.max(1.5, weight - 1), + className: 'ps-line-track', + smoothFactor: 0, + interactive: false + }).addTo(group); const line = L.polyline(latLngs, { weight, className: `ps-line ps-line-${i}`, @@ -445,7 +457,7 @@ return; } const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches; - const still = reducedMotion || Boolean(t.still); + const still = Boolean(t.still); const path: [number, number][] = t.path && t.path.length >= 2 ? t.path @@ -524,8 +536,11 @@ Math.abs(e.l.to.lat - t.to.lat) < 1e-4 && Math.abs(e.l.to.lon - t.to.lon) < 1e-4) ); - let lineEl = target?.line.getElement() as SVGPathElement | undefined; - let arrowEl = target?.arrow.getElement() as SVGPathElement | undefined; + let lineEl = (target?.line.getElement() ?? + (el?.querySelector('.ps-line') as SVGPathElement | null)) as SVGPathElement | undefined; + let arrowEl = (target?.arrow.getElement() ?? + (el?.querySelector('path[marker-mid]') as SVGPathElement | null)) as + SVGPathElement | undefined; if (lastLineEl && lastLineEl !== lineEl) { lastLineEl.style.strokeDasharray = ''; lastLineEl.style.strokeDashoffset = ''; @@ -586,11 +601,13 @@ '.ps-shark-tail' ) as HTMLElement | null; if (wrapEl) { - const bodyWiggle = t.playing && f < 1 ? Math.sin(performance.now() * 0.018) * 4 : 0; + const bodyWiggle = + !reducedMotion && t.playing && f < 1 ? Math.sin(performance.now() * 0.018) * 4 : 0; wrapEl.style.transform = `rotate(${heading + bodyWiggle}deg)`; } if (tailEl) { - const tailWiggle = t.playing && f < 1 ? Math.sin(performance.now() * 0.018 - 1.2) * 12 : 0; + const tailWiggle = + !reducedMotion && t.playing && f < 1 ? Math.sin(performance.now() * 0.018 - 1.2) * 12 : 0; tailEl.style.transform = `rotate(${tailWiggle}deg)`; } return; @@ -838,6 +855,12 @@ .map :global(.leaflet-interactive.ps-line) { stroke-opacity: 0.75; } + .map :global(.ps-line-track) { + stroke: var(--ink); + stroke-opacity: 0.22; + stroke-dasharray: 4 4; + pointer-events: none; + } .map :global(.ps-line:focus-visible) { outline: 2px solid var(--ink); outline-offset: 4px; diff --git a/src/routes/sharks/[id]/+page.svelte b/src/routes/sharks/[id]/+page.svelte index 4165a9c..e95494e 100644 --- a/src/routes/sharks/[id]/+page.svelte +++ b/src/routes/sharks/[id]/+page.svelte @@ -33,6 +33,7 @@ const shownMoves = $derived( showAll ? data.moves : data.moves.filter((m) => m.at <= activeLeg + 1) ); + const moveLayers = $derived([{ name: 'Moves', color, lines: shownMoves }]); function stop() { playing = false; @@ -158,11 +159,10 @@ min="0" max={totalMoves} step="0.002" - value={progress} - oninput={(e) => { + bind:value={progress} + oninput={() => { stop(); showAll = false; - progress = Number(e.currentTarget.value); }} aria-valuetext={sliderAriaText} /> @@ -228,7 +228,7 @@ layers={[ { name: 'Capture sites', color, sized: true, maxRadius: 12, points: data.map } ]} - lineLayers={[{ name: 'Moves', color, lines: shownMoves }]} + lineLayers={moveLayers} lineMax={4} traveller={data.track.length ? { From 1de473b315bdfc8e8d8b969a81cd47560349b3ea Mon Sep 17 00:00:00 2001 From: luen Date: Fri, 13 Nov 2026 08:38:05 +1000 Subject: [PATCH 10/13] feat(map): replace shark SVG with clean circular traveller dot (#183) --- AGENTS.md | 2 +- e2e/map-routes.spec.ts | 3 +- src/lib/components/InteractiveMap.svelte | 155 ++--------------------- 3 files changed, 14 insertions(+), 146 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 62b8260..ffb76d4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -156,7 +156,7 @@ samples/fixture/ synthetic workbooks for tests/CI (committed) - `src/lib/server/oceanRoutes.ts`: computes shortest water routes around Moorea between all pairs of nurseries using grid A* routing around the island's coastline (`src/lib/moorea-outline.json`, OpenStreetMap, ODbL 1.0). The 35 m grid rasters Moorea island with a 2 km buffer, calculates chamfer distance-to-land, snaps nursery points to nearby water, searches with an A* penalty near land to avoid hugging rocks, and smooths with raycast string-pulling. - Precomputed routes are stored in SQLite `nursery_routes` (`cache/` disposable database), bumping `IMPORTER_VERSION` to `'13'`. Never commit nursery coordinates or precomputed routes to git. -- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the slider scrubs continuously (`step="0.002"`) across all intermediate points with live line drawing, real-time distance and capture stop quick-jump pills; playback smoothly animates a bird's-eye view shark swimming along the water route at the tip of the line (rotating along the route with tail waggle, jumping under `prefers-reduced-motion`). +- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the slider scrubs continuously (`step="0.002"`) across all intermediate points with live line drawing, real-time distance and capture stop quick-jump pills; playback smoothly glides a traveller dot along the water route at the tip of the line (with progressive line drawing, jumping under `prefers-reduced-motion`). - Standalone CLI `node scripts/ocean-routes.mjs` (or `pnpm routes`, with optional `--geojson`) verifies that 0 routes cross land. ### Adding a new season diff --git a/e2e/map-routes.spec.ts b/e2e/map-routes.spec.ts index 8c65697..9cd3529 100644 --- a/e2e/map-routes.spec.ts +++ b/e2e/map-routes.spec.ts @@ -98,10 +98,9 @@ test('shark detail page animates move line and traveller dot along water route ( expect(animating).toBe(true); }).toPass({ timeout: 4000 }); - // Traveller shark icon exists and glides along the water route + // Traveller dot exists and glides along the water route const traveller = page.locator('.ps-traveller'); await expect(traveller).toBeVisible(); - await expect(page.locator('.ps-traveller .ps-shark-svg')).toBeVisible(); // Eventually animation finishes and stroke properties reset to normal await expect(async () => { diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index fb9c571..7a0f7eb 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -87,7 +87,7 @@ density?: MapDensity; /** Value that gets the widest line; fix it so widths don't jump as lines are added. */ lineMax?: number; - /** A bird's-eye view shark that glides from `from` to `to` along the water route whenever `key` changes (a Play button). */ + /** A dot that glides from `from` to `to` along the water route whenever `key` changes (a Play button). */ traveller?: { key: string | number; from: { lat: number; lon: number }; @@ -428,9 +428,8 @@ drawn = [{ groups: [...densityGroups, ...lineGroups, ...groups], control }]; }); - // Glide a bird's-eye view shark and animate the move line along the water route (#183). - let dot: import('leaflet').Marker | undefined; - let dotKey: string | undefined; + // Glide a dot and animate the move line along the water route (#183). + let dot: import('leaflet').CircleMarker | undefined; let lastLineEl: SVGPathElement | undefined; let lastArrowEl: SVGPathElement | undefined; let currentLineEntries: { @@ -446,7 +445,6 @@ if (!t) { dot?.remove(); dot = undefined; - dotKey = undefined; if (lastLineEl) { lastLineEl.style.strokeDasharray = ''; lastLineEl.style.strokeDashoffset = ''; @@ -456,7 +454,6 @@ lastArrowEl = undefined; return; } - const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches; const still = Boolean(t.still); const path: [number, number][] = t.path && t.path.length >= 2 @@ -467,65 +464,14 @@ ]; const at = (f: number): [number, number] => pointAlongPath(path, f); - // Compute initial heading angle (degrees clockwise from North). - let initialHeading = 0; - if (path.length >= 2) { - const refIdx = still ? path.length - 1 : 0; - const p1 = m.latLngToLayerPoint(still ? path[Math.max(0, refIdx - 1)] : path[0]); - const p2 = m.latLngToLayerPoint(still ? path[refIdx] : path[Math.min(path.length - 1, 1)]); - const dx = p2.x - p1.x; - const dy = p2.y - p1.y; - if (dx !== 0 || dy !== 0) { - initialHeading = Math.atan2(dx, -dy) * (180 / Math.PI); - } - } - - const isBlacktip = t.species !== 'Na'; - const tipColor = isBlacktip ? '#0f172a' : '#92400e'; - const sharkHtml = ` -
- - - - ${ - isBlacktip - ? ` - - - ` - : '' - } - - - - - - - - - - ${isBlacktip ? `` : ''} - - -
- `; - - const neededKey = `${t.species ?? ''}-${t.color}`; - if (!dot || dotKey !== neededKey) { - dot?.remove(); - dot = L.marker(at(still ? 1 : 0), { - icon: L.divIcon({ - className: 'ps-traveller ps-shark-marker', - html: sharkHtml, - iconSize: [32, 46], - iconAnchor: [16, 23] - }), + if (!dot) { + dot = L.circleMarker(at(still ? 1 : 0), { + radius: 7, + className: 'ps-traveller', interactive: false }).addTo(m); - dotKey = neededKey; } + dot.setStyle({ fillColor: t.color, color: '#ffffff' }); // Locate the move line matching this traveller step to progressively draw its stroke. const target = currentLineEntries.find( @@ -566,49 +512,12 @@ if (arrowEl) arrowEl.style.opacity = f >= ARROW_AT ? '1' : '0'; } - let heading = initialHeading; if (lineEl && totalLen > 0 && lineEl.getPointAtLength) { const curLen = totalLen * f; const pt = lineEl.getPointAtLength(curLen); dot.setLatLng(m.layerPointToLatLng([pt.x, pt.y])); - - const ahead = lineEl.getPointAtLength(Math.min(totalLen, curLen + 3)); - const behind = lineEl.getPointAtLength(Math.max(0, curLen - 3)); - const dx = ahead.x - behind.x; - const dy = ahead.y - behind.y; - if (dx !== 0 || dy !== 0) { - heading = Math.atan2(dx, -dy) * (180 / Math.PI); - } } else { dot.setLatLng(at(f)); - if (path.length >= 2) { - const fAhead = Math.min(1, f + 0.02); - const fBehind = Math.max(0, f - 0.02); - const pAhead = m.latLngToLayerPoint(at(fAhead)); - const pBehind = m.latLngToLayerPoint(at(fBehind)); - const dx = pAhead.x - pBehind.x; - const dy = pAhead.y - pBehind.y; - if (dx !== 0 || dy !== 0) { - heading = Math.atan2(dx, -dy) * (180 / Math.PI); - } - } - } - - const wrapEl = (dot.getElement() as HTMLElement | undefined)?.querySelector( - '.ps-shark-wrap' - ) as HTMLElement | null; - const tailEl = (dot.getElement() as HTMLElement | undefined)?.querySelector( - '.ps-shark-tail' - ) as HTMLElement | null; - if (wrapEl) { - const bodyWiggle = - !reducedMotion && t.playing && f < 1 ? Math.sin(performance.now() * 0.018) * 4 : 0; - wrapEl.style.transform = `rotate(${heading + bodyWiggle}deg)`; - } - if (tailEl) { - const tailWiggle = - !reducedMotion && t.playing && f < 1 ? Math.sin(performance.now() * 0.018 - 1.2) * 12 : 0; - tailEl.style.transform = `rotate(${tailWiggle}deg)`; } return; } @@ -640,22 +549,12 @@ } } - let heading = initialHeading; if (lineEl && totalLen > 0) { lineEl.style.strokeDashoffset = `${totalLen * (1 - eased)}`; if (arrowEl) arrowEl.style.opacity = f >= ARROW_AT ? '1' : '0'; if (lineEl.getPointAtLength) { - const curLen = totalLen * eased; - const pt = lineEl.getPointAtLength(curLen); + const pt = lineEl.getPointAtLength(totalLen * eased); marker.setLatLng(m.layerPointToLatLng([pt.x, pt.y])); - - const ahead = lineEl.getPointAtLength(Math.min(totalLen, curLen + 3)); - const behind = lineEl.getPointAtLength(Math.max(0, curLen - 3)); - const dx = ahead.x - behind.x; - const dy = ahead.y - behind.y; - if (dx !== 0 || dy !== 0) { - heading = Math.atan2(dx, -dy) * (180 / Math.PI); - } } else { marker.setLatLng(at(eased)); } @@ -663,21 +562,6 @@ marker.setLatLng(at(eased)); } - const wrapEl = (marker.getElement() as HTMLElement | undefined)?.querySelector( - '.ps-shark-wrap' - ) as HTMLElement | null; - const tailEl = (marker.getElement() as HTMLElement | undefined)?.querySelector( - '.ps-shark-tail' - ) as HTMLElement | null; - if (wrapEl) { - const bodyWiggle = f < 1 ? Math.sin((now - start) * 0.018) * 4 : 0; - wrapEl.style.transform = `rotate(${heading + bodyWiggle}deg)`; - } - if (tailEl) { - const tailWiggle = f < 1 ? Math.sin((now - start) * 0.018 - 1.2) * 12 : 0; - tailEl.style.transform = `rotate(${tailWiggle}deg)`; - } - if (f < 1) { frame = requestAnimationFrame(step); } else { @@ -832,25 +716,10 @@ background: linear-gradient(90deg, var(--seq-2), var(--seq-6)); } .map :global(.ps-traveller) { - stroke: #fff; - stroke-width: 2px; + stroke: #ffffff; + stroke-width: 2.5px; fill-opacity: 1; - } - .map :global(.ps-shark-marker) { - background: transparent !important; - border: none !important; - } - .map :global(.ps-shark-wrap) { - width: 32px; - height: 46px; - transform-origin: 16px 23px; - filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.7)); - pointer-events: none; - will-change: transform; - } - .map :global(.ps-shark-tail) { - transform-origin: 16px 33px; - will-change: transform; + filter: drop-shadow(0 1px 3px rgba(0, 0, 0, 0.45)); } .map :global(.leaflet-interactive.ps-line) { stroke-opacity: 0.75; From cf37e666a28d6e3cf854840c6af33caf87d80feb Mon Sep 17 00:00:00 2001 From: luen Date: Fri, 13 Nov 2026 09:34:44 +1000 Subject: [PATCH 11/13] style(map): style water route track as blue dotted line (#183) --- src/lib/components/InteractiveMap.svelte | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index 7a0f7eb..172ce0d 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -354,7 +354,7 @@ const latLngs = shiftedPts.map(([x, y]) => m.layerPointToLatLng([x, y])); L.polyline(latLngs, { weight: Math.max(1.5, weight - 1), - className: 'ps-line-track', + className: `ps-line-track ps-line-track-${i}`, smoothFactor: 0, interactive: false }).addTo(group); @@ -725,11 +725,17 @@ stroke-opacity: 0.75; } .map :global(.ps-line-track) { - stroke: var(--ink); - stroke-opacity: 0.22; + stroke: var(--ps-line-0, #2563eb); + stroke-opacity: 0.6; stroke-dasharray: 4 4; pointer-events: none; } + .map :global(.ps-line-track-0) { + stroke: var(--ps-line-0, #2563eb); + } + .map :global(.ps-line-track-1) { + stroke: var(--ps-line-1, #ea580c); + } .map :global(.ps-line:focus-visible) { outline: 2px solid var(--ink); outline-offset: 4px; From bd023cca15c06753fa13e8088eb49e662756cc49 Mon Sep 17 00:00:00 2001 From: luen Date: Fri, 13 Nov 2026 09:58:36 +1000 Subject: [PATCH 12/13] feat(map): hide directional arrow during route playback on shark pages (#183) --- AGENTS.md | 2 +- e2e/map-routes.spec.ts | 22 +++++++++++++++- src/lib/components/InteractiveMap.svelte | 32 ++++++++++++++++-------- 3 files changed, 44 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ffb76d4..b127f30 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -156,7 +156,7 @@ samples/fixture/ synthetic workbooks for tests/CI (committed) - `src/lib/server/oceanRoutes.ts`: computes shortest water routes around Moorea between all pairs of nurseries using grid A* routing around the island's coastline (`src/lib/moorea-outline.json`, OpenStreetMap, ODbL 1.0). The 35 m grid rasters Moorea island with a 2 km buffer, calculates chamfer distance-to-land, snaps nursery points to nearby water, searches with an A* penalty near land to avoid hugging rocks, and smooths with raycast string-pulling. - Precomputed routes are stored in SQLite `nursery_routes` (`cache/` disposable database), bumping `IMPORTER_VERSION` to `'13'`. Never commit nursery coordinates or precomputed routes to git. -- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the slider scrubs continuously (`step="0.002"`) across all intermediate points with live line drawing, real-time distance and capture stop quick-jump pills; playback smoothly glides a traveller dot along the water route at the tip of the line (with progressive line drawing, jumping under `prefers-reduced-motion`). +- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the slider scrubs continuously (`step="0.002"`) across all intermediate points with live line drawing, real-time distance and capture stop quick-jump pills; playback smoothly glides a traveller dot along the water route at the tip of the line (with progressive line drawing, jumping under `prefers-reduced-motion`). The directional arrow is visible on the blue dotted track before playback starts, and is hidden once playing or scrubbed to keep the animated line clean. - Standalone CLI `node scripts/ocean-routes.mjs` (or `pnpm routes`, with optional `--geojson`) verifies that 0 routes cross land. ### Adding a new season diff --git a/e2e/map-routes.spec.ts b/e2e/map-routes.spec.ts index 9cd3529..4c89528 100644 --- a/e2e/map-routes.spec.ts +++ b/e2e/map-routes.spec.ts @@ -83,8 +83,23 @@ test('shark detail page animates move line and traveller dot along water route ( const playBtn = page.locator('button.play'); const slider = page.locator('#capture-slider'); if ((await slider.count()) > 0) { + // Arrow is visible on dotted line before playback starts (#183) + const arrow = page.locator('.ps-arrow').first(); + if ((await arrow.count()) > 0) { + const initialOpacity = await arrow.evaluate((el) => (el as SVGElement).style.opacity); + expect(initialOpacity).not.toBe('0'); + } + // Start playback await playBtn.click(); + + // Arrow is removed when playback starts (#183) + if ((await arrow.count()) > 0) { + await expect + .poll(async () => arrow.evaluate((el) => (el as SVGElement).style.opacity)) + .toBe('0'); + } + // While stepping from capture 1 to capture 2, the line animates along the water route await expect(async () => { const animating = await page.evaluate(() => { @@ -102,7 +117,7 @@ test('shark detail page animates move line and traveller dot along water route ( const traveller = page.locator('.ps-traveller'); await expect(traveller).toBeVisible(); - // Eventually animation finishes and stroke properties reset to normal + // Eventually animation finishes, stroke properties reset to normal, and arrow remains removed await expect(async () => { const finished = await page.evaluate(() => { const line = document.querySelector('.ps-line'); @@ -110,5 +125,10 @@ test('shark detail page animates move line and traveller dot along water route ( }); expect(finished).toBe(true); }).toPass({ timeout: 5000 }); + + if ((await arrow.count()) > 0) { + const finishedOpacity = await arrow.evaluate((el) => (el as SVGElement).style.opacity); + expect(finishedOpacity).toBe('0'); + } } }); diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index 172ce0d..ba83360 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -54,7 +54,6 @@ import MooreaMap from './MooreaMap.svelte'; import { registerCsv } from './charts/csv'; import { - ARROW_AT, lineWidth, moveDuration, offsetPolyline, @@ -449,7 +448,10 @@ lastLineEl.style.strokeDasharray = ''; lastLineEl.style.strokeDashoffset = ''; } - if (lastArrowEl) lastArrowEl.style.opacity = ''; + for (const entry of currentLineEntries) { + const aEl = entry.arrow.getElement() as SVGPathElement | null; + if (aEl) aEl.style.opacity = ''; + } lastLineEl = undefined; lastArrowEl = undefined; return; @@ -492,7 +494,7 @@ lastLineEl.style.strokeDashoffset = ''; } if (lastArrowEl && lastArrowEl !== arrowEl) { - lastArrowEl.style.opacity = ''; + lastArrowEl.style.opacity = '0'; } lastLineEl = lineEl; lastArrowEl = arrowEl; @@ -509,12 +511,19 @@ lineEl.style.strokeDasharray = `${totalLen} ${totalLen}`; lineEl.style.strokeDashoffset = `${totalLen * (1 - f)}`; } - if (arrowEl) arrowEl.style.opacity = f >= ARROW_AT ? '1' : '0'; + } + + // Keep arrow visible on dotted line before playback/scrubbing starts; hide once playing or moving (#183). + const showArrow = !t.playing && f < 0.01; + for (const entry of currentLineEntries) { + const aEl = entry.arrow.getElement() as SVGPathElement | null; + if (aEl) { + aEl.style.opacity = showArrow && entry === target ? '1' : '0'; + } } if (lineEl && totalLen > 0 && lineEl.getPointAtLength) { - const curLen = totalLen * f; - const pt = lineEl.getPointAtLength(curLen); + const pt = lineEl.getPointAtLength(totalLen * f); dot.setLatLng(m.layerPointToLatLng([pt.x, pt.y])); } else { dot.setLatLng(at(f)); @@ -525,10 +534,14 @@ // Fallback self-driven RAF animation when fraction is omitted: if (still) return; + for (const entry of currentLineEntries) { + const aEl = entry.arrow.getElement() as SVGPathElement | null; + if (aEl) aEl.style.opacity = '0'; + } + if (lineEl && totalLen > 0) { lineEl.style.strokeDasharray = `${totalLen} ${totalLen}`; lineEl.style.strokeDashoffset = `${totalLen}`; - if (arrowEl) arrowEl.style.opacity = '0'; } const start = performance.now(); @@ -551,7 +564,6 @@ if (lineEl && totalLen > 0) { lineEl.style.strokeDashoffset = `${totalLen * (1 - eased)}`; - if (arrowEl) arrowEl.style.opacity = f >= ARROW_AT ? '1' : '0'; if (lineEl.getPointAtLength) { const pt = lineEl.getPointAtLength(totalLen * eased); marker.setLatLng(m.layerPointToLatLng([pt.x, pt.y])); @@ -569,7 +581,7 @@ lineEl.style.strokeDasharray = ''; lineEl.style.strokeDashoffset = ''; } - if (arrowEl) arrowEl.style.opacity = ''; + if (arrowEl) arrowEl.style.opacity = '0'; } }; frame = requestAnimationFrame(step); @@ -580,7 +592,7 @@ lineEl.style.strokeDashoffset = ''; } if (arrowEl) { - arrowEl.style.opacity = ''; + arrowEl.style.opacity = '0'; } }; }); From ebfbba239af0d945a09b327bb5ef8b0fbb5733f9 Mon Sep 17 00:00:00 2001 From: luen Date: Fri, 13 Nov 2026 10:15:49 +1000 Subject: [PATCH 13/13] feat(sharks): default to All moves with arrows on page load (#183) --- AGENTS.md | 2 +- e2e/map-routes.spec.ts | 38 +++++++++++++++++------- src/lib/components/InteractiveMap.svelte | 30 +++++++++++++++++++ src/routes/sharks/[id]/+page.svelte | 19 ++++++++---- 4 files changed, 73 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b127f30..36b9665 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -156,7 +156,7 @@ samples/fixture/ synthetic workbooks for tests/CI (committed) - `src/lib/server/oceanRoutes.ts`: computes shortest water routes around Moorea between all pairs of nurseries using grid A* routing around the island's coastline (`src/lib/moorea-outline.json`, OpenStreetMap, ODbL 1.0). The 35 m grid rasters Moorea island with a 2 km buffer, calculates chamfer distance-to-land, snaps nursery points to nearby water, searches with an A* penalty near land to avoid hugging rocks, and smooths with raycast string-pulling. - Precomputed routes are stored in SQLite `nursery_routes` (`cache/` disposable database), bumping `IMPORTER_VERSION` to `'13'`. Never commit nursery coordinates or precomputed routes to git. -- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the slider scrubs continuously (`step="0.002"`) across all intermediate points with live line drawing, real-time distance and capture stop quick-jump pills; playback smoothly glides a traveller dot along the water route at the tip of the line (with progressive line drawing, jumping under `prefers-reduced-motion`). The directional arrow is visible on the blue dotted track before playback starts, and is hidden once playing or scrubbed to keep the animated line clean. +- Move lines on `/recaptures` and `/sharks/[id]` render multi-point polylines along the water route, offset rightwards if reversed, and display water distance (`≥ X km by water`, with direct straight-line distance alongside). On shark pages, the map defaults to an "All moves" overview on load with directional arrows on all paths; clicking Play steps through the captures in order with continuous slider scrubbing (`step="0.002"`), progressive line drawing, real-time distance and capture stop pills, gliding a traveller dot along the water route with directional arrows hidden during playback to keep the animated line clean (jumping under `prefers-reduced-motion`). - Standalone CLI `node scripts/ocean-routes.mjs` (or `pnpm routes`, with optional `--geojson`) verifies that 0 routes cross land. ### Adding a new season diff --git a/e2e/map-routes.spec.ts b/e2e/map-routes.spec.ts index 4c89528..3202577 100644 --- a/e2e/map-routes.spec.ts +++ b/e2e/map-routes.spec.ts @@ -83,20 +83,27 @@ test('shark detail page animates move line and traveller dot along water route ( const playBtn = page.locator('button.play'); const slider = page.locator('#capture-slider'); if ((await slider.count()) > 0) { - // Arrow is visible on dotted line before playback starts (#183) - const arrow = page.locator('.ps-arrow').first(); - if ((await arrow.count()) > 0) { - const initialOpacity = await arrow.evaluate((el) => (el as SVGElement).style.opacity); - expect(initialOpacity).not.toBe('0'); + // Defaults to "All moves" overview on page load with arrows visible (#183) + const allMovesBtn = page.locator('button.stop-btn', { hasText: 'All moves' }); + await expect(allMovesBtn).toHaveClass(/active/); + await expect(playBtn).toHaveText('Play'); + + const arrows = await page.locator('.ps-arrow').all(); + expect(arrows.length).toBeGreaterThan(0); + for (const arrow of arrows) { + const opacity = await arrow.evaluate((el) => (el as SVGElement).style.opacity); + expect(opacity).not.toBe('0'); } // Start playback await playBtn.click(); + await expect(allMovesBtn).not.toHaveClass(/active/); // Arrow is removed when playback starts (#183) - if ((await arrow.count()) > 0) { + const activeArrow = page.locator('.ps-arrow').first(); + if ((await activeArrow.count()) > 0) { await expect - .poll(async () => arrow.evaluate((el) => (el as SVGElement).style.opacity)) + .poll(async () => activeArrow.evaluate((el) => (el as SVGElement).style.opacity)) .toBe('0'); } @@ -117,7 +124,7 @@ test('shark detail page animates move line and traveller dot along water route ( const traveller = page.locator('.ps-traveller'); await expect(traveller).toBeVisible(); - // Eventually animation finishes, stroke properties reset to normal, and arrow remains removed + // Eventually animation finishes, stroke properties reset to normal, button shows Replay, and arrow remains removed await expect(async () => { const finished = await page.evaluate(() => { const line = document.querySelector('.ps-line'); @@ -126,9 +133,20 @@ test('shark detail page animates move line and traveller dot along water route ( expect(finished).toBe(true); }).toPass({ timeout: 5000 }); - if ((await arrow.count()) > 0) { - const finishedOpacity = await arrow.evaluate((el) => (el as SVGElement).style.opacity); + await expect(playBtn).toHaveText('Replay'); + if ((await activeArrow.count()) > 0) { + const finishedOpacity = await activeArrow.evaluate((el) => (el as SVGElement).style.opacity); expect(finishedOpacity).toBe('0'); } + + // Clicking All moves restores all moves with their arrows + await allMovesBtn.click(); + await expect(allMovesBtn).toHaveClass(/active/); + await expect(playBtn).toHaveText('Play'); + for (const arrow of arrows) { + await expect + .poll(async () => arrow.evaluate((el) => (el as SVGElement).style.opacity)) + .not.toBe('0'); + } } }); diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index ba83360..01f1bab 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -99,6 +99,7 @@ still?: boolean; fraction?: number; playing?: boolean; + showAll?: boolean; }; /** Accessible name of the map region. */ label: string; @@ -456,6 +457,35 @@ lastArrowEl = undefined; return; } + + // When showing all moves overview, display all lines solid with their arrows, without a traveller dot (#183). + if (t.showAll) { + dot?.remove(); + dot = undefined; + if (el) { + const lines = el.querySelectorAll('.ps-line'); + lines.forEach((l) => { + l.style.strokeDasharray = ''; + l.style.strokeDashoffset = ''; + }); + const arrows = el.querySelectorAll('.ps-arrow'); + arrows.forEach((a) => { + a.style.opacity = '1'; + }); + } + for (const entry of currentLineEntries) { + const lEl = entry.line.getElement() as SVGPathElement | null; + if (lEl) { + lEl.style.strokeDasharray = ''; + lEl.style.strokeDashoffset = ''; + } + const aEl = entry.arrow.getElement() as SVGPathElement | null; + if (aEl) aEl.style.opacity = '1'; + } + lastLineEl = undefined; + lastArrowEl = undefined; + return; + } const still = Boolean(t.still); const path: [number, number][] = t.path && t.path.length >= 2 diff --git a/src/routes/sharks/[id]/+page.svelte b/src/routes/sharks/[id]/+page.svelte index e95494e..48b2698 100644 --- a/src/routes/sharks/[id]/+page.svelte +++ b/src/routes/sharks/[id]/+page.svelte @@ -19,7 +19,7 @@ const totalMoves = $derived(Math.max(1, stops - 1)); let progress = $state(0); let playing = $state(false); - let showAll = $state(false); + let showAll = $state(true); // Which leg of the track is active (0 to totalMoves - 1): const activeLeg = $derived(Math.min(totalMoves - 1, Math.floor(progress))); @@ -41,10 +41,10 @@ function play() { if (playing) return stop(); - showAll = false; - if (progress >= totalMoves - 0.001) { + if (showAll || progress >= totalMoves - 0.001) { progress = 0; } + showAll = false; playing = true; } @@ -60,6 +60,14 @@ progress = totalMoves; } + $effect(() => { + // Default to All moves overview when opening or switching sharks (#183). + const _id = data.ind.id; + stop(); + showAll = Boolean(data.moves.length); + progress = data.moves.length ? totalMoves : 0; + }); + $effect(() => { if (!playing) return; let lastTime: number | null = null; @@ -150,7 +158,7 @@ {#if data.moves.length}