Compare commits

...

30 Commits

Author SHA1 Message Date
Maurice 6068c34c35 fix(atlas): keep auth.service at its size, finish the last ratchets
- The public config's feature switches, the Atlas comparison among them,
  move into a helper, so auth.service shrinks instead of growing past its
  size baseline (lowered to the new length).
- French "continents" in the many form is the French word too.
- useAtlasCountryActions no longer imports the API: off the offline list.
- The eslint baseline follows two lower counts.
2026-11-29 00:21:10 +01:00
Maurice 06b08cd9d5 fix(atlas): name the globe hook dependencies, cover the mesh routes
The second run of the globe Atlas was red on:

- Client lint: the engine getter is a stable callback now, so the hooks
  that call it name it (and the refs and setters they read); an unused
  navigate and a seven parameter label helper are gone.
- Atlas coverage: the mesh controller and the people and flights routes
  get unit tests, an unused region name helper is removed.
- The French "Atlas" is marked as the same word, index.css is back at its
  length, the server people service is formatted, and the baselines drop
  the deleted AtlasPage and follow the lower counts.
2026-11-28 23:48:47 +01:00
Maurice 10713e41cd fix(atlas): clear the client gates of the globe Atlas
Client lint, checks and tests were red on the globe Atlas:

- The views own the globe and sky refs and hand them into useAtlasGlobe,
  so reading its state while rendering no longer counts as reading refs.
- Helpers that shared a file with components move to their own modules
  (badge tiers, medal label, Dawarich notes, hub tabs, period label).
- The place search derives its loading state, the search resets its
  active row on input, and the two silenced hook dependencies are named.
- placeLabels, the hover chip and the overview figures are split up.
- Raw text sizes become type tiers, the badge unlock docks on --z-overlay.
- The stats card test follows the GlobeStat props; baselines lowered to
  the counts the run reported.
2026-11-28 23:14:17 +01:00
Maurice d78dc79e21 feat(i18n): the globe Atlas in every language 2026-11-28 22:35:20 +01:00
Maurice 4f8c3f045e feat(atlas): the globe Atlas with its hub, on desktop and phone
The Atlas page is now the globe. Everything the classic map offered
carries over: visited countries and regions, planned countries, the
wishlist with places and target dates, Dawarich, tours, plugin layers and
the place search. New:

- regions on the globe, with how much of a country has been seen
  (#2675, #316, #487)
- flight arcs (#1369, #2642)
- a hub with statistics, badges, wishlist, Dawarich, tours and travellers
- an instance ranking, traveller profiles and a compare overlay
- a timeline that plays back how the map grew
- phone layouts of their own: sheets, chips and swipe actions

The classic Leaflet Atlas and its phone screen are removed.
2026-11-28 22:35:20 +01:00
Maurice c7cb0bc067 feat(atlas): a WebGL globe engine
One shader morphs an orthographic globe into a flat map as the zoom
grows. Country and region meshes are built in a worker from the TopoJSON,
picked on the GPU and coloured from a status texture; borders, coasts and
flight arcs are instanced screen-space lines. Regions are fetched ahead of
the zoom and kept to a bounded set; labels avoid each other. Includes the
day and night line, the moon in its phase and the badge medals.
2026-11-28 22:35:11 +01:00
Maurice 68af65a2a6 feat(atlas): read and write the Atlas offline
The Atlas reads go network first and fall back to a snapshot kept in a new
Dexie table (v17, append-only). Marks, unmarks and wishlist deletes made
offline wait in their own account-level queue, replayed in order with an
idempotency key, and every read lays them over the kept answer.
2026-11-28 22:35:11 +01:00
Maurice 04d134755a feat(atlas): flight routes, travellers and badges on the server
- GET /api/addons/atlas/flights folds the user's flight bookings into
  routes, airports and totals for the globe's arcs (#1369, #2642).
- GET /api/addons/atlas/people answers the Atlas side of other travellers
  on the instance: counts, visited countries and earned badges, never
  trips, places or dates. A user hides themselves with the atlas_hidden
  setting; the admin switch atlas_compare_enabled turns it off for all.
- shared/src/atlas/atlas-badges.ts holds the badge rules, computed from the
  data a user already has, so nothing is stored.
- MCP: list_atlas_flight_routes, list_atlas_badges, list_atlas_travellers.
2026-11-28 22:35:11 +01:00
Maurice 8510d4a729 build(atlas): build the globe geometry from the bundled boundaries
scripts/build-atlas-mesh.mjs turns the admin-0 and admin-1 GeoJSON the
server already ships into TopoJSON at three levels of detail per world and
two per country's regions, smoothed, quantized and Brotli-packed under
content-hashed names, plus a manifest with every country's anchor, box and
region index. It runs at build time (npm run build, npm run dev when the
sources changed, and the Docker server stage); the output is not committed.

/api/addons/atlas/mesh serves the manifest and the files as they are
(immutable, a year), decompressing as a stream for a client without br.
2026-11-28 22:35:10 +01:00
Maurice 5989ba5f1f fix(map): draw a reopened trip's routes from the device at once
The rounds that pace their router requests told a cached leg from a request by how long it took, anything past 60 ms counting as a request. Since routes are kept on the device, a leg read back after a reload is an IndexedDB read, which on a page busy drawing the map often takes longer, so every leg waited out a request's pause and the trip filled in one leg a second as if it were routed again. The whole trip's route, the road trip day rounds and the join release now count whether a router actually answered. A relay that refused also kept its rest only in memory, so every reload asked it again for the first day; the rest now holds on the device until it ends.

Closes #3228
2026-11-28 22:21:09 +01:00
Maurice 7c0c749bcc fix(llm-parse): read a model answer whose keys carry stray whitespace
Small local models now and then write a key with a space around it, such as 'departureTime ', and the mappers look every field up by its exact name, so an imported booking lost its times. Every model answer now has its keys trimmed at the one place all of them pass through (parseLenientJson for a written answer, toReservationList for a filled tool call, and the Anthropic client's own root key lookup). Values stay as they are; an exact key wins over one that only trims to the same name.

Closes #3260
2026-11-28 22:21:09 +01:00
Maurice 94163f76e0 build(server): compile with SWC instead of tsc so the build fits a small container
tsc needed about 3.4 GB of heap for the server build, all of it for the type graph, while the build never failed on type errors anyway. An install that builds from source on a 4 GB container (the Proxmox script gives Node 75% of its memory) ran out of heap with 5.2.2. SWC compiles the files tsconfig.build.json names, one at a time and with the options read from it, in about a second and 130 MB; the type check stays with npm run typecheck in CI. Built with both on the same commit, dist holds the same 2390 files, and the server boots with the same 859 routes and 226 modules and answers the same requests the same way.
2026-11-28 20:41:56 +01:00
Maurice c39f739b7f fix(costs): ignore a settlement answer that lands after the ledger unmounted
A read still in flight when the Costs view closed set state on the gone component; in a torn-down test environment React then failed on the missing window and the run reported an unhandled error.
2026-11-28 19:21:59 +01:00
Maurice 7e9ab58a16 chore(deps): move vitest, its coverage providers and jest-dom to 5 together
Vitest 5 resolves only with coverage-v8 and coverage-istanbul of the same version, and jest-dom 8 is the first release whose matcher types merge with its Assertion. The sharded CI jobs read and write the blob reports under .vitest/blob, where 5 puts them, and clearMocks stays off as in 4.
2026-11-28 18:58:05 +01:00
Maurice 41772c0d8e fix(ssrf): answer a pinned lookup on a later tick so a failed connect cannot crash the server
Called back at once, a connect that fails right away (no route to an IPv6 address) tore the socket down while tls.connect was still setting it up; undici saw 'fetch failed' and the socket's own error then reached no listener and ended the process. The pinned lookup now answers on the next tick, as dns.lookup does.
2026-11-28 18:20:00 +01:00
Maurice d6ce33c51c chore(client): drop the React imports nothing reads
typescript-eslint 8.74 no longer takes the classic JSX pragma for the automatic runtime, so an unused default React import is reported now. The no-unused-vars baseline of the app code drops by the one it already counted.
2026-11-28 17:54:38 +01:00
Maurice edb1eab0c3 chore(server): drop the @types/bcryptjs stub now that bcryptjs ships its types 2026-11-28 17:40:25 +01:00
Maurice 91a37286ca fix(native): import @noble/hashes 2 through its .js subpaths 2026-11-28 17:40:24 +01:00
dependabot[bot] 382c1a78dc ci: bump SonarSource/sonarqube-scan-action
Bumps the actions-minor-and-patch group with 1 update: [SonarSource/sonarqube-scan-action](https://github.com/sonarsource/sonarqube-scan-action).


Updates `SonarSource/sonarqube-scan-action` from 8.5.0 to 8.5.1
- [Release notes](https://github.com/sonarsource/sonarqube-scan-action/releases)
- [Commits](https://github.com/sonarsource/sonarqube-scan-action/compare/59202af334b4ba7b5db01b701b8e79f8b3bef0f4...70bad232163b09d998ea0707ee80c0ec80798c16)

---
updated-dependencies:
- dependency-name: SonarSource/sonarqube-scan-action
  dependency-version: 8.5.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions-minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 17:38:10 +01:00
dependabot[bot] b3c2f0b7e2 chore(plugin-sdk): bump @types/node in /plugin-sdk
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 22.20.5 to 26.6.10.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 26.6.10
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 17:38:09 +01:00
dependabot[bot] c785a0950a chore(plugin-sdk): bump the plugin-sdk-minor-and-patch group
Bumps the plugin-sdk-minor-and-patch group in /plugin-sdk with 2 updates: [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) and [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest).


Updates `@vitest/coverage-v8` from 5.1.1 to 5.1.2
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v5.1.2/packages/coverage-v8)

Updates `vitest` from 5.1.1 to 5.1.2
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v5.1.2/packages/vitest)

---
updated-dependencies:
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 5.1.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: plugin-sdk-minor-and-patch
- dependency-name: vitest
  dependency-version: 5.1.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: plugin-sdk-minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 17:38:09 +01:00
dependabot[bot] c8615e0362 chore(deps): bump @noble/hashes from 1.8.0 to 2.4.0
Bumps [@noble/hashes](https://github.com/paulmillr/noble-hashes) from 1.8.0 to 2.4.0.
- [Release notes](https://github.com/paulmillr/noble-hashes/releases)
- [Changelog](https://github.com/paulmillr/noble-hashes/blob/main/CHANGELOG.md)
- [Commits](https://github.com/paulmillr/noble-hashes/compare/1.8.0...2.4.0)

---
updated-dependencies:
- dependency-name: "@noble/hashes"
  dependency-version: 2.4.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 17:38:09 +01:00
dependabot[bot] bc6b56c84c chore(deps): bump bcryptjs and @types/bcryptjs
Bumps [bcryptjs](https://github.com/dcodeIO/bcrypt.js) and [@types/bcryptjs](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/bcryptjs). These dependencies needed to be updated together.

Updates `bcryptjs` from 2.4.3 to 3.0.3
- [Release notes](https://github.com/dcodeIO/bcrypt.js/releases)
- [Commits](https://github.com/dcodeIO/bcrypt.js/compare/2.4.3...v3.0.3)

Updates `@types/bcryptjs` from 2.4.6 to 3.0.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/bcryptjs)

---
updated-dependencies:
- dependency-name: bcryptjs
  dependency-version: 3.0.3
  dependency-type: direct:production
  update-type: version-update:semver-major
- dependency-name: "@types/bcryptjs"
  dependency-version: 3.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 17:38:08 +01:00
dependabot[bot] c00b6dd636 chore(deps): bump the npm-minor-and-patch group across 1 directory with 6 updates
Bumps the npm-minor-and-patch group with 6 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@assistant-ui/react](https://github.com/assistant-ui/assistant-ui/tree/HEAD/packages/react) | `0.15.37` | `0.15.38` |
| [@trivago/prettier-plugin-sort-imports](https://github.com/trivago/prettier-plugin-sort-imports) | `6.0.2` | `6.0.3` |
| [@types/leaflet](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/leaflet) | `1.9.22` | `1.9.23` |
| [@types/react](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/react) | `19.3.0` | `19.3.2` |
| [rollup-plugin-visualizer](https://github.com/btd/rollup-plugin-visualizer) | `7.1.3` | `7.3.0` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.73.0` | `8.74.0` |



Updates `@assistant-ui/react` from 0.15.37 to 0.15.38
- [Release notes](https://github.com/assistant-ui/assistant-ui/releases)
- [Changelog](https://github.com/assistant-ui/assistant-ui/blob/main/packages/react/CHANGELOG.md)
- [Commits](https://github.com/assistant-ui/assistant-ui/commits/@assistant-ui/react@0.15.38/packages/react)

Updates `@trivago/prettier-plugin-sort-imports` from 6.0.2 to 6.0.3
- [Release notes](https://github.com/trivago/prettier-plugin-sort-imports/releases)
- [Changelog](https://github.com/trivago/prettier-plugin-sort-imports/blob/main/CHANGELOG.md)
- [Commits](https://github.com/trivago/prettier-plugin-sort-imports/compare/v6.0.2...v6.0.3)

Updates `@types/leaflet` from 1.9.22 to 1.9.23
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/leaflet)

Updates `@types/react` from 19.3.0 to 19.3.2
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react)

Updates `rollup-plugin-visualizer` from 7.1.3 to 7.3.0
- [Changelog](https://github.com/btd/rollup-plugin-visualizer/blob/master/CHANGELOG.md)
- [Commits](https://github.com/btd/rollup-plugin-visualizer/compare/v7.1.3...v7.3.0)

Updates `typescript-eslint` from 8.73.0 to 8.74.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.74.0/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: "@assistant-ui/react"
  dependency-version: 0.15.38
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-and-patch
- dependency-name: "@trivago/prettier-plugin-sort-imports"
  dependency-version: 6.0.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-and-patch
- dependency-name: "@types/leaflet"
  dependency-version: 1.9.23
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-and-patch
- dependency-name: "@types/react"
  dependency-version: 19.3.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-and-patch
- dependency-name: rollup-plugin-visualizer
  dependency-version: 7.3.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-minor-and-patch
- dependency-name: typescript-eslint
  dependency-version: 8.74.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 17:38:08 +01:00
Maurice 7e01f9661b fix(help): name the wildcard of the help asset route for Express 5 2026-11-28 17:34:18 +01:00
Maurice dee1a361c3 fix(postgres): keep plugin columns named like PostgreSQL 19's new functions
Besides uuid, 19 brings error_on_null, tid_block, tid_offset and oid8 to
the catalog, and since the catalog list is the same for every server the
guard refused a plugin's s.error_on_null column on 14 to 18 too, where it
had always passed. error_on_null and the tuple id parts only read their
argument and join the allowlist, where PGPLUG-022 checks their overloads;
oid8 only converts, like oid, and joins the column names.
2026-11-28 17:33:56 +01:00
Maurice d94f97f9ae fix(postgres): let plugin SQL keep its uuid columns and casts on every server
PostgreSQL 19's catalog brings a uuid(bytea) conversion, and once its name
joined the catalog list the guard refused every uuid it read as a call or a
field: `t.uuid` and `uuid($1)` failed on 14 to 18 too, where they had
always passed. uuid joins the other type name conversions on the plugin
allowlist, so PGPLUG-022 checks its overloads on the 19 lane.
2026-11-28 17:33:56 +01:00
Maurice aad9272b2e fix(postgres): know PostgreSQL 19's catalog functions and refuse regdatabase
PostgreSQL 19 adds 41 functions to pg_catalog that the plugin guard's
catalog list did not hold, so PGPLUG-021 failed on the 19 lane and a plugin
could call the new ones the allowlist does not name. They are now in
catalog-functions.txt, taken from 19's pg_proc.dat; none of them joins the
plugin allowlist.

19 also adds the object identifier type regdatabase, whose input looks a
database of the cluster up by its name. A cast to it passed the guard, so a
plugin could probe which databases the server holds. It now joins the other
name lookup types, its array type with it.
2026-11-28 17:33:55 +01:00
Maurice 59f6e349bf feat(postgres): support PostgreSQL 19
PostgreSQL 19 was released on 19.11.2026, and TREK refused it at boot as
newer than the 14 to 18 it supported (discussion #3214). It now supports 14
to 19.

The image installs the version 19 client tools from PGDG's main component,
since the per-major component can trail a new release; a client handles
every server up to its own major, so pg_dump, pg_restore and psql 19 back up
and restore every supported server. The tools are looked for in the 19
directory first. Installs that pointed TREK_DB_PG_BIN_DIR at the old
/usr/lib/postgresql/18/bin keep working: the image keeps that path as a link
to the 19 tools. CI runs the Postgres lane on 14 and 19 instead of 14 and
18, so the job count stays the same, and the Docker job boots on 19. The
list of server functions and roles that reach the host was checked against
the release notes; PostgreSQL 19 adds none. The compose example stays on 18,
because an existing database stays on the major it was created with.
2026-11-28 17:33:55 +01:00
Jan Kleine dc4b7854d7 fix(helm): add home and sources to the chart so Renovate finds its release notes 2026-11-28 15:24:50 +01:00
363 changed files with 19839 additions and 11420 deletions
+14 -14
View File
@@ -35,7 +35,7 @@ permissions:
# Server tests i/10 one slice of the server suite, with coverage
# Server coverage merges the slices, checks the per-domain
# thresholds, uploads lcov
# Server Postgres 14 i/3, Server Postgres 18 i/3
# Server Postgres 14 i/3, Server Postgres 19 i/3
# per supported major, in three slices: the probe
# (the repository SQL against Postgres, first slice
# only), then a slice of the lane (every suite that
@@ -55,7 +55,7 @@ permissions:
# Client e2e i/2 one slice of the browser flows in Chromium and
# WebKit, in the Playwright container
# Docker and Helm builds the image and boots it until ready, on
# SQLite and on Postgres 18; lints and renders the
# SQLite and on Postgres 19; lints and renders the
# Helm chart and checks the compose files
# Sonar SonarCloud analysis, not required
# ci-ok the one required check (below)
@@ -600,7 +600,7 @@ jobs:
uses: actions/upload-artifact@v6
with:
name: server-blob-${{ matrix.shard }}
path: server/.vitest-reports/
path: server/.vitest/blob/
include-hidden-files: true
if-no-files-found: error
retention-days: 1
@@ -621,7 +621,7 @@ jobs:
uses: actions/download-artifact@v7
with:
pattern: server-blob-*
path: server/.vitest-reports/
path: server/.vitest/blob/
merge-multiple: true
- name: Merge the slices and check the thresholds
@@ -639,7 +639,7 @@ jobs:
retention-days: 1
# TREK on Postgres, once per supported major: the oldest (14) and the newest
# (18). Both steps run against the same service, the probe on an empty
# (19). Both steps run against the same service, the probe on an empty
# database of its own, the lane on databases it creates and drops.
#
# The probe (server/scripts/pg-probe.ts): against an empty Postgres it
@@ -696,7 +696,7 @@ jobs:
strategy:
fail-fast: false
matrix:
postgres: [14, 18]
postgres: [14, 19]
shard: [1, 2, 3]
services:
postgres:
@@ -757,14 +757,14 @@ jobs:
if-no-files-found: ignore
retention-days: 14
# The image ships the 18 client tools, which write settings a 14 server
# The image ships the 19 client tools, which write settings a 14 server
# does not know; the backup round trip runs with the same tools here.
- name: Install the PostgreSQL 18 client tools
- name: Install the PostgreSQL 19 client tools
run: |
set -euo pipefail
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y >/dev/null
sudo apt-get install -y --no-install-recommends postgresql-client-18 >/dev/null
/usr/lib/postgresql/18/bin/pg_restore --version
sudo apt-get install -y --no-install-recommends postgresql-client-19 >/dev/null
/usr/lib/postgresql/19/bin/pg_restore --version
- name: Run the Postgres lane
if: ${{ !cancelled() }}
@@ -1028,7 +1028,7 @@ jobs:
uses: actions/upload-artifact@v6
with:
name: client-blob-${{ matrix.shard }}
path: client/.vitest-reports/
path: client/.vitest/blob/
include-hidden-files: true
if-no-files-found: error
retention-days: 1
@@ -1049,7 +1049,7 @@ jobs:
uses: actions/download-artifact@v7
with:
pattern: client-blob-*
path: client/.vitest-reports/
path: client/.vitest/blob/
merge-multiple: true
- name: Merge the slices and check the thresholds
@@ -1347,7 +1347,7 @@ jobs:
set -euo pipefail
docker network create trek-ci-pg
docker run -d --name trek-ci-db --network trek-ci-pg \
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:18
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:19
for _ in $(seq 1 30); do
docker exec trek-ci-db pg_isready -U postgres -d trek >/dev/null 2>&1 && break
sleep 2
@@ -1468,7 +1468,7 @@ jobs:
path: plugin-sdk/coverage/
- name: Scan
uses: SonarSource/sonarqube-scan-action@59202af334b4ba7b5db01b701b8e79f8b3bef0f4 # v8.5.0
uses: SonarSource/sonarqube-scan-action@70bad232163b09d998ea0707ee80c0ec80798c16 # v8.5.1
env:
# SonarQube Cloud is the scan action's default host, so no
# SONAR_HOST_URL — the token is a sonarcloud.io token for the
+5 -1
View File
@@ -55,7 +55,8 @@ coverage
coverage-*/
*.lcov
.nyc_output
# Blob reports of a sharded vitest run (test.yml)
# Blob reports of a sharded vitest run (test.yml) and the other files vitest writes
.vitest
.vitest-reports
# Cache
@@ -73,3 +74,6 @@ minio-licence.key
.run
.full-review
# Built by server/scripts/build-atlas-mesh.mjs (npm run dev/build, Docker build)
server/assets/atlas-mesh/
+1 -1
View File
@@ -137,7 +137,7 @@ These principles come out of a full-repo audit and shape all new code:
## Quality gates in CI
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 18, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 18, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 19, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 19, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
- **Job names read "<Area> <what>[ <variant>][ i/n]"** (`Server tests 3/10`, `Server Postgres 14 2/3`, `Docker and Helm`): the area first, one of Changes, Shared, Server, Client, Docker or Sonar, then lower case, with no colon, no parentheses and no middle dot, and a slice only at the end, so the checks list sorts by area. The workflow is named `CI`, so a check reads `CI / Server tests 3/10`. Job ids are the names in kebab-case (`server-tests`), the jobs stand in `test.yml` in area order, and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list; `scripts/ci/workflow-jobs.test.mjs` fails on a name outside it. `ci-ok`, `lint` and `check-target` keep their names: the ruleset requires them by name.
- **What the folded jobs hold.** `Shared tests` is the plugin SDK's typecheck and coverage, run before the root install so the SDK resolves only its own dependencies, then i18n parity and shared's coverage. `Client types` is the typecheck and the strict ratchet; `Client checks` the source ratchets, then the production build with `check:gl-split`. `Docker and Helm` builds and boots the image when the image area changed and checks the chart and compose files when the deploy area changed. Inside a folded job each group of steps runs after a failure in another, so one red check shows every gate that failed; the step names say which.
+21 -12
View File
@@ -41,9 +41,10 @@ COPY server/package.json ./server/
RUN npm ci --workspace=server --ignore-scripts
COPY --from=shared-builder /app/shared/dist ./shared/dist
COPY server/ ./server/
# tsc needs more than the 2 GB heap Node picks on a host with about 12 GB of RAM;
# on a bigger build machine the default is larger, so only small hosts failed.
RUN NODE_OPTIONS=--max-old-space-size=4096 npm run build --workspace=server
# The globe Atlas geometry is built from the committed boundary files (no network,
# deterministic) here rather than committed; it lands in server/assets with the rest.
RUN node server/scripts/build-atlas-mesh.mjs
RUN npm run build --workspace=server
# ── Stage 4: production runtime ──────────────────────────────────────────────
FROM node:24-trixie-slim
@@ -73,22 +74,30 @@ COPY server/package.json ./server/
# The upgrade takes the Debian security fixes the base image was built before
# (zlib, 11/2026, failed the image scan until node:24-trixie-slim caught up).
#
# postgresql-client-18 brings pg_dump, pg_restore and psql to
# /usr/lib/postgresql/18/bin, which back up and restore an install on Postgres
# postgresql-client-19 brings pg_dump, pg_restore and psql to
# /usr/lib/postgresql/19/bin, which back up and restore an install on Postgres
# (TREK_DB_URL). A client handles every server up to its own major and refuses
# a newer one, so the image carries the newest major TREK supports (14 to 18).
# a newer one, so the image carries the newest major TREK supports (14 to 19).
# Debian 13 ships 17 only, so it comes from the PostgreSQL project's apt
# repository (PGDG): the `18` component lists that major's packages and no
# other, and the repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2
# 44A0 7FCC 7D46 ACCC 4CF8) is kept beside the entrypoint instead of fetched at
# build time. Raise both together when TREK supports a newer major.
# repository (PGDG): its `main` component carries every major the project
# supports, and the package name pins the one installed. The per-major
# components can trail a new release, so the image does not rely on them. The
# repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2 44A0 7FCC 7D46
# ACCC 4CF8) is kept beside the entrypoint instead of fetched at build time.
# Raise the package together with SUPPORTED_SERVER_MAJORS in
# server/src/db/engine/postgres/server-checks.ts.
# Earlier images carried the version 18 tools, and installs that set
# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/18/bin (the old .env.example value)
# would lose backups and the pre-migrate snapshot after updating, so that path
# stays as a link to the 19 tools, which handle every supported server.
COPY server/scripts/pgdg-apt-key.asc /etc/apt/keyrings/pgdg.asc
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main 18' \
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main' \
> /etc/apt/sources.list.d/pgdg.list && \
apt-get update && \
apt-get upgrade -y --no-install-recommends && \
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \
libkitinerary-bin libsqlite3-0 postgresql-client-19 && \
mkdir -p /usr/lib/postgresql/18 && ln -s /usr/lib/postgresql/19/bin /usr/lib/postgresql/18/bin && \
npm ci --workspace=server --omit=dev --ignore-scripts && \
{ ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor || true; } && \
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
+1 -1
View File
@@ -288,7 +288,7 @@ docker compose up -d
See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)
for the full walkthrough.
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 18 database instead. The
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 19 database instead. The
[`docker-compose.postgres.yml`](docker-compose.postgres.yml) example starts one beside TREK, and the
[Postgres guide](https://github.com/liketrek/TREK/wiki/Database-Postgres) covers the requirements, the backups and
how to move an existing SQLite install to Postgres with the command TREK ships for it.
+3
View File
@@ -2,4 +2,7 @@ apiVersion: v2
name: trek
version: 5.2.2
description: Minimal Helm chart for TREK app
home: https://github.com/liketrek/TREK
sources:
- https://github.com/liketrek/TREK
appVersion: "5.2.2"
+1 -1
View File
@@ -190,7 +190,7 @@ env:
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser
# (nor a member of one, nor hold a right that reaches the server's files or programs): a
# restore runs the backup's SQL as that role and refuses one that could reach the database host. The wiki page shows the
# SQL that creates such a role. PostgreSQL 14 to 18 is supported.
# SQL that creates such a role. PostgreSQL 14 to 19 is supported.
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
database:
url: ""
+2 -2
View File
@@ -102,9 +102,9 @@ test('#1809 iPhone: flow screens scroll the document, full-screen ones do not',
// deliberately do NOT scroll the document (and so keep the address bar), and
// the map must not collapse to zero height now that the shell has none.
await page.goto('/atlas')
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 })
await expect(page.locator('canvas[aria-label="Atlas"]')).toBeVisible({ timeout: 20_000 })
const atlas = await page.evaluate(() => {
const map = document.querySelector('.leaflet-container') as HTMLElement
const map = document.querySelector('canvas[aria-label="Atlas"]') as HTMLElement
window.scrollBy(0, 400)
return {
top: document.scrollingElement!.scrollTop,
+14 -10
View File
@@ -53,7 +53,7 @@
"format:check": "prettier --check \"src/**/*.tsx\" \"src/**/*.css\""
},
"dependencies": {
"@assistant-ui/react": "0.15.37",
"@assistant-ui/react": "0.15.38",
"@capacitor/action-sheet": "^8.1.1",
"@capacitor/android": "^8.6.2",
"@capacitor/app": "^8.1.1",
@@ -102,12 +102,13 @@
"@fontsource/shrikhand": "^5.3.0",
"@fontsource/yellowtail": "^5.3.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4",
"@noble/hashes": "^1.8.0",
"@noble/hashes": "^2.4.0",
"@simplewebauthn/browser": "^14.0.0",
"@trek/shared": "*",
"axios": "^1.21.0",
"dexie": "^4.4.7",
"drag-drop-touch": "^1.3.1",
"earcut": "^3.0.2",
"heic-to": "^1.6.7",
"iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4",
@@ -126,6 +127,7 @@
"rehype-sanitize": "^6.0.0",
"remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1",
"topojson-client": "^3.1.0",
"tz-lookup": "^6.1.25",
"zod": "^4.6.7",
"zustand": "^5.0.15"
@@ -136,16 +138,18 @@
"@jscpd/core": "^4.2.5",
"@jscpd/tokenizer": "^4.2.6",
"@playwright/test": "^1.65.1",
"@testing-library/jest-dom": "^6.10.0",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^8.0.0",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.13",
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/leaflet": "^1.9.22",
"@trivago/prettier-plugin-sort-imports": "^6.0.3",
"@types/leaflet": "^1.9.23",
"@types/node": "^26.6.11",
"@types/react": "^19.3.0",
"@types/react": "^19.3.2",
"@types/react-dom": "^19.3.0",
"@types/topojson-client": "^3.1.5",
"@vitejs/plugin-react": "^6.2.1",
"@vitest/coverage-v8": "^4.1.12",
"@vitest/coverage-v8": "^5.1.2",
"autoprefixer": "^10.7.0",
"eslint": "^10.11.0",
"eslint-config-flat-gitignore": "^2.4.0",
@@ -159,13 +163,13 @@
"prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0",
"prettier-plugin-tailwindcss": "^0.8.1",
"rollup-plugin-visualizer": "^7.1.2",
"rollup-plugin-visualizer": "^7.3.0",
"sharp": "^0.35.5",
"tailwindcss": "^3.4.19",
"typescript": "^6.0.3",
"typescript-eslint": "^8.73.0",
"typescript-eslint": "^8.74.0",
"vite": "8.3.8",
"vite-plugin-pwa": "^2.0.0",
"vitest": "^4.1.12"
"vitest": "^5.1.2"
}
}
+21 -22
View File
@@ -1,24 +1,24 @@
{
"src": {
"@typescript-eslint/no-non-null-assertion": 354,
"@typescript-eslint/no-misused-promises": 820,
"no-console": 88,
"complexity": 216,
"@typescript-eslint/no-explicit-any": 138,
"trek/no-swallowed-catch": 126,
"@typescript-eslint/no-non-null-assertion": 345,
"@typescript-eslint/no-misused-promises": 812,
"no-console": 85,
"complexity": 215,
"@typescript-eslint/no-explicit-any": 114,
"trek/no-swallowed-catch": 124,
"max-params": 31,
"trek/store-without-selector": 66,
"react-hooks/refs": 533,
"react-hooks/set-state-in-effect": 189,
"trek/store-without-selector": 65,
"react-hooks/refs": 522,
"react-hooks/set-state-in-effect": 188,
"@typescript-eslint/no-floating-promises": 162,
"react-hooks/exhaustive-deps": 113,
"@typescript-eslint/no-unused-vars": 117,
"react-hooks/immutability": 28,
"max-lines-per-function": 127,
"react-hooks/exhaustive-deps": 112,
"@typescript-eslint/no-unused-vars": 100,
"react-hooks/immutability": 26,
"max-lines-per-function": 126,
"react-hooks/static-components": 38,
"react-hooks/preserve-manual-memoization": 12,
"no-useless-assignment": 7,
"no-empty": 19,
"no-empty": 18,
"trek/no-window-globals": 41,
"react-refresh/only-export-components": 44,
"unused-disable-directive": 5,
@@ -34,18 +34,17 @@
"react-hooks/exhaustive-deps": 44
},
"tests": {
"@typescript-eslint/no-explicit-any": 489,
"@typescript-eslint/no-non-null-assertion": 1872,
"@typescript-eslint/no-explicit-any": 484,
"@typescript-eslint/no-non-null-assertion": 1849,
"@typescript-eslint/no-misused-promises": 22,
"@typescript-eslint/no-unused-vars": 51,
"@typescript-eslint/no-unused-vars": 48,
"@typescript-eslint/no-floating-promises": 33,
"trek/no-window-globals": 325,
"trek/no-swallowed-catch": 14,
"react-hooks/globals": 5,
"react-hooks/refs": 22,
"trek/no-window-globals": 321,
"trek/no-swallowed-catch": 6,
"react-hooks/globals": 4,
"react-hooks/refs": 16,
"@typescript-eslint/no-this-alias": 1,
"trek/store-without-selector": 3,
"@typescript-eslint/no-unsafe-function-type": 2,
"no-console": 2,
"react-refresh/only-export-components": 1
}
+22 -12
View File
@@ -135,24 +135,24 @@
{
"feature": "Atlas country/region action sheet",
"hooks": ["src/pages/atlas/useAtlasCountryActions.ts"],
"desktop": ["src/pages/AtlasPage.tsx"],
"desktop": ["src/pages/atlas/AtlasCountryActionDialog.tsx"],
"mobile": ["src/mobile/screens/atlas/MAtlasCountryPopup.tsx"]
},
{
"feature": "Atlas globe",
"hooks": ["src/pages/atlas/useAtlasGlobe.ts", "src/pages/atlas/useGlobeStats.ts"],
"desktop": ["src/pages/atlas/AtlasGlobeView.tsx"],
"mobile": ["src/mobile/screens/atlas/MAtlasGlobe.tsx"]
},
{
"feature": "Atlas page: atlasModel",
"hooks": ["src/pages/atlas/atlasModel.ts"],
"desktop": [
"src/components/Atlas/AtlasCountryPlaces.tsx",
"src/components/shared/CountryFlag.tsx",
"src/pages/AtlasPage.tsx"
"src/pages/atlas/AtlasGlobeView.tsx"
],
"mobile": ["src/mobile/screens/atlas/MAtlas.tsx", "src/mobile/screens/atlas/MAtlasBucketSheet.tsx"]
},
{
"feature": "Atlas page: useAtlas",
"hooks": ["src/pages/atlas/useAtlas.ts"],
"desktop": ["src/pages/AtlasPage.tsx"],
"mobile": ["src/mobile/screens/atlas/MAtlas.tsx", "src/mobile/screens/atlas/atlasController.ts"]
"mobile": ["src/mobile/screens/atlas/MAtlasGlobe.tsx"]
},
{
"feature": "Audit log",
@@ -1127,8 +1127,8 @@
"src/mobile/screens/admin/MAdminUi.tsx": "Phone only admin UI primitives (button, card, field, input, secret input, sheet frame).",
"src/mobile/screens/admin/MPluginVersionDate.tsx": "Markup only; the published date of a plugin version in MAdminPluginsPanel, formatted with the user's date format through useFormatDate.",
"src/mobile/screens/admin/MStorageReclaimCard.tsx": "Markup only; renders the reclaim view and handlers that MAdminStoragePanel takes from useStoragePanel, the twin of StorageReclaimSection.",
"src/mobile/screens/atlas/MAtlasSearch.tsx": "Phone full screen country search overlay; options, suggestions and selection come through props from MAtlas.",
"src/mobile/screens/atlas/MAtlasStatsCard.tsx": "Markup only; renders the AtlasStats that MAtlas passes in.",
"src/mobile/screens/atlas/MAtlas.tsx": "The phone route entry; it only renders MAtlasGlobe, which runs on useAtlasGlobe in the \"Atlas globe\" pair.",
"src/mobile/screens/atlas/MAtlasStatsCard.tsx": "Markup only; renders the globe figures from useGlobeStats that MAtlasGlobe passes in.",
"src/mobile/screens/collections/MCollCategoryPicker.tsx": "Phone only category dropdown; value and categories come through props from the collection sheets.",
"src/mobile/screens/collections/MCollInvites.tsx": "Markup only; the invites and accept and decline come through props from useCollections via MCollections.",
"src/mobile/screens/collections/MCollLabelsSheet.tsx": "Phone label sheet; create, update, delete and assign come through props from useCollections.",
@@ -1207,6 +1207,16 @@
"src/mobile/screens/trip/tabs/tabModel.ts": "Phone tab prop type and status colour tokens only the phone tabs use.",
"src/mobile/screens/trip/tabs/transportsModel.ts": "Phone transport card readers (metadata, day and time cells) for MTransportsTab and MBookingsTab.",
"src/mobile/screens/vacay/MVacayMonth.tsx": "Markup only; its day cell colours come from the phone vacayDayModel.",
"src/mobile/screens/vacay/vacayDayModel.ts": "Phone day cell colour model for MVacayMonth; the desktop card styles its cells inline."
"src/mobile/screens/vacay/vacayDayModel.ts": "Phone day cell colour model for MVacayMonth; the desktop card styles its cells inline.",
"src/mobile/screens/atlas/hub/MAtlasHub.tsx": "The Atlas hub as a phone sheet: the tab strip and the sheets on top; the desktop opens AtlasGlobePassport, a dialog with its own markup, over the same useAtlasGlobe state.",
"src/mobile/screens/atlas/hub/MHubOverview.tsx": "Phone layout of one tab of the Atlas hub sheet (MAtlasHub); the desktop draws the same tab inside AtlasGlobePassport with its own markup, and both read the state of useAtlasGlobe and the derived values of pages/atlas/atlasHubModel.ts.",
"src/mobile/screens/atlas/hub/MHubBadges.tsx": "Phone layout of one tab of the Atlas hub sheet (MAtlasHub); the desktop draws the same tab inside AtlasGlobePassport with its own markup, and both read the state of useAtlasGlobe and the derived values of pages/atlas/atlasHubModel.ts.",
"src/mobile/screens/atlas/hub/MHubWishlist.tsx": "Phone layout of one tab of the Atlas hub sheet (MAtlasHub); the desktop draws the same tab inside AtlasGlobePassport with its own markup, and both read the state of useAtlasGlobe and the derived values of pages/atlas/atlasHubModel.ts.",
"src/mobile/screens/atlas/hub/MHubTours.tsx": "Phone layout of one tab of the Atlas hub sheet (MAtlasHub); the desktop draws the same tab inside AtlasGlobePassport with its own markup, and both read the state of useAtlasGlobe and the derived values of pages/atlas/atlasHubModel.ts.",
"src/mobile/screens/atlas/hub/MHubTravellers.tsx": "Phone layout of one tab of the Atlas hub sheet (MAtlasHub); the desktop draws the same tab inside AtlasGlobePassport with its own markup, and both read the state of useAtlasGlobe and the derived values of pages/atlas/atlasHubModel.ts.",
"src/mobile/screens/atlas/hub/mHubKit.tsx": "The phone's building blocks for the Atlas hub tabs on the --m-* tokens; markup only, the desktop has its own kit in pages/atlas/atlasHubKit.tsx.",
"src/mobile/screens/atlas/hub/MHubDawarich.tsx": "Phone layout of the Atlas hub's Dawarich tab; the desktop tab AtlasGlobeDawarich draws its own markup over the same useDawarichAtlas hook.",
"src/mobile/screens/atlas/MAtlasLayersSheet.tsx": "The globe's layers as a phone sheet (switches and the colouring); the desktop opens GlobeLayersDialog over the same useAtlasGlobe state.",
"src/mobile/screens/atlas/MAtlasCountrySheets.tsx": "The globe's country action card and country sheet on the phone; the desktop opens GlobeCountryDialogs over the same useAtlasGlobe state and useAtlasCountryActions."
}
}
-20
View File
@@ -139,7 +139,6 @@
"src/components/Admin/useSchoolHolidayCatalog.ts",
"src/components/Atlas/AtlasCountryPlaces.test.tsx",
"src/components/Atlas/AtlasCountryPlaces.tsx",
"src/components/Atlas/useGlassGlare.ts",
"src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx",
"src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx",
"src/components/BackgroundTasks/BackgroundTasksWidget.tsx",
@@ -266,10 +265,6 @@
"src/components/Dashboard/CollectionsWidget.tsx",
"src/components/Dawarich/DawarichAcceptDialog.test.tsx",
"src/components/Dawarich/DawarichAcceptDialog.tsx",
"src/components/Dawarich/DawarichAtlasDialog.test.tsx",
"src/components/Dawarich/DawarichAtlasDialog.tsx",
"src/components/Dawarich/DawarichAtlasSidePanel.test.tsx",
"src/components/Dawarich/DawarichAtlasSidePanel.tsx",
"src/components/Dawarich/DawarichBadge.test.tsx",
"src/components/Dawarich/DawarichBadge.tsx",
"src/components/Dawarich/DawarichSuggestionsPanel.test.tsx",
@@ -1146,7 +1141,6 @@
"src/constants/tripTabs.ts",
"src/db/cacheAssignment.ts",
"src/db/offlineDb.test.ts",
"src/db/offlineDb.ts",
"src/help/contexts/admin.ts",
"src/help/contexts/atlas.ts",
"src/help/contexts/collections.ts",
@@ -1284,12 +1278,9 @@
"src/mobile/screens/admin/MAdminUsersSection.tsx",
"src/mobile/screens/admin/MApiProviderBlocks.tsx",
"src/mobile/screens/atlas/MAtlas.tsx",
"src/mobile/screens/atlas/MAtlasBucketSheet.tsx",
"src/mobile/screens/atlas/MAtlasCountryPopup.test.tsx",
"src/mobile/screens/atlas/MAtlasCountryPopup.tsx",
"src/mobile/screens/atlas/MAtlasSearch.tsx",
"src/mobile/screens/atlas/MAtlasStatsCard.tsx",
"src/mobile/screens/atlas/atlasController.ts",
"src/mobile/screens/collections/MCollAddSheet.tsx",
"src/mobile/screens/collections/MCollCategoryPicker.tsx",
"src/mobile/screens/collections/MCollEditSheet.tsx",
@@ -1440,9 +1431,7 @@
"src/mobile/useIsPhone.ts",
"src/pages/AdminPage.test.tsx",
"src/pages/AdminPage.tsx",
"src/pages/AtlasPage.test.tsx",
"src/pages/AtlasPage.tsx",
"src/pages/AtlasPage.wiring.test.tsx",
"src/pages/CollectionsPage.test.tsx",
"src/pages/CollectionsPage.tsx",
"src/pages/CollectionsPage.wiring.test.tsx",
@@ -1497,7 +1486,6 @@
"src/pages/admin/AdminSettingsTab.test.tsx",
"src/pages/admin/AdminSettingsTab.tsx",
"src/pages/admin/AdminStatCard.tsx",
"src/pages/admin/AdminUpdateBanner.test.tsx",
"src/pages/admin/AdminUpdateBanner.tsx",
"src/pages/admin/AdminUserModals.test.tsx",
"src/pages/admin/AdminUserModals.tsx",
@@ -1509,13 +1497,8 @@
"src/pages/admin/adminModel.ts",
"src/pages/admin/useAdmin.ts",
"src/pages/admin/useNotificationDefaults.ts",
"src/pages/atlas/AtlasCountrySearch.tsx",
"src/pages/atlas/AtlasLayerToggle.test.tsx",
"src/pages/atlas/AtlasLayerToggle.tsx",
"src/pages/atlas/atlasModel.test.ts",
"src/pages/atlas/atlasModel.ts",
"src/pages/atlas/useAtlas.test.tsx",
"src/pages/atlas/useAtlas.ts",
"src/pages/collections/collectionsModel.test.ts",
"src/pages/collections/collectionsModel.ts",
"src/pages/collections/useCollections.test.tsx",
@@ -1888,10 +1871,7 @@
"tests/unit/mobile/admin/MAdminSheets.test.tsx",
"tests/unit/mobile/admin/MAdminStoragePanel.test.tsx",
"tests/unit/mobile/admin/MAdminUsersSection.test.tsx",
"tests/unit/mobile/atlas/MAtlas.test.tsx",
"tests/unit/mobile/atlas/MAtlasBucketSheet.test.tsx",
"tests/unit/mobile/atlas/MAtlasCountryPopup.test.tsx",
"tests/unit/mobile/atlas/MAtlasSearch.test.tsx",
"tests/unit/mobile/atlas/MAtlasStatsCard.test.tsx",
"tests/unit/mobile/collections/MCollAddSheet.test.tsx",
"tests/unit/mobile/collections/MCollCategoryPicker.test.tsx",
+4 -2
View File
@@ -72,8 +72,8 @@ const UNUSED_BASELINE = join(HERE, 'i18n-unused-baseline.json');
/**
* Where else a translation key can be named: the server sends keys for the
* client to translate (system notices, notification channels), the plugin
* SDK names the ones plugin surfaces use, and the shared book engine names
* its layout templates. Read only to find which en keys are reached.
* SDK names the ones plugin surfaces use, the shared book engine names
* its layout templates and the Atlas badge rules their titles. Read only to find which en keys are reached.
*/
export const REFERENCE_ROOTS = [
// The address screen the native apps ship (vite.native.config.js): its own
@@ -82,6 +82,8 @@ export const REFERENCE_ROOTS = [
join(HERE, '..', '..', 'server', 'src'),
join(HERE, '..', '..', 'plugin-sdk', 'src'),
join(HERE, '..', '..', 'shared', 'src', 'book'),
// The Atlas badge rules name each badge's title and description keys.
join(HERE, '..', '..', 'shared', 'src', 'atlas'),
];
/** How many en keys a template may reach and still pass without an entry below. */
-1
View File
@@ -13,7 +13,6 @@
"src/components/Collections/ListEditorModal.tsx": 1,
"src/components/Collections/MSaveToCollectionSheet.tsx": 3,
"src/components/Dawarich/DawarichAcceptDialog.tsx": 3,
"src/components/Dawarich/DawarichAtlasDialog.tsx": 3,
"src/components/Dawarich/DawarichSuggestionsPanel.tsx": 1,
"src/components/Journey/ContributorInviteDialog.tsx": 1,
"src/components/Journey/JourneyDetailPageAddTripDialog.tsx": 1,
-3
View File
@@ -42,7 +42,6 @@
"src/components/Collections/useSaveTripPlacesToList.ts",
"src/components/Collections/useTripCopyPicker.ts",
"src/components/Dashboard/useCollectionLists.ts",
"src/components/Dawarich/DawarichAtlasDialog.tsx",
"src/components/Files/FileManagerAuthedImg.tsx",
"src/components/Files/FileManagerImageLightbox.tsx",
"src/components/Files/docsync/useConflicts.ts",
@@ -130,8 +129,6 @@
"src/pages/OAuthAuthorizePage.tsx",
"src/pages/admin/useAdmin.ts",
"src/pages/admin/useNotificationDefaults.ts",
"src/pages/atlas/useAtlas.ts",
"src/pages/atlas/useAtlasCountryActions.ts",
"src/pages/collections/useCollections.ts",
"src/pages/dashboard/useDashboard.ts",
"src/pages/dashboard/useTripSearch.ts",
-2
View File
@@ -82,7 +82,6 @@
"mobile/screens/trip/map/MMapArea.tsx": 3,
"mobile/screens/trip/tabs/MFileLightbox.tsx": 2,
"mobile/screens/vacay/MVacayMonth.tsx": 1,
"pages/AtlasPage.tsx": 2,
"pages/JourneyDetailPage.tsx": 1,
"pages/JourneyPublicPage.tsx": 3,
"pages/LoginPage.tsx": 23,
@@ -90,7 +89,6 @@
"pages/VacayPage.tsx": 1,
"pages/admin/AdminNotificationsTab.tsx": 1,
"pages/admin/AdminSettingsTab.tsx": 1,
"pages/atlas/AtlasLayerToggle.tsx": 1,
"pages/sharedTrip/SharedMap.tsx": 4,
"styles/collections.css": 1,
"styles/studio.css": 7,
+2
View File
@@ -1,4 +1,5 @@
{
"components/AtlasGlobe/atlasGlobe.css": 1,
"components/Collections/CollectionMap.tsx": 1,
"components/Packing/PackingItemDetail.tsx": 1,
"components/Studio/LineHandles.tsx": 1,
@@ -8,5 +9,6 @@
"mobile/screens/trip/MTripShell.tsx": 1,
"mobile/screens/vacay/MVacay.tsx": 1,
"pages/CollectionsPage.tsx": 1,
"pages/atlas/AtlasGlobeView.tsx": 1,
"pages/tripPlanner/PlanMapStage.tsx": 4
}
+1 -2
View File
@@ -8,7 +8,7 @@
"src/components/Map/MapView.tsx": 1200,
"src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2116,
"src/components/Planner/DayDetailPanel.test.tsx": 2332,
"src/components/Planner/DayDetailPanel.test.tsx": 2331,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2908,
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
@@ -20,7 +20,6 @@
"src/pages/JourneyDetailPage.test.tsx": 3886,
"src/pages/LoginPage.tsx": 1273,
"src/pages/TripPlannerPage.tsx": 1127,
"src/pages/atlas/useAtlas.ts": 1207,
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
"src/styles/studio.css": 1918
-2
View File
@@ -110,14 +110,12 @@
"src/mobile/screens/trip/sheets/MReservationSheet.tsx": 1,
"src/mobile/screens/trip/tabs/transportsModel.ts": 1,
"src/mobile/screens/vacay/MVacaySettingsSheet.tsx": 1,
"src/pages/AtlasPage.tsx": 6,
"src/pages/FilesPage.tsx": 1,
"src/pages/JourneyDetailPage.tsx": 1,
"src/pages/LoginPage.tsx": 1,
"src/pages/VacayPage.tsx": 1,
"src/pages/admin/useAdmin.ts": 4,
"src/pages/atlas/atlasModel.ts": 2,
"src/pages/atlas/useAtlas.ts": 9,
"src/pages/collections/collectionsModel.ts": 1,
"src/pages/journeyDetail/useJourneyDetail.ts": 3,
"src/pages/sharedTrip/SharedPlanView.tsx": 1,
+1 -7
View File
@@ -21,7 +21,6 @@
"components/Collections/CollectionHero.tsx": 1,
"components/Collections/MSaveToCollectionSheet.tsx": 12,
"components/Collections/StatusBadge.tsx": 4,
"components/Dawarich/DawarichAtlasDialog.tsx": 3,
"components/Files/FileManagerAvatarChip.tsx": 1,
"components/Files/FileManagerImageLightbox.tsx": 8,
"components/Journey/ContributorInviteDialog.tsx": 76,
@@ -163,11 +162,8 @@
"mobile/screens/admin/MAdminUi.tsx": 7,
"mobile/screens/admin/MAdminUsersSection.tsx": 13,
"mobile/screens/admin/MApiProviderBlocks.tsx": 10,
"mobile/screens/atlas/MAtlas.tsx": 5,
"mobile/screens/atlas/MAtlasBucketSheet.tsx": 14,
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 11,
"mobile/screens/atlas/MAtlasSearch.tsx": 5,
"mobile/screens/atlas/MAtlasStatsCard.tsx": 3,
"mobile/screens/atlas/MAtlasStatsCard.tsx": 2,
"mobile/screens/collections/MCollAddSheet.tsx": 6,
"mobile/screens/collections/MCollCategoryPicker.tsx": 2,
"mobile/screens/collections/MCollEditSheet.tsx": 2,
@@ -282,7 +278,6 @@
"mobile/screens/vacay/MVacaySettingsSheet.tsx": 34,
"mobile/screens/vacay/MVacayShareSheet.tsx": 10,
"mobile/screens/vacay/vacayDayModel.ts": 1,
"pages/AtlasPage.tsx": 32,
"pages/DashboardPage.tsx": 1,
"pages/FilesPage.tsx": 11,
"pages/ForgotPasswordPage.tsx": 18,
@@ -297,7 +292,6 @@
"pages/ResetPasswordPage.tsx": 23,
"pages/TripPlannerPage.tsx": 7,
"pages/VacayPage.tsx": 13,
"pages/atlas/useAtlas.ts": 2,
"pages/collections/useCollections.ts": 1,
"pages/login/MfaCodeStep.tsx": 4,
"pages/sharedTrip/SharedChrome.tsx": 2,
+7 -4
View File
@@ -2,6 +2,8 @@
"components/Admin/GitHubPanel.tsx": 3,
"components/Admin/PluginPoiCategoryList.tsx": 1,
"components/Admin/useCategoryAdmin.ts": 1,
"components/AtlasGlobe/BadgeMedal.tsx": 2,
"components/AtlasGlobe/badgeTiers.ts": 4,
"components/Budget/CostsPanel.tsx": 1,
"components/Budget/CostsToolbar.tsx": 1,
"components/Collab/CollabNotesFilePreviewPortal.tsx": 3,
@@ -11,7 +13,6 @@
"components/Collections/ImportCollectionModal.tsx": 1,
"components/Collections/MoveToListModal.tsx": 1,
"components/Collections/SaveTripPlacesToListModal.tsx": 1,
"components/Dawarich/DawarichAtlasSidePanel.tsx": 1,
"components/Files/FileManagerImageLightbox.tsx": 1,
"components/Files/FileManagerRow.tsx": 3,
"components/Files/FileManagerToolbar.tsx": 1,
@@ -56,9 +57,8 @@
"components/shared/PasswordChecklist.tsx": 2,
"mobile/components/MSheet.tsx": 1,
"mobile/components/MWalletButton.tsx": 1,
"mobile/screens/atlas/MAtlas.tsx": 1,
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 2,
"mobile/screens/atlas/MAtlasSearch.tsx": 1,
"mobile/screens/atlas/hub/MHubTravellers.tsx": 1,
"mobile/screens/collections/MCollEditSheet.tsx": 2,
"mobile/screens/collections/MCollPlaceSheet.tsx": 2,
"mobile/screens/collections/MCollShareSheet.tsx": 1,
@@ -71,8 +71,11 @@
"mobile/screens/trip/roadtrip/MRtKindSheet.tsx": 1,
"mobile/screens/trip/roadtrip/MRtStopSheet.tsx": 1,
"mobile/screens/trip/sheets/MCostSheet.tsx": 1,
"pages/AtlasPage.tsx": 1,
"pages/admin/AdminUserModals.tsx": 1,
"pages/atlas/AtlasCountryActionDialog.tsx": 1,
"pages/atlas/AtlasGlobeView.tsx": 2,
"pages/atlas/atlasGlobePaint.ts": 10,
"pages/atlas/useAtlasGlobe.ts": 1,
"pages/sharedTrip/SharedChrome.tsx": 4,
"pages/sharedTrip/SharedMap.tsx": 2
}
-1
View File
@@ -1,4 +1,3 @@
import React from 'react'
import { render, screen, waitFor, act } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router'
import { describe, it, expect, beforeEach, onTestFinished, vi } from 'vitest'
+3 -2
View File
@@ -320,7 +320,7 @@ function RouteFallback() {
}
export default function App() {
const { loadUser, isAuthenticated, demoMode, setManaged, setDemoMode, setDevMode, setIsPrerelease, setAppVersion, setHasMapsKey, setHasAmapKey, setPlacesProvider, setServerTimezone, setAppRequireMfa, setTripRemindersEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, setPlacesEnrichEnabled, setPlaceShadowEnabled } = useAuthStore()
const { loadUser, isAuthenticated, demoMode, setManaged, setDemoMode, setDevMode, setIsPrerelease, setAppVersion, setHasMapsKey, setHasAmapKey, setPlacesProvider, setServerTimezone, setAppRequireMfa, setTripRemindersEnabled, setAtlasCompareEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, setPlacesEnrichEnabled, setPlaceShadowEnabled } = useAuthStore()
const { loadSettings } = useSettingsStore()
const { loadAddons } = useAddonStore()
const { loadPlugins } = usePluginStore()
@@ -351,7 +351,7 @@ export default function App() {
}, Math.min(30_000, 1_000 * 2 ** attempt))
})
})
fetchAppConfig(0).then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; max_upload_mb?: number; permissions?: Record<string, PermissionLevel> }) => {
fetchAppConfig(0).then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; atlas_compare_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; max_upload_mb?: number; permissions?: Record<string, PermissionLevel> }) => {
setManaged(!!config?.managed)
setDemoMode(!!config?.demo_mode)
if (config?.dev_mode) setDevMode(true)
@@ -363,6 +363,7 @@ export default function App() {
if (config?.timezone) setServerTimezone(config.timezone)
if (config?.require_mfa !== undefined) setAppRequireMfa(!!config.require_mfa)
if (config?.trip_reminders_enabled !== undefined) setTripRemindersEnabled(config.trip_reminders_enabled)
if (config?.atlas_compare_enabled !== undefined) setAtlasCompareEnabled(config.atlas_compare_enabled)
if (config?.places_photos_enabled !== undefined) setPlacesPhotosEnabled(config.places_photos_enabled)
if (config?.places_autocomplete_enabled !== undefined) setPlacesAutocompleteEnabled(config.places_autocomplete_enabled)
if (config?.places_details_enabled !== undefined) setPlacesDetailsEnabled(config.places_details_enabled)
-1
View File
@@ -1,4 +1,3 @@
import React from 'react'
import { render, waitFor, act } from '@testing-library/react'
import { MemoryRouter } from 'react-router'
import { describe, it, expect, beforeEach, vi } from 'vitest'
-1
View File
@@ -1,4 +1,3 @@
import React from 'react'
import { render, screen } from '@testing-library/react'
import { MemoryRouter } from 'react-router'
import { describe, it, expect, beforeEach, vi } from 'vitest'
+14 -1
View File
@@ -1,6 +1,6 @@
import type { ComponentType } from 'react'
import { useTranslation } from '../../i18n'
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Radar } from 'lucide-react'
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Radar, Trophy } from 'lucide-react'
import EmptyState from '../shared/EmptyState'
import DawarichIcon from '../shared/DawarichIcon'
import AirTrailIcon from '../shared/AirTrailIcon'
@@ -94,6 +94,8 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
wandererOffered,
toggleToursWanderer,
mapSwitches,
atlasCompare,
toggleAtlasCompare,
} = useAddonManager()
if (loading) {
return (
@@ -109,6 +111,17 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
* parent as shelf rows, and each shelf only shows while its parent is on —
* a provider toggled under a disabled Journey would hit the server's 409. */
const shelfFor = (addon: Addon) => {
if (addon.id === 'atlas' && addon.enabled) {
return (
<AddonSubRow
icon={<Trophy size={14} />}
title={t('admin.atlasCompare.title')}
description={t('admin.atlasCompare.subtitle')}
enabled={atlasCompare}
onToggle={() => void toggleAtlasCompare()}
/>
)
}
if (addon.id === 'packing' && addon.enabled && onToggleBagTracking) {
return (
<AddonSubRow
@@ -2,7 +2,7 @@ import type { AdminFeatureToggleResponse } from '@trek/shared';
import { Bike, Footprints, MountainSnow } from 'lucide-react';
import { useEffect, useEffectEvent, useState } from 'react';
import { adminApi } from '../../../api/client';
import { adminApi, authApi } from '../../../api/client';
import { cycleMapAdminApi, hikingMapAdminApi, skiRoutingAdminApi } from '../../../api/tourBaseMaps';
import { wandererAdminApi } from '../../../api/wanderer';
import { useTranslation } from '../../../i18n';
@@ -43,6 +43,9 @@ export function useAddonManager() {
const [toursHikingMap, setToursHikingMap] = useState(false);
const [toursCycleMap, setToursCycleMap] = useState(false);
const [toursSkiRouting, setToursSkiRouting] = useState(false);
// The Atlas ranking switch is an app setting the app config already carries.
const atlasCompare = useAuthStore((s) => s.atlasCompareEnabled);
const setAtlasCompare = useAuthStore((s) => s.setAtlasCompareEnabled);
const loadAddons = async () => {
try {
@@ -105,6 +108,11 @@ export function useAddonManager() {
void refreshGlobalAddons();
toast.success(t('admin.addons.toast.updated'));
};
/** Whether travellers on this instance see the Atlas ranking and each other's profiles. */
const toggleAtlasCompare = () =>
flipToursSwitch(atlasCompare, setAtlasCompare, (enabled) =>
authApi.updateAppSettings({ atlas_compare_enabled: enabled })
);
const toggleToursWanderer = () => flipToursSwitch(toursWanderer, setToursWanderer, wandererAdminApi.update);
/** The maps and the piste router Tours offers on their operators' terms, one switch each (MAP-01, BIK-06, SKI-02). */
const mapSwitches = [
@@ -167,5 +175,7 @@ export function useAddonManager() {
wandererOffered,
toggleToursWanderer,
mapSwitches,
atlasCompare,
toggleAtlasCompare,
};
}
@@ -1,150 +0,0 @@
// FE-STA2-PANE-001 to FE-STA2-PANE-006
// STA-02: the Atlas tab of the user's own tour activities: the distance large
// with how many tours at its corner, the climb, the types, what the numbers
// rest on, and the full list in a dialog.
import userEvent from '@testing-library/user-event';
import { summarizeTourActivities, type TourActivityStatsEntry, type TourActivityStatsResponse } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildSettings } from '../../../../tests/helpers/factories';
import { render, screen } from '../../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
import { useSettingsStore } from '../../../store/settingsStore';
import { AtlasTourActivityPane } from './AtlasTourActivityPane';
import type { TourActivityStats } from './useTourActivityStats';
const hook = vi.hoisted(() => ({ current: null as unknown, active: [] as boolean[] }));
vi.mock('./useTourActivityStats', () => ({
useTourActivityStats: (active: boolean) => {
hook.active.push(active);
return hook.current;
},
}));
const TODAY = '2026-10-20';
function entry(overrides: Partial<TourActivityStatsEntry> = {}): TourActivityStatsEntry {
return {
place_id: 1,
name: 'Ridge',
tour_type: 'hike',
trip: { id: 5, title: 'Alps' },
derived_from_place_id: null,
date: '2026-07-02',
basis: 'plan',
track: null,
day_count: 1,
distance_km: 12,
ascent_m: 800,
descent_m: 790,
excluded: false,
...overrides,
};
}
function statsOf(data: TourActivityStatsResponse | null, overrides: Partial<TourActivityStats> = {}) {
const stats: TourActivityStats = {
status: data ? 'ready' : 'loading',
data,
summary: data ? summarizeTourActivities(data.entries, { today: TODAY }) : null,
period: 'all',
setPeriod: vi.fn(),
periods: ['all', 'thisYear', 'last12'],
type: 'all',
setType: vi.fn(),
types: ['all', 'hike', 'kayak'],
pending: new Set(),
setExcluded: vi.fn().mockResolvedValue(undefined),
retry: vi.fn(),
...overrides,
};
hook.current = stats;
return stats;
}
const data: TourActivityStatsResponse = {
entries: [
entry(),
entry({ place_id: 2, name: 'Summit', date: '2026-08-01', distance_km: 20.5, ascent_m: 1200, descent_m: 1200 }),
entry({
place_id: 3,
name: 'Lake',
tour_type: 'kayak',
basis: 'track',
track: { place_id: 9, name: 'Watch' },
distance_km: 8,
ascent_m: null,
descent_m: null,
}),
],
uncounted: { unassigned: 0, undated: 1 },
};
beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
hook.active = [];
seedStore(useSettingsStore, { settings: buildSettings({ distance_unit: 'metric' }) });
});
describe('AtlasTourActivityPane', () => {
it('FE-STA2-PANE-001: follows whether the tab is shown, silent before, loading until the read is there', () => {
statsOf(null, { status: 'idle' });
const { rerender } = render(<AtlasTourActivityPane active={false} />);
expect(hook.active).toEqual([false]);
expect(screen.queryByRole('status')).not.toBeInTheDocument();
statsOf(null);
rerender(<AtlasTourActivityPane active />);
expect(hook.active).toEqual([false, true]);
expect(screen.getByRole('status')).toHaveTextContent('Loading');
});
it('FE-STA2-PANE-002: shows the distance large with the tour count at its corner, and the climb', () => {
statsOf(data);
render(<AtlasTourActivityPane active />);
expect(screen.getByTestId('atlas-tour-activity-distance')).toHaveTextContent('40.5km');
expect(screen.getByTestId('atlas-tour-activity-count')).toHaveTextContent('3');
expect(screen.getByTestId('atlas-tour-activity-ascent')).toHaveTextContent('2000m');
expect(screen.getByTestId('atlas-tour-activity-type-hike')).toHaveTextContent('2');
expect(screen.getByTestId('atlas-tour-activity-type-kayak')).toHaveTextContent('8 km');
});
it('FE-STA2-PANE-003: says what the numbers rest on and what does not count', () => {
statsOf(data);
render(<AtlasTourActivityPane active />);
expect(screen.getByTestId('tour-activity-basis-plan')).toHaveTextContent('Planned2');
expect(screen.getByTestId('tour-activity-basis-track')).toHaveTextContent('Recorded1');
expect(screen.getByTestId('tour-activity-undated')).toHaveTextContent('1');
});
it('FE-STA2-PANE-004: one type chosen leaves the type columns out; nothing done says so', () => {
statsOf(data, { type: 'hike', summary: summarizeTourActivities(data.entries, { today: TODAY, type: 'hike' }) });
const { rerender } = render(<AtlasTourActivityPane active />);
expect(screen.queryByTestId('atlas-tour-activity-type-hike')).not.toBeInTheDocument();
statsOf(data, { summary: summarizeTourActivities(data.entries, { today: TODAY, from: '2027-01-01' }) });
rerender(<AtlasTourActivityPane active />);
expect(screen.getByText('No completed tours in this period')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Show tours' })).not.toBeInTheDocument();
});
it('FE-STA2-PANE-005: the full list opens in the dialog', async () => {
statsOf(data);
const user = userEvent.setup();
render(<AtlasTourActivityPane active />);
await user.click(screen.getByRole('button', { name: 'Show tours' }));
expect(screen.getByRole('heading', { name: 'My tour activities' })).toBeInTheDocument();
expect(screen.getByTestId('tour-activity-list')).toBeInTheDocument();
});
it('FE-STA2-PANE-006: offline and failed reads say so, a failed one with a retry', async () => {
statsOf(null, { status: 'offline' });
const { rerender } = render(<AtlasTourActivityPane active />);
expect(screen.getByText(/needs a connection/i)).toBeInTheDocument();
const failed = statsOf(null, { status: 'error' });
rerender(<AtlasTourActivityPane active />);
expect(screen.getByRole('alert')).toHaveTextContent('Tour activities could not be loaded');
await userEvent.setup().click(screen.getByRole('button', { name: 'Try again' }));
expect(failed.retry).toHaveBeenCalled();
});
});
@@ -1,223 +0,0 @@
import type { TourActivitySummary } from '@trek/shared';
import { Footprints, ListOrdered } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../../i18n';
import type { DistanceUnit } from '../../../types';
import { fs } from '../../shared/DialogShell';
import { Tooltip } from '../../shared/Tooltip';
import { CardAction, InfoDot } from '../../Tours/tourParts';
import { ActivityFilters, ActivityStatusLine, BasisBadges, UncountedBadges } from './tourActivityParts';
import { distanceReading, heightReading, typeIcon, typeLabel, useDistanceUnit } from './tourActivityReading';
import { TourActivityStatsDialog } from './TourActivityStatsDialog';
import { splitMeasure } from './tourActivityStatsModel';
import { useTourActivityStats, type TourActivityStats } from './useTourActivityStats';
/** The wash the hero tile sits on, as the Atlas numbers do: the text colour, faintly, over the glass. */
const HERO_TINT = 'color-mix(in srgb, var(--text-primary) 7%, transparent)';
/** How many types the strip names before the dialog takes over. */
const STRIP_TYPES = 3;
const EYEBROW = 'mt-1.5 whitespace-nowrap font-semibold uppercase tracking-wide text-content-faint';
function Divider() {
return <span aria-hidden="true" className="mx-3 my-3 w-0.5 flex-none rounded-full bg-edge-faint" />;
}
/**
* The distance of the period, large, with how many tours at its corner; the
* tour count stands in when no tour knows its distance.
*/
function Hero({ summary, unit }: { summary: TourActivitySummary; unit: DistanceUnit }) {
const { t } = useTranslation();
const reading = distanceReading(summary.totals, unit);
const shown = reading ? splitMeasure(reading.text) : { value: String(summary.totals.count), unit: '' };
const countLabel = `${t('tours.mode.tours')}: ${summary.totals.count}`;
return (
<div
className="relative mx-2 my-2 flex flex-col justify-center rounded-xl px-5 py-4"
style={{ background: HERO_TINT }}
>
<div className="flex items-baseline gap-1.5" data-testid="atlas-tour-activity-distance">
<span className="font-black tabular-nums leading-none text-content" style={fs(40, 'title')}>
{shown.value}
</span>
{shown.unit && (
<span className="font-medium text-content-muted" style={fs(14, 'body')}>
{shown.unit}
</span>
)}
</div>
<span className={EYEBROW} style={fs(9)}>
{reading ? t('tours.detail.distance') : t('tours.mode.tours')}
</span>
{reading && (
<Tooltip label={countLabel}>
<span
aria-label={countLabel}
data-testid="atlas-tour-activity-count"
className="absolute -end-2 -top-2 inline-flex h-[22px] items-center gap-1 rounded-full bg-surface-card px-2 font-geist font-semibold tabular-nums text-content shadow-sm ring-1 ring-inset ring-edge-faint"
style={fs(11)}
>
<Footprints size={11} strokeWidth={2.2} className="flex-none text-content-muted" />
{summary.totals.count}
</span>
</Tooltip>
)}
</div>
);
}
/** A height sum as the Atlas numbers stand: the value, its unit, and what it is below. */
function Figure({ label, text, testId }: { label: string; text: string; testId: string }) {
const { value, unit } = splitMeasure(text);
return (
<div className="flex flex-none flex-col items-center justify-center px-3 py-4" data-testid={testId}>
<span className="flex items-baseline gap-1">
<span className="font-black tabular-nums leading-none text-content" style={fs(24, 'subtitle')}>
{value}
</span>
<span className="font-medium text-content-muted" style={fs(11, 'body')}>
{unit}
</span>
</span>
<span className={EYEBROW} style={fs(9)}>
{label}
</span>
</div>
);
}
/** The types of the period, the most tours first: each an icon with its count at the corner, its distance below. */
function TypeColumns({ summary, unit }: { summary: TourActivitySummary; unit: DistanceUnit }) {
const { t } = useTranslation();
return (
<div className="flex flex-none items-center gap-4 px-2 py-3">
{summary.types.slice(0, STRIP_TYPES).map((scope) => {
const Icon = typeIcon(scope.type);
const distance = distanceReading(scope, unit);
const label = `${typeLabel(scope.type, t)}: ${scope.count}${distance ? `, ${distance.text}` : ''}`;
return (
<Tooltip key={scope.type} label={label}>
<span
aria-label={label}
className="flex flex-col items-center gap-1.5"
data-testid={`atlas-tour-activity-type-${scope.type}`}
>
<span className="relative">
<span className="grid h-8 w-8 place-items-center rounded-full bg-surface-card text-content-secondary shadow-sm ring-1 ring-inset ring-edge-faint">
<Icon size={15} strokeWidth={1.9} />
</span>
<span
className="absolute -end-1.5 -top-1.5 grid h-4 min-w-4 place-items-center rounded-full bg-accent px-1 font-geist font-semibold tabular-nums text-accent-text ring-2 ring-surface-card"
style={fs(9)}
>
{scope.count}
</span>
</span>
{distance && (
<span
className="whitespace-nowrap font-semibold tabular-nums text-content-secondary"
style={fs(11, 'body')}
>
{distance.text}
</span>
)}
</span>
</Tooltip>
);
})}
</div>
);
}
/** What the sums rest on, what does not count, and the way into the full list. */
interface StripProps {
stats: TourActivityStats;
summary: TourActivitySummary;
onOpen: () => void;
}
function SideColumn({ stats, summary, onOpen }: StripProps) {
const { t } = useTranslation();
const uncounted = stats.data?.uncounted ?? { unassigned: 0, undated: 0 };
return (
<div className="flex flex-none flex-col items-start justify-center gap-1.5 px-3 py-3">
<div className="flex flex-wrap items-center gap-1.5">
<BasisBadges byBasis={summary.totals.byBasis} />
<InfoDot label={t('tours.stats.title')} description={t('tours.stats.basisInfo')} />
</div>
<div className="flex flex-wrap items-center gap-1.5">
<UncountedBadges upcoming={summary.upcoming} {...uncounted} />
</div>
{summary.done.length > 0 && (
<CardAction icon={<ListOrdered size={13} strokeWidth={2.2} />} onClick={onOpen}>
{t('tours.stats.showTours')}
</CardAction>
)}
</div>
);
}
/** The numbers of the period, or why there are none, with the filters before them. */
function Strip({ stats, summary, onOpen }: StripProps) {
const { t } = useTranslation();
const unit = useDistanceUnit();
const ascent = heightReading(summary.totals.ascentM, unit);
const descent = heightReading(summary.totals.descentM, unit);
const counted = summary.totals.count > 0;
return (
<>
<div className="flex flex-none flex-col items-start justify-center gap-1.5 px-3 py-3">
<ActivityFilters stats={stats} quiet />
</div>
{counted ? (
<>
<Hero summary={summary} unit={unit} />
{ascent && <Figure label={t('tours.detail.ascent')} text={ascent.text} testId="atlas-tour-activity-ascent" />}
{descent && (
<Figure label={t('tours.detail.descent')} text={descent.text} testId="atlas-tour-activity-descent" />
)}
{stats.type === 'all' && summary.types.length > 1 && (
<>
<Divider />
<TypeColumns summary={summary} unit={unit} />
</>
)}
</>
) : (
<p className="m-0 flex max-w-[260px] items-center px-4 py-5 text-content-muted" style={fs(12, 'body')}>
{t(stats.data?.entries.length ? 'tours.stats.none' : 'tours.stats.empty')}
</p>
)}
<Divider />
<SideColumn stats={stats} summary={summary} onOpen={onOpen} />
</>
);
}
/**
* STA-02: the Atlas tab of the user's own tour activities: the period and type,
* the distance done with how many tours at its corner, the climb, the types,
* and what the numbers rest on (the trip planning, or recorded tracks where
* linked). The full list, where a tour can be left out, opens in a dialog. The
* read waits until the tab is first shown.
*/
export function AtlasTourActivityPane({ active, maxWidth }: { active: boolean; maxWidth?: number }) {
const stats = useTourActivityStats(active);
const [open, setOpen] = useState(false);
return (
<div
className="flex w-full items-stretch justify-center overflow-x-auto px-2"
style={{ maxWidth }}
data-testid="atlas-tour-activity"
>
{stats.summary ? (
<Strip stats={stats} summary={stats.summary} onOpen={() => setOpen(true)} />
) : (
<div className="flex items-center px-6 py-5">
<ActivityStatusLine stats={stats} />
</div>
)}
<TourActivityStatsDialog stats={stats} open={open} onClose={() => setOpen(false)} />
</div>
);
}
@@ -18,18 +18,10 @@ import { Tooltip } from '../../shared/Tooltip';
import { FigureBadge } from '../../Tours/paddle/FigureBadge';
import { TourDayRowPill } from '../../Tours/TourDayRowFacts';
import { tourDayRowIcon } from '../../Tours/tourDayRowIcon';
import { typeIcon, typeLabel, type Translate } from './tourActivityReading';
import { periodYear, type ActivityPeriod, type ActivityType } from './tourActivityStatsModel';
import { periodLabel, typeIcon, typeLabel } from './tourActivityReading';
import { type ActivityType } from './tourActivityStatsModel';
import type { TourActivityStats } from './useTourActivityStats';
/** What a period is called in the filter. */
function periodLabel(period: ActivityPeriod, t: Translate): string {
if (period === 'all') return t('tours.stats.period.all');
if (period === 'thisYear') return t('tours.stats.period.thisYear');
if (period === 'last12') return t('tours.stats.period.last12');
return String(periodYear(period));
}
/** The period and type filters, as head band pills or quiet ones in a panel. */
export function ActivityFilters({ stats, quiet = false }: { stats: TourActivityStats; quiet?: boolean }) {
const { t } = useTranslation();
@@ -4,7 +4,7 @@ import { useSettingsStore } from '../../../store/settingsStore';
import type { DistanceUnit } from '../../../types';
import { formatDistance, formatElevation } from '../../../utils/units';
import { tourDayRowIcon } from '../../Tours/tourDayRowIcon';
import { sumReading, type ActivityType } from './tourActivityStatsModel';
import { periodYear, sumReading, type ActivityPeriod, type ActivityType } from './tourActivityStatsModel';
export type Translate = (key: string, params?: Record<string, unknown>) => string;
@@ -37,3 +37,11 @@ export function heightReading(sum: TourActivityTotals['ascentM'], unit: Distance
export function partialHint(sum: TourActivityTotals['distanceKm'], t: Translate): string {
return t('tours.scope.partialBody', { known: sum.known, of: sum.of });
}
/** What a period is called in the filter. */
export function periodLabel(period: ActivityPeriod, t: Translate): string {
if (period === 'all') return t('tours.stats.period.all');
if (period === 'thisYear') return t('tours.stats.period.thisYear');
if (period === 'last12') return t('tours.stats.period.last12');
return String(periodYear(period));
}
@@ -1,48 +0,0 @@
import { useRef, type RefObject } from 'react'
export interface GlassGlare {
/** Goes on the panel itself — the glare is measured against its box. */
panelRef: RefObject<HTMLDivElement | null>
/** The soft light under the cursor. */
glareRef: RefObject<HTMLDivElement | null>
/** The lit stretch of border around it. */
borderGlareRef: RefObject<HTMLDivElement | null>
onMouseMove: (e: { clientX: number; clientY: number }) => void
onMouseLeave: () => void
}
/**
* The Atlas panels' liquid-glass hover: a pool of light under the cursor and the
* piece of border nearest to it lighting up.
*
* Extracted so a second panel beside the first one behaves identically. Two
* hand-copied versions of a gradient are two versions that drift, and the whole
* point of the effect is that the panels look like one material.
*
* Written straight to the DOM rather than through state: this runs on every
* mousemove, and a re-render per frame would cost more than the effect is worth.
*/
export function useGlassGlare(dark: boolean): GlassGlare {
const panelRef = useRef<HTMLDivElement>(null)
const glareRef = useRef<HTMLDivElement>(null)
const borderGlareRef = useRef<HTMLDivElement>(null)
const onMouseMove = (e: { clientX: number; clientY: number }): void => {
if (!panelRef.current || !glareRef.current || !borderGlareRef.current) return
const rect = panelRef.current.getBoundingClientRect()
const x = e.clientX - rect.left
const y = e.clientY - rect.top
glareRef.current.style.background = `radial-gradient(circle 300px at ${x}px ${y}px, ${dark ? 'rgba(255,255,255,0.025)' : 'rgba(255,255,255,0.25)'} 0%, transparent 70%)`
glareRef.current.style.opacity = '1'
borderGlareRef.current.style.opacity = '1'
borderGlareRef.current.style.maskImage = `radial-gradient(circle 150px at ${x}px ${y}px, black 0%, transparent 100%)`
borderGlareRef.current.style.webkitMaskImage = `radial-gradient(circle 150px at ${x}px ${y}px, black 0%, transparent 100%)`
}
const onMouseLeave = (): void => {
if (glareRef.current) glareRef.current.style.opacity = '0'
if (borderGlareRef.current) borderGlareRef.current.style.opacity = '0'
}
return { panelRef, glareRef, borderGlareRef, onMouseMove, onMouseLeave }
}
@@ -0,0 +1,120 @@
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { GlobeEngine, type AtlasMeshManifest, type GlobeHit } from './GlobeEngine';
import { placeLabels, type GlobeLabel } from './globeLabels';
import { globeTheme } from './globeTheme';
export interface AtlasGlobeHandle {
engine: GlobeEngine | null;
}
export interface AtlasGlobeProps {
fetchJson: (path: string) => Promise<unknown>;
dark: boolean;
/** Country name for a label, by ISO A2 (localised by the caller). */
labelFor: (a2: string) => string | null;
/** Whether a country's region names are drawn when zoomed in. */
labelRegionsOf?: (a2: string) => boolean;
/** Paints statuses once the geometry is in (and again whenever this changes). */
paint: (engine: GlobeEngine) => void;
paintKey: unknown;
onHover?: (hit: GlobeHit | null, x: number, y: number) => void;
onSelect?: (hit: GlobeHit | null, x: number, y: number) => void;
onReady?: (manifest: AtlasMeshManifest) => void;
onFrame?: (engine: GlobeEngine) => void;
onError?: (err: unknown) => void;
insetBottom?: number;
className?: string;
}
/**
* The Atlas globe: a WebGL2 canvas driven by GlobeEngine, with country names
* as HTML labels on top so every script, the user's text size and screen
* readers work without a glyph atlas.
*/
const AtlasGlobe = forwardRef<AtlasGlobeHandle, AtlasGlobeProps>(function AtlasGlobe(props, ref) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const labelsRef = useRef<HTMLDivElement>(null);
const engineRef = useRef<GlobeEngine | null>(null);
const propsRef = useRef(props);
propsRef.current = props;
const [ready, setReady] = useState(false);
useImperativeHandle(
ref,
() => ({
get engine() {
return engineRef.current;
},
}),
[]
);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
let engine: GlobeEngine;
try {
engine = new GlobeEngine({
canvas,
fetchJson: (p) => propsRef.current.fetchJson(p),
theme: globeTheme(propsRef.current.dark),
onHover: (h, x, y) => propsRef.current.onHover?.(h, x, y),
onSelect: (h, x, y) => propsRef.current.onSelect?.(h, x, y),
onError: (e) => propsRef.current.onError?.(e),
onReady: () => {
if (engine.manifest) propsRef.current.onReady?.(engine.manifest);
propsRef.current.paint(engine);
setReady(true);
},
onFrame: (e) => {
if (labelsRef.current)
placeLabels(labelsRef.current, labelPool, e, propsRef.current.labelFor, propsRef.current.labelRegionsOf);
propsRef.current.onFrame?.(e);
},
});
} catch (err) {
propsRef.current.onError?.(err);
return;
}
const labelPool: GlobeLabel[] = [];
engine.onRegionLoaded = () => propsRef.current.paint(engine);
engineRef.current = engine;
return () => {
engine.dispose();
engineRef.current = null;
};
}, []);
const { dark, paint, paintKey } = props;
useEffect(() => {
engineRef.current?.setTheme(globeTheme(dark));
}, [dark]);
// paint changes with everything it reads; paintKey also with the regions that
// arrived since, which paint reads from the engine.
useEffect(() => {
const e = engineRef.current;
if (e && ready && paintKey !== undefined) {
paint(e);
e.kick();
}
}, [paint, paintKey, ready]);
useEffect(() => {
engineRef.current?.setInsetBottom(props.insetBottom ?? 0);
}, [props.insetBottom]);
return (
<div className={props.className} style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
<canvas
ref={canvasRef}
style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', touchAction: 'none', cursor: 'grab' }}
aria-label="Atlas"
role="img"
/>
<div ref={labelsRef} aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }} />
</div>
);
});
export default AtlasGlobe;
@@ -0,0 +1,173 @@
import type { BadgeMotif, BadgeTier } from '@trek/shared';
import {
CalendarClock,
Compass,
Earth,
Flag,
Flame,
Footprints,
Globe,
Map as MapIcon,
Moon,
Orbit,
Plane,
PlaneTakeoff,
Sailboat,
Snowflake,
Sparkles,
Star,
TowerControl,
TreePalm,
type LucideIcon,
} from 'lucide-react';
import React from 'react';
import { TIERS } from './badgeTiers';
/**
* A badge as a hexagonal glass medal: a tinted glass body, a ring in the tier's
* metal, and a motif drawn for this badge alone. The shine is a CSS layer that
* follows the pointer (see .ag-medal in atlasGlobe.css). Map/medal paint, not UI
* surfaces, so the colours are literal here.
*/
const HEX = '46,3 89,27 89,77 46,101 3,77 3,27';
const INNER = '46,12 80,31 80,73 46,92 12,73 12,31';
const INK = '#e0f2fe'; // theme-lint-disable: medal line art
const ACCENT = '#7dd3fc'; // theme-lint-disable: medal line art
/**
* One drawn symbol per motif, from the same icon set as the rest of TREK so every
* medal reads at a glance and shares one stroke weight. Badges that come in steps
* (5, 10, 25 countries) carry their number under the symbol.
*/
const ICONS: Record<BadgeMotif, LucideIcon> = {
first: Footprints,
countries: Flag,
continents: Earth,
seven: Earth,
region: MapIcon,
earth: Orbit,
moon: Moon,
flights: Plane,
longhaul: PlaneTakeoff,
airports: TowerControl,
dateline: CalendarClock,
equator: Globe,
hemispheres: Compass,
tropics: TreePalm,
polar: Snowflake,
streak: Flame,
burst: Sparkles,
wish: Star,
islands: Sailboat,
};
function Motif({ motif, label }: { motif: BadgeMotif; label?: string }): React.ReactElement {
const Icon = ICONS[motif];
if (motif === 'seven') {
// All seven continents: the globe with seven lit points around it.
return (
<>
<Icon x={31} y={37} size={30} color={INK} strokeWidth={1.6} />
{Array.from({ length: 7 }, (_, i) => {
const a = (i / 7) * Math.PI * 2 - Math.PI / 2;
return <circle key={i} cx={46 + Math.cos(a) * 25} cy={52 + Math.sin(a) * 25} r="2.4" fill={ACCENT} />;
})}
</>
);
}
if (!label) return <Icon x={28} y={34} size={36} color={INK} strokeWidth={1.5} />;
const long = label.length >= 4;
return (
<>
<Icon x={33} y={28} size={26} color={INK} strokeWidth={1.7} />
<text
x="46"
y="75"
textAnchor="middle"
fontWeight="700"
fontSize={long ? 11 : label.length === 3 ? 13 : 15}
letterSpacing="0.2"
fill={INK}
>
{label}
</text>
</>
);
}
export interface BadgeMedalProps {
motif: BadgeMotif;
tier: BadgeTier;
earned: boolean;
/** 0..1 progress ring for a badge not yet earned. */
progress?: number;
/** Short text some motifs carry (a number, a country code). */
label?: string;
/** Back side: shown instead of the motif. */
back?: React.ReactNode;
size?: number;
id: string;
}
export default function BadgeMedal({
motif,
tier,
earned,
progress = 0,
label,
back,
size = 92,
id,
}: BadgeMedalProps): React.ReactElement {
const [c1, c2] = TIERS[tier];
const g = `bm-${id}`;
return (
<svg viewBox="0 0 92 104" width={size} height={(size * 104) / 92} aria-hidden="true">
<defs>
<linearGradient id={`${g}-r`} x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stopColor={c1} />
<stop offset="0.5" stopColor={c2} />
<stop offset="1" stopColor={c1} />
</linearGradient>
<radialGradient id={`${g}-f`} cx="0.35" cy="0.25" r="0.9">
<stop offset="0" stopColor="rgb(125 211 252 / 0.32)" />
<stop offset="0.55" stopColor="rgb(30 41 70 / 0.82)" />
<stop offset="1" stopColor="rgb(10 14 28 / 0.96)" />
</radialGradient>
<filter id={`${g}-g`} x="-30%" y="-30%" width="160%" height="160%">
<feGaussianBlur stdDeviation="2" result="b" />
<feMerge>
<feMergeNode in="b" />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
</defs>
<polygon
points={HEX}
fill={`url(#${g}-f)`}
stroke={`url(#${g}-r)`}
strokeWidth={earned ? 5 : 2}
strokeOpacity={earned ? 1 : 0.35}
strokeDasharray={earned ? undefined : '4 3'}
/>
<polygon points={INNER} fill="none" stroke="rgb(255 255 255 / 0.14)" strokeWidth="1" />
{!earned && progress > 0 && (
<polygon
points={INNER}
fill="none"
stroke={ACCENT}
strokeWidth="2.4"
pathLength={100}
strokeDasharray={`${Math.round(progress * 100)} 100`}
strokeLinecap="round"
filter={`url(#${g}-g)`}
/>
)}
<g opacity={earned ? 1 : 0.38} filter={`url(#${g}-g)`}>
{back ?? <Motif motif={motif} label={label} />}
</g>
<path d="M10 28 L46 8 L82 28" fill="none" stroke="rgb(255 255 255 / 0.35)" strokeWidth="1.2" />
</svg>
);
}
@@ -0,0 +1,11 @@
import React from 'react';
import DawarichIcon from '../shared/DawarichIcon';
/** Dawarich's mark at an icon's size, round like the symbols beside it. */
export default function DawarichMark({ size = 16 }: { size?: number }): React.ReactElement {
return (
<span className="flex flex-none overflow-hidden rounded-full" style={{ width: size + 2, height: size + 2 }}>
<DawarichIcon size={size + 2} />
</span>
);
}
@@ -0,0 +1,803 @@
/**
* Drives the Atlas globe: camera with inertia and a zoom spring, gestures,
* loading the right level of detail and the regions in view, picking, and one
* animation loop that only runs while something moves.
*
* Framework free. AtlasGlobe.tsx mounts it and feeds it data; it reports back
* through the callbacks in GlobeEngineOptions.
*/
import type { Topology } from 'topojson-specification';
import { GlobeRenderer, MAX_FEATURES, type ArcLayer, type GlobeTheme } from './GlobeRenderer';
import {
frameParams,
MAX_ZOOM,
MIN_ZOOM,
morphOf,
projectPoint,
RAD,
sunVector,
xSqueeze,
type FrameParams,
type GlobeCamera,
type GlobeViewport,
} from './globeMath';
import { buildOcean, type BuiltLayer, type LineMesh } from './globeMesh';
import type { MeshRequest, MeshResponse } from './globeMesh.worker';
export interface AtlasMeshManifest {
version: number;
lods: string[];
regionLods: string[];
world: Record<string, string>;
countries: Array<{
a2: string | null;
a3: string;
name: string;
anchor: [number, number] | null;
bbox: number[];
area: number;
}>;
regions: Record<string, { bbox: number[]; counted: number; total: number; index: string }>;
/** [a2, code, name, nameEn, lon, lat] per region */
regionSearch?: string;
attribution: string[];
}
export interface RegionIndex {
bbox: number[];
counted: number;
features: Array<{
code: string | null;
name: string | null;
nameEn: string | null;
anchor: [number, number] | null;
counted: boolean;
}>;
files: Record<string, string>;
}
export interface GlobeEngineOptions {
canvas: HTMLCanvasElement;
/** Fetches a JSON file below /api/addons/atlas/mesh/ (auth and API base are the caller's). */
fetchJson: (path: string) => Promise<unknown>;
theme: GlobeTheme;
initial?: Partial<GlobeCamera>;
onFrame?: (engine: GlobeEngine) => void;
onHover?: (hit: GlobeHit | null, x: number, y: number) => void;
onSelect?: (hit: GlobeHit | null, x: number, y: number) => void;
onReady?: () => void;
onError?: (err: unknown) => void;
}
export type GlobeHit =
| { kind: 'country'; index: number; a2: string | null }
| { kind: 'region'; a2: string; code: string | null; name: string | null };
/** Zoom from which regions crossfade in, and from which the finer region files load. */
export const REGION_FADE_START = 5;
export const REGION_FADE_END = 6;
/**
* From here on the regions in view are fetched ahead, while the zoom is still
* on its way, so they are drawn by the time they fade in instead of a beat later.
*/
const REGION_PREFETCH_ZOOM = 3;
/** How often the view is checked for regions to fetch, in seconds. */
const REGION_SCAN_EVERY = 0.2;
/** A region file that failed is asked for again after this long, not every frame. */
const REGION_RETRY_AFTER = 20;
const REGION_FINE_ZOOM = 8;
const WORLD_LOD_ZOOM: Array<[string, number]> = [
['l2', 4.2],
['l1', 2.0],
['l0', 0],
];
const MAX_EDGE: Record<string, number> = { l0: 8, l1: 4, l2: 2, r0: 3, r1: 1.5 };
const FIRST_REGION_ID = 512;
export class GlobeEngine {
readonly renderer: GlobeRenderer;
readonly cam: GlobeCamera = { lon: 10, lat: 30, zoom: 1 };
manifest: AtlasMeshManifest | null = null;
readonly regionIndex = new Map<string, RegionIndex>();
/** Status-texture id of each country's first region. */
readonly regionBase = new Map<string, number>();
vp: GlobeViewport = { width: 1, height: 1, baseRadius: 1, globeY: 0, flatY: 0 };
frame: FrameParams;
theme: GlobeTheme;
hover = -1;
selected = -1;
selectedOutline: LineMesh | null = null;
arcs: ArcLayer[] = [];
arcStart = 0;
revealStart = 0;
/** Set while something orbits the globe and needs every frame. */
ambient = false;
private reducedMotion =
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
private idleTimer = 0;
/** Extra px at the bottom the map should keep clear (sheets, docks). */
insetBottom = 0;
private opts: GlobeEngineOptions;
private dpr = 1;
private targetZoom = 1;
private vx = 0;
private vy = 0;
private dragging = false;
private pointers = new Map<number, { x: number; y: number }>();
private pinch: { d: number; z: number } | null = null;
private down: { x: number; y: number; t: number } | null = null;
private fly: { from: GlobeCamera; to: GlobeCamera; t0: number; dur: number } | null = null;
private raf = 0;
private idleFrames = 0;
private alive = true;
private worker: Worker;
private job = 0;
private pending = new Map<number, { resolve: (l: BuiltLayer) => void; reject: (err: Error) => void }>();
private worldLoading = new Set<string>();
private regionLoading = new Set<string>();
private regionFailedAt = new Map<string, number>();
private regionScanAt = -1;
private inViewRegionKeys: ReadonlySet<string> = new Set();
private prefetchQueue: string[] = [];
private prefetchTimer = 0;
private nextRegionId = FIRST_REGION_ID;
private ink: { id: number; lon: number; lat: number; t0: number } | null = null;
private t0 = performance.now();
private lastHoverAt = 0;
private resizeObs: ResizeObserver;
private regionKeys: string[] = [];
private zoomAnchor: { x: number; y: number; lon: number; lat: number } | null = null;
private sun: [number, number, number] = sunVector(new Date());
private sunAt = 0;
constructor(opts: GlobeEngineOptions) {
this.opts = opts;
this.theme = opts.theme;
Object.assign(this.cam, opts.initial ?? {});
this.targetZoom = this.cam.zoom;
this.renderer = new GlobeRenderer(opts.canvas);
this.renderer.setOcean(buildOcean());
this.frame = frameParams(this.cam, this.vp);
this.worker = new Worker(new URL('./globeMesh.worker.ts', import.meta.url), { type: 'module' });
// A build that fails rejects its own job only: the caller decides what that
// means (a region stays plain, a missing world level keeps the coarser one).
this.worker.onmessage = (e: MessageEvent<MeshResponse>) => {
const job = this.pending.get(e.data.job);
this.pending.delete(e.data.job);
if (!job) return;
if (e.data.layer) job.resolve(e.data.layer);
else job.reject(new Error(e.data.error ?? 'Atlas mesh build failed'));
};
this.bindInput(opts.canvas);
this.resizeObs = new ResizeObserver(() => this.resize());
this.resizeObs.observe(opts.canvas);
opts.canvas.addEventListener('webglcontextlost', this.onContextLost);
this.resize();
void this.boot();
}
// ---------------------------------------------------------------- loading
private build(topo: Topology, object: string, maxEdge: number, idBase: number): Promise<BuiltLayer> {
const job = ++this.job;
return new Promise((resolve, reject) => {
this.pending.set(job, { resolve, reject });
this.worker.postMessage({ job, topo, object, maxEdge, idBase } satisfies MeshRequest);
});
}
/**
* A fetch tried again with growing pauses (1, 2, 4, 8 s): a server that is
* restarting or a connection that drops for a moment must not leave the
* globe empty for good.
*/
private async fetchRetrying(path: string): Promise<unknown> {
for (let n = 0; ; n++) {
try {
return await this.opts.fetchJson(path);
} catch (err) {
if (n >= 4 || !this.alive) throw err;
await new Promise((r) => window.setTimeout(r, 1000 * 2 ** n));
}
}
}
private async boot(): Promise<void> {
try {
this.manifest = (await this.fetchRetrying('manifest')) as AtlasMeshManifest;
await this.loadWorld('l0');
this.revealStart = this.now();
this.opts.onReady?.();
this.kick();
} catch (err) {
this.opts.onError?.(err);
}
}
private async loadWorld(lod: string): Promise<void> {
if (!this.manifest || this.renderer.hasWorld(lod) || this.worldLoading.has(lod)) return;
this.worldLoading.add(lod);
try {
const topo = (await this.fetchRetrying(`world/${this.manifest.world[lod]}`)) as Topology;
const layer = await this.build(topo, 'countries', MAX_EDGE[lod], 0);
if (!this.alive) return;
this.renderer.setWorld(lod, layer);
this.kick();
} finally {
this.worldLoading.delete(lod);
}
}
async loadRegionIndex(a2: string): Promise<RegionIndex | null> {
const have = this.regionIndex.get(a2);
if (have) return have;
const entry = this.manifest?.regions[a2];
if (!entry) return null;
const idx = (await this.opts.fetchJson(entry.index)) as RegionIndex;
if (!this.regionIndex.has(a2)) {
this.regionIndex.set(a2, idx);
if (this.nextRegionId + idx.features.length < MAX_FEATURES) {
this.regionBase.set(a2, this.nextRegionId);
this.nextRegionId += idx.features.length;
}
}
return this.regionIndex.get(a2) ?? null;
}
private async loadRegion(a2: string, lod: string): Promise<void> {
const key = `${a2}:${lod}`;
if (this.renderer.hasRegion(key) || this.regionLoading.has(key)) return;
const failedAt = this.regionFailedAt.get(key);
if (failedAt !== undefined && this.now() - failedAt < REGION_RETRY_AFTER) return;
this.regionLoading.add(key);
try {
const idx = await this.loadRegionIndex(a2);
const base = this.regionBase.get(a2);
if (!idx || base === undefined) return;
const topo = (await this.opts.fetchJson(idx.files[lod])) as Topology;
const layer = await this.build(topo, 'regions', MAX_EDGE[lod], base);
if (!this.alive) return;
this.renderer.setRegion(key, layer, this.inViewRegionKeys);
this.onRegionLoaded?.(a2);
this.kick();
} catch {
// A country's regions are detail on top of a working globe: one that does
// not load leaves the country plain and is asked for again later, it does
// not turn the whole Atlas into an error.
this.regionFailedAt.set(key, this.now());
} finally {
this.regionLoading.delete(key);
}
}
/**
* Fetches the coarse regions of these countries in the background, one at a
* time while the browser is idle (the owner passes the countries the user is
* most likely to zoom into), so their first zoom finds them ready.
*/
prefetchRegions(codes: string[]): void {
const known = new Set(this.prefetchQueue);
for (const a2 of codes) if (this.manifest?.regions[a2] && !known.has(a2)) this.prefetchQueue.push(a2);
this.schedulePrefetch();
}
private schedulePrefetch(): void {
if (this.prefetchTimer || !this.prefetchQueue.length || !this.alive) return;
const next = () => {
this.prefetchTimer = 0;
const a2 = this.prefetchQueue.shift();
if (!a2 || !this.alive) return;
void this.loadRegion(a2, 'r0').finally(() => this.schedulePrefetch());
};
const idle = (window as Window & { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number })
.requestIdleCallback;
this.prefetchTimer = idle ? idle(next, { timeout: 1500 }) : window.setTimeout(next, 120);
}
/** Called after a country's regions arrived, so the owner can colour them. */
onRegionLoaded: ((a2: string) => void) | null = null;
private worldKey(): string {
for (const [lod, z] of WORLD_LOD_ZOOM) if (this.cam.zoom >= z && this.renderer.hasWorld(lod)) return lod;
for (const [lod] of WORLD_LOD_ZOOM.slice().reverse()) if (this.renderer.hasWorld(lod)) return lod;
return 'l0';
}
private wantedWorld(): string {
for (const [lod, z] of WORLD_LOD_ZOOM) if (this.cam.zoom >= z) return lod;
return 'l0';
}
/** Countries with regions whose box overlaps the view, nearest first. */
private countriesInView(): string[] {
const m = this.manifest;
if (!m) return [];
const out: Array<[string, number]> = [];
const { width, height } = this.vp;
for (const c of m.countries) {
if (!c.a2 || !m.regions[c.a2]) continue;
const [w, s, e, n] = c.bbox;
let best = Infinity;
let inView = false;
for (const [lon, lat] of [
[(w + e) / 2, (s + n) / 2],
[w, s],
[e, n],
[w, n],
[e, s],
c.anchor ?? [(w + e) / 2, (s + n) / 2],
]) {
const p = projectPoint(lon, lat, this.frame);
if (p.visible < 0) continue;
if (p.x > -200 && p.x < width + 200 && p.y > -200 && p.y < height + 200) inView = true;
best = Math.min(best, Math.hypot(p.x - width / 2, p.y - height / 2));
}
if (inView) out.push([c.a2, best]);
}
return out
.sort((a, b) => a[1] - b[1])
.slice(0, 10)
.map((x) => x[0]);
}
// ---------------------------------------------------------------- camera
private now(): number {
return (performance.now() - this.t0) / 1000;
}
resize(): void {
const c = this.opts.canvas;
const r = c.getBoundingClientRect();
this.dpr = Math.min(2, window.devicePixelRatio || 1);
c.width = Math.max(1, Math.round(r.width * this.dpr));
c.height = Math.max(1, Math.round(r.height * this.dpr));
const narrow = r.width < 640;
const usable = r.height - this.insetBottom;
this.vp = {
width: r.width,
height: r.height,
baseRadius: narrow ? r.width * 0.42 : Math.min(r.width, usable) * 0.31,
// On a phone the globe sits a little lower, clear of the search and buttons on top.
globeY: narrow ? usable * 0.54 : usable * 0.5,
flatY: usable * 0.5,
};
this.kick();
}
setInsetBottom(px: number): void {
if (Math.abs(px - this.insetBottom) < 1) return;
this.insetBottom = px;
this.resize();
}
setTheme(theme: GlobeTheme): void {
this.theme = theme;
this.kick();
}
flyTo(lon: number, lat: number, zoom = Math.max(this.cam.zoom, 1), dur = 1100): void {
let dl = lon - this.cam.lon;
dl = ((dl + 540) % 360) - 180;
this.fly = {
from: { ...this.cam },
to: { lon: this.cam.lon + dl, lat: Math.max(-70, Math.min(70, lat)), zoom },
t0: performance.now(),
dur,
};
this.vx = this.vy = 0;
this.kick();
}
/** Flies so a country's box fills the view. */
flyToBox(bbox: number[], minZoom = 1, maxZoom = 7): void {
const [w, s, e, n] = bbox;
const span = Math.max(e - w, (n - s) * 1.6, 0.5);
const zoom = Math.max(minZoom, Math.min(maxZoom, (110 / span) ** 0.85));
this.flyTo((w + e) / 2, (s + n) / 2, zoom);
}
zoomBy(f: number): void {
this.targetZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, this.targetZoom * f));
this.kick();
}
startInk(id: number, lon: number, lat: number): void {
this.ink = { id, lon, lat, t0: this.now() };
this.kick();
}
setSelected(id: number, outline: LineMesh | null): void {
this.selected = id;
this.selectedOutline = outline;
this.kick();
}
setArcs(arcs: ArcLayer[]): void {
this.arcs = arcs;
this.arcStart = this.now();
this.kick();
}
project(lon: number, lat: number): ReturnType<typeof projectPoint> {
return projectPoint(lon, lat, this.frame);
}
get morph(): number {
return this.frame.t;
}
get regionAlpha(): number {
const z = this.cam.zoom;
return Math.max(0, Math.min(1, (z - REGION_FADE_START) / (REGION_FADE_END - REGION_FADE_START)));
}
// ---------------------------------------------------------------- input
private bindInput(c: HTMLCanvasElement): void {
c.addEventListener('pointerdown', this.onDown);
c.addEventListener('pointermove', this.onMove);
c.addEventListener('pointerup', this.onUp);
c.addEventListener('pointercancel', this.onUp);
c.addEventListener('pointerleave', this.onLeave);
c.addEventListener('wheel', this.onWheel, { passive: false });
c.addEventListener('dblclick', this.onDbl);
}
private local(e: PointerEvent | WheelEvent | MouseEvent): { x: number; y: number } {
const r = this.opts.canvas.getBoundingClientRect();
return { x: e.clientX - r.left, y: e.clientY - r.top };
}
private onDown = (e: PointerEvent): void => {
this.opts.canvas.setPointerCapture(e.pointerId);
const p = this.local(e);
this.pointers.set(e.pointerId, p);
this.down = { ...p, t: performance.now() };
this.vx = this.vy = 0;
this.fly = null;
this.zoomAnchor = null;
this.dragging = true;
this.clearHover();
if (this.pointers.size === 2) {
const [a, b] = [...this.pointers.values()];
this.pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), z: this.targetZoom };
}
this.kick();
};
private onMove = (e: PointerEvent): void => {
const p = this.local(e);
const prev = this.pointers.get(e.pointerId);
if (prev) {
this.pointers.set(e.pointerId, p);
if (this.pointers.size === 2 && this.pinch) {
const [a, b] = [...this.pointers.values()];
const d = Math.hypot(a.x - b.x, a.y - b.y);
this.targetZoom = Math.max(MIN_ZOOM * 0.85, Math.min(MAX_ZOOM * 1.1, (this.pinch.z * d) / this.pinch.d));
this.cam.zoom = this.targetZoom;
this.kick();
return;
}
if (this.pointers.size > 1) return;
const k = 1 / (this.frame.scale * RAD);
const kx = k / xSqueeze(this.frame);
const dx = p.x - prev.x;
const dy = p.y - prev.y;
this.cam.lon -= dx * kx;
this.cam.lat = Math.max(-80, Math.min(80, this.cam.lat + dy * k));
this.vx = dx * kx * 0.85 + this.vx * 0.15;
this.vy = dy * k * 0.85 + this.vy * 0.15;
this.kick();
return;
}
const now = performance.now();
if (now - this.lastHoverAt < 45) return;
this.lastHoverAt = now;
const hit = this.hitAt(p.x, p.y);
const id = hit ? this.idOf(hit) : -1;
if (id !== this.hover) {
this.hover = id;
this.kick();
}
this.opts.onHover?.(hit, p.x, p.y);
};
private onUp = (e: PointerEvent): void => {
if (!this.pointers.has(e.pointerId)) return;
this.pointers.delete(e.pointerId);
if (this.pointers.size < 2) this.pinch = null;
if (this.pointers.size > 0) return;
this.dragging = false;
const p = this.local(e);
if (this.down && Math.hypot(p.x - this.down.x, p.y - this.down.y) < 6 && performance.now() - this.down.t < 400) {
this.vx = this.vy = 0;
this.opts.onSelect?.(this.hitAt(p.x, p.y), p.x, p.y);
}
this.down = null;
this.kick();
};
private onLeave = (): void => {
if (this.dragging) return;
this.hover = -1;
this.opts.onHover?.(null, 0, 0);
this.kick();
};
/** Drops the hover while the camera moves; the next pointer move picks again. */
private clearHover(): void {
if (this.hover === -1) return;
this.hover = -1;
this.opts.onHover?.(null, 0, 0);
}
private onWheel = (e: WheelEvent): void => {
e.preventDefault();
this.clearHover();
const before = this.targetZoom;
const f = Math.exp(-e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.0016));
this.targetZoom = Math.max(MIN_ZOOM * 0.9, Math.min(MAX_ZOOM, before * f));
// On the flat map the place under the cursor stays under the cursor while the
// zoom glides; tick() moves the centre to keep it there, frame by frame.
if (this.frame.t > 0.5 && this.targetZoom !== before) {
const p = this.local(e);
const geo = this.unprojectFlat(p.x, p.y);
this.zoomAnchor = { x: p.x, y: p.y, lon: geo[0], lat: geo[1] };
}
this.fly = null;
this.kick();
};
/** Screen point to lon/lat on the flat map (t = 1); close enough while t > 0.5. */
private unprojectFlat(x: number, y: number): [number, number] {
const f = this.frame;
const k = 1 / (f.scale * RAD);
return [this.cam.lon + ((x - f.originX) * k) / xSqueeze(f), this.cam.lat - (y - f.originY) * k];
}
/** Moves the centre so the anchored place sits under its screen point again. */
private holdAnchor(): void {
const a = this.zoomAnchor;
if (!a) return;
for (let i = 0; i < 2; i++) {
const f = frameParams(this.cam, this.vp);
const k = 1 / (f.scale * RAD);
this.cam.lat = Math.max(-80, Math.min(80, a.lat + (a.y - f.originY) * k));
this.cam.lon = a.lon - ((a.x - f.originX) * k) / xSqueeze(f);
}
}
private onDbl = (e: MouseEvent): void => {
const p = this.local(e);
const hit = this.hitAt(p.x, p.y);
if (!hit) this.zoomBy(1.8);
};
private onContextLost = (e: Event): void => {
e.preventDefault();
this.opts.onError?.(new Error('WebGL context lost'));
};
// ---------------------------------------------------------------- picking
idOf(hit: GlobeHit): number {
if (hit.kind === 'country') return hit.index;
const idx = this.regionIndex.get(hit.a2);
const base = this.regionBase.get(hit.a2);
if (!idx || base === undefined) return -1;
const i = idx.features.findIndex((f) => f.code === hit.code);
return i < 0 ? -1 : base + i;
}
/**
* The country under the middle of the view, the one whose regions get their
* names. Read from the pick buffer, so it is the country really there and not
* the first whose bounding box holds the point (France's box spans half the
* world with its overseas parts). The read-back is not free, so it is only
* redone when the camera moved, at most every 150 ms.
*/
focusCountry(): string | null {
const now = this.now();
const cam = `${this.cam.lon.toFixed(3)},${this.cam.lat.toFixed(3)},${this.cam.zoom.toFixed(2)}`;
if (cam === this.focusCam || now - this.focusAt < 0.15) return this.focus;
this.focusAt = now;
this.focusCam = cam;
const hit = this.hitAt(this.vp.width / 2, this.vp.height / 2);
this.focus = hit?.a2 ?? null;
return this.focus;
}
private focus: string | null = null;
private focusAt = -1;
private focusCam = '';
hitAt(x: number, y: number): GlobeHit | null {
const id = this.renderer.pick(x, y, this.regionAlpha > 0.5);
if (id < 0) return null;
if (id < FIRST_REGION_ID) {
const c = this.manifest?.countries[id];
return c ? { kind: 'country', index: id, a2: c.a2 } : null;
}
for (const [a2, base] of this.regionBase) {
const idx = this.regionIndex.get(a2);
if (idx && id >= base && id < base + idx.features.length) {
const f = idx.features[id - base];
return { kind: 'region', a2, code: f.code, name: f.nameEn ?? f.name };
}
}
return null;
}
// ---------------------------------------------------------------- loop
/** Starts the loop if it sleeps. */
kick(): void {
this.idleFrames = 0;
if (this.idleTimer) {
window.clearTimeout(this.idleTimer);
this.idleTimer = 0;
}
if (!this.raf && this.alive) this.raf = requestAnimationFrame(this.tick);
}
private tick = (): void => {
this.raf = 0;
if (!this.alive) return;
let moving = false;
const now = performance.now();
if (this.fly) {
const p = Math.min(1, (now - this.fly.t0) / this.fly.dur);
const e = p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2;
const { from, to } = this.fly;
this.cam.lon = from.lon + (to.lon - from.lon) * e;
this.cam.lat = from.lat + (to.lat - from.lat) * e;
// Pull back a little mid-flight, so long hops read as travel.
const hop = Math.min(1, Math.abs(to.lon - from.lon) / 120) * Math.sin(Math.PI * e) * 0.35;
this.cam.zoom = Math.max(MIN_ZOOM, from.zoom + (to.zoom - from.zoom) * e - hop * from.zoom);
this.targetZoom = this.cam.zoom;
if (p >= 1) {
this.fly = null;
this.targetZoom = to.zoom;
}
moving = true;
}
if (!this.dragging && !this.fly && (Math.abs(this.vx) > 1e-3 || Math.abs(this.vy) > 1e-3)) {
this.cam.lon -= this.vx;
this.cam.lat = Math.max(-80, Math.min(80, this.cam.lat + this.vy));
this.vx *= 0.93;
this.vy *= 0.93;
moving = true;
}
if (!this.pinch) {
if (this.targetZoom < MIN_ZOOM) this.targetZoom += (MIN_ZOOM - this.targetZoom) * 0.18;
if (this.targetZoom > MAX_ZOOM) this.targetZoom += (MAX_ZOOM - this.targetZoom) * 0.18;
}
const dz = (this.targetZoom - this.cam.zoom) * 0.2;
if (Math.abs(dz) > 1e-4) {
this.cam.zoom += dz;
moving = true;
if (this.zoomAnchor && morphOf(this.cam.zoom) > 0.5) this.holdAnchor();
} else {
this.zoomAnchor = null;
}
this.cam.lon = ((this.cam.lon + 540) % 360) - 180;
this.frame = frameParams(this.cam, this.vp);
const want = this.wantedWorld();
// A finer level that cannot load leaves the coarser one on screen.
if (!this.renderer.hasWorld(want)) this.loadWorld(want).catch(() => undefined);
// Fetch ahead, by where the zoom is heading and not only where it is, and
// during the motion too: the coarse regions well before they fade in, the
// fine ones a step before they are drawn.
const heading = Math.max(this.cam.zoom, this.targetZoom);
const scanNow = this.now();
if (heading >= REGION_PREFETCH_ZOOM && scanNow - this.regionScanAt >= REGION_SCAN_EVERY) {
this.regionScanAt = scanNow;
const fine = heading >= REGION_FINE_ZOOM - 1;
const inView = this.countriesInView();
// What is in view now is what must not be dropped, and the last to go.
this.inViewRegionKeys = new Set(inView.flatMap((a2) => [`${a2}:r0`, `${a2}:r1`]));
for (const k of this.inViewRegionKeys) this.renderer.touchRegion(k);
for (const a2 of inView) {
void this.loadRegion(a2, 'r0');
if (fine) void this.loadRegion(a2, 'r1');
}
}
this.regionKeys = this.collectRegionKeys();
const time = this.now();
if (time - this.sunAt > 30) {
this.sun = sunVector(new Date());
this.sunAt = time;
}
let inkActive = false;
let ink: { id: number; lon: number; lat: number; radius: number } | null = null;
if (this.ink) {
const p = (time - this.ink.t0) / 0.75;
inkActive = p < 1;
ink = {
id: this.ink.id,
lon: this.ink.lon,
lat: this.ink.lat,
radius: (1 - Math.pow(1 - Math.min(1, p), 3)) * Math.PI,
};
if (!inkActive) this.ink = null;
}
const arcProgress = Math.min(1.001, (time - this.arcStart) / 1.6);
this.renderer.draw({
frame: this.frame,
dpr: this.dpr,
width: this.vp.width,
height: this.vp.height,
time,
revealStart: this.revealStart,
hover: this.hover,
selected: this.selected,
ink,
regionAlpha: this.regionAlpha,
theme: this.theme,
arcs: this.arcs,
arcProgress,
regionKeys: this.regionKeys,
worldKey: this.worldKey(),
selectedOutline: this.selectedOutline,
sun: this.sun,
night: this.theme.dark ? 0.34 : 0.1,
});
this.opts.onFrame?.(this);
const revealing = time - this.revealStart < 3.2;
const twinkle = this.theme.dark && this.frame.t < 0.9;
if (moving || inkActive || revealing || arcProgress < 1 || this.dragging) this.idleFrames = 0;
else this.idleFrames++;
// Things that orbit (moon, satellites) need every frame while the globe shows;
// otherwise keep only the stars alive at a low rate once everything rests.
const ambient = this.ambient && this.frame.t < 0.6 && !document.hidden && !this.reducedMotion;
if (this.idleFrames < 3 || ambient) this.raf = requestAnimationFrame(this.tick);
else if (twinkle) this.idleTimer = window.setTimeout(() => this.kick(), 90);
};
private collectRegionKeys(): string[] {
if (this.regionAlpha <= 0) return [];
const fine = this.cam.zoom >= REGION_FINE_ZOOM;
const out: string[] = [];
for (const a2 of this.regionIndex.keys()) {
const k1 = `${a2}:r1`;
const k0 = `${a2}:r0`;
if (fine && this.renderer.hasRegion(k1)) out.push(k1);
else if (this.renderer.hasRegion(k0)) out.push(k0);
else if (this.renderer.hasRegion(k1)) out.push(k1);
}
return out;
}
get zoom(): number {
return this.cam.zoom;
}
isMorphing(): boolean {
const t = morphOf(this.cam.zoom);
return t > 0 && t < 1;
}
dispose(): void {
this.alive = false;
this.prefetchQueue = [];
window.clearTimeout(this.idleTimer);
cancelAnimationFrame(this.raf);
this.resizeObs.disconnect();
this.worker.terminate();
const c = this.opts.canvas;
c.removeEventListener('pointerdown', this.onDown);
c.removeEventListener('pointermove', this.onMove);
c.removeEventListener('pointerup', this.onUp);
c.removeEventListener('pointercancel', this.onUp);
c.removeEventListener('pointerleave', this.onLeave);
c.removeEventListener('wheel', this.onWheel);
c.removeEventListener('dblclick', this.onDbl);
c.removeEventListener('webglcontextlost', this.onContextLost);
this.renderer.dispose();
}
}
@@ -0,0 +1,68 @@
import { Star } from 'lucide-react';
import { forwardRef, useImperativeHandle, useRef } from 'react';
import type { GlobeEngine } from './GlobeEngine';
export interface GlobePin {
key: string;
lon: number;
lat: number;
title: string;
/** A wish that was reached (ticked off by hand or by a recording). */
reached?: boolean;
onClick?: () => void;
}
export interface GlobePinsHandle {
layout: (engine: GlobeEngine) => void;
}
/**
* Places pinned on the globe, the bucket list's wishes with coordinates. Small
* star buttons moved per frame with transform; hidden behind the horizon.
*/
const GlobePins = forwardRef<GlobePinsHandle, { pins: GlobePin[] }>(function GlobePins({ pins }, ref) {
const refs = useRef<Array<HTMLButtonElement | null>>([]);
useImperativeHandle(
ref,
() => ({
layout(engine: GlobeEngine) {
const { width, height } = engine.vp;
pins.forEach((p, i) => {
const el = refs.current[i];
if (!el) return;
const s = engine.project(p.lon, p.lat);
const show = s.visible > 0.02 && s.x > -20 && s.x < width + 20 && s.y > -20 && s.y < height + 20;
el.style.transform = `translate3d(${s.x.toFixed(1)}px, ${s.y.toFixed(1)}px, 0) translate(-50%, -50%)`;
el.style.opacity = show ? String(Math.min(1, s.visible * 6)) : '0';
el.style.pointerEvents = show ? 'auto' : 'none';
});
},
}),
[pins]
);
return (
<>
{pins.map((p, i) => (
<button
key={p.key}
ref={(el) => {
refs.current[i] = el;
}}
type="button"
onClick={p.onClick}
title={p.title}
aria-label={p.title}
// No press transition: the global one animates transform, and a pin moved
// every frame would trail the globe and spring back to its place.
data-no-press
className="ag-pin absolute start-0 top-0"
data-reached={p.reached ? '1' : '0'}
>
<Star size={11} strokeWidth={2.4} />
</button>
))}
</>
);
});
export default GlobePins;
@@ -0,0 +1,592 @@
/**
* WebGL2 renderer of the Atlas globe. Owns the GPU state only: programs,
* layer buffers, the status textures and the picking target. What to show
* comes in through setStatus()/setLayer() and one draw() per frame.
*
* Colours live in two small textures indexed by feature id, so marking a
* country rewrites four bytes instead of rebuilding geometry.
*/
import type { FrameParams } from './globeMath';
import type { BuiltLayer, FillMesh, LineMesh } from './globeMesh';
import { FILL_FS, FILL_VS, LINE_FS, LINE_VS, PICK_FS, RIM_FS, SKY_FS, SKY_VS } from './globeShaders';
export const STATUS_TEX_W = 256;
export const STATUS_TEX_H = 64;
export const MAX_FEATURES = STATUS_TEX_W * STATUS_TEX_H;
export type Rgb = [number, number, number];
export interface GlobeTheme {
land: Rgb;
ocean: Rgb;
oceanDeep: Rgb;
space0: Rgb;
space1: Rgb;
glow: Rgb;
border: [number, number, number, number];
coast: [number, number, number, number];
regionBorder: [number, number, number, number];
selection: [number, number, number, number];
arc: [number, number, number, number];
dark: boolean;
}
export interface ArcLayer {
/** per segment: a.lon, a.lat, b.lon, b.lat, hA, hB, sA, sB */
data: Float32Array;
count: number;
width: number;
}
export interface DrawState {
frame: FrameParams;
dpr: number;
width: number;
height: number;
time: number;
revealStart: number;
hover: number;
selected: number;
ink: { id: number; lon: number; lat: number; radius: number } | null;
regionAlpha: number;
theme: GlobeTheme;
arcs: ArcLayer[];
arcProgress: number;
/** Region layers to draw, by key. */
regionKeys: string[];
worldKey: string;
selectedOutline: LineMesh | null;
/** Unit vector to the sun in earth-fixed coordinates. */
sun: [number, number, number];
night: number;
}
interface Program {
prog: WebGLProgram;
u: Record<string, WebGLUniformLocation | null>;
a: Record<string, number>;
}
interface GpuFill {
vao: WebGLVertexArrayObject;
pickVao: WebGLVertexArrayObject;
count: number;
buffers: WebGLBuffer[];
}
interface GpuLines {
vao: WebGLVertexArrayObject;
count: number;
buffers: WebGLBuffer[];
}
interface GpuLayer {
fill: GpuFill;
coast: GpuLines;
borders: GpuLines;
}
function compile(gl: WebGL2RenderingContext, type: number, src: string): WebGLShader {
const s = gl.createShader(type) as WebGLShader;
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(s);
gl.deleteShader(s);
throw new Error(`Atlas globe shader failed: ${log ?? 'unknown'}`);
}
return s;
}
function link(gl: WebGL2RenderingContext, vs: string, fs: string): Program {
const prog = gl.createProgram() as WebGLProgram;
gl.attachShader(prog, compile(gl, gl.VERTEX_SHADER, vs));
gl.attachShader(prog, compile(gl, gl.FRAGMENT_SHADER, fs));
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
throw new Error(`Atlas globe program failed: ${gl.getProgramInfoLog(prog) ?? 'unknown'}`);
}
const u: Program['u'] = {};
const n = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS) as number;
for (let i = 0; i < n; i++) {
const info = gl.getActiveUniform(prog, i);
if (info) u[info.name] = gl.getUniformLocation(prog, info.name);
}
const a: Program['a'] = {};
const m = gl.getProgramParameter(prog, gl.ACTIVE_ATTRIBUTES) as number;
for (let i = 0; i < m; i++) {
const info = gl.getActiveAttrib(prog, i);
if (info) a[info.name] = gl.getAttribLocation(prog, info.name);
}
return { prog, u, a };
}
/** How many region layers (a country at one detail) stay on the GPU at most. */
const MAX_REGION_LAYERS = 64;
export class GlobeRenderer {
readonly gl: WebGL2RenderingContext;
private fillP: Program;
private pickP: Program;
private lineP: Program;
private skyP: Program;
private rimP: Program;
private quad: WebGLVertexArrayObject;
private cornerBuf: WebGLBuffer;
private statusTex: WebGLTexture;
private fxTex: WebGLTexture;
private status = new Uint8Array(MAX_FEATURES * 4);
private fx = new Uint8Array(MAX_FEATURES * 4);
private statusDirty = true;
private ocean: GpuFill | null = null;
private worlds = new Map<string, GpuLayer>();
private regions = new Map<string, GpuLayer>();
private arcs = new Map<ArcLayer, GpuLines>();
private outline: { src: LineMesh; gpu: GpuLines } | null = null;
private pickFbo: WebGLFramebuffer | null = null;
private pickTex: WebGLTexture | null = null;
private pickSize = [0, 0];
private last: DrawState | null = null;
constructor(canvas: HTMLCanvasElement) {
const gl = canvas.getContext('webgl2', {
antialias: true,
alpha: false,
premultipliedAlpha: false,
preserveDrawingBuffer: false,
});
if (!gl) throw new Error('WebGL2 unavailable');
this.gl = gl;
this.fillP = link(gl, FILL_VS, FILL_FS);
this.pickP = link(gl, FILL_VS, PICK_FS);
this.lineP = link(gl, LINE_VS, LINE_FS);
this.skyP = link(gl, SKY_VS, SKY_FS);
this.rimP = link(gl, SKY_VS, RIM_FS);
this.quad = this.makeQuad();
this.cornerBuf = gl.createBuffer() as WebGLBuffer;
gl.bindBuffer(gl.ARRAY_BUFFER, this.cornerBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, -1, 1, -1, 0, 1, 0, 1, 1, -1, 1, 1]), gl.STATIC_DRAW);
this.statusTex = this.makeTex();
this.fxTex = this.makeTex();
}
private makeTex(): WebGLTexture {
const gl = this.gl;
const t = gl.createTexture() as WebGLTexture;
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, STATUS_TEX_W, STATUS_TEX_H, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
return t;
}
private makeQuad(): WebGLVertexArrayObject {
const gl = this.gl;
const vao = gl.createVertexArray() as WebGLVertexArrayObject;
gl.bindVertexArray(vao);
const b = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, b);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
for (const p of [this.skyP, this.rimP]) {
const loc = p.a.a_pos;
if (loc === undefined) continue;
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
}
gl.bindVertexArray(null);
return vao;
}
/** rgba: colour + fill strength. fx: hatch, reveal order (0..255), outline, spare. */
setStatus(
id: number,
rgba: [number, number, number, number],
fx: [number, number, number, number] = [0, 0, 0, 0]
): void {
if (id < 0 || id >= MAX_FEATURES) return;
this.status.set(rgba, id * 4);
this.fx.set(fx, id * 4);
this.statusDirty = true;
}
clearStatus(from: number, to: number): void {
this.status.fill(0, from * 4, to * 4);
this.fx.fill(0, from * 4, to * 4);
this.statusDirty = true;
}
private uploadFill(m: FillMesh): GpuFill {
const gl = this.gl;
const buffers: WebGLBuffer[] = [];
const make = (data: Float32Array | Uint32Array, target: number): WebGLBuffer => {
const b = gl.createBuffer() as WebGLBuffer;
gl.bindBuffer(target, b);
gl.bufferData(target, data, gl.STATIC_DRAW);
buffers.push(b);
return b;
};
const llB = make(m.ll, gl.ARRAY_BUFFER);
const refB = make(m.ref, gl.ARRAY_BUFFER);
const fidB = make(m.fid, gl.ARRAY_BUFFER);
const idxB = make(m.index, gl.ELEMENT_ARRAY_BUFFER);
const vaoFor = (p: Program): WebGLVertexArrayObject => {
const vao = gl.createVertexArray() as WebGLVertexArrayObject;
gl.bindVertexArray(vao);
const bind = (name: string, buf: WebGLBuffer, size: number): void => {
const loc = p.a[name];
if (loc === undefined || loc < 0) return;
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
};
bind('a_ll', llB, 2);
bind('a_ref', refB, 2);
bind('a_fid', fidB, 1);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idxB);
gl.bindVertexArray(null);
return vao;
};
return { vao: vaoFor(this.fillP), pickVao: vaoFor(this.pickP), count: m.index.length, buffers };
}
private uploadLines(seg: Float32Array, count: number, stride: 4 | 8): GpuLines {
const gl = this.gl;
const p = this.lineP;
const vao = gl.createVertexArray() as WebGLVertexArrayObject;
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, this.cornerBuf);
gl.enableVertexAttribArray(p.a.a_corner);
gl.vertexAttribPointer(p.a.a_corner, 2, gl.FLOAT, false, 0, 0);
const b = gl.createBuffer() as WebGLBuffer;
gl.bindBuffer(gl.ARRAY_BUFFER, b);
gl.bufferData(gl.ARRAY_BUFFER, seg, gl.STATIC_DRAW);
const bytes = stride * 4;
const attr = (name: string, offset: number): void => {
const loc = p.a[name];
if (loc === undefined || loc < 0) return;
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, bytes, offset);
gl.vertexAttribDivisor(loc, 1);
};
attr('a_a', 0);
attr('a_b', 8);
if (stride === 8) {
attr('a_h', 16);
attr('a_s', 24);
}
gl.bindVertexArray(null);
return { vao, count, buffers: [b] };
}
private uploadLayer(l: BuiltLayer): GpuLayer {
return {
fill: this.uploadFill(l.fill),
coast: this.uploadLines(l.coast.seg, l.coast.count, 4),
borders: this.uploadLines(l.borders.seg, l.borders.count, 4),
};
}
private freeLayer(g: GpuLayer | null): void {
if (!g) return;
const gl = this.gl;
for (const part of [g.fill, g.coast, g.borders]) {
for (const b of part.buffers) gl.deleteBuffer(b);
gl.deleteVertexArray(part.vao);
}
gl.deleteVertexArray(g.fill.pickVao);
}
setOcean(m: FillMesh): void {
this.ocean = this.uploadFill(m);
}
setWorld(key: string, l: BuiltLayer): void {
const next = this.uploadLayer(l);
this.freeLayer(this.worlds.get(key) ?? null);
this.worlds.set(key, next);
}
hasWorld(key: string): boolean {
return this.worlds.has(key);
}
/**
* Keeps a country's regions on the GPU. Past MAX_REGION_LAYERS the ones held
* longest go (never one of `inUse`, the layers drawn now): a long session
* over many countries would otherwise keep every region it ever touched.
* Gone ones come back from the browser cache when they are wanted again.
*/
setRegion(key: string, l: BuiltLayer, inUse: ReadonlySet<string> = new Set()): void {
const next = this.uploadLayer(l);
this.freeLayer(this.regions.get(key) ?? null);
this.regions.delete(key);
this.regions.set(key, next);
for (const old of [...this.regions.keys()]) {
if (this.regions.size <= MAX_REGION_LAYERS) break;
if (old === key || inUse.has(old)) continue;
this.freeLayer(this.regions.get(old) ?? null);
this.regions.delete(old);
}
}
/** Marks a region layer as just used, so it is the last to go. */
touchRegion(key: string): void {
const layer = this.regions.get(key);
if (!layer) return;
this.regions.delete(key);
this.regions.set(key, layer);
}
hasRegion(key: string): boolean {
return this.regions.has(key);
}
private arcGpu(a: ArcLayer): GpuLines {
let g = this.arcs.get(a);
if (!g) {
g = this.uploadLines(a.data, a.count, 8);
this.arcs.set(a, g);
}
return g;
}
/** Frees the arc buffers of layers no longer drawn. */
private pruneArcs(keep: ArcLayer[]): void {
for (const [k, v] of this.arcs) {
if (keep.includes(k)) continue;
for (const b of v.buffers) this.gl.deleteBuffer(b);
this.gl.deleteVertexArray(v.vao);
this.arcs.delete(k);
}
}
private outlineGpu(m: LineMesh): GpuLines {
if (this.outline?.src === m) return this.outline.gpu;
if (this.outline) {
for (const b of this.outline.gpu.buffers) this.gl.deleteBuffer(b);
this.gl.deleteVertexArray(this.outline.gpu.vao);
}
const gpu = this.uploadLines(m.seg, m.count, 4);
this.outline = { src: m, gpu };
return gpu;
}
private setProjection(p: Program, s: DrawState): void {
const gl = this.gl;
const f = s.frame;
gl.uniform2f(p.u.u_center, f.centerLon, f.centerLat);
gl.uniform1f(p.u.u_t, f.t);
gl.uniform1f(p.u.u_scale, f.scale * s.dpr);
gl.uniform2f(p.u.u_origin, f.originX * s.dpr, f.originY * s.dpr);
gl.uniform2f(p.u.u_viewport, s.width * s.dpr, s.height * s.dpr);
}
private get world(): GpuLayer | null {
return this.last ? (this.worlds.get(this.last.worldKey) ?? null) : null;
}
draw(s: DrawState): void {
const gl = this.gl;
this.last = s;
const W = Math.round(s.width * s.dpr);
const H = Math.round(s.height * s.dpr);
gl.viewport(0, 0, W, H);
gl.disable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
const th = s.theme;
const f = s.frame;
// Sky
gl.useProgram(this.skyP.prog);
gl.uniform2f(this.skyP.u.u_viewport, W, H);
gl.uniform2f(this.skyP.u.u_globe, f.originX * s.dpr, f.originY * s.dpr);
gl.uniform1f(this.skyP.u.u_radius, f.scale * s.dpr);
gl.uniform1f(this.skyP.u.u_t, f.t);
gl.uniform1f(this.skyP.u.u_time, s.time);
gl.uniform2f(this.skyP.u.u_drift, f.centerLon, f.centerLat);
gl.uniform3fv(this.skyP.u.u_space0, th.space0);
gl.uniform3fv(this.skyP.u.u_space1, th.space1);
gl.uniform3fv(this.skyP.u.u_glow, th.glow);
gl.uniform1f(this.skyP.u.u_dark, th.dark ? 1 : 0);
gl.bindVertexArray(this.quad);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
if (this.statusDirty) {
gl.bindTexture(gl.TEXTURE_2D, this.statusTex);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, STATUS_TEX_W, STATUS_TEX_H, gl.RGBA, gl.UNSIGNED_BYTE, this.status);
gl.bindTexture(gl.TEXTURE_2D, this.fxTex);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, STATUS_TEX_W, STATUS_TEX_H, gl.RGBA, gl.UNSIGNED_BYTE, this.fx);
this.statusDirty = false;
}
// Fills
const p = this.fillP;
gl.useProgram(p.prog);
this.setProjection(p, s);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, this.statusTex);
gl.uniform1i(p.u.u_status, 0);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, this.fxTex);
gl.uniform1i(p.u.u_fx, 1);
gl.uniform3fv(p.u.u_land, th.land);
gl.uniform3fv(p.u.u_ocean, th.ocean);
gl.uniform3fv(p.u.u_oceanDeep, th.oceanDeep);
gl.uniform1f(p.u.u_time, s.time);
gl.uniform1f(p.u.u_revealStart, s.revealStart);
gl.uniform1i(p.u.u_hover, s.hover);
gl.uniform1i(p.u.u_selected, s.selected);
gl.uniform1i(p.u.u_inkId, s.ink ? s.ink.id : -1);
gl.uniform2f(p.u.u_inkLL, s.ink ? (s.ink.lon * Math.PI) / 180 : 0, s.ink ? (s.ink.lat * Math.PI) / 180 : 0);
gl.uniform1f(p.u.u_inkR, s.ink ? s.ink.radius : 0);
gl.uniform1f(p.u.u_dpr, s.dpr);
gl.uniform1f(p.u.u_layerAlpha, 1);
gl.uniform3fv(p.u.u_sun, s.sun);
gl.uniform1f(p.u.u_night, s.night);
gl.uniform1f(p.u.u_shadeMin, th.dark ? 0.42 : 0.82);
// Dark mode lights a hovered country up; on near-white land in light mode it tints it blue.
if (th.dark) gl.uniform4f(p.u.u_hoverTint, 1, 1, 1, 0.09);
else gl.uniform4f(p.u.u_hoverTint, 0.42, 0.56, 0.82, 0.16);
if (this.ocean) {
gl.uniform1i(p.u.u_mode, 1);
gl.bindVertexArray(this.ocean.vao);
gl.drawElements(gl.TRIANGLES, this.ocean.count, gl.UNSIGNED_INT, 0);
}
const regionsOn = s.regionAlpha > 0.001 && s.regionKeys.some((k) => this.regions.has(k));
if (this.world) {
gl.uniform1i(p.u.u_mode, 0);
gl.uniform1f(p.u.u_dimBase, 1);
gl.uniform1f(p.u.u_regionFade, s.regionAlpha);
gl.bindVertexArray(this.world.fill.vao);
gl.drawElements(gl.TRIANGLES, this.world.fill.count, gl.UNSIGNED_INT, 0);
}
if (regionsOn) {
gl.uniform1i(p.u.u_mode, 2);
gl.uniform1f(p.u.u_layerAlpha, s.regionAlpha);
for (const k of s.regionKeys) {
const r = this.regions.get(k);
if (!r) continue;
gl.bindVertexArray(r.fill.vao);
gl.drawElements(gl.TRIANGLES, r.fill.count, gl.UNSIGNED_INT, 0);
}
}
// Lines
const lp = this.lineP;
gl.useProgram(lp.prog);
this.setProjection(lp, s);
gl.uniform1f(lp.u.u_lift, 0);
gl.uniform1f(lp.u.u_progress, 2);
gl.uniform1f(lp.u.u_glow, 0);
const lines = (g: GpuLines, color: number[], width: number): void => {
if (!g.count) return;
gl.uniform4fv(lp.u.u_color, color);
gl.uniform1f(lp.u.u_width, width * s.dpr);
gl.bindVertexArray(g.vao);
gl.vertexAttrib2f(lp.a.a_h, 0, 0);
gl.vertexAttrib2f(lp.a.a_s, 0, 0);
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, g.count);
};
if (regionsOn) {
const c = [...th.regionBorder];
c[3] *= s.regionAlpha;
for (const k of s.regionKeys) {
const r = this.regions.get(k);
if (r) lines(r.borders, c, 0.7);
}
}
if (this.world) {
lines(this.world.borders, th.border, 0.8);
lines(this.world.coast, th.coast, 0.9);
}
if (s.selectedOutline) {
gl.uniform1f(lp.u.u_glow, 0.55);
lines(this.outlineGpu(s.selectedOutline), th.selection, 1.8);
gl.uniform1f(lp.u.u_glow, 0);
}
if (this.arcs.size > s.arcs.length) this.pruneArcs(s.arcs);
if (s.arcs.length) {
gl.uniform1f(lp.u.u_lift, 1);
gl.uniform1f(lp.u.u_progress, s.arcProgress);
for (const a of s.arcs) {
const g = this.arcGpu(a);
gl.uniform4fv(lp.u.u_color, th.arc);
gl.uniform1f(lp.u.u_width, a.width * s.dpr);
gl.uniform1f(lp.u.u_glow, 0.35);
gl.bindVertexArray(g.vao);
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, g.count);
}
gl.uniform1f(lp.u.u_lift, 0);
}
// Rim light over the limb
gl.useProgram(this.rimP.prog);
gl.uniform2f(this.rimP.u.u_viewport, W, H);
gl.uniform2f(this.rimP.u.u_globe, f.originX * s.dpr, f.originY * s.dpr);
gl.uniform1f(this.rimP.u.u_radius, f.scale * s.dpr);
gl.uniform1f(this.rimP.u.u_t, f.t);
gl.uniform3fv(this.rimP.u.u_glow, th.glow);
gl.bindVertexArray(this.quad);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.bindVertexArray(null);
}
/** Feature id under a CSS-pixel position, or -1. Renders an id pass of the last frame. */
pick(x: number, y: number, includeRegions: boolean): number {
const s = this.last;
if (!s) return -1;
const gl = this.gl;
const W = Math.round(s.width * s.dpr);
const H = Math.round(s.height * s.dpr);
if (!this.pickFbo || this.pickSize[0] !== W || this.pickSize[1] !== H) {
if (this.pickTex) gl.deleteTexture(this.pickTex);
if (this.pickFbo) gl.deleteFramebuffer(this.pickFbo);
this.pickTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.pickTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, W, H, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
this.pickFbo = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, this.pickFbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.pickTex, 0);
this.pickSize = [W, H];
}
gl.bindFramebuffer(gl.FRAMEBUFFER, this.pickFbo);
gl.viewport(0, 0, W, H);
gl.disable(gl.BLEND);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
const p = this.pickP;
gl.useProgram(p.prog);
this.setProjection(p, s);
if (this.world) {
gl.bindVertexArray(this.world.fill.pickVao);
gl.drawElements(gl.TRIANGLES, this.world.fill.count, gl.UNSIGNED_INT, 0);
}
if (includeRegions) {
for (const k of s.regionKeys) {
const r = this.regions.get(k);
if (!r) continue;
gl.bindVertexArray(r.fill.pickVao);
gl.drawElements(gl.TRIANGLES, r.fill.count, gl.UNSIGNED_INT, 0);
}
}
const px = new Uint8Array(4);
gl.readPixels(Math.round(x * s.dpr), H - Math.round(y * s.dpr) - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.bindVertexArray(null);
gl.enable(gl.BLEND);
const id = px[0] + (px[1] << 8) + (px[2] << 16);
return id - 1;
}
dispose(): void {
const gl = this.gl;
for (const w of this.worlds.values()) this.freeLayer(w);
this.worlds.clear();
for (const r of this.regions.values()) this.freeLayer(r);
this.regions.clear();
// The context is left alive: React mounts twice in development and the
// second engine takes over the same canvas.
void gl;
}
}
@@ -0,0 +1,92 @@
import { forwardRef, useImperativeHandle, useMemo, useRef } from 'react';
import type { GlobeEngine } from './GlobeEngine';
import { moonPhase, smoothstep } from './globeMath';
export interface GlobeSkyHandle {
layout: (engine: GlobeEngine) => void;
/** A shooting star across the sky, for the moment something is marked. */
shootingStar: () => void;
}
/**
* What hangs in the sky around the globe: the moon in its real phase, and the
* shooting star that crosses when a country is marked. The moon is placed per
* frame without React rendering.
*/
const GlobeSky = forwardRef<GlobeSkyHandle, { dark: boolean }>(function GlobeSky({ dark }, ref) {
const moonRef = useRef<HTMLDivElement>(null);
const starHost = useRef<HTMLDivElement>(null);
const phase = useMemo(() => moonPhase(new Date()), []);
useImperativeHandle(
ref,
() => ({
layout(engine: GlobeEngine) {
const f = engine.frame;
const { width, height } = engine.vp;
const fade = 1 - smoothstep(0.05, 0.6, f.t);
if (!moonRef.current) return;
if (!dark) {
moonRef.current.style.opacity = '0';
return;
}
const d = Math.max(f.scale * 1.75, Math.min(width, height) * 0.42);
const x = f.originX + Math.cos(-0.65) * d * 1.25;
const y = f.originY + Math.sin(-0.65) * d * 0.62;
moonRef.current.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -50%)`;
moonRef.current.style.opacity = String(fade * 0.95);
},
shootingStar() {
const host = starHost.current;
if (!host || !dark || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
const el = document.createElement('div');
el.className = 'ag-shooting-star';
el.style.left = `${host.clientWidth * (0.55 + Math.random() * 0.35)}px`;
el.style.top = `${host.clientHeight * (0.05 + Math.random() * 0.25)}px`;
host.appendChild(el);
el.animate(
[
{ transform: 'rotate(-28deg) translateX(0) scaleX(0.2)', opacity: 0 },
{ transform: 'rotate(-28deg) translateX(-90px) scaleX(1)', opacity: 1, offset: 0.25 },
{ transform: 'rotate(-28deg) translateX(-420px) scaleX(0.6)', opacity: 0 },
],
{ duration: 1100, easing: 'cubic-bezier(.2,.6,.3,1)' }
).onfinish = () => el.remove();
},
}),
[dark]
);
// The lit part of the moon: the disc with an ellipse carving the shadow.
const lit = phase.lit;
const waxing = phase.phase < 0.5;
const k = Math.abs(1 - 2 * lit);
const shadowPath = `M 14 1 A 13 13 0 0 ${waxing ? 0 : 1} 14 27 A ${(13 * k).toFixed(2)} 13 0 0 ${lit > 0.5 === waxing ? 1 : 0} 14 1 Z`;
return (
<>
<div ref={starHost} aria-hidden="true" className="pointer-events-none absolute inset-0 overflow-hidden" />
<div
ref={moonRef}
aria-hidden="true"
className="pointer-events-none absolute start-0 top-0"
style={{ filter: 'drop-shadow(0 0 14px rgb(220 230 255 / 0.35))' }}
>
<svg width="28" height="28" viewBox="0 0 28 28">
<defs>
<radialGradient id="ag-moon" cx="0.4" cy="0.35" r="0.75">
<stop offset="0" stopColor="rgb(244 246 251)" />
<stop offset="1" stopColor="rgb(170 179 197)" />
</radialGradient>
</defs>
<circle cx="14" cy="14" r="13" fill="url(#ag-moon)" />
<circle cx="10" cy="10" r="2.4" fill="rgb(0 0 0)" opacity="0.07" />
<circle cx="17" cy="17" r="3.2" fill="rgb(0 0 0)" opacity="0.06" />
<path d={shadowPath} fill="rgb(7 10 20)" opacity="0.88" />
</svg>
</div>
</>
);
});
export default GlobeSky;
@@ -0,0 +1,55 @@
import type { LucideIcon } from 'lucide-react';
import React from 'react';
export interface GlobeStat {
key: string;
icon: LucideIcon;
value: React.ReactNode;
label: string;
onClick?: () => void;
}
const CARD =
'ag-liquid-card flex w-[132px] flex-none flex-col justify-between gap-2 rounded-[14px] px-3 py-2.5 text-start transition-colors';
/**
* The Atlas numbers in the bottom corner: the frosted card every floating map
* control in TREK uses, holding one small card per number (badge in badge).
* A number with an action is a button.
*/
export default function GlobeStatsBar({
stats,
className = 'bottom-[22px] start-[22px] max-w-[calc(100%-120px)]',
}: {
stats: GlobeStat[];
className?: string;
}): React.ReactElement {
return (
<div
className={`ag-liquid pointer-events-auto absolute flex gap-1.5 overflow-x-auto rounded-[20px] p-1.5 ${className}`}
style={{ scrollbarWidth: 'none' }}
>
{stats.map((s) => {
const Icon = s.icon;
const body = (
<>
<span className="flex items-start justify-between gap-2">
<span className="text-title font-semibold tabular-nums leading-none text-content">{s.value}</span>
<Icon size={16} strokeWidth={1.9} className="mt-0.5 flex-none text-content-muted" />
</span>
<span className="whitespace-nowrap text-caption text-content-muted">{s.label}</span>
</>
);
return s.onClick ? (
<button key={s.key} type="button" onClick={s.onClick} className={CARD}>
{body}
</button>
) : (
<div key={s.key} className={CARD}>
{body}
</div>
);
})}
</div>
);
}
@@ -0,0 +1,311 @@
/*
* The globe Atlas chrome: glass capsules, labels, the country card.
* The globe is its own night sky, so the glass is tuned against it rather than
* against the app surfaces. The scene is a night sky in both modes; the controls
* on top (search, zoom, stats) follow the app's light or dark mode.
*/
.atlas-globe {
--ag-glass: linear-gradient(180deg, rgb(255 255 255 / 0.11), rgb(255 255 255 / 0.04));
--ag-glass-solid: rgb(16 20 34 / 0.9);
--ag-edge: rgb(255 255 255 / 0.13);
--ag-edge-hi: rgb(255 255 255 / 0.3);
--ag-hi: inset 0 1px 0 rgb(255 255 255 / 0.22);
--ag-shadow: 0 12px 32px rgb(0 0 0 / 0.38);
--ag-ink: rgb(238 242 255);
--ag-muted: rgb(150 160 182);
--ag-faint: rgb(100 110 132);
--ag-accent: rgb(125 211 252);
--ag-mint: rgb(94 234 212);
--ag-label: rgb(226 232 245 / 0.92);
--ag-label-shadow: 0 1px 2px rgb(0 0 0 / 0.85), 0 0 10px rgb(0 0 0 / 0.55);
position: relative;
color: var(--ag-ink);
background: rgb(3 5 12);
}
html:not(.dark) .ag-btn {
background: rgb(15 23 42 / 0.04);
}
html:not(.dark) .ag-btn[data-on='1'] {
background: rgb(37 99 235 / 0.12);
border-color: rgb(37 99 235 / 0.4);
}
html:not(.dark) .ag-bar {
background: rgb(15 23 42 / 0.08);
}
.ag-glass {
background: var(--ag-glass);
border: 1px solid var(--ag-edge);
box-shadow: var(--ag-hi), var(--ag-shadow);
backdrop-filter: blur(18px) saturate(150%);
-webkit-backdrop-filter: blur(18px) saturate(150%);
}
[data-no-transparency] .ag-glass,
.atlas-globe[data-moving='1'] .ag-glass-big {
backdrop-filter: none;
-webkit-backdrop-filter: none;
background: var(--ag-glass-solid);
}
.atlas-globe-label {
position: absolute;
left: 0; /* rtl-lint-disable: placed by a measured x on the canvas, physical on purpose */
top: 0;
white-space: nowrap;
font-weight: 500;
letter-spacing: 0.01em;
color: var(--ag-label);
text-shadow: var(--ag-label-shadow);
will-change: transform, opacity;
transition: opacity 0.25s;
}
.atlas-globe-label[data-region='1'] {
font-weight: 400;
opacity: 0.85;
letter-spacing: 0.02em;
}
.ag-num {
font-variant-numeric: tabular-nums;
letter-spacing: -0.02em;
}
.ag-muted {
color: var(--ag-muted);
}
.ag-faint {
color: var(--ag-faint);
}
.ag-btn {
border: 1px solid var(--ag-edge);
background: rgb(255 255 255 / 0.06);
transition:
border-color 0.2s,
background 0.2s;
}
.ag-btn:hover {
border-color: var(--ag-edge-hi);
}
.ag-btn[data-on='1'] {
background: rgb(125 211 252 / 0.18);
border-color: rgb(125 211 252 / 0.5);
}
.ag-bar {
height: 6px;
border-radius: 99px;
background: rgb(255 255 255 / 0.09);
overflow: hidden;
}
.ag-bar > i {
display: block;
height: 100%;
border-radius: 99px;
background: linear-gradient(90deg, var(--ag-accent), var(--ag-mint));
box-shadow: 0 0 12px rgb(125 211 252 / 0.55);
transition: width 0.9s cubic-bezier(0.2, 0.9, 0.2, 1);
}
/* A badge in the Passport: a glass medal that tilts towards the pointer and flips. */
.ag-medal {
perspective: 600px;
cursor: default;
}
.ag-medal[data-earned='1'] {
cursor: pointer;
}
.ag-medal-body {
position: relative;
display: block;
width: 92px;
height: 104px;
transform-style: preserve-3d;
transform: rotateX(var(--rx, 0deg)) rotateY(calc(var(--ry, 0deg) + var(--flip, 0deg)));
transition: transform 0.7s cubic-bezier(0.2, 0.9, 0.25, 1.1);
}
.ag-medal[data-flipped='1'] {
--flip: 180deg;
}
.ag-medal-face,
.ag-medal-back {
position: absolute;
inset: 0;
backface-visibility: hidden;
}
.ag-medal-back {
transform: rotateY(180deg);
}
.ag-medal-shine {
position: absolute;
inset: 0;
clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%);
background:
radial-gradient(60% 45% at var(--mx, 30%) var(--my, 20%), rgb(255 255 255 / 0.5), rgb(255 255 255 / 0) 60%),
linear-gradient(
115deg,
rgb(125 211 252 / 0) 30%,
rgb(167 139 250 / 0.22) 45%,
rgb(94 234 212 / 0.2) 55%,
rgb(125 211 252 / 0) 70%
);
mix-blend-mode: screen;
pointer-events: none;
}
.ag-medal[data-earned='0'] .ag-medal-shine {
opacity: 0.25;
}
.ag-shooting-star {
position: absolute;
width: 140px;
height: 2px;
border-radius: 99px;
transform-origin: right center;
background: linear-gradient(90deg, rgb(255 255 255 / 0), rgb(255 255 255 / 0.95));
box-shadow: 0 0 10px rgb(186 230 253 / 0.8);
}
@media (prefers-reduced-motion: reduce) {
.ag-medal-body {
transform: rotateY(var(--flip, 0deg));
}
.ag-bar > i,
.atlas-globe-label {
transition: none;
}
}
/*
* The controls on top of the scene wear TREK's map chrome, like every floating
* map control in the app: the sidebar surface, the app's text colours and the
* map control shadow. Only the scene itself (sky, globe, labels) is Atlas's own.
*/
:root .atlas-globe.atlas-globe {
--ag-glass: var(--sidebar-bg);
--ag-glass-solid: var(--sidebar-bg);
--ag-edge: var(--border-primary);
--ag-edge-hi: var(--text-faint, var(--border-primary));
--ag-hi: 0 0 0 0 transparent;
--ag-shadow: 0 2px 10px rgb(0 0 0 / 0.25);
--ag-ink: var(--text-primary);
--ag-muted: var(--text-muted);
--ag-faint: var(--text-faint, var(--text-muted));
}
:root .atlas-globe .ag-glass {
backdrop-filter: blur(20px) saturate(180%);
-webkit-backdrop-filter: blur(20px) saturate(180%);
}
/*
* TREK's liquid glass (the dashboard tiles' tokens, dashboard.css) for every
* control over the globe: shells, the stat cards inside them, the search, chips.
*/
.atlas-globe {
/* Over the night sky the dashboard's glass needs more white to still read as white. */
--glass-bg: linear-gradient(135deg, oklch(1 0 0 / 0.92) 0%, oklch(0.99 0.006 75 / 0.82) 100%);
--glass-border: oklch(1 0 0 / 0.75);
--glass-shadow: 0 1px 2px oklch(0.4 0.02 60 / 0.05), 0 12px 32px -14px oklch(0.3 0.02 60 / 0.2);
--glass-highlight: inset 0 1px 0 oklch(1 0 0 / 0.8);
--glass-blur: blur(22px) saturate(1.7);
--glass-card: oklch(1 0 0 / 0.7);
}
.dark .atlas-globe {
--glass-bg: linear-gradient(135deg, oklch(0.31 0 0 / 0.58) 0%, oklch(0.25 0 0 / 0.42) 100%);
--glass-border: oklch(1 0 0 / 0.1);
--glass-shadow: 0 1px 2px oklch(0 0 0 / 0.3), 0 12px 32px -14px oklch(0 0 0 / 0.55);
--glass-highlight: inset 0 1px 0 oklch(1 0 0 / 0.09);
--glass-card: oklch(1 0 0 / 0.05);
}
[data-no-transparency] .atlas-globe {
--glass-bg: var(--bg-card);
--glass-border: var(--border-primary);
--glass-highlight: 0 0 0 0 transparent;
--glass-blur: none;
--glass-card: var(--bg-tertiary, var(--bg-card));
}
.atlas-globe .ag-liquid {
background: var(--glass-bg);
border: 1px solid var(--glass-border);
box-shadow: var(--glass-shadow), var(--glass-highlight);
backdrop-filter: var(--glass-blur);
-webkit-backdrop-filter: var(--glass-blur);
}
.atlas-globe .ag-liquid-card {
background: var(--glass-card);
border: 1px solid var(--glass-border);
box-shadow: var(--glass-highlight);
}
.atlas-globe .ag-liquid-card:is(button):hover {
background: color-mix(in oklch, var(--glass-card), var(--text-primary) 6%);
}
/* A wish with coordinates pinned on the globe: a small amber disc with a star. */
.ag-pin {
display: grid;
place-items: center;
width: 22px;
height: 22px;
border-radius: 999px;
color: rgb(255 255 255);
background: rgb(245 158 11);
border: 1.5px solid rgb(255 255 255 / 0.9);
box-shadow:
0 2px 8px rgb(0 0 0 / 0.45),
0 0 14px rgb(251 191 36 / 0.45);
will-change: transform, opacity;
transition: opacity 0.2s;
}
.ag-pin[data-reached='1'] {
background: rgb(20 184 166);
box-shadow:
0 2px 8px rgb(0 0 0 / 0.45),
0 0 14px rgb(45 212 191 / 0.45);
}
/* The ring of light behind a badge that was just reached. */
.ag-unlock-ring {
position: absolute;
width: 220px;
height: 220px;
margin-top: -36px;
border-radius: 999px;
background: radial-gradient(circle, rgb(125 211 252 / 0.35) 0%, rgb(167 139 250 / 0.18) 40%, transparent 70%);
animation: ag-unlock-pulse 1.6s ease-out infinite;
pointer-events: none;
}
@keyframes ag-unlock-pulse {
0% {
transform: scale(0.7);
opacity: 0.9;
}
100% {
transform: scale(1.5);
opacity: 0;
}
}
@@ -0,0 +1,9 @@
import type { BadgeTier } from '@trek/shared';
/** The two tones of each tier's metal, light and deep; medal paint, not UI surfaces. */
export const TIERS: Record<BadgeTier, [string, string]> = {
bronze: ['#f5b06b', '#a55a1e'], // theme-lint-disable: medal metal
silver: ['#eef2f7', '#8a97ab'], // theme-lint-disable: medal metal
gold: ['#fde68a', '#c98a0e'], // theme-lint-disable: medal metal
aurora: ['#5eead4', '#a78bfa'], // theme-lint-disable: medal metal
};
@@ -0,0 +1,184 @@
/**
* Country and region names over the globe. A small pool of absolutely placed
* elements moved with transform only; the largest countries win when two
* labels would overlap.
*/
import type { GlobeEngine } from './GlobeEngine';
export interface GlobeLabel {
el: HTMLDivElement;
key: string;
}
interface Candidate {
key: string;
text: string;
x: number;
y: number;
rank: number;
region: boolean;
fade: number;
}
const MAX_LABELS = 150;
const MAX_REGION_LABELS = 120;
/**
* Region names start here, well after the region fills have faded in: on a
* phone at 14, on a wider screen, which shows far more at once, only at 18.
*/
const REGION_LABEL_ZOOM_PHONE = 14;
const REGION_LABEL_ZOOM_WIDE = 18;
/** The width below which the globe counts as on a phone, as GlobeEngine lays it out. */
const NARROW_WIDTH = 640;
function minAreaFor(zoom: number): number {
// Square degrees a country needs before its name shows at this zoom.
return 700 / Math.pow(zoom, 2.4);
}
export function placeLabels(
host: HTMLDivElement,
pool: GlobeLabel[],
engine: GlobeEngine,
labelFor: (a2: string) => string | null,
labelRegionsOf?: (a2: string) => boolean
): void {
const m = engine.manifest;
if (!m) return;
const zoom = engine.zoom;
const { width } = engine.vp;
const cands: Candidate[] = [];
const regionsOn = zoom >= (width < NARROW_WIDTH ? REGION_LABEL_ZOOM_PHONE : REGION_LABEL_ZOOM_WIDE);
const named = regionsOn ? regionCandidates(engine, cands) : new Set<string>();
countryCandidates(engine, cands, named, labelFor, labelRegionsOf);
cands.sort((a, b) => b.rank - a.rank);
let regionCount = 0;
const placed: Array<[number, number, number, number]> = [];
const chosen: Candidate[] = [];
for (const c of cands) {
if (chosen.length >= MAX_LABELS) break;
if (c.region && regionCount >= MAX_REGION_LABELS) continue;
const w = c.text.length * (c.region ? 6.2 : 6.6) + 8;
const h = 16;
const box: [number, number, number, number] = [c.x - w / 2, c.y - h / 2, c.x + w / 2, c.y + h / 2];
if (placed.some((b) => box[0] < b[2] && box[2] > b[0] && box[1] < b[3] && box[3] > b[1])) continue;
placed.push(box);
chosen.push(c);
if (c.region) regionCount++;
}
while (pool.length < chosen.length) {
const el = document.createElement('div');
el.className = 'atlas-globe-label text-caption';
host.appendChild(el);
pool.push({ el, key: '' });
}
pool.forEach((l, i) => {
const c = chosen[i];
if (!c) {
if (l.el.style.opacity !== '0') l.el.style.opacity = '0';
return;
}
if (l.key !== c.key) {
l.key = c.key;
l.el.textContent = c.text;
l.el.dataset.region = c.region ? '1' : '';
}
l.el.style.transform = `translate3d(${c.x.toFixed(1)}px, ${c.y.toFixed(1)}px, 0) translate(-50%, -50%)`;
l.el.style.opacity = String(Math.max(0, Math.min(1, c.fade)));
});
}
/**
* From the region label zoom on, every country in view with regions names
* them, and its own name gives way (Kansas, not "United States" above it).
* The regions nearest the middle of the view come first, the country under the
* middle ahead of all; the collision check keeps it from being a wall.
* Returns the countries whose regions were named.
*/
function regionCandidates(engine: GlobeEngine, cands: Candidate[]): Set<string> {
const { width, height } = engine.vp;
const focus = centreCountry(engine);
const named = new Set<string>();
const cx = width / 2;
const cy = height / 2;
for (const [a2, idx] of engine.regionIndex) {
for (const f of idx.features) {
if (!f.anchor) continue;
const p = engine.project(f.anchor[0], f.anchor[1]);
if (p.visible < 0.1 || p.x < 0 || p.x > width || p.y < 0 || p.y > height) continue;
named.add(a2);
const near = 1 - Math.min(1, Math.hypot(p.x - cx, p.y - cy) / Math.hypot(cx, cy));
cands.push({
key: `${a2}:${f.code ?? f.name}`,
text: f.nameEn ?? f.name ?? '',
x: p.x,
y: p.y,
rank: (a2 === focus ? 2e7 : 1e7) + near * 1e6,
region: true,
fade: engine.regionAlpha,
});
}
}
return named;
}
/** Country names, the large ones first; the user's own countries are named earlier than the rest. */
function countryCandidates(
engine: GlobeEngine,
cands: Candidate[],
named: Set<string>,
labelFor: (a2: string) => string | null,
labelRegionsOf?: (a2: string) => boolean
): void {
const m = engine.manifest;
if (!m) return;
const { width, height } = engine.vp;
const minArea = minAreaFor(engine.zoom);
const regionA = engine.regionAlpha;
for (const c of m.countries) {
if (!c.a2 || !c.anchor || named.has(c.a2)) continue;
const mine = labelRegionsOf ? labelRegionsOf(c.a2) : false;
if (c.area < minArea * (mine ? 0.3 : 1)) continue;
const p = engine.project(c.anchor[0], c.anchor[1]);
if (p.visible < 0.12 || p.x < -40 || p.x > width + 40 || p.y < -20 || p.y > height + 20) continue;
const text = labelFor(c.a2);
if (!text) continue;
cands.push({
key: c.a2,
text,
x: p.x,
y: p.y,
rank: c.area * (mine ? 4 : 1) * (1 - regionA * 0.7),
region: false,
fade: Math.min(1, p.visible * 4) * (1 - regionA * 0.55),
});
}
}
/** The country whose label anchor sits nearest the middle of the view. */
function centreCountry(engine: GlobeEngine): string | null {
const under = engine.focusCountry();
if (under) return engine.regionIndex.has(under) ? under : null;
// Open water in the middle (a coast, a lake): the country with regions whose
// label point is nearest to the middle of the view.
const m = engine.manifest;
if (!m) return null;
const { width, height } = engine.vp;
let best: string | null = null;
let bestD = Math.min(width, height) * 0.35;
for (const a2 of engine.regionIndex.keys()) {
const c = m.countries.find((x) => x.a2 === a2);
if (!c?.anchor) continue;
const p = engine.project(c.anchor[0], c.anchor[1]);
if (p.visible <= 0) continue;
const d = Math.hypot(p.x - width / 2, p.y - height / 2);
if (d < bestD) {
bestD = d;
best = a2;
}
}
return best;
}
@@ -0,0 +1,111 @@
import { describe, expect, it } from 'vitest';
import {
angularDistance,
arcSegments,
frameParams,
interpolateGreatCircle,
moonPhase,
MORPH_END,
MORPH_START,
morphOf,
projectPoint,
sunVector,
wrapPi,
xSqueeze,
type GlobeViewport,
} from './globeMath';
const VP: GlobeViewport = { width: 1000, height: 800, baseRadius: 300, globeY: 400, flatY: 400 };
describe('globeMath', () => {
it('wraps angles into [-pi, pi)', () => {
expect(wrapPi(0)).toBe(0);
expect(wrapPi(Math.PI * 3)).toBeCloseTo(-Math.PI);
expect(wrapPi(-Math.PI * 1.5)).toBeCloseTo(Math.PI / 2);
});
it('is a globe below the morph and a flat map above it', () => {
expect(morphOf(1)).toBe(0);
expect(morphOf(MORPH_START)).toBe(0);
expect(morphOf(MORPH_END)).toBe(1);
const mid = morphOf((MORPH_START + MORPH_END) / 2);
expect(mid).toBeGreaterThan(0.4);
expect(mid).toBeLessThan(0.6);
});
it('puts the centre of the camera on the screen centre, on the globe and flat', () => {
for (const zoom of [1, 6]) {
const f = frameParams({ lon: 10, lat: 45, zoom }, VP);
const p = projectPoint(10, 45, f);
expect(p.x).toBeCloseTo(500, 3);
expect(p.y).toBeCloseTo(400, 3);
expect(p.visible).toBeGreaterThan(0);
}
});
it('hides the far side of the globe', () => {
const f = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP);
expect(projectPoint(180, 0, f).visible).toBeLessThan(0);
expect(projectPoint(60, 0, f).visible).toBeGreaterThan(0);
// An orthographic globe: 90 degrees east sits on the limb, one radius away.
expect(projectPoint(89.9, 0, f).x).toBeCloseTo(800, 0);
});
it('keeps proportions at the centre latitude once flat', () => {
const f = frameParams({ lon: 10, lat: 50, zoom: 8 }, VP);
const a = projectPoint(10, 50, f);
const east = projectPoint(11, 50, f);
const north = projectPoint(10, 51, f);
const dx = east.x - a.x;
const dy = a.y - north.y;
// One degree east is cos(50 deg) of one degree north, as on the ground.
expect(dx / dy).toBeCloseTo(Math.cos((50 * Math.PI) / 180), 2);
expect(xSqueeze(f)).toBeCloseTo(Math.cos((50 * Math.PI) / 180), 3);
});
it('does not tear a shape across the back of the globe', () => {
const f = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP);
// Both sides of the antimeridian, unwrapped against one reference, stay apart by
// their real distance rather than flipping to opposite screen edges.
const a = projectPoint(179, 10, f, 179, 10);
const b = projectPoint(-179, 10, f, 179, 10);
expect(Math.abs(a.x - b.x)).toBeLessThan(20);
});
it('measures great circles', () => {
expect(angularDistance(0, 0, 90, 0)).toBeCloseTo(Math.PI / 2);
const [lon, lat] = interpolateGreatCircle(0, 0, 90, 0, 0.5);
expect(lon).toBeCloseTo(45);
expect(lat).toBeCloseTo(0);
});
it('cuts an arc into lifted, ordered segments', () => {
const { data, count } = arcSegments([{ a: [8.57, 50.03], b: [-73.78, 40.64] }], 10);
expect(count).toBe(10);
// Lift is zero at both airports and highest in the middle.
expect(data[4]).toBe(0);
expect(data[(count - 1) * 8 + 5]).toBeCloseTo(0, 6);
expect(data[5 * 8 + 4]).toBeGreaterThan(data[1 * 8 + 4]);
// Progress runs from 0 to 1.
expect(data[6]).toBe(0);
expect(data[(count - 1) * 8 + 7]).toBe(1);
});
it('points the sun at the right hemisphere through the year', () => {
const june = sunVector(new Date(Date.UTC(2026, 5, 21, 12)));
const december = sunVector(new Date(Date.UTC(2026, 11, 21, 12)));
expect(Math.hypot(...june)).toBeCloseTo(1);
expect(june[2]).toBeGreaterThan(0.38);
expect(december[2]).toBeLessThan(-0.38);
// Around noon UTC the sun stands near the Greenwich meridian.
const lon = (Math.atan2(june[1], june[0]) * 180) / Math.PI;
expect(Math.abs(lon)).toBeLessThan(10);
});
it('knows the moon phase', () => {
const full = moonPhase(new Date(Date.UTC(2026, 0, 3, 10)));
expect(full.lit).toBeGreaterThan(0.95);
const fresh = moonPhase(new Date(Date.UTC(2026, 0, 18, 19)));
expect(fresh.lit).toBeLessThan(0.05);
});
});
@@ -0,0 +1,235 @@
/**
* The Atlas globe projection, in plain numbers. The vertex shaders in
* globeShaders.ts run the same formula on the GPU; this copy places labels,
* hit-tests the camera and is what the unit tests pin.
*
* One parameter `t` morphs an orthographic globe (t = 0) into an
* equirectangular map (t = 1) without a cut: the sphere first turns so the
* centre latitude sits on the equator by (1 - t), then the hemisphere unrolls
* with x = sin(k·λ)/k, which is the globe at k = 1 and the flat map as k → 0.
*/
export const RAD = Math.PI / 180;
const TAU = Math.PI * 2;
/** Zoom where the globe starts to unroll and where it lies flat. */
export const MORPH_START = 1.35;
export const MORPH_END = 2.6;
export const MIN_ZOOM = 0.85;
export const MAX_ZOOM = 32;
export interface GlobeCamera {
/** Centre longitude and latitude in degrees. */
lon: number;
lat: number;
/** 1 = the whole globe fits; higher zooms in. */
zoom: number;
}
export interface GlobeViewport {
/** Size in CSS pixels. */
width: number;
height: number;
/** Globe radius at zoom 1, CSS pixels. */
baseRadius: number;
/** Screen position of the globe centre at t = 0 and of the map centre at t = 1. */
globeY: number;
flatY: number;
}
export function smoothstep(a: number, b: number, x: number): number {
const t = Math.max(0, Math.min(1, (x - a) / (b - a)));
return t * t * (3 - 2 * t);
}
export function morphOf(zoom: number): number {
return smoothstep(MORPH_START, MORPH_END, zoom);
}
export function wrapPi(a: number): number {
return a - TAU * Math.floor((a + Math.PI) / TAU);
}
export interface FrameParams {
t: number;
k: number;
scale: number;
originX: number;
originY: number;
centerLon: number;
centerLat: number;
}
export function frameParams(cam: GlobeCamera, vp: GlobeViewport): FrameParams {
const t = morphOf(cam.zoom);
return {
t,
k: 1 - t * 0.9995,
scale: vp.baseRadius * cam.zoom,
originX: vp.width / 2,
originY: vp.globeY + (vp.flatY - vp.globeY) * t,
centerLon: cam.lon * RAD,
centerLat: cam.lat * RAD,
};
}
export interface ScreenPoint {
x: number;
y: number;
/** Positive while the point is on the visible side; larger is further from the edge. */
visible: number;
/** 1 facing the viewer, 0 at the limb (globe); 1 everywhere once flat. */
shade: number;
}
/**
* Projects a point given in degrees. `refLon/refLat` is the point the
* longitude is unwrapped against (the polygon or segment it belongs to), so a
* shape that crosses the back of the globe never tears across the screen.
*/
export function projectPoint(
lonDeg: number,
latDeg: number,
f: FrameParams,
refLonDeg = lonDeg,
refLatDeg = latDeg
): ScreenPoint {
const lon = lonDeg * RAD;
const lat = latDeg * RAD;
const refLon = refLonDeg * RAD;
const refLat = refLatDeg * RAD;
const phiR = f.centerLat * (1 - f.t);
const cphi = Math.cos(phiR);
const sphi = Math.sin(phiR);
const dlr = wrapPi(refLon - f.centerLon);
const dl = dlr + wrapPi(lon - f.centerLon - dlr);
const cl = Math.cos(lat);
const px = cl * Math.sin(dl);
const py = Math.sin(lat);
const pz = cl * Math.cos(dl);
const qy = py * cphi - pz * sphi;
const qz = py * sphi + pz * cphi;
let lam = Math.atan2(px, qz);
const phi = Math.asin(Math.max(-1, Math.min(1, qy)));
const cr = Math.cos(refLat);
const rx = cr * Math.sin(dlr);
const rz = Math.sin(refLat) * sphi + cr * Math.cos(dlr) * cphi;
const lamR = Math.atan2(rx, rz);
lam = lamR + wrapPi(lam - lamR);
const x = (Math.sin(f.k * lam) / f.k) * (Math.cos(phi) * (1 - f.t) + f.t) * xSqueeze(f);
const y = Math.sin(phi) * (1 - f.t) + phi * f.t;
const c = Math.acos(Math.max(-1, Math.min(1, Math.cos(phi) * Math.cos(lam))));
const lim = Math.min(Math.PI, (0.5 * Math.PI) / f.k);
return {
x: f.originX + x * f.scale,
y: f.originY - (y - f.centerLat * f.t) * f.scale,
visible: Math.abs(lam) <= Math.PI ? lim - c : -1,
shade: Math.max(0, Math.cos(c)) * (1 - f.t) + f.t,
};
}
/** How much the flat map squeezes longitude: the cosine of the centre latitude. */
export function xSqueeze(f: FrameParams): number {
return 1 + (Math.max(0.3, Math.cos(f.centerLat)) - 1) * f.t;
}
/** Great-circle distance in radians between two points given in degrees. */
export function angularDistance(lon1: number, lat1: number, lon2: number, lat2: number): number {
const a1 = lat1 * RAD;
const a2 = lat2 * RAD;
const d = (lon2 - lon1) * RAD;
const c = Math.sin(a1) * Math.sin(a2) + Math.cos(a1) * Math.cos(a2) * Math.cos(d);
return Math.acos(Math.max(-1, Math.min(1, c)));
}
/** Point along the great circle from a to b at fraction s (degrees in, degrees out). */
export function interpolateGreatCircle(
lon1: number,
lat1: number,
lon2: number,
lat2: number,
s: number
): [number, number] {
const p1 = [
Math.cos(lat1 * RAD) * Math.cos(lon1 * RAD),
Math.cos(lat1 * RAD) * Math.sin(lon1 * RAD),
Math.sin(lat1 * RAD),
];
const p2 = [
Math.cos(lat2 * RAD) * Math.cos(lon2 * RAD),
Math.cos(lat2 * RAD) * Math.sin(lon2 * RAD),
Math.sin(lat2 * RAD),
];
const d = angularDistance(lon1, lat1, lon2, lat2);
if (d < 1e-9) return [lon1, lat1];
const a = Math.sin((1 - s) * d) / Math.sin(d);
const b = Math.sin(s * d) / Math.sin(d);
const x = a * p1[0] + b * p2[0];
const y = a * p1[1] + b * p2[1];
const z = a * p1[2] + b * p2[2];
return [Math.atan2(y, x) / RAD, Math.atan2(z, Math.hypot(x, y)) / RAD];
}
/**
* Unit vector to the sun in earth-fixed coordinates (x towards 0°/0°, z north)
* for a moment in time. Low-precision solar position, good to a fraction of a
* degree, which is plenty for a day/night line.
*/
export function sunVector(date: Date): [number, number, number] {
const d = date.getTime() / 86400000 - 10957.5; // days since J2000
const g = (357.529 + 0.98560028 * d) * RAD;
const q = 280.459 + 0.98564736 * d;
const L = (q + 1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g)) * RAD;
const e = (23.439 - 0.00000036 * d) * RAD;
const decl = Math.asin(Math.sin(e) * Math.sin(L));
const ra = Math.atan2(Math.cos(e) * Math.sin(L), Math.cos(L));
const gmst = ((280.46061837 + 360.98564736629 * d) % 360) * RAD;
const lon = ra - gmst;
return [Math.cos(decl) * Math.cos(lon), Math.cos(decl) * Math.sin(lon), Math.sin(decl)];
}
/** Moon phase 0..1 (0 new, 0.5 full) and illuminated share, for a moment in time. */
export function moonPhase(date: Date): { phase: number; lit: number } {
const synodic = 29.530588853;
const ref = Date.UTC(2000, 0, 6, 18, 14);
const days = (date.getTime() - ref) / 86400000;
const phase = (((days % synodic) + synodic) % synodic) / synodic;
return { phase, lit: (1 - Math.cos(phase * 2 * Math.PI)) / 2 };
}
/**
* A flight arc as instanced segments for the line shader: per segment
* a.lon, a.lat, b.lon, b.lat (radians), lift at a and b, and the share of the
* arc reached at a and b (so the arc can draw itself in).
*/
export function arcSegments(
routes: Array<{ a: [number, number]; b: [number, number] }>,
steps = 48
): { data: Float32Array; count: number } {
const out = new Float32Array(routes.length * steps * 8);
let o = 0;
for (const r of routes) {
const d = angularDistance(r.a[0], r.a[1], r.b[0], r.b[1]);
const peak = 0.015 + d * 0.06;
let prev = interpolateGreatCircle(r.a[0], r.a[1], r.b[0], r.b[1], 0);
for (let i = 1; i <= steps; i++) {
const s0 = (i - 1) / steps;
const s1 = i / steps;
const next = interpolateGreatCircle(r.a[0], r.a[1], r.b[0], r.b[1], s1);
out[o++] = prev[0] * RAD;
out[o++] = prev[1] * RAD;
out[o++] = next[0] * RAD;
out[o++] = next[1] * RAD;
out[o++] = peak * Math.sin(Math.PI * s0);
out[o++] = peak * Math.sin(Math.PI * s1);
out[o++] = s0;
out[o++] = s1;
prev = next;
}
}
return { data: out, count: o / 8 };
}
@@ -0,0 +1,85 @@
import type { Topology } from 'topojson-specification';
import { describe, expect, it } from 'vitest';
import { buildLayer, buildOcean, densify, tessellate } from './globeMesh';
/** Two squares sharing one edge, as TopoJSON with that edge stored once. */
const TWO_SQUARES: Topology = {
type: 'Topology',
arcs: [
[
[10, 0],
[10, 10],
], // shared
[
[10, 10],
[0, 10],
[0, 0],
[10, 0],
],
[
[10, 0],
[20, 0],
[20, 10],
[10, 10],
],
],
objects: {
countries: {
type: 'GeometryCollection',
geometries: [
{ type: 'Polygon', id: 0, arcs: [[0, 1]] },
{ type: 'Polygon', id: 1, arcs: [[~0, 2]] },
],
},
},
};
describe('globeMesh', () => {
it('splits triangles until every edge is short enough', () => {
const coords = [0, 0, 40, 0, 0, 40];
const tris = tessellate(coords, [0, 1, 2], 8);
for (let i = 0; i < tris.length; i += 3) {
const [a, b, c] = [tris[i], tris[i + 1], tris[i + 2]];
for (const [p, q] of [
[a, b],
[b, c],
[c, a],
]) {
expect(Math.hypot(coords[p * 2] - coords[q * 2], coords[p * 2 + 1] - coords[q * 2 + 1])).toBeLessThanOrEqual(
8 + 1e-9
);
}
}
expect(tris.length / 3).toBeGreaterThan(10);
});
it('densifies lines without moving their ends', () => {
const d = densify(
[
[0, 0],
[10, 0],
],
2
);
expect(d).toHaveLength(6);
expect(d[0]).toEqual([0, 0]);
expect(d[5]).toEqual([10, 0]);
});
it('builds fills with the right ids and the shared border once', () => {
const layer = buildLayer(TWO_SQUARES, 'countries', 100, (n) => 40 + n);
const ids = new Set(Array.from(layer.fill.fid));
expect(ids).toEqual(new Set([40, 41]));
expect(layer.fill.index.length % 3).toBe(0);
// The shared edge is one border segment, the outline is the coast.
expect(layer.borders.count).toBe(1);
expect(layer.coast.count).toBeGreaterThanOrEqual(6);
// Everything leaves in radians.
expect(Math.max(...Array.from(layer.fill.ll))).toBeLessThanOrEqual((20 * Math.PI) / 180 + 1e-6);
});
it('covers the whole sphere with the ocean grid', () => {
const o = buildOcean(30);
expect(o.index.length).toBe((360 / 30) * (180 / 30) * 6);
});
});
@@ -0,0 +1,220 @@
/**
* Turns a TopoJSON level of detail into GPU-ready arrays: triangles for the
* fills, segments for the borders. Pure, so the worker and the tests share it.
*
* Coordinates leave here in radians. Each fill vertex carries the centre of its
* polygon as the reference the shader unwraps longitude against, so a polygon
* that crosses the back of the globe stays in one piece.
*/
import earcut from 'earcut';
import type { LineString, MultiLineString, MultiPolygon, Polygon, Position } from 'geojson';
import { feature, mesh } from 'topojson-client';
import type { GeometryCollection, Topology } from 'topojson-specification';
const RAD = Math.PI / 180;
export interface FillMesh {
/** lon, lat per vertex (radians) */
ll: Float32Array;
/** reference lon, lat per vertex (radians) */
ref: Float32Array;
/** feature id per vertex */
fid: Float32Array;
index: Uint32Array;
}
export interface LineMesh {
/** per segment: a.lon, a.lat, b.lon, b.lat (radians) */
seg: Float32Array;
count: number;
}
export interface BuiltLayer {
fill: FillMesh;
coast: LineMesh;
borders: LineMesh;
}
/** Splits triangles until no edge is longer than maxEdge degrees, so they bend with the sphere. */
export function tessellate(coords: number[], tris: number[], maxEdge: number): number[] {
const out: number[] = [];
const mid = new Map<string, number>();
const midpoint = (a: number, b: number): number => {
const key = a < b ? `${a}:${b}` : `${b}:${a}`;
let m = mid.get(key);
if (m === undefined) {
m = coords.length / 2;
coords.push((coords[a * 2] + coords[b * 2]) / 2, (coords[a * 2 + 1] + coords[b * 2 + 1]) / 2);
mid.set(key, m);
}
return m;
};
const len = (a: number, b: number): number =>
Math.hypot(coords[a * 2] - coords[b * 2], coords[a * 2 + 1] - coords[b * 2 + 1]);
const stack: Array<[number, number, number]> = [];
for (let i = 0; i < tris.length; i += 3) stack.push([tris[i], tris[i + 1], tris[i + 2]]);
while (stack.length) {
const [a, b, c] = stack.pop() as [number, number, number];
const ab = len(a, b);
const bc = len(b, c);
const ca = len(c, a);
const m = Math.max(ab, bc, ca);
if (m <= maxEdge) {
out.push(a, b, c);
} else if (m === ab) {
const d = midpoint(a, b);
stack.push([a, d, c], [d, b, c]);
} else if (m === bc) {
const d = midpoint(b, c);
stack.push([a, b, d], [a, d, c]);
} else {
const d = midpoint(c, a);
stack.push([a, b, d], [d, b, c]);
}
}
return out;
}
/** Inserts points so no segment is longer than maxEdge degrees. */
export function densify(line: Position[], maxEdge: number): Position[] {
const out: Position[] = [line[0]];
for (let i = 1; i < line.length; i++) {
const [x0, y0] = line[i - 1];
const [x1, y1] = line[i];
const n = Math.max(1, Math.ceil(Math.hypot(x1 - x0, y1 - y0) / maxEdge));
for (let k = 1; k <= n; k++) out.push([x0 + ((x1 - x0) * k) / n, y0 + ((y1 - y0) * k) / n]);
}
return out;
}
function polygonsOf(g: Polygon | MultiPolygon | null): Position[][][] {
if (!g) return [];
return g.type === 'Polygon' ? [g.coordinates] : g.coordinates;
}
function centreOf(ring: Position[]): [number, number] {
let w = Infinity;
let e = -Infinity;
let s = Infinity;
let n = -Infinity;
for (const [x, y] of ring) {
if (x < w) w = x;
if (x > e) e = x;
if (y < s) s = y;
if (y > n) n = y;
}
return [(w + e) / 2, (s + n) / 2];
}
class Grow {
data: Float32Array;
length = 0;
constructor(n = 4096) {
this.data = new Float32Array(n);
}
push(...v: number[]): void {
if (this.length + v.length > this.data.length) {
const next = new Float32Array(Math.max(this.data.length * 2, this.length + v.length));
next.set(this.data);
this.data = next;
}
for (const x of v) this.data[this.length++] = x;
}
done(): Float32Array {
return this.data.slice(0, this.length);
}
}
function linesOf(ml: MultiLineString | LineString, maxEdge: number): LineMesh {
const seg = new Grow();
const parts = ml.type === 'MultiLineString' ? ml.coordinates : [ml.coordinates];
for (const part of parts) {
if (part.length < 2) continue;
const d = densify(part, maxEdge);
for (let i = 1; i < d.length; i++) seg.push(d[i - 1][0] * RAD, d[i - 1][1] * RAD, d[i][0] * RAD, d[i][1] * RAD);
}
const arr = seg.done();
return { seg: arr, count: arr.length / 4 };
}
/**
* Builds one layer. `ids` maps a topology feature's numeric id to the id the
* status texture knows it by (countries: their manifest index; regions: a block
* reserved for that country).
*/
export function buildLayer(
topo: Topology,
objectName: string,
maxEdge: number,
ids: (topoId: number) => number
): BuiltLayer {
const obj = topo.objects[objectName] as GeometryCollection;
const fc = feature(topo, obj);
const ll = new Grow(1 << 16);
const ref = new Grow(1 << 16);
const fid = new Grow(1 << 15);
let index: number[] = [];
let vbase = 0;
for (const f of fc.features) {
const id = ids(Number(f.id));
for (const poly of polygonsOf(f.geometry as Polygon | MultiPolygon)) {
if (!poly.length || poly[0].length < 4) continue;
const flat: number[] = [];
const holes: number[] = [];
poly.forEach((ring, ri) => {
if (ri > 0) holes.push(flat.length / 2);
for (let i = 0; i < ring.length - 1; i++) flat.push(ring[i][0], ring[i][1]);
});
const tris = tessellate(flat, earcut(flat, holes, 2), maxEdge);
const [cx, cy] = centreOf(poly[0]);
for (let i = 0; i < flat.length; i += 2) {
ll.push(flat[i] * RAD, flat[i + 1] * RAD);
ref.push(cx * RAD, cy * RAD);
fid.push(id);
}
for (const t of tris) index.push(vbase + t);
vbase += flat.length / 2;
}
if (index.length > 1 << 20) index = index.slice();
}
const coast = mesh(topo, obj, (a, b) => a === b) as MultiLineString;
const borders = mesh(topo, obj, (a, b) => a !== b) as MultiLineString;
return {
fill: { ll: ll.done(), ref: ref.done(), fid: fid.done(), index: Uint32Array.from(index) },
coast: linesOf(coast, maxEdge),
borders: linesOf(borders, maxEdge),
};
}
/** A latitude/longitude grid over the whole sphere, the ocean the land sits on. */
export function buildOcean(step = 6): FillMesh {
const ll: number[] = [];
const ref: number[] = [];
const fid: number[] = [];
const index: number[] = [];
let v = 0;
for (let lon = -180; lon < 180; lon += step) {
for (let lat = -90; lat < 90; lat += step) {
const cx = (lon + step / 2) * RAD;
const cy = (lat + step / 2) * RAD;
for (const [x, y] of [
[lon, lat],
[lon + step, lat],
[lon + step, lat + step],
[lon, lat + step],
]) {
ll.push(x * RAD, Math.min(90, y) * RAD);
ref.push(cx, cy);
fid.push(0);
}
index.push(v, v + 1, v + 2, v, v + 2, v + 3);
v += 4;
}
}
return {
ll: Float32Array.from(ll),
ref: Float32Array.from(ref),
fid: Float32Array.from(fid),
index: Uint32Array.from(index),
};
}
@@ -0,0 +1,43 @@
/// <reference lib="webworker" />
/**
* Builds globe layers off the main thread. The main thread fetches the
* topology (it owns auth and the API base) and hands it over; this worker
* triangulates and sends the arrays back as transferables.
*/
import type { Topology } from 'topojson-specification';
import { buildLayer, type BuiltLayer } from './globeMesh';
export interface MeshRequest {
job: number;
topo: Topology;
object: string;
maxEdge: number;
/** Status-texture id of topology feature 0; feature n gets idBase + n. */
idBase: number;
}
export interface MeshResponse {
job: number;
layer?: BuiltLayer;
error?: string;
}
const scope = self as unknown as DedicatedWorkerGlobalScope;
scope.onmessage = (e: MessageEvent<MeshRequest>) => {
const { job, topo, object, maxEdge, idBase } = e.data;
try {
const layer = buildLayer(topo, object, maxEdge, (n) => idBase + n);
const transfer = [
layer.fill.ll.buffer,
layer.fill.ref.buffer,
layer.fill.fid.buffer,
layer.fill.index.buffer,
layer.coast.seg.buffer,
layer.borders.seg.buffer,
];
scope.postMessage({ job, layer } satisfies MeshResponse, transfer);
} catch (err) {
scope.postMessage({ job, error: err instanceof Error ? err.message : String(err) } satisfies MeshResponse);
}
};
@@ -0,0 +1,308 @@
/**
* GLSL for the Atlas globe. PROJECT is the GPU twin of projectPoint() in
* globeMath.ts; a change to one belongs in the other.
*/
const PROJECT = /* glsl */ `
uniform vec2 u_center; // centre lon, lat in radians
uniform float u_t; // 0 globe .. 1 flat map
uniform float u_scale; // device px per radian
uniform vec2 u_origin; // device px of the centre
uniform vec2 u_viewport; // device px
const float PI = 3.14159265;
float wrapPi(float a) { return a - 2.0 * PI * floor((a + PI) / (2.0 * PI)); }
// xy: screen px, z: visibility (> 0 visible), w: shade
vec4 project(vec2 ll, vec2 ref) {
float k = 1.0 - u_t * 0.9995;
float phiR = u_center.y * (1.0 - u_t);
float cphi = cos(phiR), sphi = sin(phiR);
float dlr = wrapPi(ref.x - u_center.x);
float dl = dlr + wrapPi(ll.x - u_center.x - dlr);
float cl = cos(ll.y);
vec3 p = vec3(cl * sin(dl), sin(ll.y), cl * cos(dl));
float qy = p.y * cphi - p.z * sphi;
float qz = p.y * sphi + p.z * cphi;
float lam = atan(p.x, qz);
float phi = asin(clamp(qy, -1.0, 1.0));
float cr = cos(ref.y);
float lamR = atan(cr * sin(dlr), sin(ref.y) * sphi + cr * cos(dlr) * cphi);
lam = lamR + wrapPi(lam - lamR);
// Flat, longitude is squeezed by the cosine of the centre latitude, so shapes keep
// their proportions where the user looks instead of widening towards the poles.
float xs = mix(1.0, max(0.3, cos(u_center.y)), u_t);
float x = sin(k * lam) / k * (cos(phi) * (1.0 - u_t) + u_t) * xs;
float y = sin(phi) * (1.0 - u_t) + phi * u_t;
vec2 s = u_origin + vec2(x, -(y - u_center.y * u_t)) * u_scale;
float c = acos(clamp(cos(phi) * cos(lam), -1.0, 1.0));
float lim = min(PI, 0.5 * PI / k);
float vis = abs(lam) <= PI ? lim - c : -1.0;
float shade = max(0.0, cos(c)) * (1.0 - u_t) + u_t;
return vec4(s, vis, shade);
}
vec4 toClip(vec2 s) {
return vec4(s.x / u_viewport.x * 2.0 - 1.0, 1.0 - s.y / u_viewport.y * 2.0, 0.0, 1.0);
}
`;
export const FILL_VS = /* glsl */ `#version 300 es
precision highp float;
${PROJECT}
in vec2 a_ll; // radians
in vec2 a_ref; // radians
in float a_fid;
out float v_vis;
out float v_shade;
out vec2 v_ll;
flat out int v_fid;
void main() {
vec4 p = project(a_ll, a_ref);
v_vis = p.z;
v_shade = p.w;
v_ll = a_ll;
v_fid = int(a_fid + 0.5);
gl_Position = toClip(p.xy);
}
`;
export const FILL_FS = /* glsl */ `#version 300 es
precision highp float;
precision highp usampler2D;
in float v_vis;
in float v_shade;
in vec2 v_ll;
flat in int v_fid;
uniform sampler2D u_status; // rgb colour, a strength
uniform sampler2D u_fx; // r hatch, g reveal order, b outline flag
uniform int u_mode; // 0 land, 1 ocean, 2 region layer
uniform vec3 u_land;
uniform vec3 u_ocean;
uniform vec3 u_oceanDeep;
uniform float u_layerAlpha;
uniform float u_time;
uniform float u_revealStart;
uniform int u_hover;
uniform int u_selected;
uniform int u_inkId;
uniform vec2 u_inkLL;
uniform float u_inkR;
uniform float u_dpr;
uniform float u_t;
uniform float u_dimBase;
uniform float u_regionFade;
uniform vec3 u_sun; // unit vector to the sun, earth-fixed
uniform float u_night; // how strongly the night side darkens
uniform float u_shadeMin; // brightness at the limb (light mode keeps it high)
uniform vec4 u_hoverTint; // rgb + strength; selection uses 1.8x the strength
out vec4 outColor;
vec4 fetch(sampler2D tex, int id) { return texelFetch(tex, ivec2(id % 256, id / 256), 0); }
void main() {
if (v_vis < 0.0) discard;
float edge = smoothstep(0.0, 0.004, v_vis);
float light = mix(u_shadeMin, 1.0, pow(v_shade, 0.65));
vec3 nrm = vec3(cos(v_ll.y) * cos(v_ll.x), cos(v_ll.y) * sin(v_ll.x), sin(v_ll.y));
float sunDot = dot(nrm, u_sun);
float day = smoothstep(-0.12, 0.1, sunDot);
float nightMul = mix(1.0 - u_night, 1.0, day);
if (u_mode == 1) {
vec3 col = mix(u_oceanDeep, u_ocean, pow(v_shade, 0.9));
col *= mix(1.0 - u_night * 0.7, 1.0, day);
// A faint glint where the sun stands over the sea.
col += vec3(0.35, 0.45, 0.6) * pow(max(0.0, sunDot), 40.0) * 0.25 * (1.0 - u_t) * v_shade;
outColor = vec4(col, edge);
return;
}
vec4 st = fetch(u_status, v_fid);
vec4 fx = fetch(u_fx, v_fid);
float reveal = clamp((u_time - u_revealStart - fx.g * 1.6) / 0.45, 0.0, 1.0);
float a = st.a * reveal;
if (v_fid == u_inkId) {
vec3 p1 = vec3(cos(v_ll.y) * cos(v_ll.x), cos(v_ll.y) * sin(v_ll.x), sin(v_ll.y));
vec3 p2 = vec3(cos(u_inkLL.y) * cos(u_inkLL.x), cos(u_inkLL.y) * sin(u_inkLL.x), sin(u_inkLL.y));
float d = acos(clamp(dot(p1, p2), -1.0, 1.0));
a *= 1.0 - smoothstep(u_inkR - 0.01, u_inkR, d);
}
// A country whose regions are on screen steps back so its regions read.
if (u_mode == 0 && fx.b > 0.5) a *= 1.0 - 0.32 * u_regionFade;
vec3 base = u_land * (u_mode == 2 ? 1.0 : u_dimBase);
vec3 col = mix(base, st.rgb, a);
if (fx.r > 0.5) {
float h = step(mod(gl_FragCoord.x + gl_FragCoord.y, 7.0 * u_dpr), 1.6 * u_dpr);
col = mix(col, st.rgb, h * 0.9 * reveal);
a = max(a, h * 0.9 * reveal);
}
if (v_fid == u_selected) col = mix(col, u_hoverTint.rgb, u_hoverTint.a * 1.8);
else if (v_fid == u_hover) col = mix(col, u_hoverTint.rgb, u_hoverTint.a);
col *= light;
// Night darkens the land; what you marked keeps most of its colour, like lights on.
col *= mix(nightMul, 1.0, a * 0.75);
float alpha = edge;
if (u_mode == 2) alpha *= u_layerAlpha * max(a, (v_fid == u_hover || v_fid == u_selected) ? 0.25 : 0.0);
outColor = vec4(col, alpha);
}
`;
export const PICK_FS = /* glsl */ `#version 300 es
precision highp float;
in float v_vis;
in float v_shade;
in vec2 v_ll;
flat in int v_fid;
uniform int u_idBase;
out vec4 outColor;
void main() {
if (v_vis < 0.0) discard;
int id = v_fid + 1;
outColor = vec4(float(id & 255) / 255.0, float((id >> 8) & 255) / 255.0, float((id >> 16) & 255) / 255.0, 1.0);
}
`;
/** Instanced screen-space lines: borders, coasts, outlines and flight arcs. */
export const LINE_VS = /* glsl */ `#version 300 es
precision highp float;
${PROJECT}
in vec2 a_corner; // x: 0 start .. 1 end, y: -1 .. 1 across
in vec2 a_a; // radians
in vec2 a_b; // radians
in vec2 a_h; // lift of a and b (arcs), share of the radius
in vec2 a_s; // position along the whole line, 0..1, at a and b
uniform float u_width; // device px
uniform float u_lift; // 1 lifts arcs above the surface
out float v_vis;
out float v_across;
out float v_s;
out float v_shade;
vec2 lifted(vec4 p, float h) {
vec2 d = p.xy - u_origin;
vec2 globe = u_origin + d * (1.0 + h);
vec2 flat2 = p.xy - vec2(0.0, h * u_scale * 0.35);
return mix(globe, flat2, u_t);
}
void main() {
vec2 mid = (a_a + a_b) * 0.5;
if (abs(a_a.x - a_b.x) > PI) mid.x = a_a.x;
vec4 pa = project(a_a, mid);
vec4 pb = project(a_b, mid);
vec2 sa = u_lift > 0.5 ? lifted(pa, a_h.x) : pa.xy;
vec2 sb = u_lift > 0.5 ? lifted(pb, a_h.y) : pb.xy;
vec2 dir = sb - sa;
float len = length(dir);
dir = len > 1e-5 ? dir / len : vec2(1.0, 0.0);
vec2 n = vec2(-dir.y, dir.x);
vec2 s = mix(sa, sb, a_corner.x) + n * a_corner.y * (u_width * 0.5 + 1.0) + dir * (a_corner.x * 2.0 - 1.0) * 0.5;
float hv = mix(a_h.x, a_h.y, a_corner.x);
v_vis = mix(pa.z, pb.z, a_corner.x) + (u_lift > 0.5 ? hv * 0.6 : 0.0);
v_across = a_corner.y * (u_width * 0.5 + 1.0);
v_s = mix(a_s.x, a_s.y, a_corner.x);
v_shade = mix(pa.w, pb.w, a_corner.x);
gl_Position = toClip(s);
}
`;
export const LINE_FS = /* glsl */ `#version 300 es
precision highp float;
in float v_vis;
in float v_across;
in float v_s;
in float v_shade;
uniform vec4 u_color;
uniform float u_width;
uniform float u_progress; // draws the line up to this share (arcs drawing in)
uniform float u_glow;
out vec4 outColor;
void main() {
if (v_vis < 0.0 || v_s > u_progress) discard;
float d = abs(v_across);
float core = 1.0 - smoothstep(u_width * 0.5 - 0.5, u_width * 0.5 + 0.5, d);
float a = core;
if (u_glow > 0.0) a = max(core, exp(-d * d / (u_width * u_width * 1.2)) * u_glow);
float limb = smoothstep(0.0, 0.03, v_vis);
outColor = vec4(u_color.rgb, u_color.a * a * limb * mix(0.55, 1.0, v_shade));
}
`;
/** Full-screen quad for the backdrop: deep space, stars, atmosphere. */
export const SKY_VS = /* glsl */ `#version 300 es
precision highp float;
in vec2 a_pos;
out vec2 v_uv;
void main() {
v_uv = a_pos * 0.5 + 0.5;
gl_Position = vec4(a_pos, 0.0, 1.0);
}
`;
export const SKY_FS = /* glsl */ `#version 300 es
precision highp float;
in vec2 v_uv;
uniform vec2 u_viewport; // device px
uniform vec2 u_globe; // device px of the globe centre
uniform float u_radius; // device px
uniform float u_t;
uniform float u_time;
uniform vec2 u_drift; // parallax from the camera, radians
uniform vec3 u_space0;
uniform vec3 u_space1;
uniform vec3 u_glow;
uniform float u_dark;
out vec4 outColor;
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
float stars(vec2 px, float cell, float density, float size) {
vec2 g = floor(px / cell);
vec2 f = fract(px / cell);
float h = hash(g);
if (h > density) return 0.0;
vec2 c = vec2(hash(g + 3.1), hash(g + 7.7)) * 0.8 + 0.1;
float d = length(f - c) * cell;
float tw = 0.65 + 0.35 * sin(u_time * (0.6 + h * 2.0) + h * 40.0);
return smoothstep(size, 0.0, d) * tw * (0.4 + 0.6 * hash(g + 1.3));
}
void main() {
vec2 px = v_uv * u_viewport;
px.y = u_viewport.y - px.y;
float r = length(px - u_globe);
vec3 col = mix(u_space1, u_space0, smoothstep(0.0, max(u_viewport.x, u_viewport.y) * 0.8, r));
float sky = (1.0 - u_t * 0.9) * u_dark;
// Milky way: a soft band across the sky, drifting with the camera.
vec2 q = px / u_viewport.y + u_drift * vec2(0.08, 0.05);
float band = exp(-pow((q.y - 0.35 - 0.45 * q.x + 0.25) * 3.2, 2.0));
float dust = hash(floor(px * 0.5)) * 0.5 + 0.5;
col += vec3(0.20, 0.24, 0.42) * band * 0.10 * sky * dust;
vec2 sp = px + u_drift * vec2(60.0, 40.0) * u_viewport.y / 900.0;
float s = stars(sp, 38.0, 0.20, 1.6) + stars(sp * 1.7 + 13.0, 31.0, 0.12, 1.1) * 0.7 + band * stars(sp * 2.3 + 5.0, 17.0, 0.35, 0.9) * 0.8;
col += vec3(0.85, 0.9, 1.0) * s * sky;
// Atmosphere: a glow hugging the globe, gone once the map lies flat.
float atm = (1.0 - smoothstep(0.0, 0.7, u_t));
float outside = smoothstep(u_radius * 0.985, u_radius * 1.0, r);
float glow = exp(-max(0.0, r - u_radius) / (u_radius * 0.075)) * outside;
col += u_glow * glow * 0.55 * atm;
outColor = vec4(col, 1.0);
}
`;
/** A thin bright rim on the limb, drawn over the globe. */
export const RIM_FS = /* glsl */ `#version 300 es
precision highp float;
in vec2 v_uv;
uniform vec2 u_viewport;
uniform vec2 u_globe;
uniform float u_radius;
uniform float u_t;
uniform vec3 u_glow;
out vec4 outColor;
void main() {
vec2 px = v_uv * u_viewport;
px.y = u_viewport.y - px.y;
float r = length(px - u_globe);
float inner = smoothstep(u_radius * 0.82, u_radius, r) * (1.0 - smoothstep(u_radius, u_radius * 1.004, r));
float a = pow(inner, 3.0) * 0.55 * (1.0 - smoothstep(0.0, 0.5, u_t));
outColor = vec4(u_glow, a);
}
`;
@@ -0,0 +1,65 @@
/**
* Map paint for the Atlas globe. These are rendering colours for WebGL, not UI
* surfaces, so they are numbers here rather than appearance tokens; the accent
* is read from the live --accent token so the globe follows the user's scheme.
*/
import type { GlobeTheme, Rgb } from './GlobeRenderer';
export function hexToRgb(hex: string): Rgb {
const h = hex.replace('#', '').trim();
const full =
h.length === 3
? h
.split('')
.map((c) => c + c)
.join('')
: h.slice(0, 6);
const n = parseInt(full, 16);
if (Number.isNaN(n)) return [0.5, 0.5, 0.5];
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}
export function rgbToBytes(c: Rgb): [number, number, number] {
return [Math.round(c[0] * 255), Math.round(c[1] * 255), Math.round(c[2] * 255)];
}
function readCssColor(name: string, fallback: string): string {
if (typeof document === 'undefined') return fallback;
const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
return /^#[0-9a-f]{3,8}$/i.test(v) ? v : fallback;
}
export function globeTheme(dark: boolean): GlobeTheme {
const accent = hexToRgb(readCssColor('--accent', dark ? '#e4e4e7' : '#111827'));
if (dark) {
return {
land: [0.15, 0.18, 0.27],
ocean: [0.07, 0.11, 0.22],
oceanDeep: [0.025, 0.04, 0.09],
space0: [0.008, 0.012, 0.03],
space1: [0.04, 0.06, 0.13],
glow: [0.49, 0.78, 0.99],
border: [0.03, 0.04, 0.09, 0.9],
coast: [0.55, 0.75, 1.0, 0.16],
regionBorder: [0.9, 0.95, 1.0, 0.32],
selection: [1, 1, 1, 0.95],
arc: [0.88, 0.95, 1.0, 0.95],
dark: true,
};
}
// Daylight: a clear sky, a bright sea, warm grey land and white borders.
return {
land: [0.985, 0.985, 0.98],
ocean: [0.72, 0.84, 0.96],
oceanDeep: [0.55, 0.7, 0.88],
space0: [0.88, 0.93, 0.98],
space1: [0.75, 0.85, 0.96],
glow: [0.62, 0.8, 1.0],
border: [0.72, 0.78, 0.86, 0.9],
coast: [0.3, 0.45, 0.65, 0.3],
regionBorder: [0.75, 0.8, 0.88, 0.75],
selection: [accent[0], accent[1], accent[2], 0.95],
arc: [0.16, 0.32, 0.72, 0.9],
dark: false,
};
}
@@ -16,7 +16,7 @@ import type { CostsSettlementResponse } from './costsModel';
import { useCostsLedger } from './useCostsLedger';
import { useFreezeMissingRates } from './useFreezeMissingRates';
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-023
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-024
const fx = vi.hoisted(() => ({
// One stable converter, the way useExchangeRates hands out a memoised one: USD is half a euro.
@@ -183,6 +183,28 @@ describe('useCostsLedger: loading', () => {
expect(result.current.settlement).toEqual(SETTLEMENT);
});
it('FE-BUDGET-LEDGER-024: a settlement answer that lands after the ledger is gone changes no state', async () => {
let fail: (reason: Error) => void = () => undefined;
settlementMock().mockImplementation(
() =>
new Promise<CostsSettlementResponse>((_resolve, reject) => {
fail = reject;
})
);
const { unmount } = setup();
await waitFor(() => expect(settlementMock()).toHaveBeenCalled());
unmount();
// React reads window.event when a state update is scheduled, and a test
// environment that is already torn down has no window.
vi.stubGlobal('window', undefined);
try {
fail(new Error('gone'));
await new Promise((resolve) => setTimeout(resolve, 20));
} finally {
vi.unstubAllGlobals();
}
});
it('FE-BUDGET-LEDGER-006: hands the unconverted rows to the rate freeze, which reads the settlement again once healed', async () => {
const { result } = setup();
await waitFor(() => expect(result.current.settlement).not.toBeNull());
@@ -120,6 +120,13 @@ export function useCostsLedger({
// Only the latest read may land: an answer for the currency picked before would
// otherwise overwrite the one for the currency shown now.
const latestRead = useRef(0);
// An answer that lands after the ledger is gone has nobody to show it to.
useEffect(() => {
const reads = latestRead;
return () => {
reads.current += 1;
};
}, []);
// The browser's own figure for the display currency goes along, for the server to
// answer in it when it cannot fetch a quote itself.
@@ -1,5 +1,4 @@
// FE-COMP-MSAVESHEET-001 to FE-COMP-MSAVESHEET-016
import React from 'react';
import { afterEach, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';
import type { Collection, CollectionListResponse, CollectionMembership, CollectionSaveResult } from '@trek/shared';
@@ -1,5 +1,4 @@
// FE-COMP-SAVETOCOL-001 to FE-COMP-SAVETOCOL-020
import React from 'react';
import { afterEach, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';
import type { Collection, CollectionListResponse, CollectionMembership, CollectionSaveResult } from '@trek/shared';
@@ -1,4 +1,3 @@
import React from 'react';
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { http, HttpResponse } from 'msw';
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render';
@@ -1,637 +0,0 @@
// FE-DAWARICH-ATLASDLG-001 to FE-DAWARICH-ATLASDLG-029
/**
* The room where Dawarich's two Atlas questions get answered.
*
* Nothing in here runs on its own, and that is the whole design: the Atlas is a
* curated list that carries tombstones precisely so a country somebody removed
* stays removed, so every read and every write starts with a person pressing a
* button. What is worth pinning is therefore not "does it fetch" but everything
* arranged around the fetch.
*
* - **What is written, and dated when.** A wish is ticked off on the day it was
* reached, not on today, and wishes reached on the same day travel in one
* request. A regression here either back-dates somebody's list wrongly or
* turns one confirmation into twenty requests.
* - **The five states each half can be in.** Unasked, in flight, answered,
* answered with nothing, answered with caveats. The confirm button is
* rendered or absent rather than merely greyed out, so each state has to
* decide whether that control exists at all, and the caveats under the list
* are only said when there is something to say.
* - **Refusing to write blind.** Offline is not a server error: nothing was
* sent, and "something went wrong talking to Dawarich" for a train tunnel
* sends people hunting for a bug in their own instance.
* - **Both shells.** The phone gets an MSheet with its own footer, the desktop
* a Modal; the body between them is the same tree, so a regression that
* dropped one shell would otherwise only surface on a device.
*/
import React from 'react'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, waitFor } from '../../../tests/helpers/render'
import { act, fireEvent } from '@testing-library/react'
import { setForcedOffline } from '../../sync/networkMode'
import { DawarichOfflineError } from '../../repo/dawarichRepo'
import DawarichAtlasDialog from './DawarichAtlasDialog'
const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
vi.mock('../shared/Toast', () => ({ useToast: () => toast, default: () => toast }))
const repo = {
bucketScan: vi.fn(),
atlasSuggestions: vi.fn(),
}
vi.mock('../../repo/dawarichRepo', () => ({
dawarichRepo: {
bucketScan: (...args: unknown[]) => repo.bucketScan(...args),
atlasSuggestions: (...args: unknown[]) => repo.atlasSuggestions(...args),
},
DawarichOfflineError: class extends Error {},
}))
const api = {
confirmBucketVisits: vi.fn(),
acceptAtlasCountries: vi.fn(),
}
vi.mock('../../api/dawarich', () => ({
dawarichApi: {
confirmBucketVisits: (...args: unknown[]) => api.confirmBucketVisits(...args),
acceptAtlasCountries: (...args: unknown[]) => api.acceptAtlasCountries(...args),
},
}))
// The one thing the dialog reads about the device. A hoisted flag rather than a
// resize: useIsPhone is matchMedia-driven and the global stub always answers false.
const phone = vi.hoisted(() => ({ value: false }))
vi.mock('../../mobile/useIsPhone', () => ({ useIsPhone: () => phone.value }))
const SCAN = {
matches: [
{
itemId: 11,
name: 'Museum Ludwig',
match: { at: '2026-09-10T14:00:00Z', minutes: 145, distanceMeters: 49, points: 60 },
alreadyVisited: false,
},
{
itemId: 12,
name: 'Kölner Dom',
match: { at: '2026-09-09T14:00:00Z', minutes: 30, distanceMeters: 80, points: 12 },
alreadyVisited: true,
},
{ itemId: 13, name: 'Rheinpark', match: null, alreadyVisited: false },
],
skippedWithoutCoordinates: 2,
truncated: false,
fetchedAt: '2026-09-12T10:00:00Z',
}
const COUNTRIES = {
countries: [
{ countryCode: 'DE', sourceName: 'Germany', cities: [{ name: 'Cologne', minutes: 400, lastSeenAt: '2026-09-10T10:00:00Z' }], alreadyVisited: true },
{ countryCode: 'NL', sourceName: 'Netherlands', cities: [{ name: 'Maastricht', minutes: 90, lastSeenAt: '2026-09-08T10:00:00Z' }], alreadyVisited: false },
],
unresolved: ['Freedonia'],
fetchedAt: '2026-09-12T10:00:00Z',
}
/**
* Three wishes reached on two days. The pair sharing a timestamp is the whole
* point of the fixture: the dialog groups by the date it is about to write, and
* a regression that lost the grouping would send one request per wish. The
* third one sits far enough away to be reported in kilometres rather than
* metres, which is the other half of the row's arithmetic.
*/
const SAME_DAY = {
matches: [
{
itemId: 21,
name: 'Van Gogh Museum',
match: { at: '2026-08-02T11:00:00Z', minutes: 95, distanceMeters: 30, points: 40 },
alreadyVisited: false,
},
{
itemId: 22,
name: 'Rijksmuseum',
match: { at: '2026-08-02T11:00:00Z', minutes: 120, distanceMeters: 55, points: 51 },
alreadyVisited: false,
},
{
itemId: 23,
name: 'Kinderdijk',
match: { at: '2026-07-30T09:00:00Z', minutes: 70, distanceMeters: 1400, points: 22 },
alreadyVisited: false,
},
],
skippedWithoutCoordinates: 0,
truncated: false,
fetchedAt: '2026-09-12T10:00:00Z',
}
/**
* A reading with nothing to apologise for: no unmatched names, one country with
* more cities than fit beside a flag and one with none at all.
*/
const MORE_COUNTRIES = {
countries: [
{
countryCode: 'FR',
sourceName: 'France',
cities: ['Paris', 'Lyon', 'Nice', 'Nantes'].map(name => ({
name,
minutes: 120,
lastSeenAt: '2026-08-02T10:00:00Z',
})),
alreadyVisited: false,
},
{ countryCode: 'BE', sourceName: 'Belgium', cities: [], alreadyVisited: false },
],
unresolved: [],
fetchedAt: '2026-09-12T10:00:00Z',
}
/** A promise this test settles by hand, to pin down what is on screen mid-flight. */
function deferred<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>(res => {
resolve = res
})
return { promise, resolve }
}
function open(props: Partial<React.ComponentProps<typeof DawarichAtlasDialog>> = {}) {
return render(<DawarichAtlasDialog isOpen onClose={vi.fn()} {...props} />)
}
beforeEach(() => {
phone.value = false
setForcedOffline(false)
toast.success.mockReset()
toast.error.mockReset()
repo.bucketScan.mockReset().mockResolvedValue(SCAN)
repo.atlasSuggestions.mockReset().mockResolvedValue(COUNTRIES)
api.confirmBucketVisits.mockReset().mockResolvedValue({ updated: 1 })
api.acceptAtlasCountries.mockReset().mockResolvedValue({ marked: 1 })
})
// Force-offline is module state, not component state: left on, it would leak
// into the next file's writes.
afterEach(() => setForcedOffline(false))
describe('DawarichAtlasDialog', () => {
it('FE-DAWARICH-ATLASDLG-001: asks nothing on its own — the scan runs when the reader says so', () => {
open()
expect(repo.bucketScan).not.toHaveBeenCalled()
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
})
it('FE-DAWARICH-ATLASDLG-002: offers no confirmation before there is anything to confirm', () => {
open()
// Hidden until a result is on screen rather than merely disabled: a greyed
// out "Tick off 0" is a dead control asking to be understood, and `hidden`
// keeps it out of the accessibility tree too.
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
})
it('FE-DAWARICH-ATLASDLG-003: a scan lists what it found, with the distance, the time and the day', async () => {
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
const row = screen.getByRole('checkbox', { name: 'Museum Ludwig' })
expect(row.textContent).toContain('49 m away')
expect(row.textContent).toContain('2 h 25 min')
// A wish with no match at all is not a row — there is nothing to decide.
expect(screen.queryByRole('checkbox', { name: 'Rheinpark' })).not.toBeInTheDocument()
})
it('FE-DAWARICH-ATLASDLG-004: open wishes start selected, already ticked ones do not', async () => {
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
expect(screen.getByRole('checkbox', { name: 'Kölner Dom' })).toHaveAttribute('aria-checked', 'false')
expect(screen.getByRole('checkbox', { name: 'Kölner Dom' })).toBeDisabled()
})
it('FE-DAWARICH-ATLASDLG-005: unticking a row takes it out of what gets written', async () => {
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
expect(screen.getByRole('button', { name: /Tick off 0/ })).toBeDisabled()
})
it('FE-DAWARICH-ATLASDLG-006: confirming writes exactly the picked wishes and reports back', async () => {
const onChanged = vi.fn()
open({ onChanged })
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
// With the date the stay was actually reached on — a wish from last year
// ticked off with today's date is a wrong entry in a list people keep.
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledWith([11], '2026-09-10T14:00:00Z'))
expect(onChanged).toHaveBeenCalled()
// Marked in place rather than rescanned — one upstream request per wish is
// not worth spending to tell the reader what they just did.
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeDisabled())
expect(repo.bucketScan).toHaveBeenCalledTimes(1)
})
it('FE-DAWARICH-ATLASDLG-007: the countries tab offers only what the Atlas does not already have', async () => {
open({ initialTab: 'countries' })
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
expect(screen.queryByRole('checkbox', { name: 'Germany' })).not.toBeInTheDocument()
// A country Dawarich named but TREK could not code is said out loud, not dropped.
expect(screen.getByText(/Freedonia/)).toBeInTheDocument()
})
it('FE-DAWARICH-ATLASDLG-008: confirming countries sends their codes', async () => {
open({ initialTab: 'countries' })
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
await waitFor(() => expect(api.acceptAtlasCountries).toHaveBeenCalledWith(['NL']))
})
it('FE-DAWARICH-ATLASDLG-009: a scan that fails says so and leaves the dialog usable', async () => {
repo.bucketScan.mockRejectedValue({ response: { data: { error: 'Dawarich rejected the API key.' } } })
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Dawarich rejected the API key.'))
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
})
it('FE-DAWARICH-ATLASDLG-010: while the recordings are being read there are placeholders and nothing to press', async () => {
const scan = deferred<typeof SCAN>()
repo.bucketScan.mockReturnValueOnce(scan.promise)
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
expect(screen.getByText('Checking…')).toBeInTheDocument()
expect(screen.queryByRole('checkbox')).toBeNull()
// Neither control exists yet: there is nothing to confirm, and "check again"
// before the first answer is a second request for the same thing.
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
expect(screen.queryByRole('button', { name: 'Check again' })).toBeNull()
await act(async () => {
scan.resolve(SCAN)
})
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
})
it('FE-DAWARICH-ATLASDLG-011: a scan that found nothing says so in a sentence and offers no confirmation', async () => {
repo.bucketScan.mockResolvedValue({ ...SCAN, matches: [], skippedWithoutCoordinates: 0 })
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() =>
expect(screen.getByText('Nothing on your wishlist turned up in your recordings.')).toBeInTheDocument(),
)
// Absent, not greyed out: a dead "Tick off 0" under an empty state only asks
// to be understood.
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
// The rule stays on screen, because it is the answer to "why did nothing
// turn up": driving past a wish does not count as reaching it.
expect(screen.getByText(/A wish counts as reached within 250 m and after 20 minutes/)).toBeInTheDocument()
})
it('FE-DAWARICH-ATLASDLG-012: the caveats under a scan are only said when there are any', async () => {
repo.bucketScan.mockResolvedValue({ ...SCAN, skippedWithoutCoordinates: 0, truncated: true })
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() =>
expect(screen.getByText('Only the first entries were checked. Run it again for the rest.')).toBeInTheDocument(),
)
// Nothing was skipped this time, so nothing is said about skipping: a
// "0 entries have no coordinates" line is noise dressed as information.
expect(screen.queryByText(/have no coordinates/)).toBeNull()
})
it('FE-DAWARICH-ATLASDLG-013: a country shows the first of its cities, one without any shows none', async () => {
repo.atlasSuggestions.mockResolvedValue(MORE_COUNTRIES)
open({ initialTab: 'countries' })
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'France' })).toBeInTheDocument())
const france = screen.getByRole('checkbox', { name: 'France' })
// The badge counts all four; the line beside it names three, which is what
// fits beside a flag at the width a phone gives this dialog.
expect(france.textContent).toContain('4 cities')
expect(france.textContent).toContain('Paris, Lyon, Nice')
expect(france.textContent).not.toContain('Nantes')
expect(screen.getByRole('checkbox', { name: 'Belgium' }).textContent).not.toContain('cities')
// Everything matched, so the dialog does not mention matching at all.
expect(screen.queryByText(/could not match these to a country/)).toBeNull()
expect(screen.getByText('The last 12 months were looked at.')).toBeInTheDocument()
})
it('FE-DAWARICH-ATLASDLG-014: a reading with nothing new in it says so rather than showing an empty list', async () => {
// Germany alone, and the Atlas already has it.
repo.atlasSuggestions.mockResolvedValue({ ...COUNTRIES, countries: [COUNTRIES.countries[0]] })
open({ initialTab: 'countries' })
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() =>
expect(screen.getByText('Your recordings show no countries TREK does not already have.')).toBeInTheDocument(),
)
expect(screen.queryByRole('button', { name: /Add \d+ countr/ })).toBeNull()
})
it('FE-DAWARICH-ATLASDLG-015: wishes reached on one day travel in one request, another day in its own', async () => {
repo.bucketScan.mockResolvedValue(SAME_DAY)
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Rijksmuseum' })).toBeInTheDocument())
// Over a kilometre out is said in kilometres: "1400 m away" is a
// measurement, "1.4 km away" is how far it was.
expect(screen.getByRole('checkbox', { name: 'Kinderdijk' }).textContent).toContain('1.4 km away')
fireEvent.click(screen.getByRole('button', { name: /Tick off 3/ }))
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledTimes(2))
// Grouped by date, not ordered by it: the row order inside a day is the
// sort's business and nothing here depends on it.
const calls = api.confirmBucketVisits.mock.calls as Array<[number[], string]>
const byDate = new Map(calls.map(([ids, at]) => [at, [...ids].sort((a, b) => a - b)]))
expect(byDate.get('2026-08-02T11:00:00Z')).toEqual([21, 22])
expect(byDate.get('2026-07-30T09:00:00Z')).toEqual([23])
// Both answers counted, not just the last one to come back.
expect(toast.success).toHaveBeenCalledWith('2 wishes ticked off')
})
it('FE-DAWARICH-ATLASDLG-016: an unticked wish is left out of the write entirely', async () => {
repo.bucketScan.mockResolvedValue(SAME_DAY)
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Kinderdijk' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('checkbox', { name: 'Kinderdijk' }))
fireEvent.click(screen.getByRole('checkbox', { name: 'Rijksmuseum' }))
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
// One request, for one day, carrying one id. The day whose other wish was
// dropped does not travel half-empty, and the other day does not travel at all.
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledTimes(1))
expect(api.confirmBucketVisits).toHaveBeenCalledWith([21], '2026-08-02T11:00:00Z')
})
it('FE-DAWARICH-ATLASDLG-017: a row that was unticked can be put back', async () => {
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'false')
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
expect(screen.getByRole('button', { name: /Tick off 1/ })).toBeEnabled()
})
it('FE-DAWARICH-ATLASDLG-018: offline, a wish confirmation is refused before anything is sent', async () => {
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
setForcedOffline(true)
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now'))
// Not attempted at all: a confirmation fired into a dead connection hangs to
// a timeout and then reports a server error for something no server saw.
expect(api.confirmBucketVisits).not.toHaveBeenCalled()
// And the selection survives, so pressing it again once there is signal is enough.
expect(screen.getByRole('button', { name: /Tick off 1/ })).toBeEnabled()
})
it('FE-DAWARICH-ATLASDLG-019: offline, a country confirmation is refused before anything is sent', async () => {
open({ initialTab: 'countries' })
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
setForcedOffline(true)
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now'))
expect(api.acceptAtlasCountries).not.toHaveBeenCalled()
})
it('FE-DAWARICH-ATLASDLG-020: a write that failed leaves every row exactly as it was', async () => {
// A rejection with no `{ error }` envelope at all: a socket that died
// mid-request rather than a server that answered.
api.confirmBucketVisits.mockRejectedValue(new Error('socket hang up'))
const onChanged = vi.fn()
open({ onChanged })
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
// Nothing was marked off locally, so a second attempt still has something to
// send, and the Atlas is not asked to re-read for a write that never landed.
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeEnabled()
expect(onChanged).not.toHaveBeenCalled()
})
it('FE-DAWARICH-ATLASDLG-021: a refusal carrying no readable reason still gets a sentence', async () => {
// An `{ error }` that is not a string is not a message: falling through to
// the generic sentence beats printing "[object Object]" at somebody.
api.acceptAtlasCountries.mockRejectedValue({ response: { data: { error: { code: 502 } } } })
open({ initialTab: 'countries' })
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toHaveAttribute('aria-checked', 'true')
})
it('FE-DAWARICH-ATLASDLG-022: a read that never left the device reads as a connection, not a failure', async () => {
// The repo refuses offline reads itself, and its refusal has to survive the
// trip through failureText as the connection message rather than as
// "something went wrong talking to Dawarich", which points at the instance.
repo.atlasSuggestions.mockRejectedValue(new DawarichOfflineError())
open({ initialTab: 'countries' })
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() =>
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now')),
)
// Still unasked, so the button that asks is the one on screen.
expect(screen.getByRole('button', { name: 'Look for countries' })).toBeInTheDocument()
})
it('FE-DAWARICH-ATLASDLG-023: the other tab asks the other question, and each keeps its own answer', async () => {
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: /Countries/ }))
// Switching tabs asks nothing on its own: a country reading costs an
// upstream request, and nobody asked for it by moving their eyes.
expect(repo.atlasSuggestions).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: /Wishlist/ }))
// The scan is still there, and was not repeated for the return trip.
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument()
expect(repo.bucketScan).toHaveBeenCalledTimes(1)
})
it('FE-DAWARICH-ATLASDLG-024: "Check again" re-runs the scan and is inert while it runs', async () => {
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
const second = deferred<typeof SCAN>()
repo.bucketScan.mockReturnValueOnce(second.promise)
fireEvent.click(screen.getByRole('button', { name: 'Check again' }))
// A second press while the first is in flight would run the whole scan twice:
// one upstream request per wish, for the same answer.
expect(screen.getByRole('button', { name: 'Check again' })).toBeDisabled()
await act(async () => {
second.resolve(SCAN)
})
await waitFor(() => expect(screen.getByRole('button', { name: 'Check again' })).toBeEnabled())
expect(repo.bucketScan).toHaveBeenCalledTimes(2)
})
it('FE-DAWARICH-ATLASDLG-025: "Check again" on the countries tab re-reads the countries, not the wishes', async () => {
open({ initialTab: 'countries' })
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Check again' }))
await waitFor(() => expect(repo.atlasSuggestions).toHaveBeenCalledTimes(2))
expect(repo.bucketScan).not.toHaveBeenCalled()
// A year back from the moment it was asked, both times: the window is the
// same question asked again, not a widening one.
const calls = repo.atlasSuggestions.mock.calls as Array<[string, string]>
for (const [from, to] of calls) {
expect(Date.parse(to) - Date.parse(from)).toBe(365 * 24 * 60 * 60 * 1000)
}
expect(Date.parse(calls[1][0])).toBeGreaterThanOrEqual(Date.parse(calls[0][0]))
})
it('FE-DAWARICH-ATLASDLG-026: on a phone it is a sheet, and the count and the confirm live in its own footer', async () => {
phone.value = true
const onClose = vi.fn()
open({ onClose })
expect(screen.getByRole('dialog', { name: 'Dawarich' })).toBeInTheDocument()
// The desktop modal puts the title in a heading: its absence is the tell
// that the right shell rendered.
expect(screen.queryByRole('heading', { name: /Dawarich/ })).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
expect(screen.getByText('1 selected')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledWith([11], '2026-09-10T14:00:00Z'))
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
expect(onClose).toHaveBeenCalled()
})
it('FE-DAWARICH-ATLASDLG-027: a country that was just added stops being offered, and the Atlas is told', async () => {
const onChanged = vi.fn()
open({ initialTab: 'countries', onChanged })
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('1 country added'))
// Marked in place rather than re-read: the reading costs an upstream request
// and the only thing that changed is what the reader just pressed. The row
// leaving the list is what says the write landed.
await waitFor(() =>
expect(screen.getByText('Your recordings show no countries TREK does not already have.')).toBeInTheDocument(),
)
expect(screen.queryByRole('checkbox', { name: 'Netherlands' })).toBeNull()
expect(screen.queryByRole('button', { name: /Add \d+ countr/ })).toBeNull()
expect(repo.atlasSuggestions).toHaveBeenCalledTimes(1)
// The Atlas keeps its own map and its own counts; without this the country
// it was just told about only appears there after a reload.
expect(onChanged).toHaveBeenCalledTimes(1)
})
it('FE-DAWARICH-ATLASDLG-028: a request that died without a reason at all still gets a sentence', async () => {
// An aborted request rejects with nothing: not an Error, not a response.
// Reaching into `.response.data` on that must not be the thing that takes
// the dialog down, because a crash here loses the scan the reader is
// looking at as well as the message they needed.
repo.bucketScan.mockRejectedValue(undefined)
open()
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
})
it('FE-DAWARICH-ATLASDLG-029: a country can be unticked and put back, and only the ticked ones are written', async () => {
// Both offers start ticked, which is the useful default but not the answer
// every time: a border crossed on the way to somewhere else is a country
// Dawarich saw and the reader does not want in their Atlas. Taking one out
// has to actually take it out of the write, and changing one's mind has to
// put it back, because the Atlas carries tombstones and an unwanted country
// added here is removed by hand afterwards.
repo.atlasSuggestions.mockResolvedValue(MORE_COUNTRIES)
open({ initialTab: 'countries' })
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Belgium' })).toBeInTheDocument())
expect(screen.getByRole('button', { name: /Add 2 countries/ })).toBeEnabled()
fireEvent.click(screen.getByRole('checkbox', { name: 'Belgium' }))
expect(screen.getByRole('checkbox', { name: 'Belgium' })).toHaveAttribute('aria-checked', 'false')
// Out and back in again: the tick is a toggle, not a one-way door.
fireEvent.click(screen.getByRole('checkbox', { name: 'France' }))
expect(screen.getByRole('button', { name: /Add 0 countries/ })).toBeDisabled()
fireEvent.click(screen.getByRole('checkbox', { name: 'France' }))
expect(screen.getByRole('checkbox', { name: 'France' })).toHaveAttribute('aria-checked', 'true')
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
// Belgium was never sent, so nothing has to be undone in the Atlas after.
await waitFor(() => expect(api.acceptAtlasCountries).toHaveBeenCalledWith(['FR']))
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('1 country added'))
// And it is still on offer, still unticked, for the trip it does belong to.
expect(screen.getByRole('checkbox', { name: 'Belgium' })).toHaveAttribute('aria-checked', 'false')
})
})
@@ -1,575 +0,0 @@
import React, { useId, useState } from 'react'
import { Building2, Check, CalendarDays, Globe2, Hourglass, Info, Loader2, MapPin, RefreshCw, Star } from 'lucide-react'
import type { DawarichAtlasSuggestions, DawarichBucketScan } from '@trek/shared'
import { DAWARICH_BUCKET_MATCH_MIN_MINUTES, DAWARICH_BUCKET_MATCH_RADIUS_M } from '@trek/shared'
import { useTranslation } from '../../i18n'
import { useToast } from '../shared/Toast'
import { Skeleton } from '../shared/Skeleton'
import { SlidingTabs } from '../shared/SlidingTabs'
import { DialogFooter, DialogHeader, DialogShell, NEUTRAL_TINT } from '../shared/DialogShell'
import MSheet from '../../mobile/components/MSheet'
import { FormSheetHeader } from '../../mobile/screens/trip/sheets/PlSheetChrome'
import { useIsPhone } from '../../mobile/useIsPhone'
import DawarichIcon from '../shared/DawarichIcon'
import DawarichBadge from './DawarichBadge'
import { dawarichApi } from '../../api/dawarich'
import { dawarichRepo, DawarichOfflineError } from '../../repo/dawarichRepo'
import { isEffectivelyOffline } from '../../sync/networkMode'
import { formatDuration } from './dawarichSuggestionModel'
import { cityLine, countryLabel, countryWindow, formatDistance, newCountries, orderedMatches } from './dawarichAtlasModel'
type Tab = 'wishes' | 'countries'
/**
* Everything Dawarich can answer about the Atlas, in a room of its own.
*
* It used to be a card wedged under the wishlist, which made two different
* questions — "which wishes did I actually reach?" and "which countries was I
* in?" — look like one paragraph of small print. Both are offers that need
* reading before they are accepted, and reading needs space, so they get a
* dialog with a tab each, one selection model and one confirm button.
*
* Nothing here runs on its own. The Atlas is curated — it carries tombstones
* precisely so a country somebody removed stays removed — and a background job
* that ticked countries off would be fighting its owner.
*/
export default function DawarichAtlasDialog({
isOpen,
initialTab = 'wishes',
onClose,
onChanged,
}: {
isOpen: boolean
/** Which question was asked to open it — the panel has a button per tab. */
initialTab?: Tab
onClose: () => void
/** Called after something was written, so the Atlas can re-read itself. */
onChanged?: () => void
}): React.ReactElement {
const { t, locale } = useTranslation()
const toast = useToast()
const phone = useIsPhone()
const labelId = useId()
const [tab, setTab] = useState<Tab>(initialTab)
const [scan, setScan] = useState<DawarichBucketScan | null>(null)
const [scanning, setScanning] = useState(false)
const [picked, setPicked] = useState<Set<number>>(new Set())
const [countries, setCountries] = useState<DawarichAtlasSuggestions | null>(null)
const [loadingCountries, setLoadingCountries] = useState(false)
const [pickedCountries, setPickedCountries] = useState<Set<string>>(new Set())
// One write at a time: the button stays on screen while the request is in
// flight, and a second press would send the same confirmation twice.
const [writing, setWriting] = useState(false)
const matches = orderedMatches(scan?.matches ?? [])
const openMatches = matches.filter(match => !match.alreadyVisited)
const offered = newCountries(countries?.countries ?? [])
const runScan = async (): Promise<void> => {
setScanning(true)
try {
const result = await dawarichRepo.bucketScan()
setScan(result)
// Everything with a match and not already ticked starts selected: the
// common case is "yes, all of those", and unticking the odd one is less
// work than ticking twenty.
setPicked(new Set(result.matches.filter(m => m.match && !m.alreadyVisited).map(m => m.itemId)))
} catch (err) {
toast.error(failureText(err, t))
} finally {
setScanning(false)
}
}
const loadCountries = async (): Promise<void> => {
setLoadingCountries(true)
try {
const { from, to } = countryWindow(new Date())
const result = await dawarichRepo.atlasSuggestions(from, to)
setCountries(result)
setPickedCountries(new Set(newCountries(result.countries).map(c => c.countryCode)))
} catch (err) {
toast.error(failureText(err, t))
} finally {
setLoadingCountries(false)
}
}
const confirmWishes = async (): Promise<void> => {
if (picked.size === 0 || writing) return
// Writes are online-only: the reads are gated in the repo, and firing a
// confirmation into a dead connection would hang to a timeout and then
// report a server error for something the server never saw.
if (isEffectivelyOffline()) {
toast.error(t('dawarich.error.offline'))
return
}
setWriting(true)
try {
// Ticked off on the day each wish was reached, not on today. The dialog is
// holding that date for every row it is about to write, so it says it;
// grouping by date keeps that to one request per day rather than per wish.
const byDate = new Map<string, number[]>()
for (const m of matches) {
if (!picked.has(m.itemId) || !m.match) continue
const bucket = byDate.get(m.match.at)
if (bucket) bucket.push(m.itemId)
else byDate.set(m.match.at, [m.itemId])
}
const results = await Promise.all(
[...byDate].map(([at, ids]) => dawarichApi.confirmBucketVisits(ids, at)),
)
const result = { updated: results.reduce((sum, r) => sum + r.updated, 0) }
toast.success(t('dawarich.bucket.confirmed', { count: result.updated }))
// Marked in place rather than rescanned: the scan costs one upstream
// request per wish, and the reader already knows what they just ticked.
setScan(prev =>
prev === null
? prev
: { ...prev, matches: prev.matches.map(m => (picked.has(m.itemId) ? { ...m, alreadyVisited: true } : m)) },
)
setPicked(new Set())
onChanged?.()
} catch (err) {
toast.error(failureText(err, t))
} finally {
setWriting(false)
}
}
const confirmCountries = async (): Promise<void> => {
if (pickedCountries.size === 0 || writing) return
if (isEffectivelyOffline()) {
toast.error(t('dawarich.error.offline'))
return
}
setWriting(true)
try {
const result = await dawarichApi.acceptAtlasCountries([...pickedCountries])
toast.success(t('dawarich.atlas.accepted', { count: result.marked }))
setCountries(prev =>
prev === null
? prev
: {
...prev,
countries: prev.countries.map(c =>
pickedCountries.has(c.countryCode) ? { ...c, alreadyVisited: true } : c,
),
},
)
setPickedCountries(new Set())
onChanged?.()
} catch (err) {
toast.error(failureText(err, t))
} finally {
setWriting(false)
}
}
const toggle = <T,>(set: Set<T>, value: T): Set<T> => {
const next = new Set(set)
if (next.has(value)) next.delete(value)
else next.add(value)
return next
}
const busy = tab === 'wishes' ? scanning : loadingCountries
const loaded = tab === 'wishes' ? scan !== null : countries !== null
const selected = tab === 'wishes' ? picked.size : pickedCountries.size
// Nothing was found, so there is nothing to confirm — the empty state says so
// in a sentence, and a greyed-out "Add 0 countries" underneath it only asks to
// be understood.
const anything = tab === 'wishes' ? matches.length > 0 : offered.length > 0
// The same two questions in both shells — only the frame differs.
const body = (
<div className="space-y-4">
<SlidingTabs<Tab>
tabs={[
{ id: 'wishes', label: t('dawarich.atlas.tab.wishes'), icon: Star, count: openMatches.length || undefined },
{ id: 'countries', label: t('dawarich.atlas.tab.countries'), icon: Globe2, count: offered.length || undefined },
]}
activeTab={tab}
onChange={setTab}
size="sm"
fullWidth
/>
{tab === 'wishes' ? (
<Section
icon={Star}
title={t('dawarich.bucket.title')}
description={t('dawarich.bucket.description')}
action={t('dawarich.bucket.scan')}
busyLabel={t('dawarich.bucket.scanning')}
busy={scanning}
loaded={scan !== null}
onRun={() => { void runScan() }}
empty={matches.length === 0}
emptyLabel={t('dawarich.bucket.noMatches')}
notes={[
scan && scan.skippedWithoutCoordinates > 0
? t('dawarich.bucket.skipped', { count: scan.skippedWithoutCoordinates })
: null,
scan?.truncated ? t('dawarich.bucket.truncated') : null,
t('dawarich.bucket.rule', {
meters: DAWARICH_BUCKET_MATCH_RADIUS_M,
count: DAWARICH_BUCKET_MATCH_MIN_MINUTES,
}),
]}
>
{matches.map(match => (
<Row
key={match.itemId}
name={match.name}
checked={picked.has(match.itemId)}
disabled={match.alreadyVisited}
onToggle={() => setPicked(prev => toggle(prev, match.itemId))}
leading={
<span className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-surface-secondary">
<Star className="w-4 h-4 text-accent-on" />
</span>
}
>
{match.alreadyVisited ? (
<DawarichBadge icon={Check} tone="success" size="sm">
{t('dawarich.bucket.alreadyVisited')}
</DawarichBadge>
) : (
<>
<DawarichBadge icon={MapPin} size="sm">
{formatDistance(match.match!.distanceMeters, t)}
</DawarichBadge>
<DawarichBadge icon={Hourglass} size="sm">
{formatDuration(match.match!.minutes, t)}
</DawarichBadge>
<DawarichBadge icon={CalendarDays} size="sm">
{new Date(match.match!.at).toLocaleDateString(locale, {
weekday: 'short',
day: 'numeric',
month: 'short',
})}
</DawarichBadge>
</>
)}
</Row>
))}
</Section>
) : (
<Section
icon={Globe2}
title={t('dawarich.atlas.title')}
description={t('dawarich.atlas.description')}
action={t('dawarich.atlas.load')}
busyLabel={t('dawarich.atlas.loading')}
busy={loadingCountries}
loaded={countries !== null}
onRun={() => { void loadCountries() }}
empty={offered.length === 0}
emptyLabel={t('dawarich.atlas.empty')}
notes={[
countries && countries.unresolved.length > 0
? t('dawarich.atlas.unresolved', { names: countries.unresolved.join(', ') })
: null,
countries ? t('dawarich.atlas.window') : null,
]}
>
{offered.map(country => (
<Row
key={country.countryCode}
name={countryLabel(country.countryCode, country.sourceName, locale)}
checked={pickedCountries.has(country.countryCode)}
onToggle={() => setPickedCountries(prev => toggle(prev, country.countryCode))}
leading={
// The Atlas page draws its countries with the same flags, and a
// list of country names without them looks like a spreadsheet.
<img
src={`https://flagcdn.com/w40/${country.countryCode.toLowerCase()}.png`}
alt=""
className="h-6 w-8 flex-shrink-0 rounded object-cover"
/>
}
>
{country.cities.length > 0 && (
<>
<DawarichBadge icon={Building2} size="sm">
{t('dawarich.atlas.cities', { count: country.cities.length })}
</DawarichBadge>
<span className="min-w-0 truncate text-caption text-content-muted">
{cityLine(country.cities)}
</span>
</>
)}
</Row>
))}
</Section>
)}
</div>
)
// Rendered or not, rather than `hidden`: the attribute loses to the display
// utility on the class list, so the button stayed on screen greyed out.
const confirmButton = !loaded || !anything ? null : (
<button
type="button"
onClick={() => { void (tab === 'wishes' ? confirmWishes() : confirmCountries()) }}
disabled={selected === 0 || writing}
className={
phone
? 'inline-flex h-[38px] items-center gap-2 rounded-full bg-m-act px-4 text-[0.8125rem] font-bold text-m-actfg disabled:opacity-40'
: 'inline-flex items-center gap-1.5 rounded-[10px] bg-accent px-4 py-2 text-body font-medium text-accent-text hover:opacity-90 disabled:opacity-40'
}
>
<Check className="w-3.5 h-3.5" />
{tab === 'wishes'
? t('dawarich.bucket.confirm', { count: selected })
: t('dawarich.atlas.accept', { count: selected })}
</button>
)
const againButton = loaded ? (
<button
type="button"
onClick={() => { void (tab === 'wishes' ? runScan() : loadCountries()) }}
disabled={busy}
className={
phone
? 'inline-flex h-[38px] items-center gap-2 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-4 text-[0.8125rem] font-bold text-m-muted disabled:opacity-50'
: 'inline-flex items-center gap-1.5 rounded-[10px] bg-surface-card px-3.5 py-2 text-body font-medium text-content shadow-sm ring-1 ring-edge-faint hover:bg-surface-secondary disabled:opacity-50'
}
>
{busy ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <RefreshCw className="w-3.5 h-3.5" />}
{t('dawarich.again')}
</button>
) : null
// The phone shell has its own sheet, its own rounding and its own pill
// buttons, and every other panel on it uses them.
if (phone) {
return (
<MSheet open={isOpen} onClose={onClose} variant="bottom" material="glass" ariaLabel={t('dawarich.title')}>
<div className="flex max-h-[88dvh] min-h-0 flex-col">
<FormSheetHeader
leading={
<span className="flex h-10 w-10 flex-none overflow-hidden rounded-[13px]">
<DawarichIcon size={40} />
</span>
}
title={t('dawarich.title')}
subtitle={t('dawarich.atlas.dialogSubtitle')}
onClose={onClose}
closeLabel={t('common.close')}
/>
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-3">{body}</div>
<div className="flex flex-none items-center gap-2 border-t border-[color:var(--m-rowbr)] px-[18px] pb-4 pt-3">
<span className="min-w-0 flex-1 truncate font-geist text-[0.71875rem] text-m-muted">
{selected > 0 ? t('dawarich.selected', { count: selected }) : ''}
</span>
{againButton}
{confirmButton}
</div>
</div>
</MSheet>
)
}
return (
<DialogShell
open={isOpen}
onClose={onClose}
labelledBy={labelId}
width="editor"
// The answer replaces the pitch below the tabs, so the upper edge stays put.
align="top"
header={(
<DialogHeader
// The mark fills its tile, rounded like the phone's: a small logo in a
// grey square reads as a placeholder.
tile={<span className="flex h-[46px] w-[46px] flex-none overflow-hidden rounded-[14px] shadow-sm"><DawarichIcon size={46} /></span>}
tint={NEUTRAL_TINT}
labelId={labelId}
onClose={onClose}
title={t('dawarich.title')}
sub={t('dawarich.atlas.dialogSubtitle')}
/>
)}
// Before the first answer the pitch carries its own button, so there is no bar to show.
footer={againButton || confirmButton ? (
<DialogFooter>
<span className="min-w-0 flex-1 truncate text-caption text-content-muted">
{selected > 0 ? t('dawarich.selected', { count: selected }) : ''}
</span>
{againButton}
{confirmButton}
</DialogFooter>
) : undefined}
>
{body}
</DialogShell>
)
}
/**
* One half of the dialog: the pitch before anything has been asked, the wait
* while it is being asked, and the answer.
*
* Both halves behave identically, which is the point — the two questions are
* different, the shape of answering them is not.
*/
function Section({
icon: Icon,
title,
description,
action,
busyLabel,
busy,
loaded,
onRun,
empty,
emptyLabel,
notes,
children,
}: {
icon: React.ComponentType<{ className?: string }>
title: string
description: string
action: string
busyLabel: string
busy: boolean
loaded: boolean
onRun: () => void
empty: boolean
emptyLabel: string
notes: (string | null)[]
children: React.ReactNode
}): React.ReactElement {
if (busy) {
return (
<div className="space-y-2" aria-busy>
<p className="text-caption text-content-muted">{busyLabel}</p>
{[0, 1, 2].map(i => (
<div key={i} className="flex items-center gap-3 rounded-xl border border-edge p-3">
<Skeleton width={32} height={32} radius={8} />
<div className="flex-1 space-y-1.5">
<Skeleton width="45%" height={13} radius={4} />
<Skeleton width="70%" height={11} radius={4} />
</div>
</div>
))}
</div>
)
}
if (!loaded) {
return (
<div className="flex flex-col items-center rounded-xl border border-dashed border-edge px-6 py-8 text-center">
<span className="mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-surface-secondary">
<Icon className="w-5 h-5 text-content-secondary" />
</span>
<p className="text-body font-semibold text-content">{title}</p>
<p className="mt-1.5 max-w-md text-caption text-content-muted">{description}</p>
<button
type="button"
onClick={onRun}
className="mt-4 inline-flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-caption font-semibold text-accent-text hover:bg-accent-hover"
>
<RefreshCw className="w-3.5 h-3.5" />
{action}
</button>
</div>
)
}
return (
<div className="space-y-3">
{empty ? (
<div className="rounded-xl border border-dashed border-edge px-6 py-8 text-center text-caption text-content-muted">
{emptyLabel}
</div>
) : (
<div className="space-y-1.5">{children}</div>
)}
{notes.filter(Boolean).length > 0 && (
<div className="space-y-1 border-t border-edge-faint pt-2.5">
{notes.filter(Boolean).map(note => (
<p key={note} className="flex items-start gap-1.5 text-caption text-content-faint">
<Info className="w-3 h-3 flex-shrink-0 mt-0.5" />
{note}
</p>
))}
</div>
)}
</div>
)
}
/**
* A selectable answer: what it is on the left, why it is being offered
* underneath, and a tick that says whether it will be applied.
*
* The whole row is the control — a 16px checkbox is a hard target on a phone,
* and there is nothing else in the row to click.
*/
function Row({
name,
checked,
disabled = false,
onToggle,
leading,
children,
}: {
name: string
checked: boolean
disabled?: boolean
onToggle: () => void
leading: React.ReactNode
children: React.ReactNode
}): React.ReactElement {
return (
<button
type="button"
role="checkbox"
aria-checked={checked}
aria-label={name}
disabled={disabled}
onClick={onToggle}
className={`flex w-full items-center gap-3 rounded-xl border p-2.5 text-start transition-colors ${
checked ? 'border-accent bg-accent-subtle' : 'border-edge hover:bg-surface-hover'
} ${disabled ? 'opacity-60' : ''}`}
>
<span
aria-hidden
className={`flex h-4 w-4 flex-shrink-0 items-center justify-center rounded ${
checked ? 'bg-accent' : 'border-[1.5px] border-edge'
}`}
>
{checked && <Check className="w-2.5 h-2.5 text-accent-text" strokeWidth={3} />}
</span>
{leading}
<span className="min-w-0 flex-1">
<span className="block truncate text-body font-medium text-content">{name}</span>
<span className="mt-1 flex flex-wrap items-center gap-1">{children}</span>
</span>
</button>
)
}
/**
* What to tell the reader when a question could not be asked.
*
* Being offline is not an error the server reported — nothing was sent — and
* "something went wrong" for a plane journey is the kind of message that sends
* somebody looking for a bug in their Dawarich instance.
*/
function failureText(err: unknown, t: (key: string) => string): string {
if (err instanceof DawarichOfflineError) return t('dawarich.error.offline')
return errorText(err) ?? t('dawarich.error.unknown')
}
/** The server's `{ error }` envelope, when there is one. */
function errorText(err: unknown): string | null {
const data = (err as { response?: { data?: { error?: unknown } } })?.response?.data
return typeof data?.error === 'string' ? data.error : null
}
@@ -1,174 +0,0 @@
// FE-DAWARICH-ATLASPANEL-001 to FE-DAWARICH-ATLASPANEL-007
/**
* Dawarich's own panel on the Atlas, beside the stats.
*
* The panel itself holds almost no logic, and the little it does hold is the
* kind that is invisible until it is wrong:
*
* - **It has to disappear completely when the addon is off.** Not empty, not a
* blank pane of glass in the row beside the stats: absent, so an Atlas
* without Dawarich looks exactly as it did before the integration landed.
* - **It has to ask the question that was pressed.** Two tiles, one dialog, one
* `initialTab` between them. Wiring both tiles to the same tab is a bug that
* looks like a working panel.
* - **It mounts the dialog on open and throws it away on close**, deliberately,
* so a second visit starts from a fresh question rather than from a scan
* somebody ran an hour ago.
* - **It is made of the same glass as the Atlas panel next to it.** The tint
* and the cursor glare are hand-written rgba rather than tokens (a solid
* surface token would punch an opaque hole in a panel floating over a blurred
* map), so nothing but a test stops the two panels drifting apart in the
* dark theme.
*
* The dialog is pinned by its own file and stands in for itself here, so the
* panel's decisions are observable without a scan and without mocking Dawarich.
*/
import React from 'react'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { fireEvent } from '@testing-library/react'
import { render, screen } from '../../../tests/helpers/render'
import { useAddonStore } from '../../store/addonStore'
import DawarichAtlasSidePanel from './DawarichAtlasSidePanel'
vi.mock('./DawarichAtlasDialog', () => ({
default: ({
initialTab,
onClose,
onChanged,
}: {
initialTab: string
onClose: () => void
onChanged?: () => void
}) => (
<div data-testid="atlas-dialog">
<span>asked: {initialTab}</span>
<button type="button" onClick={onClose}>
dismiss
</button>
<button type="button" onClick={() => onChanged?.()}>
wrote something
</button>
</div>
),
}))
const ADDON = { id: 'dawarich', name: 'Dawarich', type: 'integration', icon: 'route', enabled: true }
/** The glass the Atlas hands down, reduced to the one property jsdom can answer for. */
const GLASS: React.CSSProperties = { borderRadius: 20 }
/** Inline rgba comes back from jsdom respaced; nothing here cares about the spaces. */
const rgba = (el: HTMLElement): string => el.style.background.replace(/\s/g, '')
function mount(props: Partial<React.ComponentProps<typeof DawarichAtlasSidePanel>> = {}) {
return render(<DawarichAtlasSidePanel style={GLASS} dark {...props} />)
}
beforeEach(() => {
useAddonStore.setState({ addons: [ADDON], loaded: true })
})
afterEach(() => {
useAddonStore.setState({ addons: [], loaded: false })
})
describe('DawarichAtlasSidePanel', () => {
it('FE-DAWARICH-ATLASPANEL-001: an Atlas without the addon gets no panel at all', () => {
useAddonStore.setState({ addons: [{ ...ADDON, enabled: false }] })
const { container } = mount()
// Nothing rendered, rather than an empty pane of glass in the row: the
// panel is stretched to the height of the stats beside it, so an empty one
// would be a visible hole.
expect(container).toBeEmptyDOMElement()
expect(screen.queryByRole('button', { name: 'Wishlist' })).toBeNull()
})
it('FE-DAWARICH-ATLASPANEL-002: with the addon on it offers two questions and asks neither', () => {
const { container } = mount()
expect(screen.getByText('Dawarich')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Wishlist' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Countries' })).toBeInTheDocument()
// A scan costs one upstream request per wish. Nothing is asked until asked.
expect(screen.queryByTestId('atlas-dialog')).toBeNull()
// And it wears the glass it was handed rather than one of its own.
expect(container.firstElementChild).toHaveStyle({ borderRadius: '20px' })
})
it('FE-DAWARICH-ATLASPANEL-003: the wishlist tile opens the dialog on the wishlist, and closing puts it away', () => {
mount()
fireEvent.click(screen.getByRole('button', { name: 'Wishlist' }))
expect(screen.getByText('asked: wishes')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'dismiss' }))
// Unmounted, not hidden: the next visit starts from a clean question rather
// than from an answer that is an hour old.
expect(screen.queryByTestId('atlas-dialog')).toBeNull()
})
it('FE-DAWARICH-ATLASPANEL-004: the countries tile opens the same dialog on the other question', () => {
mount()
fireEvent.click(screen.getByRole('button', { name: 'Countries' }))
expect(screen.getByText('asked: countries')).toBeInTheDocument()
expect(screen.queryByText('asked: wishes')).toBeNull()
})
it('FE-DAWARICH-ATLASPANEL-005: what the dialog wrote is reported up to the Atlas', () => {
// The Atlas keeps its own counts and its own map. Without this the confirmed
// countries only appear after a reload.
const onChanged = vi.fn()
mount({ onChanged })
fireEvent.click(screen.getByRole('button', { name: 'Countries' }))
fireEvent.click(screen.getByRole('button', { name: 'wrote something' }))
expect(onChanged).toHaveBeenCalledTimes(1)
})
it('FE-DAWARICH-ATLASPANEL-006: the tiles are a tint of the light the panel is made of, per theme', () => {
const { rerender } = render(<DawarichAtlasSidePanel style={GLASS} dark={false} />)
const wishes = screen.getByRole('button', { name: 'Wishlist' })
expect(rgba(wishes)).toBe('rgba(0,0,0,0.05)')
fireEvent.mouseEnter(wishes)
expect(rgba(wishes)).toBe('rgba(0,0,0,0.09)')
fireEvent.mouseLeave(wishes)
expect(rgba(wishes)).toBe('rgba(0,0,0,0.05)')
rerender(<DawarichAtlasSidePanel style={GLASS} dark />)
// Inverted on the dark map, not merely darkened: the tile is light added to
// the glass, and a black tint on a dark blurred map is an invisible button.
expect(rgba(screen.getByRole('button', { name: 'Wishlist' }))).toBe('rgba(255,255,255,0.07)')
})
it('FE-DAWARICH-ATLASPANEL-007: the glass glare follows the cursor and goes out behind it', () => {
const { container } = mount()
const panel = container.firstElementChild as HTMLElement
const [glare, borderGlare] = Array.from(panel.children) as HTMLElement[]
expect(glare.style.opacity).toBe('0')
fireEvent.mouseMove(panel, { clientX: 140, clientY: 60 })
// The pool of light has to sit under the pointer, not merely exist: the
// panel's box measures as the origin here, so the cursor's own coordinates
// are what should end up in the gradient. An effect that lit up in a fixed
// spot would pass an opacity-only assertion and look broken on screen.
expect(glare.style.background).toContain('at 140px 60px')
expect(glare.style.opacity).toBe('1')
expect(borderGlare.style.opacity).toBe('1')
fireEvent.mouseLeave(panel)
expect(glare.style.opacity).toBe('0')
expect(borderGlare.style.opacity).toBe('0')
})
})
@@ -1,133 +0,0 @@
import React, { useState } from 'react'
import { Globe2, Star } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { useAddonStore } from '../../store/addonStore'
import { Tooltip } from '../shared/Tooltip'
import { useGlassGlare } from '../Atlas/useGlassGlare'
import DawarichIcon from '../shared/DawarichIcon'
import DawarichAtlasDialog from './DawarichAtlasDialog'
type Question = 'wishes' | 'countries'
/**
* Dawarich's own panel on the Atlas, beside the stats.
*
* The Atlas is a map with a single glass panel floating over it, and everything
* it offers lives in that panel. Dawarich answers two questions about the same
* map — which wishes were actually reached, and which countries the recordings
* say you were in — but they are *its* answers, not the Atlas's own numbers, and
* squeezed under the wishlist they read as fine print nobody asked for.
*
* So it gets a panel of its own, in the same glass and stretched to the same
* height, and the two questions are two tiles built like the stat blocks beside
* them: a mark, then a small capitalised label. The lists they produce open in a
* dialog — they are offers to read and confirm, and a bar over a world map is no
* place to read anything.
*
* Renders nothing when the addon is off, so an Atlas without Dawarich looks
* exactly as it did before.
*/
export default function DawarichAtlasSidePanel({
style,
dark,
onChanged,
}: {
/** The glass the Atlas panels are made of, handed down so the two cannot drift. */
style: React.CSSProperties
dark: boolean
/** Called after something was written, so the Atlas can re-read itself. */
onChanged?: () => void
}): React.ReactElement | null {
const { t } = useTranslation()
const addonEnabled = useAddonStore(state => state.isEnabled)
const [asked, setAsked] = useState<Question | null>(null)
const glare = useGlassGlare(dark)
if (!addonEnabled('dawarich')) return null
// theme-lint-disable — the panel floats on a blurred map: a solid surface
// token would punch an opaque hole in the glass, so the tiles are a tint of
// the same light the panel is made of.
const tile = dark ? 'rgba(255,255,255,0.07)' : 'rgba(0,0,0,0.05)'
const tileHover = dark ? 'rgba(255,255,255,0.13)' : 'rgba(0,0,0,0.09)'
const question = (id: Question, Icon: React.ComponentType<{ size?: number; strokeWidth?: number }>, label: string) => (
<button
type="button"
onClick={() => setAsked(id)}
className="group flex flex-col items-center justify-center text-content-secondary hover:text-content"
style={{
background: tile,
border: 'none',
borderRadius: 14,
cursor: 'pointer',
fontFamily: 'inherit',
gap: 6,
minWidth: 74,
padding: '10px 12px',
transition: 'background 0.15s ease, color 0.15s ease',
}}
onMouseEnter={e => { e.currentTarget.style.background = tileHover }}
onMouseLeave={e => { e.currentTarget.style.background = tile }}
>
<Icon size={17} strokeWidth={2} />
<span
className="font-bold uppercase tracking-wide whitespace-nowrap"
style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))' }}
>
{label}
</span>
</button>
)
return (
<>
<div
ref={glare.panelRef}
onMouseMove={glare.onMouseMove}
onMouseLeave={glare.onMouseLeave}
className="relative hidden md:flex flex-col justify-center gap-3 overflow-hidden px-5 py-4"
style={style}
>
{/* Liquid glass glare, and the border glow that follows the cursor —
the same two layers the Atlas panel carries. */}
<div ref={glare.glareRef} className="absolute inset-0 pointer-events-none" style={{ opacity: 0, transition: 'opacity 0.3s ease', borderRadius: 20 }} />
<div ref={glare.borderGlareRef} className="absolute inset-0 pointer-events-none" style={{
opacity: 0, transition: 'opacity 0.3s ease', borderRadius: 20,
border: dark ? '1.5px solid rgba(255,255,255,0.5)' : '2px solid rgba(0,0,0,0.15)',
}} />
{/* The long explanation moved into the tooltip: on a panel this size it
was three lines of grey that said what the two tiles already say. */}
<Tooltip label={t('dawarich.atlas.trigger')} placement="top">
<span className="relative flex items-center justify-center gap-2.5">
<span className="flex-shrink-0 overflow-hidden rounded-[9px]">
<DawarichIcon size={30} />
</span>
<span
className="truncate font-black tracking-tight text-content"
style={{ fontSize: 'calc(16px * var(--fs-scale-subtitle, 1))' }}
>
{t('dawarich.title')}
</span>
</span>
</Tooltip>
<div className="relative flex items-stretch gap-2">
{question('wishes', Star, t('dawarich.atlas.tab.wishes'))}
{question('countries', Globe2, t('dawarich.atlas.tab.countries'))}
</div>
</div>
{/* Mounted on open so every visit starts from a clean question rather than
from a scan somebody ran an hour ago. */}
{asked !== null && (
<DawarichAtlasDialog
isOpen
initialTab={asked}
onClose={() => setAsked(null)}
onChanged={onChanged}
/>
)}
</>
)
}
@@ -0,0 +1,205 @@
import type { DawarichAtlasSuggestions, DawarichBucketScan } from '@trek/shared';
import { DAWARICH_BUCKET_MATCH_MIN_MINUTES, DAWARICH_BUCKET_MATCH_RADIUS_M } from '@trek/shared';
import { useState } from 'react';
import { useTranslation } from '../../i18n';
import { DawarichOfflineError, dawarichRepo } from '../../repo/dawarichRepo';
import { isEffectivelyOffline } from '../../sync/networkMode';
import { useToast } from '../shared/Toast';
import { countryWindow, newCountries, orderedMatches } from './dawarichAtlasModel';
export type DawarichAtlasTab = 'wishes' | 'countries';
/**
* What to tell the reader when a question could not be asked. Being offline is
* not an error the server reported (nothing was sent), and "something went
* wrong" for a plane journey sends somebody looking for a bug in Dawarich.
*/
export function dawarichFailureText(err: unknown, t: (key: string) => string): string {
if (err instanceof DawarichOfflineError) return t('dawarich.error.offline');
const data = (err as { response?: { data?: { error?: unknown } } })?.response?.data;
return typeof data?.error === 'string' ? data.error : t('dawarich.error.unknown');
}
function toggled<T>(set: Set<T>, value: T): Set<T> {
const next = new Set(set);
if (next.has(value)) next.delete(value);
else next.add(value);
return next;
}
/**
* The two questions Dawarich answers for the Atlas, "which wishes did I reach?"
* and "which countries was I in?", with one selection model and one confirm:
* the state behind the Atlas dialog and the Atlas hub's Dawarich tab alike.
* Nothing runs on its own; the Atlas is curated, so every write is confirmed.
*/
export function useDawarichAtlas({
initialTab = 'wishes',
onChanged,
}: { initialTab?: DawarichAtlasTab; onChanged?: () => void } = {}) {
const { t } = useTranslation();
const toast = useToast();
const [tab, setTab] = useState<DawarichAtlasTab>(initialTab);
const [scan, setScan] = useState<DawarichBucketScan | null>(null);
const [scanning, setScanning] = useState(false);
const [picked, setPicked] = useState<Set<number>>(new Set());
const [countries, setCountries] = useState<DawarichAtlasSuggestions | null>(null);
const [loadingCountries, setLoadingCountries] = useState(false);
const [pickedCountries, setPickedCountries] = useState<Set<string>>(new Set());
// One write at a time: a second press would send the same confirmation twice.
const [writing, setWriting] = useState(false);
const matches = orderedMatches(scan?.matches ?? []);
const openMatches = matches.filter((match) => !match.alreadyVisited);
const offered = newCountries(countries?.countries ?? []);
const runScan = async (): Promise<void> => {
setScanning(true);
try {
const result = await dawarichRepo.bucketScan();
setScan(result);
// Everything with a match starts selected: the common case is "yes, all of those".
setPicked(new Set(result.matches.filter((m) => m.match && !m.alreadyVisited).map((m) => m.itemId)));
} catch (err) {
toast.error(dawarichFailureText(err, t));
} finally {
setScanning(false);
}
};
const loadCountries = async (): Promise<void> => {
setLoadingCountries(true);
try {
const { from, to } = countryWindow(new Date());
const result = await dawarichRepo.atlasSuggestions(from, to);
setCountries(result);
setPickedCountries(new Set(newCountries(result.countries).map((c) => c.countryCode)));
} catch (err) {
toast.error(dawarichFailureText(err, t));
} finally {
setLoadingCountries(false);
}
};
const confirmWishes = async (): Promise<void> => {
if (picked.size === 0 || writing) return;
// Writes are online-only: firing one into a dead connection would hang to a
// timeout and then report a server error for something the server never saw.
if (isEffectivelyOffline()) {
toast.error(t('dawarich.error.offline'));
return;
}
setWriting(true);
try {
// Ticked off on the day each wish was reached, one request per day.
const byDate = new Map<string, number[]>();
for (const m of matches) {
if (!picked.has(m.itemId) || !m.match) continue;
const ids = byDate.get(m.match.at);
if (ids) ids.push(m.itemId);
else byDate.set(m.match.at, [m.itemId]);
}
const results = await Promise.all([...byDate].map(([at, ids]) => dawarichRepo.confirmBucketVisits(ids, at)));
toast.success(t('dawarich.bucket.confirmed', { count: results.reduce((sum, r) => sum + r.updated, 0) }));
setScan((prev) =>
prev === null
? prev
: { ...prev, matches: prev.matches.map((m) => (picked.has(m.itemId) ? { ...m, alreadyVisited: true } : m)) }
);
setPicked(new Set());
onChanged?.();
} catch (err) {
toast.error(dawarichFailureText(err, t));
} finally {
setWriting(false);
}
};
const confirmCountries = async (): Promise<void> => {
if (pickedCountries.size === 0 || writing) return;
if (isEffectivelyOffline()) {
toast.error(t('dawarich.error.offline'));
return;
}
setWriting(true);
try {
const result = await dawarichRepo.acceptAtlasCountries([...pickedCountries]);
toast.success(t('dawarich.atlas.accepted', { count: result.marked }));
setCountries((prev) =>
prev === null
? prev
: {
...prev,
countries: prev.countries.map((c) =>
pickedCountries.has(c.countryCode) ? { ...c, alreadyVisited: true } : c
),
}
);
setPickedCountries(new Set());
onChanged?.();
} catch (err) {
toast.error(dawarichFailureText(err, t));
} finally {
setWriting(false);
}
};
const busy = tab === 'wishes' ? scanning : loadingCountries;
const loaded = tab === 'wishes' ? scan !== null : countries !== null;
const selected = tab === 'wishes' ? picked.size : pickedCountries.size;
// Nothing found means nothing to confirm; the empty state says so in a sentence.
const anything = tab === 'wishes' ? matches.length > 0 : offered.length > 0;
return {
tab,
setTab,
scan,
scanning,
picked,
togglePicked: (id: number) => setPicked((prev) => toggled(prev, id)),
countries,
loadingCountries,
pickedCountries,
togglePickedCountry: (code: string) => setPickedCountries((prev) => toggled(prev, code)),
writing,
matches,
openMatches,
offered,
runScan,
loadCountries,
confirmWishes,
confirmCountries,
/** Ask the open tab's question (again). */
run: () => void (tab === 'wishes' ? runScan() : loadCountries()),
/** Confirm the open tab's selection. */
confirm: () => void (tab === 'wishes' ? confirmWishes() : confirmCountries()),
busy,
loaded,
selected,
anything,
};
}
export type DawarichAtlasState = ReturnType<typeof useDawarichAtlas>;
/** What Dawarich offers for one question, built once for the desktop tab; the phone builds its own rows. */
export function dawarichNotes(
d: DawarichAtlasState,
t: (key: string, params?: Record<string, string | number>) => string
): string[] {
if (d.tab === 'wishes') {
return [
d.scan && d.scan.skippedWithoutCoordinates > 0
? t('dawarich.bucket.skipped', { count: d.scan.skippedWithoutCoordinates })
: null,
d.scan?.truncated ? t('dawarich.bucket.truncated') : null,
t('dawarich.bucket.rule', { meters: DAWARICH_BUCKET_MATCH_RADIUS_M, count: DAWARICH_BUCKET_MATCH_MIN_MINUTES }),
].filter((n): n is string => !!n);
}
return [
d.countries && d.countries.unresolved.length > 0
? t('dawarich.atlas.unresolved', { names: d.countries.unresolved.join(', ') })
: null,
d.countries ? t('dawarich.atlas.window') : null,
].filter((n): n is string => !!n);
}
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '../../../tests/helpers/render'
import { useHelpStore } from '../../store/helpStore'
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect, beforeEach } from 'vitest'
import { http, HttpResponse } from 'msw'
import { render, screen, fireEvent, waitFor, within, act } from '../../../tests/helpers/render'
@@ -1,5 +1,4 @@
// FE-COMP-JOURNEYDATEPICKER-001 to FE-COMP-JOURNEYDATEPICKER-008
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
@@ -25,7 +25,6 @@
* what stops Leaflet from being handed zero-length polylines on every trip that
* has no recording.
*/
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import type { DawarichTrack, DawarichTrackDay } from '@trek/shared'
@@ -1,5 +1,4 @@
// FE-COMP-MAPCOMPASS-001 to FE-COMP-MAPCOMPASS-007
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent, act } from '../../../tests/helpers/render'
import { MapCompassPill, type CompassMap } from './MapCompassPill'
@@ -1,5 +1,4 @@
// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-024
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '../../../tests/helpers/render'
import { MapLayerSwitcher, TourMapLayerSwitcher, MAP_ROUND_CONTROL_SIZE } from './MapLayerSwitcher'
@@ -10,7 +10,7 @@
* The click itself has to keep taking Leaflet's route and the page's: it is what closes
* an open popup on the map, and an open context menu beside it.
*/
import React, { useState } from 'react'
import { useState } from 'react'
import { flushSync } from 'react-dom'
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest'
import { render, waitFor, act } from '../../../tests/helpers/render'
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import PlaceHoverCard from './PlaceHoverCard'
+5 -4
View File
@@ -3,6 +3,7 @@ import { pluginsApi } from '../../api/client'
import type { RouteEngine, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
import { haversineKm } from '../../utils/geo'
import { countRoute } from './routeUsageCounter'
import { routerAnswer } from './routerAsks'
import { cacheRoute, keepStandIn, rememberRoute, routeInMemory, standIn, storedRoute } from './routeStore'
import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
import type { RouteAlternative } from './routeTypes'
@@ -109,12 +110,12 @@ async function routedFetch(
const sample = { profile, surface: kind, selfHosted, waypoints: waypoints.length, km }
const asked = withoutUTurnIfRefused(url)
try {
const response = await fetch(asked, { signal })
const response = await routerAnswer(fetch(asked, { signal }))
countRoute({ ...sample, failed: !response.ok })
if (response.ok || !asked.includes(U_TURN_PARAM)) return response
const plain = await droppedUTurn(asked, response)
if (!plain) return response
const second = await fetch(plain, { signal })
const second = await routerAnswer(fetch(plain, { signal }))
countRoute({ ...sample, failed: !second.ok })
return second
} catch (err) {
@@ -636,11 +637,11 @@ export async function calculateRouteWithLegs(
const pluginProfile = parsePluginProfile(profile)
if (pluginProfile) {
if (tripId == null) throw new Error('Plugin routing needs a trip context')
const { route } = await pluginsApi.pluginRoute(pluginProfile.pluginId, pluginProfile.profileId, {
const { route } = await routerAnswer(pluginsApi.pluginRoute(pluginProfile.pluginId, pluginProfile.profileId, {
tripId,
dayId: dayId ?? null,
waypoints: waypoints.map((p) => ({ lat: p.lat, lng: p.lng })),
}, { signal })
}, { signal }))
if (!route) throw new Error('No route found')
const legs = route.legs.map((leg, i): RouteSegment => ({
...legSegment(leg, i, waypoints),
@@ -0,0 +1,238 @@
import { encodePolyline6 } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { buildAssignment, buildDay, buildPlace } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import type { AssignmentsMap, Settings } from '../../types';
const RELAY = '/api/routing/valhalla/route';
const FOSSGIS_OSRM = 'https://routing.openstreetmap.de/routed-car/route/v1/driving';
const OWN_OSRM = 'https://osrm.example.org';
const OWN_VALHALLA = 'https://valhalla.example.org';
type Point = { lat: number; lon: number };
/** Valhalla's trip through some points: one leg per pair. */
function valhallaTrip(points: Point[]) {
const legs = points.slice(1).map((to, i) => ({
shape: encodePolyline6([points[i], to]),
summary: { length: 2, time: 300, has_toll: false, has_highway: false, has_ferry: false },
}));
return { trip: { legs, summary: { length: 2 * legs.length, time: 300 * legs.length } } };
}
/** OSRM's answer for a request's coordinates: one leg per pair. */
function osrmAnswer(coords: string) {
const points = coords.split(';').map((pair) => pair.split(',').map(Number));
const legs = points.slice(1).map(() => ({ distance: 1000, duration: 120 }));
return {
code: 'Ok',
routes: [{ geometry: { coordinates: points }, distance: 1000 * legs.length, duration: 120 * legs.length, legs }],
waypoints: points.map((location) => ({ location, distance: 0 })),
};
}
/** Every routing host answering, the relay as `relay` says; each request is counted. */
function listen(relay: (locations: Point[]) => Response) {
const asked: string[] = [];
const valhalla =
(name: string, answer: (locations: Point[]) => Response) =>
async ({ request }: { request: Request }) => {
asked.push(name);
const body = (await request.json()) as { locations: Point[] };
return answer(body.locations);
};
const osrm =
(name: string) =>
({ params }: { params: Record<string, unknown> }) => {
asked.push(name);
return HttpResponse.json(osrmAnswer(String(params.coords)));
};
const ok = (locations: Point[]) => HttpResponse.json(valhallaTrip(locations));
server.use(
http.post(RELAY, valhalla('relay', relay)),
http.post('https://valhalla1.openstreetmap.de/route', valhalla('fossgis-valhalla', ok)),
http.post(`${OWN_VALHALLA}/route`, valhalla('own-valhalla', ok)),
http.get(`${FOSSGIS_OSRM}/:coords`, osrm('fossgis-osrm')),
http.get(`${OWN_OSRM}/route/v1/driving/:coords`, osrm('own-osrm'))
);
return asked;
}
let seed = 0;
/** A trip of three days with three stops each, at points no other test asked for. */
function freshTrip() {
seed += 1;
const days = [1, 2, 3].map((n) => buildDay({ id: seed * 10 + n, day_number: n }));
const assignments: AssignmentsMap = {};
for (const day of days) {
assignments[String(day.id)] = [0, 1, 2].map((i) =>
buildAssignment({
day_id: day.id,
order_index: i,
place: buildPlace({ lat: 30 + seed / 10 + (day.day_number ?? 0) / 100, lng: 5 + i / 100 }),
})
);
}
return { days, assignments, reservations: [], accommodations: [], optimizeFromAccommodation: false };
}
/** A fresh page: every module, the routes in memory and the relay's rest start over; the device keeps its database. */
async function reload(settings: Partial<Settings>) {
vi.resetModules();
const { useSettingsStore } = await import('../../store/settingsStore');
useSettingsStore.setState((st) => ({ settings: { ...st.settings, ...settings } }));
return import('./tripRouteGeometry');
}
/** Lets the writes to the device cache, which nobody awaits, land. */
async function settle() {
const { offlineDb } = await import('../../db/offlineDb');
await offlineDb.routeCache.count();
await new Promise((resolve) => setTimeout(resolve, 20));
}
afterEach(() => {
vi.restoreAllMocks();
// The relay's rest is kept on the device; each test starts from a relay never asked.
localStorage.clear();
});
const PROVIDERS: [string, Partial<Settings>, (locations: Point[]) => Response][] = [
['the TREK services', {}, (locations) => HttpResponse.json(valhallaTrip(locations))],
['the TREK services, not set up here', {}, () => HttpResponse.json({ error: 'not available' }, { status: 503 })],
['the TREK services, too slow', {}, () => HttpResponse.json({ error: 'too slow' }, { status: 504 })],
['FOSSGIS', { routing_valhalla_provider: 'fossgis' }, () => HttpResponse.json({}, { status: 500 })],
['an own OSRM', { routing_base_url: OWN_OSRM }, () => HttpResponse.json({}, { status: 500 })],
['an own Valhalla', { valhalla_base_url: OWN_VALHALLA }, () => HttpResponse.json({}, { status: 500 })],
];
describe('a routed trip after a reload (#3228)', () => {
it.each(PROVIDERS)(
'RCR-001: with %s every day is drawn from the device without asking a router',
async (_name, settings, relay) => {
const asked = listen(relay);
const trip = freshTrip();
const first = await reload(settings);
const plan = first.planTripRoute(trip, 'driving');
const routed = await first.routeTripLegs(plan, { tripId: 1 });
expect(routed.flat(2).every(Boolean)).toBe(true);
expect(asked.length).toBeGreaterThan(0);
await settle();
asked.length = 0;
const second = await reload(settings);
const again = await second.routeTripLegs(second.planTripRoute(trip, 'driving'), { tripId: 1 });
expect(again.flat(2).every(Boolean)).toBe(true);
expect(asked).toEqual([]);
},
30_000
);
it('RCR-002: legs the device answers are not paced like requests, however long the device takes to read', async () => {
// A reload empties the routes in memory, so every leg is read back from the device,
// and on a page busy drawing the map such a read takes well past 60 ms. Paced as a
// request, each leg then waited 1.1 s and the trip filled in as slowly as a cold one.
const asked = listen((locations) => HttpResponse.json(valhallaTrip(locations)));
const trip = freshTrip();
const first = await reload({ routing_valhalla_provider: 'fossgis' });
await first.routeTripLegs(first.planTripRoute(trip, 'driving'), { tripId: 1 });
await settle();
asked.length = 0;
const second = await reload({ routing_valhalla_provider: 'fossgis' });
const { routeCacheRepo } = await import('../../repo/routeCacheRepo');
const read = routeCacheRepo.get.bind(routeCacheRepo);
vi.spyOn(routeCacheRepo, 'get').mockImplementation(async (key, maxAgeMs) => {
await new Promise((resolve) => setTimeout(resolve, 100));
return read(key, maxAgeMs);
});
const startedAt = performance.now();
const again = await second.routeTripLegs(second.planTripRoute(trip, 'driving'), { tripId: 1 });
expect(again.flat(2).every(Boolean)).toBe(true);
expect(asked).toEqual([]);
expect(performance.now() - startedAt).toBeLessThan(1000);
}, 30_000);
const REFUSING: [string, Partial<Settings>, (locations: Point[]) => Response][] = [
PROVIDERS[1],
[
'the TREK services, over their allowance',
{},
() => HttpResponse.json({ error: 'slow down' }, { status: 429, headers: { 'Retry-After': '600' } }),
],
];
it.each(REFUSING)(
'RCR-003: with %s a new tab does not put a day to the relay again while it rests',
async (_name, settings, relay) => {
// The relay said no for this instance, not for one tab. Kept for the tab alone, a new
// tab or a reopened app asked it again and the next day waited for the refusal.
const asked = listen(relay);
const first = await reload(settings);
await first.routeTripLegs(first.planTripRoute(freshTrip(), 'driving'), { tripId: 1 });
expect(asked.filter((name) => name === 'relay')).toHaveLength(1);
await settle();
asked.length = 0;
sessionStorage.clear();
const second = await reload(settings);
const again = await second.routeTripLegs(second.planTripRoute(freshTrip(), 'driving'), { tripId: 1 });
expect(again.flat(2).every(Boolean)).toBe(true);
expect(asked.filter((name) => name === 'relay')).toEqual([]);
},
30_000
);
const ASKING: [string, Partial<Settings>, string][] = [
['the TREK services', {}, 'relay'],
['an own Valhalla', { valhalla_base_url: OWN_VALHALLA }, 'own-valhalla'],
['an own OSRM', { routing_base_url: OWN_OSRM }, 'own-osrm'],
];
it.each(ASKING)(
'RCR-004: with %s the days a router is asked for go out a request apart',
async (_name, settings, host) => {
// The other side of RCR-002: a leg that did go out keeps its pause, or the public
// routers get a burst and answer 429 from the second request on.
const at: number[] = [];
const asked = listen((locations) => HttpResponse.json(valhallaTrip(locations)));
const trip = freshTrip();
const page = await reload(settings);
const startedAt = performance.now();
await page.routeTripLegs(page.planTripRoute(trip, 'driving'), {
tripId: 1,
onProgress: (done) => {
if (done > 0) at.push(performance.now() - startedAt);
},
});
expect(asked).toEqual([host, host, host]);
expect(at[1] - at[0]).toBeGreaterThanOrEqual(1000);
expect(at[2] - at[1]).toBeGreaterThanOrEqual(1000);
},
30_000
);
it.each([
['the TREK services', {}],
['an own OSRM', { routing_base_url: OWN_OSRM }],
] as [string, Partial<Settings>][])(
'RCR-005: with %s a round that reaches no router ends at once',
async (_name, settings) => {
// Offline, or a host that is not there: nothing went out, so nothing waits a pause.
server.use(
http.post(RELAY, () => HttpResponse.error()),
http.get(`${FOSSGIS_OSRM}/:coords`, () => HttpResponse.error()),
http.get(`${OWN_OSRM}/route/v1/driving/:coords`, () => HttpResponse.error())
);
const page = await reload(settings);
const startedAt = performance.now();
await page.routeTripLegs(page.planTripRoute(freshTrip(), 'driving'), { tripId: 1 });
expect(performance.now() - startedAt).toBeLessThan(1000);
},
30_000
);
});
@@ -0,0 +1,153 @@
import { encodePolyline6 } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { afterEach, describe, expect, it } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { useSettingsStore } from '../../store/settingsStore';
import type { Settings, Waypoint } from '../../types';
import { calculateRouteWithLegs } from './RouteCalculator';
import { routerAnswer, routerAsks } from './routerAsks';
import { resetValhallaTurns } from './valhallaRoute';
const RELAY = '/api/routing/valhalla/route';
const FOSSGIS_OSRM = 'https://routing.openstreetmap.de/routed-car/route/v1/driving';
const OWN_OSRM = 'https://osrm.example.org';
const OWN_VALHALLA = 'https://valhalla.example.org';
const PLUGIN = '/api/plugin-routes/charger/fast';
type Point = { lat: number; lon: number };
let seed = 0;
/** Points no other test asked for, so no route cache answers in their place. */
function freshDay(count: number): Waypoint[] {
seed += 1;
return Array.from({ length: count }, (_, i) => ({ lat: 20 + seed / 100, lng: 8 + i / 100 }));
}
function valhallaTrip(points: Point[]) {
const legs = points.slice(1).map((to, i) => ({
shape: encodePolyline6([points[i], to]),
summary: { length: 2, time: 300, has_toll: false, has_highway: false, has_ferry: false },
}));
return { trip: { legs, summary: { length: 2 * legs.length, time: 300 * legs.length } } };
}
function osrmAnswer(coords: string) {
const points = coords.split(';').map((pair) => pair.split(',').map(Number));
const legs = points.slice(1).map(() => ({ distance: 1000, duration: 120 }));
return {
code: 'Ok',
routes: [{ geometry: { coordinates: points }, distance: 1000 * legs.length, duration: 120 * legs.length, legs }],
waypoints: points.map((location) => ({ location, distance: 0 })),
};
}
const pluginRoute = {
pluginId: 'charger',
profile: 'fast',
coordinates: [
[20, 8],
[20, 8.01],
],
distance: 1000,
duration: 120,
legs: [{ distance: 1000, duration: 120 }],
viaPoints: [],
};
const choose = (patch: Partial<Settings>) =>
useSettingsStore.setState((st) => ({ settings: { ...st.settings, ...patch } }));
/** How many questions a router answered while `action` ran. */
async function answersDuring(action: () => Promise<unknown>): Promise<number> {
const before = routerAsks();
// A refused question rejects; whether it counted is what the caller looks at.
await Promise.allSettled([action()]);
return routerAsks() - before;
}
afterEach(() => {
choose({ routing_valhalla_provider: '', valhalla_base_url: '', routing_base_url: '' });
resetValhallaTurns();
});
describe('questions a router answered (#3228)', () => {
it('RASK-001: an OSRM answer counts, a refusal and a rate limit included', async () => {
choose({ routing_valhalla_provider: 'fossgis', routing_base_url: OWN_OSRM });
let status = 200;
server.use(
http.get(`${OWN_OSRM}/route/v1/driving/:coords`, ({ params }) =>
status === 200 ? HttpResponse.json(osrmAnswer(String(params.coords))) : HttpResponse.json({}, { status })
)
);
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(1);
status = 429;
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(1);
});
it('RASK-002: an OSRM that refuses the u-turn permission and is asked again counts twice', async () => {
choose({ routing_valhalla_provider: 'fossgis', routing_base_url: OWN_OSRM });
server.use(
http.get(`${OWN_OSRM}/route/v1/driving/:coords`, ({ request, params }) =>
request.url.includes('continue_straight')
? HttpResponse.json({ code: 'InvalidQuery' }, { status: 400 })
: HttpResponse.json(osrmAnswer(String(params.coords)))
)
);
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(3), { profile: 'driving' }))).toBe(2);
});
it('RASK-003: the TREK relay and an own Valhalla count', async () => {
server.use(
http.post(RELAY, async ({ request }) =>
HttpResponse.json(valhallaTrip(((await request.json()) as { locations: Point[] }).locations))
),
http.post(`${OWN_VALHALLA}/route`, async ({ request }) =>
HttpResponse.json(valhallaTrip(((await request.json()) as { locations: Point[] }).locations))
)
);
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(1);
choose({ valhalla_base_url: OWN_VALHALLA });
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(1);
});
it('RASK-004: a plugin route counts, a refusal included', async () => {
let status = 200;
server.use(
http.post(PLUGIN, () =>
status === 200 ? HttpResponse.json({ route: pluginRoute }) : HttpResponse.json({ error: 'busy' }, { status })
)
);
const ask = () => calculateRouteWithLegs(freshDay(2), { profile: 'plugin:charger/fast', tripId: 1, dayId: seed });
expect(await answersDuring(ask)).toBe(1);
status = 429;
expect(await answersDuring(ask)).toBe(1);
});
it('RASK-005: a question that never reached a router adds nothing', async () => {
// Offline, an unknown host, a refused connection: nothing went out that a router
// could count against this device, so nothing is paced for it either.
server.use(
http.post(RELAY, () => HttpResponse.error()),
http.get(`${FOSSGIS_OSRM}/:coords`, () => HttpResponse.error()),
http.get(`${OWN_OSRM}/route/v1/driving/:coords`, () => HttpResponse.error()),
http.post(PLUGIN, () => HttpResponse.error())
);
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(0);
resetValhallaTurns();
choose({ routing_valhalla_provider: 'fossgis', routing_base_url: OWN_OSRM });
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(0);
expect(
await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'plugin:charger/fast', tripId: 1 }))
).toBe(0);
});
it('RASK-006: an error that carries a router reply still counts as answered', async () => {
const before = routerAsks();
await expect(
routerAnswer(Promise.reject(Object.assign(new Error('429'), { response: { status: 429 } })))
).rejects.toThrow('429');
await expect(routerAnswer(Promise.reject(new TypeError('Failed to fetch')))).rejects.toThrow('Failed to fetch');
expect(routerAsks() - before).toBe(1);
});
});
+43
View File
@@ -0,0 +1,43 @@
/**
* How many questions a router has answered in this tab: OSRM, a Valhalla (the relay
* included) or a plugin's route provider. A route the cache answers adds nothing.
*
* The rounds that pace their requests (the whole trip's route, the road trip rail)
* compare this before and after a leg to tell a leg that went out from one the cache
* answered. They used to go by how long the leg took, and a leg read back from the
* device after a reload often takes longer than that guess allowed on a page busy
* drawing the map, so every leg waited out a request's pause and the trip filled in
* as slowly as one never routed before (#3228).
*/
let answered = 0;
/**
* Whether a failed question still reached a router: an axios error that carries the
* router's reply. A fetch that throws never got one (offline, an unknown host, a refused
* connection, a question given up).
*/
function cameBackWithAnswer(err: unknown): boolean {
return typeof err === 'object' && err !== null && 'response' in err && Boolean(err.response);
}
/**
* Waits for a question to a router and notes it once the router answered, whatever it
* said, a refusal or a rate limit included. A question that never reached one adds
* nothing, so a round that cannot reach any router (offline above all) ends at once
* instead of waiting a request's pause after every leg.
*/
export async function routerAnswer<T>(question: Promise<T>): Promise<T> {
try {
const answer = await question;
answered += 1;
return answer;
} catch (err) {
if (cameBackWithAnswer(err)) answered += 1;
throw err;
}
}
/** Questions a router has answered so far; only the difference between two readings means anything. */
export function routerAsks(): number {
return answered;
}
@@ -11,6 +11,14 @@ vi.mock('./RouteCalculator', async (importActual) => {
const { calculateRouteWithLegs, RoutingRefusedError } = await import('./RouteCalculator')
// Whether the mocked router's answers count as requests that went out. A round paces
// only those; by default the mock answers like the cache, and the pacing tests say otherwise.
const router = vi.hoisted(() => ({ overNetwork: false, asked: 0 }))
vi.mock('./routerAsks', () => ({
routerAnswer: <T>(question: Promise<T>) => question,
routerAsks: () => (router.overNetwork ? ++router.asked : router.asked),
}))
const leg = (distance: number): RouteSegment => ({
mid: [0, 0], from: [0, 0], to: [0, 0], distance, duration: 600,
distanceText: '10 km', durationText: '10 min', walkingText: '2 h', drivingText: '10 min',
@@ -39,6 +47,7 @@ const ASSIGNMENTS: AssignmentsMap = {
const input = { days: DAYS, assignments: ASSIGNMENTS, reservations: [], accommodations: [], optimizeFromAccommodation: false }
beforeEach(() => {
router.overNetwork = false
vi.mocked(calculateRouteWithLegs).mockReset()
vi.mocked(calculateRouteWithLegs).mockResolvedValue({
coordinates: [[48.86, 2.35], [48.90, 2.42]],
@@ -119,6 +128,7 @@ describe('tripRouteGeometry', () => {
it('FE-MAP-TRG-014: a host that never answers costs one leg its road, not the whole round', async () => {
neverAnswers()
router.overNetwork = true
vi.useFakeTimers()
try {
const pending = routeTrip(input, { profile: 'driving', tripId: 7 })
@@ -139,6 +149,7 @@ describe('tripRouteGeometry', () => {
// once is exactly the burst they answer with 429 from the second second on, and each
// refused leg used to stay a straight line with no distance and no word about it.
it('FE-MAP-TRG-007: asks the router one leg at a time, a second apart', async () => {
router.overNetwork = true
vi.useFakeTimers()
try {
// A round trip takes time; only a network answer is paced, a cache hit is not.
@@ -165,6 +176,7 @@ describe('tripRouteGeometry', () => {
})
it('FE-MAP-TRG-008: a rate limit is waited out and the leg asked for again', async () => {
router.overNetwork = true
vi.useFakeTimers()
try {
vi.mocked(calculateRouteWithLegs)
@@ -187,6 +199,7 @@ describe('tripRouteGeometry', () => {
})
it('FE-MAP-TRG-009: a host that says how long to wait is given that long', async () => {
router.overNetwork = true
vi.useFakeTimers()
try {
vi.mocked(calculateRouteWithLegs)
@@ -1,5 +1,6 @@
import type { RouteProfileKey } from './RouteCalculator'
import { calculateRouteWithRetries, sleepUnlessAborted as sleep } from './routeRetry'
import { routerAsks } from './routerAsks'
import { buildDayRouteRuns, type DayRouteInputs, type DayRoutePoint } from './dayRoutePlan'
import { dayViaLookup, foldViaLegs, threadVias, viasOnDayLeg, type DayViaLookup } from '../../utils/dayRouteVias'
import { projectDayItinerary } from './dayTourProjection'
@@ -185,8 +186,6 @@ export function summariseTripRoute(days: TripOverviewDay[]): TripRouteSummary {
* first and paces itself the same way).
*/
const REQUEST_SPACING_MS = 1100
/** Anything answered faster than this came out of RouteCalculator's cache, not the network. */
const CACHE_HIT_MS = 60
/**
* The longest one leg may take, its rate-limit retries included. The OSRM request has no
* deadline of its own, and a round that waits for every leg must not hang on a host that
@@ -258,10 +257,12 @@ export async function routeTripLegs(
onProgress?.(0, tasks.length)
for (let i = 0; i < tasks.length; i++) {
if (signal?.aborted) break
const startedAt = performance.now()
const asksBefore = routerAsks()
await tasks[i]()
onProgress?.(i + 1, tasks.length)
const wasNetwork = performance.now() - startedAt > CACHE_HIT_MS
// Paced by what went out, not by how long the leg took: a leg read back from the
// device after a reload can take longer than a request on a busy page (#3228).
const wasNetwork = routerAsks() !== asksBefore
if (wasNetwork && i < tasks.length - 1) await sleep(REQUEST_SPACING_MS, signal)
}
return routed
@@ -0,0 +1,29 @@
/**
* Where the TREK routing relay's rest outlives the page. Without it every reload, every
* new tab and every reopened app put the first day it routed to a relay that had just said
* it could not answer, and that day waited for the refusal again before its kept road
* showed (#3228). The relay is the instance's, so its rest holds for every tab of this
* device and ends when it would have; a device that cannot store it simply asks again.
*/
const RELAY_REST_KEY = 'trek_valhalla_relay_rest';
/** Until when the relay rests, as kept on this device; 0 when it does not. */
export function keptRelayRest(): number {
try {
const until = Number(localStorage.getItem(RELAY_REST_KEY));
return Number.isFinite(until) && until > Date.now() ? until : 0;
} catch {
// No storage here (a private window, a blocked origin): the relay is asked again.
return 0;
}
}
/** Keeps the relay's rest on this device until then; 0 forgets it. */
export function keepRelayRest(until: number): void {
try {
if (until > 0) localStorage.setItem(RELAY_REST_KEY, String(until));
else localStorage.removeItem(RELAY_REST_KEY);
} catch {
// No storage here: the rest holds for this page only.
}
}
+14 -6
View File
@@ -11,6 +11,8 @@ import { useSettingsStore } from '../../store/settingsStore'
import { decodePolyline } from './transitGeometry'
import { ferrySpansOf, type ValhallaManeuver } from './valhallaFerries'
import { haversineKm } from '../../utils/geo'
import { routerAnswer } from './routerAsks'
import { keepRelayRest, keptRelayRest } from './valhallaRelayRest'
import type { Waypoint, SnappedWaypoint, RouteAvoidClass } from '../../types'
/**
@@ -211,7 +213,13 @@ export interface ValhallaRun {
}
/** Until when this tab asks FOSSGIS instead of a relay that could not answer. */
let relayRestingUntil = 0
let relayRestingUntil = keptRelayRest()
/** Rests the relay until then, on this page and on the device (valhallaRelayRest). */
function restRelay(until: number): void {
relayRestingUntil = until
keepRelayRest(until)
}
/**
* The instance's Valhalla, or null when it should not ask one.
@@ -503,7 +511,7 @@ export async function valhallaTurn(base: string, signal?: AbortSignal): Promise<
/** Forget the last turn and a resting relay, for tests that start from a quiet host. */
export function resetValhallaTurns(): void {
lastPublicAskAt = 0
relayRestingUntil = 0
restRelay(0)
}
/**
@@ -544,13 +552,13 @@ function withDeadline(action: ValhallaRelayAction, signal?: AbortSignal): AbortS
async function askRelay(action: ValhallaRelayAction, body: object, signal?: AbortSignal): Promise<Response | null> {
let wait = RELAY_REST_MS
try {
const response = await valhallaRelayRepo.ask(action, body, withDeadline(action, signal))
const response = await routerAnswer(valhallaRelayRepo.ask(action, body, withDeadline(action, signal)))
if (!(await relayCannotAnswer(response))) return response
wait = Math.min(relayWait(response) ?? RELAY_REST_MS, RELAY_MAX_WAIT_MS)
} catch (err) {
if (signal?.aborted) throw err
}
relayRestingUntil = Date.now() + wait
restRelay(Date.now() + wait)
return null
}
@@ -575,7 +583,7 @@ export async function valhallaPost(
if (base === TREK_VALHALLA && (!publicFallback || overPublicLimit(action, body))) return new Response(null, { status: 503 })
const host = base === TREK_VALHALLA ? FOSSGIS_VALHALLA : base
await valhallaTurn(host, signal)
return fetch(`${host}/${action}`, {
return routerAnswer(fetch(`${host}/${action}`, {
method: 'POST',
// A browser cannot set User-Agent, so this is the whole of what FOSSGIS asks a
// client to identify itself with. It costs a preflight, which is answered.
@@ -583,7 +591,7 @@ export async function valhallaPost(
body: JSON.stringify(body),
// An own Valhalla routes every day, so one that hangs would hold each of them up.
signal: host === FOSSGIS_VALHALLA ? signal : withDeadline(action, signal),
})
}))
}
/** Whether a route carries more locations than the public instance takes, so it cannot stand in for the relay. */
@@ -1,4 +1,3 @@
import React from 'react'
import { createPortal } from 'react-dom'
import { useState, useRef, useEffect, useMemo } from 'react'
import { Plane, X, Check } from 'lucide-react'
@@ -1,5 +1,4 @@
// FE-PLANNER-DAYDETAIL-001 to FE-PLANNER-DAYDETAIL-101
import React from 'react';
import { fireEvent, render, screen, waitFor, within, act } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { fireEvent, render, screen } from '../../../tests/helpers/render'
import AnchoredPopover from './AnchoredPopover'
@@ -1,4 +1,3 @@
import React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { TranslationProvider } from '../../i18n'
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
import { Footprints } from 'lucide-react'
@@ -1,4 +1,3 @@
import React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { TranslationProvider } from '../../i18n'
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { fireEvent, render, screen } from '../../../tests/helpers/render'
import { useSettingsStore } from '../../store/settingsStore'
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { Fuel, Zap, Utensils } from 'lucide-react'
import { fireEvent, render, screen, within } from '../../../tests/helpers/render'
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { fireEvent, render, screen } from '../../../tests/helpers/render'
import RoadtripDayPicker from './RoadtripDayPicker'
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { fireEvent, render, screen } from '../../../tests/helpers/render'
import { useSettingsStore } from '../../store/settingsStore'
@@ -1,4 +1,3 @@
import React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen, within } from '@testing-library/react'
import { TranslationProvider } from '../../i18n'
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'
import { useSettingsStore } from '../../store/settingsStore'
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { fireEvent, render, screen } from '../../../tests/helpers/render'
import { useSettingsStore } from '../../store/settingsStore'
@@ -1,4 +1,3 @@
import React from 'react'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { fireEvent, render, screen } from '../../../tests/helpers/render'
import StopKindPicker from './StopKindPicker'
@@ -27,6 +27,7 @@ import { useRoadtripRoutes } from './useRoadtripRoutes'
import { DEFAULT_SETTINGS, useSettingsStore } from '../../store/settingsStore'
import { useTripStore } from '../../store/tripStore'
import { lineMetres } from './corridor'
import { routerAnswer } from '../Map/routerAsks'
const HAMBURG: [number, number] = [53.5511, 9.9937]
const LUENEBURG: [number, number] = [53.2464, 10.4115]
@@ -831,6 +832,45 @@ describe('useRoadtripRoutes', () => {
}
})
it('FE-ROADTRIP-ROUTES-067: days and joins the device answers slowly are still not paced like requests (#3228)', async () => {
// After a reload every road is read back from the device rather than from memory,
// and on a page busy drawing the map that read can take longer than a request. No
// router is asked here, so nothing may wait a request's 1.1 s turn.
calculateRouteWithLegs.mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(routed(1)), 100)))
const MUNICH: [number, number] = [48.1374, 11.5755]
const INNSBRUCK: [number, number] = [47.2692, 11.4041]
const BOZEN: [number, number] = [46.4983, 11.3548]
setting({ roadtrip_connect_days: true })
const daysList = [day(1, 1), day(2, 2), day(3, 3)]
const assignments = {
...map(1, [{ id: 1, at: HAMBURG, time: '09:00' }, { id: 2, at: LUENEBURG }]),
...map(2, [{ id: 3, at: BERLIN, time: '09:00' }, { id: 4, at: MUNICH }]),
...map(3, [{ id: 5, at: INNSBRUCK, time: '09:00' }, { id: 6, at: BOZEN }]),
} as AssignmentsMap
renderHook(() => useRoadtripRoutes(7, daysList, assignments))
await waitFor(() => {
expect(askedFor(INNSBRUCK, BOZEN).length).toBeGreaterThan(0)
expect(askedFor(MUNICH, INNSBRUCK).length).toBeGreaterThan(0)
}, { timeout: 1000 })
})
it('FE-ROADTRIP-ROUTES-068: days a router answers still go out a request apart (#3228)', async () => {
// The other side of FE-ROADTRIP-ROUTES-067: a day that did reach a router keeps its
// pause, or the public OSRM gets a burst and answers 429 from the second day on.
const askedAt: number[] = []
calculateRouteWithLegs.mockImplementation(() => {
askedAt.push(performance.now())
return routerAnswer(Promise.resolve(routed(1)))
})
const { days: daysList, assignments } = twoDays()
const { result } = renderHook(() => useRoadtripRoutes(7, daysList, assignments))
await waitFor(() => expect(result.current.loading).toBe(false), { timeout: 4000 })
expect(askedAt).toHaveLength(2)
expect(askedAt[1] - askedAt[0]).toBeGreaterThanOrEqual(1000)
})
it('FE-ROADTRIP-ROUTES-051: a join OSRM answered in the engine’s place is drawn, flagged, and asked for again on request', async () => {
// Filed like any answer, it stood in for the weighed road until the page was loaded
// again, and a picker on it read the stand-in line as the road already taken.
@@ -2,6 +2,7 @@ import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import { assembleRoadtrip, bookendStaysOf, carrierLegsFor, carrierSeam, foldRouteRun, hotelBookendsOn, isCarrierMode, isStationaryJoin, mergeRouteSegments, oneNightPerStay, seatCarrierStops, seatNightBookends, standsAsDay, terminalAssignmentId, viasOnLeg, type CarrierSeam, type RoadtripStop, type RoadtripRoutes, type PlanDay, type QuietDay, type RoutedLeg } from '@trek/shared/roadtrip'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { avoidedClasses, calculateRouteWithLegs, routeEngineFor, RoutingRefusedError } from '../Map/RouteCalculator'
import { routerAsks } from '../Map/routerAsks'
import { resolveLegMode } from '../Planner/legMode'
import { splitIntoRuns, parseAvoid, type DriveLimits } from './roadtripModel'
import { spillChains } from './nightSpill'
@@ -25,8 +26,6 @@ export type { RoadtripStop, RoadtripDay, RoadtripRoutes, QuietDay, AccessSpur, R
* the first handful answer and the rest come back 429.
*/
const REQUEST_SPACING_MS = 1100
/** Anything answered faster than this came out of RouteCalculator cache, not the network. */
const CACHE_HIT_MS = 60
/** How often a leg that failed (usually a rate limit) is tried again, and how long after. */
const RETRY_DELAYS_MS = [1500, 4000]
@@ -596,14 +595,15 @@ export function useRoadtripRoutes(
void (async () => {
for (let i = 0; i < tasks.length; i++) {
if (controller.signal.aborted) return
const startedAt = performance.now()
const asksBefore = routerAsks()
await tasks[i]()
if (controller.signal.aborted) return
publish()
// Only pace what actually went out. RouteCalculator answers a repeat from its
// cache in well under a millisecond, and switching back into road trip mode is
// all repeats — waiting a second between those made a warm view feel broken.
const wasNetwork = performance.now() - startedAt > CACHE_HIT_MS
// Only pace what actually went out. Switching back into road trip mode is all
// repeats, and reopening the trip reads them back from the device, which can take
// longer than a request would on a busy page: a second between those made a warm
// view feel broken and a reload look like nothing was kept (#3228).
const wasNetwork = routerAsks() !== asksBefore
if (wasNetwork && i < tasks.length - 1) await sleep(REQUEST_SPACING_MS, controller.signal)
}
if (controller.signal.aborted) return
@@ -770,7 +770,7 @@ export function useRoadtripRoutes(
// shape: it is asked for on its own, so the points the traveller dropped on it
// never reached the router and dragging one did visibly nothing.
const shaping = viasOnLeg(seam.from, seam.to, viasByDay[seam.from.ownerDayId] ?? [])
const startedAt = performance.now()
const asksBefore = routerAsks()
const r = await calculateRouteWithLegs(
[
{ lat: seam.from.lat, lng: seam.from.lng },
@@ -782,7 +782,7 @@ export function useRoadtripRoutes(
// A seam this device routed before came back from its cache and went nowhere, so
// its slot goes back before the store below re-runs this effect. Holding it made a
// trip of connected days wait a second per join on every open (#2794).
if (performance.now() - startedAt <= CACHE_HIT_MS) release()
if (routerAsks() === asksBefore) release()
if (controller.signal.aborted) return
// One leg per waypoint PAIR, so a shaped seam comes back in pieces and the rail
// wants the whole drive: merged here, exactly as a day run folds its via legs
@@ -1,4 +1,3 @@
import React from 'react';
import { render, screen } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { resetAllStores } from '../../../tests/helpers/store';
@@ -1,4 +1,3 @@
import React from 'react'
import { selectionHaptic } from '../../native/haptics'
/** The track and the knob glide with the same easing the planner's panels use. */
@@ -1,7 +1,6 @@
// FE-COMP-VCYCAL-001 to FE-COMP-VCYCAL-010
// Covers what the mocked month card in VacayCalendar.test.tsx cannot reach: the
// trip overlay, the per-day maps handed down to the cards, and the hover tooltip.
import React from 'react'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'
@@ -1,5 +1,4 @@
// FE-COMP-VCYMC-001 to FE-COMP-VCYMC-004
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent, within } from '../../../tests/helpers/render'
import VacayMonthCard from './VacayMonthCard'
@@ -1,5 +1,4 @@
// FE-COMP-VCYPERS-001 to FE-COMP-VCYPERS-007
import React from 'react'
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'
@@ -1,7 +1,6 @@
// FE-COMP-VCYSET-001 to FE-COMP-VCYSET-016
// Covers the calendar editor / draft rows and the leave-year block of VacaySettings,
// which VacaySettings.test.tsx only reaches at the surface.
import React from 'react'
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'
@@ -1,5 +1,4 @@
// FE-COMP-VCYSHR-001 to FE-COMP-VCYSHR-006
import React from 'react'
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'
@@ -1,5 +1,4 @@
// FE-COMP-VCYSTAT-001 to FE-COMP-VCYSTAT-002
import React from 'react'
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { render, screen } from '../../../tests/helpers/render'
import { resetAllStores } from '../../../tests/helpers/store'

Some files were not shown because too many files have changed in this diff Show More