Compare commits

..

157 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
github-actions[bot] a4446f16be chore: bump version to 5.2.2 [skip ci] 2026-11-28 13:20:02 +00:00
Maurice 058c3b3909 chore(notices): show 5.2.2 in the release notes modal 2026-11-28 13:19:26 +01:00
Maurice 7f3ead2c85 test(realtime): cover forgetting a closed session after a minute 2026-11-28 01:21:33 +01:00
Maurice 1553be3d5b refactor(auth): keep the per-address reset throttle in a module of its own
The reset link check grew the auth service past its size baseline.
2026-11-28 01:08:06 +01:00
Maurice fc891c16b2 chore(server): lower the test baseline of no-await-in-loop 2026-11-28 00:59:56 +01:00
Maurice bcad069705 test: keep the new tests within the lint and hand-built service ratchets 2026-11-28 00:55:51 +01:00
Maurice 610845e84d fix(realtime): refuse a ws token of a session whose sockets were just closed
A token minted shortly before its session ended could still open a socket
within its 30 seconds, and no later close would reach it.
2026-11-28 00:47:41 +01:00
Maurice 4705d88933 fix(native-release): let a held back APK go out by hand from its release tag
A run started by hand on a release tag publishes too, so a build held back
while its server was not released yet can follow once it is.
2026-11-28 00:45:52 +01:00
Maurice ed134fdef3 fix(oidc): count every back-channel logout at the door and give the attempt back when it was valid
Counting only the refused ones after the work let a burst of forged tokens run
past the limit while the provider's keys were still being fetched.
2026-11-28 00:45:24 +01:00
Maurice 8c5e7373d3 fix(android): paint the warm ground on a drawable of its own, so the window gets its theme colour back
Recolouring the decor view changed the theme's own colour drawable in place,
so restoring it once the server's page was up handed the window the warm
ground again.
2026-11-28 00:44:01 +01:00
Maurice 5b27624c33 fix(native-release): publish the Android APK for release tags only
A prerelease tag or a run started by hand is a testing build on the internal track, so it no longer replaces the public APK in liketrek/trek-android.
2026-11-28 00:35:11 +01:00
Maurice ac0f8f052d fix(android): give the window its normal colour back once the server's page is up
After a server was picked, the address screen's cream stayed behind the page for the whole session, so an older WebView showed it under the status bar with icons meant for a dark page.
2026-11-28 00:35:11 +01:00
Maurice 81b66d3170 fix(native): keep a chosen language on the app sign-in screen
The sign-in screen in the app now speaks the device language only when no language was chosen before, so the screen and the signed-in session match what the next launch shows.
2026-11-28 00:35:10 +01:00
Maurice 9bfdd10638 fix(native): hand a resumed browser sign-in over to the app like every other sign-in
When Android restarted the app during a system browser sign-in, the resumed sign-in waited on the web takeoff timer, so the sign-in screen faded to an empty page and the app rose in without its handover or success tap.
2026-11-28 00:35:10 +01:00
Maurice bbc9c72168 fix(map): ask Valhalla again for days drawn by OSRM only while the relay rested
The OSRM stand-in is kept only for a day Valhalla was asked and could not route, so a short rest or an offline session no longer keeps other days on OSRM for an hour.
2026-11-28 00:35:10 +01:00
Maurice 5c5c468489 fix(mobile): keep the photo viewers clear of a side notch in right to left languages
The screen insets stay on their own physical sides when the text runs right to left, so the close button no longer sits under the camera in landscape.
2026-11-28 00:35:09 +01:00
Maurice 5685cdfe13 fix(mobile): search a map link shared while the add-place sheet is already open
The shared link is put in the field and searched as given, instead of whatever the field held when the sheet opened.
2026-11-28 00:35:09 +01:00
Maurice 82ded80978 fix(mobile): read the stop being moved as it is now, so a change by a collaborator is not lost
The move list keeps only the stop's id and looks up its current day on every tap, and closes once the stop is gone from the place.
2026-11-28 00:35:09 +01:00
Maurice 46a2fd2bbb fix(mobile): place a timed stop moved to another day among every stored row of that day
The slot is counted over the stored rows, booked nights and hidden service stops included, as the desktop move does, so the stop no longer lands ahead of them.
2026-11-28 00:35:09 +01:00
Maurice ff676c8fc2 fix(bookings): move hotels and day-linked transports into Past once their days are over
A booking without a date of its own now reads its stay or linked day for that, as the date sort already does, so the Past section also opens once the whole trip is over.
2026-11-28 00:35:08 +01:00
Maurice 0b6a77eeb5 fix(weather): ask the forecast for the day east of UTC still reaches
Detailed weather for a trip day 16 UTC days out now asks Open-Meteo, whose range counts from the place's own date and still covers that day east of UTC; only a refusal falls back to last year's day, and that answer is cached for an hour instead of a day.
2026-11-28 00:35:08 +01:00
Maurice 7c6189f504 fix(assistant): leave room for the attached file tools when loading tool groups
A trip turn with an attached file adds read_attached_file and keep_attached_file to the session's tools, so loading groups now stops two short of the 128 tools OpenAI and Azure accept in one request.
2026-11-28 00:35:08 +01:00
Maurice 6bbe597719 fix(auth): bind a password reset link to the address it was mailed to
The reset request reads the account's address again inside the transaction that issues the link, and the link stores that address, so a link raced past an email change no longer resets the moved account. Links issued before this keep working until they expire.
2026-11-28 00:35:08 +01:00
Maurice 218304179c fix(oidc): count only refused back-channel logouts toward the rate limit
A realm-wide sign-out sends one validly signed logout per session from one address, and past 600 a minute the rest got 429 and stayed signed in. Only tokens that are refused count now, so a flood of bad tokens is still capped.
2026-11-28 00:33:50 +01:00
Maurice a6328cef3b fix(oidc): close the sockets of the sessions a back-channel logout ends by sid
A logout token naming the provider's session ended the TREK sessions but left their websockets open, so a signed-out tab kept receiving trip and journey broadcasts. Each ended session now closes its sockets, as the other revoke paths do.
2026-11-28 00:33:50 +01:00
Maurice 96d8b5c664 fix(sessions): close only the sockets of the session that ended
A ws token now carries the session it was minted under and the socket keeps it, so signing out on one device no longer drops the live socket of every other device. Ending all sessions still closes every socket of the account.
2026-11-28 00:33:42 +01:00
Maurice b5350287a4 fix(mobile): keep the shared place link type to its store, and expect notes on the desktop save 2026-11-27 23:56:19 +01:00
Maurice dbe0b847bd test(mobile): expect the past group among the empty transport groups 2026-11-27 23:49:42 +01:00
Maurice fc1022a452 chore(client): lower the theme baseline for the two photo viewers 2026-11-27 23:44:18 +01:00
Maurice 8b008a74fe fix(mobile): share the bookings tabs' sections, and fit two tests to the sheets they test
Both bookings tabs built the same status sections; listSections in the shared
filter hook now does it once. The photo sort test looks for the sheet in the
document, as the sheet is portalled to the body, and the saved place test
expects the notes the sheet now sends.
2026-11-27 23:39:30 +01:00
Maurice 1fa5c8cec2 fix(i18n): mark the French and Catalan word for notes as the same as in English 2026-11-27 23:31:23 +01:00
Maurice 443a4fd488 refactor(mobile): open what was shared into a trip from a hook of its own
The trip shell had grown past the 1000-line limit with the shared map link.
Both effects that open a shared item in the trip, the booking import and the
new place sheet, now live in useSharedIntoTrip beside the share store.
2026-11-27 23:27:17 +01:00
Maurice 8d5d34fbb3 feat(mobile): say in a trip's menu whether it is on the device
Whether a trip was kept for offline use was only to be found in the offline
settings. The trip's own menu now has an Offline entry that says it right
there: saved on this device as of the last sync, not saved yet, or not kept
here (switched off, or a finished trip nobody pinned). A tap opens the
offline settings, where everything else about it is.

Addresses discussion #1580.
2026-11-27 23:24:01 +01:00
Maurice 57fb2cf47b feat(mobile): add a place shared from Google Maps or Amap to a trip
A place shared from a maps app to TREK could only be kept among a trip's
links or read as a booking. A map link is now first offered as a place: after
the trip is picked, its new place sheet opens with the link in the search,
which looks it up at once through the existing resolver, so name, address
and position are filled in and only need saving. Other links are offered as
before.

Addresses discussion #2582.
2026-11-27 23:24:00 +01:00
Maurice 20d10d765d feat(mobile): number the stops of a day in the plan as their pins are
The map numbers a day's stops on their pins, the phone's plan did not, so
matching a pin to its row meant reading names. Each stop now carries its
number at the foot of its picture, in the pin's dark round. The count moved
into stopNumbersOfDay, which the map reads too, so a row and its pin always
agree, service stops passed over on both.

Addresses discussion #2584.
2026-11-27 23:24:00 +01:00
Maurice fd6d1969f5 feat(tours): open what a walk's stop has to tell under it
A city walk's stops showed only their names. A stop standing for a trip place
with a description, an address or a website now opens them under itself on a
tap of its name, marked by a small chevron, without leaving the walk. Stops
without anything more to say stay as they were.

Addresses discussion #3205.
2026-11-27 23:24:00 +01:00
Maurice 8c0cca536a feat(mobile): sort an entry's photos by dragging them on the phone
The phone's journal editor could only move a photo to the front. Its tiles
now take a long press and a drag into any place, through the photo order the
desktop editor already uses (saved at once, put back with a toast when the
save fails) and the touch bridge the plan's rows use. The faded tile is the
one moving, the ringed one where it lands. Moving to the front stays one tap.

Addresses discussion #2851.
2026-11-27 23:24:00 +01:00
Maurice dd1a117b92 feat(collections): show and edit the own notes of a saved place
A saved place has carried notes for a while (the API and the assistant write
them), but neither the phone sheet nor the desktop detail showed them, so
notes written there were invisible. Both now show them under the
description when there are any, and edit them beside it, through the shared
form hook.

Addresses discussion #3168.
2026-11-27 23:23:59 +01:00
Maurice 59b8d00373 feat(mobile): open journal entries to read them, with a pencil into the editor
On the phone everyone who may edit a journey got every entry straight in the
editor, so reading the journal meant scrolling a form and risking a stray
edit. An existing entry now opens as its read view: its date and time head
it, the story, place, the chosen mood and weather follow, and the entry's
settings (draft, route) and locked fields stay out of the way. A pencil in the
header switches to the editor without closing the sheet. New entries and
suggestions open in the editor as before, and a viewer's sheet is unchanged.

Addresses discussion #3007.
2026-11-27 23:23:59 +01:00
Maurice 9ea489ac97 feat(mobile): move a stop to another day from its day in the place sheet
On the phone a stop could only be removed from a day and added to another,
which lost its time and notes. A tap on the day in the place sheet now opens
the same short day list as adding, headed 'Move to another day', and moves
the stop there through the planner's move, so its time, notes and road trip
waypoints come along and a timed stop lands where its time belongs. No new
control in the plan's rows.

Addresses discussion #2583.
2026-11-27 23:23:59 +01:00
Maurice 17c56326e9 feat(mobile): fold transports and bookings that are over into a Past section
Mid-trip the transports and bookings tabs kept every flight already landed
and every check-in already done above what is still ahead. What is over (its
end, or its start where it has none, before the moment the tab opened, in
local wall-clock time) now stands in a Past section at the end, latest first.
It starts folded while something is still ahead and open once the whole trip
is over, to look back on. The desktop list is unchanged.

Addresses discussion #3156.
2026-11-27 23:23:59 +01:00
Maurice f3bdcf7ffb feat(mobile): open directions from a place's address and a booking's location
On the road the address is what the eye lands on. A tap on it in the place
sheet now does what the navigation button does (the preferred map app, or
the choice of apps), and the location row of a booking card opens
directions to it the same way, marked by a small arrow. The rest of the
booking card still opens the booking.

Addresses discussion #3213.
2026-11-27 23:23:59 +01:00
Maurice e7b900d309 fix(journey): open photos and videos full screen below the status bar, with the close button in reach
On a phone the journey's photo viewer opened inside the screen's own box
instead of over the whole screen, and its top bar, close button included, sat
under the status bar and a notch. It is now portalled to the page, its top
bar is a row of its own below the device's insets, the photo or video fills
what is left, and the page behind it no longer scrolls. The trip files
viewer, which shows videos too, keeps its header below the insets as well
and gets the same larger close button.
2026-11-27 23:23:58 +01:00
Maurice ffd9338217 fix(ci): give the Sonar upload five minutes instead of one
The release pull request's analysis report zips to about 77 MB, and the
scanner gave up on its upload to SonarCloud after the default 60 second
socket timeout three runs in a row (HttpTimeoutException on ce/submit), so
the scan never reached a quality gate.
2026-11-27 22:41:52 +01:00
Maurice 2186d8b230 test(oidc): narrow the logout token check with in, as the server compiles without strictNullChecks 2026-11-27 22:30:03 +01:00
Maurice 06aaddc34d feat(oidc): end TREK sessions when the identity provider signs a user out
OpenID Connect Back-Channel Logout 1.0: the provider calls
POST /api/auth/oidc/backchannel-logout with a logout token when a user signs
out there or an admin ends their session, and TREK ends the matching
sessions. Until now a session lived on for up to 30 days after access was
taken away at the provider.

- The token is checked as section 2.6 asks, through the verifier the login
  uses for the id_token (provider JWKS, issuer incl. a custom discovery URL,
  client id in aud), plus a recent iat, the logout event, a sub or sid, no
  nonce, an accepted typ and a jti not seen before (in-memory, bounded replay
  store; a jti whose sessions failed to end is released for the retry).
- The id_token's sid is stored on the session the SSO sign-in creates
  (nullable user_sessions.oidc_sid, both engines), and an app session handed
  off from that browser sign-in carries it too. A token with a sid ends those
  sessions only; a token with only a sub ends every session of the account.
- A valid token answers 200 with no-store also when it names nobody here; an
  invalid one 400 invalid_request, never 500, with the reason only in the
  server log. Public route with its allow-list entry, rate limited, audited
  as oidc.backchannel_logout.
- Always active: nothing changes until an admin enters the URL at the
  provider. Wiki: the URL, where it goes in Authentik, Keycloak and Pocket ID,
  and Keycloak's single token when an admin signs a user out.

Addresses discussion #3124.
2026-11-27 22:24:21 +01:00
Maurice 6f669920f1 test(realtime): wait for socket frames without awaiting in a loop
The room revocation suite polled for frames and joined its sockets one by
one, which the server lint counts as await in a loop against the tests'
baseline. It now waits on the frames as they arrive and joins in parallel.
2026-11-27 22:08:01 +01:00
Maurice 1fb20a542c fix(realtime): end a socket with its session and after a database swap
An open WebSocket outlived what it was opened with. Ending a user's
sessions (a password change or reset, an admin password change or MFA
reset, signing out other devices, a single session revoked) left their
sockets in every room and on their user channel, so a stolen session kept
listening. A backup restore or the demo reset put another database in place
while every socket stayed in its rooms, and on SQLite a restored id can
name another trip.

Ending a session now closes the user's sockets, and every reopen of the
database closes all of them; a client whose session still holds connects
again and joins what it may. A join asks once more from inside the room,
so a removal that committed while its first answer was on the way cannot
leave it behind. The trip recheck always names its trip, and its checks
are covered branch by branch.
2026-11-27 22:08:01 +01:00
Maurice d8be9a40e7 fix(realtime): take a socket out of a room once its access ends
A socket was let into a trip room or a journey's book room with one access
check and then trusted: delivery went by room membership alone. So a member
removed from a trip kept receiving every broadcast of it on the socket they
had already joined, a contributor taken off a journey kept the book's
pointers and presence and could still send pointers, and a deleted account's
sockets stayed in every room.

The gateway now installs the checks its joins run, and every write that ends
access asks the sockets already in again once it is committed and its own
event went out: a member removed or leaving (REST, MCP and plugin RPC), a
trip deleted, a contributor removed, a journey deleted, a trip's journal
link replaced, narrowed or removed. Open books are asked again with every
trip change, since a book can be open through a trip's journal. A socket
that no longer passes leaves the room, and a book that loses somebody tells
the others. A deleted account's sockets are closed. An answer that cannot be
had counts as no access.
2026-11-27 22:08:01 +01:00
Maurice 512584b4f1 fix(native): catch the status bar style call where the app has no status bar plugin
An unanswered rejection from StatusBar.setStyle surfaced in the sign-in
screen's tests, where the web build has no such plugin. Unimplemented is no
failure; anything else is reported as the other native calls are.
2026-11-27 21:48:56 +01:00
Maurice 985998e757 test(login): submit the app sign-in form with its required fields filled 2026-11-27 21:42:57 +01:00
Maurice 742c0dd72d fix(login): keep the app sign-in screen within the eslint ratchets
Split the other ways in out of one component (complexity), finish the async
handlers with void instead of handing promises to React, report a landscape
that fails to load instead of logging it, let the handover wait on settled
settings rather than catching them, and move the one-time code field's props
into a module of their own so MfaCodeStep only exports its component.
2026-11-27 21:42:56 +01:00
Maurice efd34df038 fix(login): name the SSO button SSO when the provider has no display name, as OIDC-only does 2026-11-27 21:42:56 +01:00
Maurice 321980c95b test(login): build the sign-in page's own config shape in the app screen tests 2026-11-27 21:42:56 +01:00
Maurice d4595269b5 refactor(login): both sign-in screens take their headings and labels from loginModel
LoginPage grew past its size baseline with the app's branch. Its heading,
subtitle and submit label chains now come from loginModel, which the app's
screen already used, so the file shrinks by 21 lines and the baseline follows.
The model translates the keys itself, written out, so the i18n key check
keeps seeing them.
2026-11-27 21:42:55 +01:00
Maurice 32de7adbf6 feat(native): app sign-in screen that continues the address screen
Inside the iOS and Android app the sign-in page looked like the web form it
is in a browser: a white card on grey, the web header and a language menu,
reached through a white page, a grey spinner and another white page, and left
through the 2.6 s takeoff animation.

- AppLogin: the address screen's landscape with the connected server on its
  glass card (Change leads back to the address screen), and its fields,
  buttons and type on the same warm page. Same useLogin hook, so password,
  remember me, forgot password, SSO, OIDC-only, passkey, demo, MFA, password
  change, registration and invites all stay as they are.
- The app speaks the device language with English as the fallback; no
  language menu there.
- Handover: theme-boot.js marks a page inside the app that nobody signed in
  to yet, which then starts on the address screen's colour, waits with its
  spinner, and fades the sign-in screen in. After signing in the screen steps
  back while the settings load and the app rises in, instead of the takeoff.
- Android: the WebView and window keep the address screen's colour across the
  restart onto the server, and the status bar icons stay readable where an
  older WebView lays the page out below the bar (shell and sign-in).
- loginModel holds the headings, button labels and SSO links both sign-in
  screens share.

The browser's sign-in page is unchanged.
2026-11-27 21:42:39 +01:00
Maurice fef7ac4587 fix(map): set the trip overview aside for the visit instead of switching it off
Making room for the day details went through the overview's remembered
switch, which the account keeps per trip and syncs to every device. A day
sheet on the phone, or two cards that did not fit on a narrow window, turned
the overview off everywhere without the traveller touching the pill.

The overview is now set aside for this visit only: the remembered switch
stays as it was, the pill shows it off and brings it back with one tap, and
a reload shows it again. The route overview hook keeps its declared return
type with the new hasPlannedRoute flag.
2026-11-27 21:07:07 +01:00
Luffy 7a57c58dd0 fix(map): prevent trip overview and day details from overlapping 2026-11-27 21:07:07 +01:00
Maurice 3dd63331bc fix(tours): format the dropdown changes and lower the hook ref baseline
The editor dropdown change drops the options ref useAnchoredPosition kept
for its measure callback, so the react-hooks/refs count falls by one and
the baseline follows it. The new and touched files are formatted, and the
new rail test gets its id like the rest of the file.
2026-11-27 20:51:46 +01:00
Luffy 20c8457f18 fix(tours): keep editor dropdowns inside the sidebar 2026-11-27 20:51:46 +01:00
Maurice eaef3c014e test(pdf): read the export's note cards without non-null assertions
The markdown test for the day notes reached its cards with three non-null
assertions, which the client lint counts against the tests' baseline. A
small lookup that fails with the missing selector reads them instead.
2026-11-27 20:35:01 +01:00
Maurice f02c0e088b fix(journey): keep the journal shown when a reload after a change fails
The journal views read the journal again after their own changes (saved
settings, a finished entry, an added trip, picked provider photos) by
calling loadJourney and dropping the promise. loadJourney rethrows every
failure, so a reload that failed, offline or timed out, became an unhandled
rejection with nothing shown to the user. In CI the same happened whenever a
test ended with such a read still open: the teardown runs the pending timers,
the request timeout fired, and the run failed on the unhandled error.

The store gets refreshJourney, which reads the journal and answers whether
the read landed instead of rejecting; a 404 still turns into notFound. The
shared journal hook hands it to the desktop and the phone view and to the
map layers in place of the raw loader, and the Studio uses it for its own
reads.
2026-11-27 20:27:29 +01:00
Maurice 2915ea573a fix(bookings): say what happens to an imported booking's cost on save
Reviewing an imported booking that carries a price shows the cost that
the save will link. Under it the dialog printed the create button's hint,
"Saves the booking, then opens the Costs editor", but this row is no
button: saving an imported booking adds the cost by itself, as the import
always has, and opens no editor. Following the hint, people waited for an
editor that never came.

The preview row now says the cost is added to Costs when the booking is
saved, in every language. The create button keeps its own hint.

Closes #3237
2026-11-27 20:13:31 +01:00
Maurice 407de33560 fix(booking-import): import a booking the document calls confirmed as confirmed
The mail import already wrote a booking as confirmed when its metadata held
reservationStatus, but nothing ever filled that field: the KItinerary mapper
dropped schema.org's reservationStatus, the AI reading was neither asked
for it nor given it in its response schema (a schema-bound provider fills
declared properties only), and the review form, the file import confirm
path and the assistant's import card all started every booking as pending.

The mapper now reads reservationStatus from every node, schema.org URL,
bare ReservationConfirmed or a plain word alike, and keeps it in the
item's metadata as TREK's word. The AI prompt and response schema ask for
it. One shared helper turns it into the status a booking is saved with:
confirmed when the document said so, pending otherwise, so a cancellation
or an unknown value still lands as pending. The review form prefill, the
mail import, the confirm path and the assistant card all use it.

Closes #3238
2026-11-27 20:08:19 +01:00
Maurice addcbe4801 fix(pdf): render markdown in day notes, booking notes and the day intro
The planner renders a day note's second line and a booking's notes as
markdown, and place texts in the PDF already went through the app's
sanitized markdown pipeline (#2692). Day notes, booking notes and the day
intro were still printed through escHtml, so the export showed the raw
syntax (asterisks, list dashes, rules) instead of the formatting.

They now use the same sanitized pipeline as bare markup inside their own
card, without the info row a place text gets, and drop the pre-line
whitespace that would double every markdown line break. Raw HTML in a
note is still printed as text.

Closes #3236
2026-11-27 19:58:00 +01:00
Maurice a9fd443b63 feat(db): present a Postgres client certificate from sslcert and sslkey in TREK_DB_URL
A Postgres server that authenticates clients by certificate could not be
used: TREK read only sslmode and sslrootcert from TREK_DB_URL, so neither
the connection pool nor pg_dump, pg_restore and psql ever offered a client
certificate (discussion #3215).

TREK_DB_URL now also takes libpq's sslcert and sslkey. Both must be given
together and only with a verifying sslmode, and each file must be readable,
or the boot refuses with the same kind of message as for sslrootcert. The
pool gets them as its TLS cert and key, the tools as PGSSLCERT and
PGSSLKEY. The Postgres wiki page shows the URL, how to mount the files with
Compose or the chart's extraVolumes, and libpq's rule for the key file's
permissions, which the backup tools enforce.
2026-11-26 23:35:18 +01:00
Maurice b8dffdbb13 fix(files): serve the stored offline copy when a live download stalls
Opening a document that was stored for offline use fetched it from the
server first and only fell back to the stored copy when the request
rejected. On a weak or stalled connection the request never rejects, so a
boarding pass already on the phone could spin indefinitely.

With a stored copy, the live download now gets five seconds, request and
body together; after that the stored copy is served and the download is
aborted. A connection that breaks while the body arrives serves the copy as
well. An HTTP error that comes back in time still surfaces over the copy,
and without a stored copy the download waits as long as it always did. The
test file is now formatted and leaves the format baseline.
2026-11-26 23:35:18 +01:00
Maurice 3b42ffa67b feat(helm): render extra Kubernetes objects from an extraObjects list
The chart had no way to ship objects of the operator's own next to TREK, so
a backup CronJob, a ConfigMap for it or any other helper had to live in a
second release or be applied by hand (discussion #3194). extraObjects takes
a list, empty by default so nothing renders, and renders each item through
tpl: a map as YAML, a string as written, so names such as
{{ .Release.Name }} resolve in both forms.

The values comment, the chart README and the Helm wiki page say that braces
are evaluated in both forms, that a backup job must mount the data volume
read only, and that it should copy TREK's own backup archives rather than
the live travel.db. Those archives carry the encryption key unless
ENCRYPTION_KEY comes from the environment, so their destination needs the
same protection as the volume. CI renders a variant with a CronJob in the
map form and a ConfigMap in the string form, checks it with kubeconform
-strict, and fails when a {{ is left unrendered.
2026-11-26 23:35:18 +01:00
Maurice 2ea1c99e31 ci(native): publish the Play-signed Android APK to liketrek/trek-android for installs outside Google Play
People who install apps from GitHub (Obtainium and the like) asked for the
Android app outside Google Play. After the Play upload, the release job now
fetches the universal APK Google Play builds of that same bundle, signed
with the Play app signing key, and publishes it with a checksum to
liketrek/trek-android: one release per app version, a newer build of the
same version replacing its APK. A phone can move between the Play install
and this APK without uninstalling, and Play Billing and push work in it
wherever Google Play services do.

It runs only inside the app builds that already happen, so a server release
without app changes publishes nothing. A build is held back while the app
needs a newer native API than the latest server release answers, so no APK
asks for a server that is not out yet. The APKs live in their own repository
so app releases never show up in the server's release list or update check.
2026-11-26 23:12:27 +01:00
Maurice d383d3527b fix(oauth): bind an authorization code to the session that consented, not to the password version
Reading the password version from the oauth domain meant injecting the
users repository, which the auth domain owns. The sessions domain answers
the same question and more: a password reset or change ends every session
of the user, and a sign-out ends the one that consented. The code now
carries that session's id and both token endpoints issue tokens for it
only while the session is active, checked in the transaction that writes
them. A token from before sessions were tracked has no session to check
and passes, as it does everywhere until it expires. A refused code is
audited as session_ended.
2026-11-26 22:46:15 +01:00
Maurice 05843c8e5b test(oauth): give the pending-code fixture its password version and format the controller test 2026-11-26 22:32:44 +01:00
Maurice 19270adef8 test(oauth): read the granted code without non-null assertions 2026-11-26 22:26:58 +01:00
Maurice f9ab280b7e fix(oauth): an authorization code mints tokens only while the password it was granted under holds
The consent page mints a two-minute authorization code from the cookie
session. A password reset or change revokes the user's OAuth tokens but
left such a pending code alone, so a code granted before the reset still
redeemed afterwards into a fresh token pair at either token endpoint.

The code now carries the password version of the session that consented,
and both token endpoints issue tokens for it only while that version is
still the account's, checked in the transaction that writes the tokens.
A refused code answers invalid_grant as any other and is audited as
password_changed.
2026-11-26 22:21:46 +01:00
Maurice c88d3abc5e fix(auth): a native app hand-off code redeems only while the session that minted it stands
The browser side of the native sign-in mints a one-time code from its
cookie session, and the app redeems it within a minute for a session of
its own. The code was bound to the account alone, so one minted before a
password reset, a sign-out or a revoked session still redeemed afterwards
into a fresh session, carrying access across the point where the account
took it back.

The code now carries the session it came from: its password version and,
for a tracked session, its id. Redeeming it mints a session only while the
password is unchanged and that session is still active, checked in the
same transaction that mints the new one.
2026-11-26 22:14:12 +01:00
Maurice 10d95a39ac fix(map): open a day the routing relay could not answer drawn, without waiting for it again
On an instance that routes its days with Valhalla (the TREK services by
default), a day the relay could not answer in time was drawn by OSRM and
kept only under the OSRM key. The next visit missed the Valhalla key, asked
the relay again and waited out its deadline, up to twelve seconds a day,
before the kept road showed, so every reload showed straight lines first.

OSRM's answer now stands in for such a day for an hour under a key of its
own, on the device only. Reopening the trip draws it at once; after the
hour the relay is asked again and its answer becomes the day's. Days that
avoid something keep asking Valhalla, since the stand-in drives the road
they mean to leave out.

Closes #3228
2026-11-26 22:09:59 +01:00
Maurice 7d802081ce test(assistant): replay the changed requests side by side in ANTH-010 2026-11-26 20:04:40 +01:00
Maurice 7586126797 fix(assistant): send Anthropic's thinking back only where the conversation before it is unchanged
Follow-up messages failed with HTTP 400 on Anthropic once a thread held an
answer that thought: the API binds each thinking block to everything the
request sends before it and refuses the request when any of that changed.
It changes in normal use: a tool group loaded later in the turn, an earlier
tool answer cut short once a new question follows, a held change applied
since, a trip card that moved on.

Each recorded step now keeps a fingerprint of what its request sent before
it (model, system blocks, tools, history). On replay its thinking blocks go
back only while that fingerprint still matches; otherwise the step goes back
without them, which the API accepts. Records written before this change
carry no fingerprint and go back without their thinking.

A refusal from Anthropic is now logged with the path its message names
(such as messages.1.content.0), without the rest of the message.

Closes #3094
2026-11-26 20:00:00 +01:00
Maurice 9fa2bef101 test(journey): keep the journey page suite's journal and handlers in its helper
The suite carried its sample journal and the journal's default handlers inline, and waiting for the reload in FE-PAGE-JOURNEYDETAIL-153 took it past its size limit. Both move to tests/helpers/journeyDetail.ts beside seedJourneyOwner; the file is 142 lines shorter and its size baseline follows.
2026-11-26 14:21:04 +01:00
Maurice ed1bba9371 test(client): finish moving the tests to msw 3
Two more window.location stand-ins sat on http://localhost while the
page runs on http://localhost:3000; they now use locationAt like the
rest, which brings back the plugin settings answer FE-COMP-
PLUGINSETTINGS-020 waits for. FE-PAGE-JOURNEYDETAIL-153 ended while the
journal reload it set off was still out, which timed out after the
test; it now waits for that read. The reload mocks in
versionHandover.test.ts carry the signatures of location.replace and
location.reload, as locationAt's overrides require.
2026-11-26 14:03:46 +01:00
Maurice 3c1cf8b347 chore(server): lower the strict baseline of the repository base class
MikroORM 7.2.12's typings leave trek-repository.ts with 4 strict errors instead of 8; the ratchet holds it there.
2026-11-26 14:03:46 +01:00
Maurice 1ed77870f9 test(db): see the unnamed temp files SQLite 3.54 opens on Linux
SQLite 3.54, which better-sqlite3 13.2.0 bundles, opens its temp files
with O_TMPFILE where the system has it. On Linux such a file has no
name: among the process's descriptors it reads <dir>/#<inode> (deleted)
instead of etilqs_<random>. The watcher only looked for the name, so
the control test saw nothing, and the test that TREK's own connection
never touches a temp file would have passed whatever happened. The
watcher now knows both forms; the control proves again that it sees
them.
2026-11-26 14:03:46 +01:00
Maurice 22ee4dbac7 ci(dependabot): let MikroORM and msw move again
Both are on their new versions now: MikroORM 7.2.12 with the OAuth
repositories writing the client the way it accepts, and the client tests
on msw 3. Their ignore entries go. better-sqlite3 and kysely, which
@mikro-orm/sqlite pins exactly, join the MikroORM group instead of being
ignored, so the three move in one pull request. cron and the musl rollup
pins stay held back for their own reasons.
2026-11-26 13:41:29 +01:00
Maurice 6926591112 fix(admin): a default setting reset right after typing is the value that stays
Typing a new Mapbox token or CARTO key and clicking that field's reset
link straight away sent two requests at once: the field's save on blur,
then the reset. Nothing ordered them, so when the server handled the
save last, the key typed a moment ago was stored again while the field
showed it cleared, on the desktop tab and on the phone screen alike.

The hook both shells share now sends its writes one after another, in
the order they were made (useWritesInOrder; a write that fails does not
hold up the next). FE-ADMIN-DUS-032 types, clicks reset at once and
makes the save the slower request; it fails without the order.
FE-HOOK-WRITES-001 to 003 cover the helper.
2026-11-26 13:41:28 +01:00
Maurice 66382e791b fix(admin): keep the dev notification buttons mounted while the panel updates
The desktop panel declared its button component inside its render, so
every state change (each lookup landing, each send starting and ending)
made a new component type and React remounted every button: focus and
hover were lost, and a click that arrived during a re-render went to a
button that was no longer there. Btn now lives at module level and takes
the send in flight as a prop, as the phone panel's Btn already does.
FE-ADMIN-DEVNOTIF-017 holds a button across the lookups landing and
expects the same element; it fails with the old panel.
2026-11-26 13:41:28 +01:00
Maurice 32837afe2e chore(deps-dev): bump msw from 2.15.0 to 3.0.8 and move the client tests to it
msw 3 renames onUnhandledRequest to onUnhandledFrame and reports every
network frame there; the setup judges the HTTP frames as before (another
origin is an error, the page's own a warning).

It also resolves a relative handler, and its fetch interceptor a
relative URL, against location.href at the time of the request, while
jsdom's XHR sends to the document's own address. Tests that replaced
window.location with a stand-in on http://localhost while the page runs
on http://localhost:3000 sent their requests past every handler.
tests/helpers/location.ts builds such stand-ins on the page's own origin
(locationAt, pageUrl), and every one of them now uses it.

msw no longer escapes fake timers, and responses are timed differently,
which surfaced tests that ended with work still running: a held request
answering in the next test, a lookup still out when the assertions ran,
a reload switched by counting reads. Each of those now waits for, or
releases, what it started, and answers by what happened rather than by
a count.

The day panel suites share their setup through
tests/helpers/dayDetailPanel.ts instead of a copy each, which keeps the
larger one under its size limit.
2026-11-26 13:15:45 +01:00
Maurice 05f4c84885 test(reservations): cover the traveller insert that ignores existing rows
ReservationTravelers.insertIgnore had no test of its own. MikroORM 7.2.10 changed how upsertMany with a composite conflict key matches rows read back after a conflict, which is exactly the case of a traveller already on the booking next to a new one in one call. RS9-001 to RS9-004 pin that case, a duplicate id, another booking's row and an empty list; the first two fail with a plain insert.
2026-11-26 12:57:32 +01:00
Maurice 6905729ab6 chore(deps): bump MikroORM from 7.2.8 to 7.2.12 with better-sqlite3 13.2.0 and kysely 0.29.9
From 7.2.9 on, MikroORM reads a bare value given for a relation as the
target's primary key. The client relation of oauth_tokens and
oauth_consents points at oauth_clients.client_id, a unique column that
is not the primary key, so every token mint and every consent grant was
refused ("Cannot set OauthTokens.client to a reference of OauthClients
without the value of OauthClients.client_id"): every OAuth and MCP
sign-in would have failed.

insertToken now hands the referenced column itself to the relation
(oauthClientRef), which MikroORM writes to client_id as it is.
upsertGrant writes the row with Kysely's onConflict on
UNIQUE(client_id, user_id), because em.upsert takes that same value as
the data of a new OauthClients entity. The test fixtures that seed
tokens and consents use the same helper. Reading client_id back is
unchanged; the repository tests seed clients whose primary key differs
from their client_id, one of them a decoy whose primary key equals
another client's client_id.

The lockfile resolves the MikroORM tree from scratch, so there is one
@mikro-orm/core again instead of a second copy next to @mikro-orm/nestjs.
better-sqlite3 13.2.0 ships prebuilt binaries for every platform the
image builds, musl included.
2026-11-26 12:39:43 +01:00
Maurice 85aa1c91ff test(booking-import): check the upload limits the route sets, not Nest's whole set
NestJS 11.2.12 adds its default parts limit to every multer interceptor, so the options hold one more key than the route names.
2026-11-26 11:26:35 +01:00
Maurice de9901d941 refactor(files): drop the drop zone's noClick option, which is its default
Keeps useFileManager within the function length limit now that it names noPaste; react-dropzone's noClick defaults to false, so a click still opens the picker.
2026-11-26 11:26:35 +01:00
Maurice 95a0cd2f77 ci(dependabot): hold back the updates that cannot move on their own
The last grouped update showed which packages break when Dependabot moves
them alone: MikroORM from 7.2.9 on refuses the OAuth repositories'
foreign key writes, better-sqlite3 and kysely are pinned by
@mikro-orm/sqlite, cron by @nestjs/schedule, the musl rollup pins have
to follow the installed rollup, and msw 3 is a migration of the client
tests. Each is held back with its reason and moves by hand. The rules
name the version update types rather than the whole package wherever
that is enough, and a security advisory for any of them still shows in
the Security tab.
2026-11-26 11:15:46 +01:00
Maurice f922068a8e chore(deps): bump express from 4.22.3 to 5.3.0 and @types/express to 5.0.6
Nest already serves every request through Express 5. Only the parsers,
the static handler and their types still came from the direct Express 4
dependency, so this moves those three and keeps their behaviour:

- body-parser 2 leaves req.body undefined when it did not read a body,
  where body-parser 1 left an empty object. A bodyless POST to a route
  whose fields are all optional answered 400, and a plugin route got
  null. emptyBodyDefault restores the empty object for everything but
  /mcp, which stays raw (BOOT-009, PACK-3T-004).
- serve-static 2 no longer exposes its mime table. The Brotli copy of
  an asset is typed through mime-types 3 with the fallback send uses,
  so it keeps the Content-Type of the original file (PRECOMP-001).
- @types/express 5 types a route param as string or string[]; the
  photo route names its single :filename param.

The MCP SDK resolves the same Express 5.3 now; Nest keeps the 5.2.1 it
pins.
2026-11-26 11:09:32 +01:00
Maurice 5c5d85ef60 chore(deps): bump NestJS to 11.2.12, @nestjs/swagger to 11.4.8 and jimp to 1.7.0
The NestJS part of the grouped Dependabot update, without the packages
that cannot move yet: MikroORM stays on 7.2.8 together with the
better-sqlite3 and kysely versions it pins, cron stays on the 4.4.0
that @nestjs/schedule pins exactly, and the musl rollup pins stay on
the rollup version the lockfile installs.

What changed in Nest does not reach TREK's own paths: TrekWsAdapter
builds its server and binds every handler itself, so the new WsAdapter
defaults do not apply, and the new limit of 1000 multipart parts per
request is far above what the upload routes receive.
2026-11-26 11:04:58 +01:00
Maurice d83e98366b chore(deps): bump react-dropzone from 14.4.1 to 20.2.1
react-dropzone 19.2 turned on a paste handler of its own on the drop
zone. The file panel already uploads pasted files once for the whole
panel, after the upload permission check, so a paste while the zone
had focus sent every file twice. The zone's paste handling is switched
off with noPaste; FE-COMP-FILEMANAGER-039 pastes on the zone itself
and expects a single upload.

prop-types and loose-envify leave the lockfile with the old version.
2026-11-26 11:03:21 +01:00
Maurice 756eae39ff chore(deps-dev): bump @types/node from 25.9.8 to 26.6.11
Type definitions only; the image and .nvmrc stay on Node 24. npm drops the stale peer flag from the optional rollup binaries while it rewrites the lockfile; nothing installs with --omit=peer.
2026-11-26 11:02:10 +01:00
Maurice 4f66a344ca fix(auth): retire password reset links when the account's email or password changes
A reset link is a credential sent to the address the account had when it
was asked for. It stayed valid for its full hour after the account moved
to another address or got a new password, so a link sent to the old
mailbox could still set a password on the account.

Changing the email in the user's own settings, changing the password,
and an admin changing a user's email or setting a password now consume
every live reset link of that user, in the same transaction as the
change. Saving the same address, or it in another case, keeps the link,
and a link asked for afterwards works as before.
2026-11-26 10:17:13 +01:00
Maurice 96b2778c2f fix(native): keep the server picker clear of Android's navigation bar
On Android the web view can report env(safe-area-inset-*) as 0 while the
app draws edge to edge, so the buttons at the foot of the app's first
screens sat under the three-button navigation bar and the logo under the
status bar. Capacitor's SystemBars plugin writes the real insets to the
page as --safe-area-inset-*; the first screens now read them as one more
floor next to env() and the insets iOS measures itself. Where Capacitor
lays the web view out between the bars it writes 0, and in a browser the
variables are unset, so nothing changes there.

Closes #3221
2026-11-26 10:10:22 +01:00
Maurice 98c883b4e8 test(assistant): load the tool cap's groups without awaiting in a loop
The cap suite added eleven no-await-in-loop and two non-null assertion
warnings to the server tests, past the lint ratchet. Independent sessions
now run side by side and the sequential loads go through a recursive
helper.
2026-11-25 22:48:57 +01:00
Maurice df82208bd5 fix(assistant): keep every step within the 128 tools OpenAI and Azure accept
A trip chat offered 130 tools in its first step and up to 359 with every
group loaded. OpenAI's APIs and Azure refuse a request with more than 128
function tools (array_above_max_length), so the trip assistant failed at
once on an OpenAI style or Azure Foundry connection, while Anthropic and
the ChatGPT login took the longer list.

The trip's bookings, its packing lists and to-dos, changes to its budget
and its tags now load as groups like the addons do, which brings the core
to 63 tools, so any one group fits beside it. Loading a group that would
pass the limit unloads the one used longest ago, a call to one of its
tools loads it again, and groups asked for together that do not fit are
named so the model loads them later. The groups that are part of the trip
carry no domain on their change cards. Reading the costs stays in the
core.
2026-11-25 22:34:41 +01:00
Maurice 18867d9499 fix(weather): answer the day 16 days out with climate instead of an error
The detailed weather took the forecast path for any day whose distance
from now was at most 16 days, measured as a fraction of a day. Open-Meteo's
forecast reaches today + 15 calendar days, and the day 16 out lies 15.x
days from now, so it was asked of the forecast, refused with a 400, and
the day showed "No weather data". The cutoff now counts calendar days and
sends anything past today + 15 to the climate path. The forecast measures
its range from the place's own date, which trails UTC in the Americas for
part of the day, so a refusal of that range also falls back to climate.

Closes #3216
2026-11-25 22:21:16 +01:00
github-actions[bot] 13910464e5 chore: bump version to 5.2.1 [skip ci] 2026-11-25 13:18:29 +00:00
Maurice 903868c08c feat(release): show the iOS and Android apps in the 5.2.1 notice, the account settings and the user menu
The release notice moves to 5.2.1 and gets a tile across the release column
with the App Store and Google Play cards, each with a QR code that opens the
store page. The headliner, intro, footnote and note texts are shorter so the
tile fits, in every locale.

Settings > Account shows the same store cards in its right column, except
inside the native app itself. The user menu footer adds round links to
Patreon, Ko-fi and Buy Me a Coffee beside Discord, left out on managed
installs and in the native apps like every donation link.
2026-11-25 13:32:18 +01:00
Maurice 434baaf6fd fix(native-auth): send the app's SSO sign-in through the identity provider every time
The app signs in through a browser sheet that shares the system browser's
cookies. When that browser still held a TREK session from an earlier
sign-in, the hand-off page skipped the identity provider and offered to
continue at once, so a provider set to demand re-authentication (Pocket ID's
"requires re-authentication") was never asked, and signing out of the app
and in again with SSO asked for nothing.

The SSO button now always goes through the identity provider. It decides as
before: a provider with a running session lets the user through, one that
demands re-authentication asks for it. A sign-in with a password or passkey
still continues with the browser's session after the explicit tap.

Refs #3014
2026-11-25 10:52:34 +01:00
Maurice d9d901e52d fix(ci): lower the client non-null baseline and arm the wait before PMEDIA-006 advances
Client lint was red because the day plan change took 13 non-null assertions
out of DayPlanSidebar: the count is 354 now, so the baseline goes down to it.

Server tests 6/10 timed out in PMEDIA-006. The test advanced the fake clock
right after asking for the rendition, but the wait it meant to run out is only
armed once the copy has started; on a slow runner the clock moved past a timer
that did not exist yet and the test hung for 15 seconds. It now waits for the
copy to start first, as PMEDIA-006b already does.
2026-11-25 10:37:46 +01:00
Maurice 50cb9364f6 fix(atlas): count the cities the address parser used to miss
The Atlas reads a place's city from its address text, and several common
address shapes lost it:

- The TREK index writes "street, postcode, locality" with no country, and the
  parser always dropped the last part as the country, so a place picked from
  TREK's own search counted no city.
- A city that is its own region (Berlin, Wien, Malé) was skipped as the region
  even where it stands beside its postcode, which is how such an address names
  its city.
- An atoll or a state written with its generic word ("Kaafu Atoll" for the
  region Kaafu) was not recognised as the region and counted as the city of
  every island in it.
- Country names came from a short English and German list, so "Maldives",
  "Österreich" or "Italia" could be counted as a city.

The locality of a postcode-and-locality tail now counts, a region-named part
with a postcode counts when no part before it names a city, a region matches
with its generic word, and countries are recognised by their name in every
language TREK speaks. A region named without a postcode (a mountain in
"Bayern", a resort in "Kaafu") still counts no city, and the lines the parser
already read right read the same.

Closes #3200
2026-11-25 10:29:09 +01:00
Maurice b6c50eb146 fix(wallet): date a booking's pass by its stay or linked day when it has no time of its own
The Wallet pass took its date only from the booking's own time or, for a
journey, its departure stop. A hotel whose check-in and check-out live on its
stay, and a booking linked to a day that carries only a clock, have neither,
so Wallet answered "Give the booking a date first" for a booking the app
shows with its dates. A TestFlight tester hit it with a hotel booked from
8 to 11 January.

The pass context now reads the dates of the days a booking is linked to and,
for a hotel, the first and last day of its stay with its check-in and
check-out times. The pass falls back to them in the order the app uses
(bookingDates): the booking's own time first, then the stay or the linked
day, with the booking's or the stay's clock. A booking with no date anywhere
is still refused.
2026-11-25 10:25:10 +01:00
Maurice c1c77d89b5 fix(day-plan): make the legs from a booking or the hotel tappable on the phone
On the phone timeline only a leg that leaves a stop opened the travel mode
menu. The leg from the morning hotel to the first stop, the leg from the last
stop back to the hotel and the leg from a booking's arrival to the next stop
stayed inert, although the desktop day plan already changes them through the
stop at their other end. A TestFlight tester could not tap the walk from their
train's arrival to the hotel.

The timeline now knows which stop owns each of these legs: the first stop's
incoming mode for the morning hotel leg and for a leg out of a booking, the
last stop's outgoing mode for the evening hotel leg. Tapping them in edit mode
opens the same menu as on the desktop, and the phone sets the incoming mode
the way the desktop does.

A leg no stop owns, such as a booking's arrival to the hotel, has no mode to
store. It follows the day default, and on both the phone and the desktop it
now offers the public transit search where a trip has dates, instead of
reacting to nothing.
2026-11-25 10:21:43 +01:00
Maurice 70af8132ef fix(booking-import): let the model choose when a document names several booking types
The keyword table that picks the extraction schema took the first pattern
that matched, with transport tested first since #2076. A hotel confirmation
that mentioned the airport bus, the train station or the cruise port was
therefore extracted with the bus, train or ferry schema. Those schemas have
no hotel name, address or check-in and check-out, so the model returned a
transport booking without the stay's data and the import dropped it.

The keywords now only decide alone when a document names one type. When it
names several, the model gets the union schema narrowed to exactly those
types, with each type's field meanings, and picks. The flight gate is
unchanged: flight numbers still take the flight path only when no other
transport is named. Event words decide only when nothing else is named,
since "ticket" is printed on every transport ticket, and the lodging
pattern also knows motel, accommodation, apartment, guest house, Unterkunft
and Ferienwohnung.
2026-11-25 10:09:24 +01:00
Maurice 85182d2f52 chore(deps): group MikroORM and NestJS updates, hold NestJS majors
Each family releases in lockstep and now arrives as one PR. NestJS majors wait until nestjs-zod supports NestJS 12.
2026-11-25 00:10:14 +01:00
Maurice c65e9bf76e fix(auth): move passkeys to SimpleWebAuthn 14, which no longer fetches a CRL a client names
@simplewebauthn/server 13.3.3 fetched the CRL address in an android-key
attestation certificate before it checked the chain or the signature, with
no timeout or size cap, so anyone signed in could make the server request
any URL by registering a passkey. 14.1.0 only checks revocation for a chain
it validated against Google's pinned roots.

14.x refuses an expected origin with a path, a trailing slash or an
uppercase host and an RP ID that is not lower case, where 13.x only failed
to match them. The configured origins are now reduced to the origin the
browser reports and the RP ID is lower-cased, so such settings keep
working; an origins list in which nothing parses leaves passkeys
unconfigured instead of falling back to APP_URL. Verification gets the
algorithm list the options offer, and stored transports are read as plain
strings.

Stored credentials keep their format. typescript-eslint moves to 8.73.0.
2026-11-25 00:10:14 +01:00
Maurice 3754518d37 fix(ai): say why ChatGPT refused a sign-in, and start a fresh one after any refusal
Every refusal of the code by OpenAI's token endpoint came back as "The
sign-in took too long", and the endpoint's own error was dropped without a
log line. Only invalid_grant means the code ran out or was used already; any
other refusal (invalid_client, a redirect or resource mismatch) now names
its OAuth error in the answer and in a warning with the endpoint's
description, so an admin can see what went wrong.

The server takes a sign-in once whatever it answers, but the panel only
started a fresh one after "expired", so the next try after any other
refusal used a spent sign-in. It now starts a fresh one after every refusal
the server sent; offline and a wrong address keep the one in progress, as
neither reached it.

The address the sign-in window ends on is also taken without http://, the
way the hint under the field and the address bar show it.

Closes #3196
2026-11-24 23:59:33 +01:00
Maurice eed5f75487 docs(readme): space Data sources like the other sections 2026-11-24 23:56:08 +01:00
Maurice f29112698e docs(readme): show See all features as a plain heading
The graphic card goes again; the toggle now reads as a third-level heading.
2026-11-24 23:54:54 +01:00
Maurice d556d706b7 docs(readme): drop the feature tile grid, make See all features a card
The Plan, track, share tile grid goes. The See all features toggle is now a card in the style of the app cards, light and dark, with the feature areas as small chips and a chevron, so the full list is easier to spot.
2026-11-24 23:53:58 +01:00
Maurice 71673085bb docs(readme): make the app store cards flatter
A smaller QR code, and the store's mark beside the first line instead of in a box of its own, so each card is about a quarter less tall.
2026-11-24 23:51:05 +01:00
Maurice 19a01d493b docs(readme): set the sponsor line in normal text size 2026-11-24 23:49:59 +01:00
Maurice 462f08727c docs(readme): shorten the sponsor and AI notes, drop the PWA section
The sponsor line at the top goes; the dataforest cloud block further down is now its logo under a small POWERED BY and one line. The AI usage section is one sentence with its link. The PWA install steps and their link in the quick navigation go, since the store apps now sit at the top.
2026-11-24 23:49:20 +01:00
Maurice 58298703e1 docs(readme): drop the line under the app cards 2026-11-24 23:48:23 +01:00
Maurice 17e75947f0 docs(readme): drop the Docker badge 2026-11-24 23:47:36 +01:00
Maurice 4f1e29b02c docs(readme): drop the Sonar and CI status badges 2026-11-24 23:46:48 +01:00
Maurice d1ee3ceccb docs(readme): show the app stores as cards with their QR code
Two cards, one per store, in a light and a dark version that follow GitHub's theme: the QR code on white on the left, the store's mark and name on the right. They replace the bordered table and the two shield badges, and each card links to its store.
2026-11-24 23:45:47 +01:00
Maurice 69a976e942 docs(readme): put the iOS and Android apps near the top, shorten the sponsor section
A QR code and a store button for the App Store and Google Play sit right
under the introduction, with a line that the app connects to your own TREK
server and a link to the Native Apps page. The QR codes are SVGs on a white
ground, so they scan in GitHub's light and dark theme alike.

The dataforest cloud section keeps its logo and every sponsor link but says
the same in one paragraph instead of four.
2026-11-24 23:41:22 +01:00
Maurice f928f4b1ca fix(postgres): connect over a Unix socket
TREK_DB_URL could not name a Unix socket. MikroORM builds the pool from the
URL's own host and drops a host parameter, so
postgresql://trek@localhost/trek?host=/var/run/postgresql connected to
localhost over TCP. A percent-encoded socket path as the host reached the
pool, but the client tools got it undecoded in PGHOST, so backups, restores
and the safety copy before a migration failed.

The server address is now read once, the way libpq reads a connection URL:
a host or port parameter takes the place of the URL's own, and a host
written into the URL is percent-decoded. The pool and the client tools both
get that address. The wiki and .env.example show the socket form.
2026-11-24 23:15:34 +01:00
Maurice aa79d6286a fix(paddle): read the Geofabrik region list again
The admin's paddle region picker failed with "The list of regions cannot be
fetched right now". Geofabrik's index now writes a continent's parent as
null instead of leaving the key out, and the schema took only a string or
nothing, so the whole list was refused over nine entries.

The optional fields now take null as well, and the entries are read one by
one: an entry in a shape TREK does not know costs only that region and is
counted in a warning. A list of which nothing can be read is still refused.

Closes #3195
2026-11-24 22:32:17 +01:00
Maurice eeff0398a7 fix(mail-import): retry a busy AI provider and never drop a booking mail in silence
A forwarded booking mail whose AI read failed in passing (a 503 "high
demand", a rate limit, a timeout) was settled at once with an inbox entry
nobody read again, and a manual import printed "no reservations found"
under the AI error as if the file held none.

Both LLM clients now send a failed request again up to twice, honouring
Retry-After within the request timeout. The mail pipeline puts such a mail
back in the queue and keeps the inbox entry only after its last try, and
these attempts no longer count toward the daily AI limit.

The mail prompt now names the answer's shape, { "bookings": [...] }, for
providers that get no tool. An answer in another shape used to read as
"not a booking" and the mail was discarded without a trace; it now ends
as a failed read the person sees in the inbox.

The import warnings lose their dashes, and the image sets LANG=C.UTF-8 so
KItinerary stops warning about the C locale on every run.
2026-11-24 13:30:22 +01:00
Maurice 7fe4fbb683 fix(plugins): mark a plugin that waits for re-consent as failed at boot
A plugin whose files now declare permissions it was never granted is
refused before its process starts, so the supervisor's status hook never
ran and the row kept the 'active' it had from the last run. The plugin
list and the navigation kept offering it while its page answered
"Plugin not available". The boot now stores the refusal as the plugin's
error, so Admin > Plugins says why and the navigation drops it.
2026-11-24 13:20:36 +01:00
Maurice afbeef64c2 style(notices): format the release notice strings with Prettier
The 5.2.0 release modal copy kept short strings on their own line, which
lint:format rejects for files outside its baseline.
2026-11-24 12:23:59 +01:00
Maurice 293ec89db4 fix(map): pin mapbox-gl to 3.32.0 so vector tiles load beside maplibre-gl
mapbox-gl 3.33 and later read the worker class registry key before they
handle Set and Error. maplibre-gl, which ships in the same bundle, stamps
that key on both built-ins, so mapbox-gl looks up a registry entry it never
made and every vector tile fails with "Cannot read properties of undefined
(reading 'omit')". The Mapbox basemap stays blank while raster layers such
as satellite still load. 5.2.0 shipped mapbox-gl 3.35.2; 3.36.0-rc.1 still
has the same order.

Pin the last release that handles the built-ins first, keep Dependabot off
3.33 and later, and add a test that reads the shipped serializer and fails
on a version with the registry read first.
2026-11-24 00:04:19 +01:00
887 changed files with 35143 additions and 15104 deletions
+33
View File
@@ -26,15 +26,48 @@ updates:
prefix: chore(deps)
prefix-development: chore(deps-dev)
groups:
# Packages that release in lockstep move together, so a PR never pins
# half of them on one version and half on the next.
# better-sqlite3 and kysely are pinned exactly by @mikro-orm/sqlite and
# share its connection, so they move with MikroORM.
mikro-orm:
patterns: ['@mikro-orm/*', better-sqlite3, kysely]
update-types: [minor, patch]
nestjs:
patterns: ['@nestjs/*']
update-types: [minor, patch]
npm-minor-and-patch:
update-types: [minor, patch]
ignore:
# nestjs-zod, which validates every request body, does not support
# NestJS 12 yet. The framework moves by hand once it does.
- dependency-name: '@nestjs/*'
update-types: [version-update:semver-major]
# TypeScript 7 is the native compiler and has no JavaScript API yet:
# typescript-eslint, the coverage instrumenter and the Postgres probe all
# call into it (readConfigFile, ScriptTarget). It moves by hand once the
# tooling supports it.
- dependency-name: typescript
update-types: [version-update:semver-major]
# mapbox-gl 3.33 and later read the worker registry key before handling
# Set and Error, and maplibre-gl, bundled beside it, stamps that key on
# both built-ins: every vector tile then fails with "reading 'omit'".
# glWorkerRegistry.test.ts fails on a version with that order; it moves
# by hand once mapbox-gl checks the built-ins first again.
- dependency-name: mapbox-gl
versions: ['>=3.33.0']
# The packages below move by hand, each for its reason. A security
# advisory for one of them still shows up in the Security tab, where it
# is handled together with that reason.
#
# Pinned exactly by @nestjs/schedule; a newer cron of our own would be a
# second copy whose CronJob the scheduler does not accept.
- dependency-name: cron
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
# Root pins that must name the rollup version the lockfile installs (the
# Alpine image needs the musl binaries).
- dependency-name: '@rollup/rollup-linux-*-musl'
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
# plugin-sdk is standalone with a lockfile of its own and ships to npm.
- package-ecosystem: npm
+55 -1
View File
@@ -105,9 +105,63 @@ jobs:
track: ${{ inputs.track || 'internal' }}
status: draft
# The same build for installs outside Google Play: the universal APK Google
# Play makes of this bundle, signed with the Play app signing key, published
# to liketrek/trek-android for Obtainium (wiki/Native-Apps.md). Only for a
# release tag, and held back while the app needs a server version that is
# not released yet.
- name: Whether the latest server release serves this build
id: released
env:
GH_TOKEN: ${{ github.token }}
run: |
tag=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name)
git fetch --depth=1 origin "refs/tags/$tag:refs/tags/$tag"
git show "$tag:server/src/nest/health/features.controller.ts" > "$RUNNER_TEMP/released-features.ts"
node scripts/ci/android-apk-release.mjs guard "$RUNNER_TEMP/released-features.ts" >> "$GITHUB_OUTPUT"
- name: Universal APK from Google Play
if: steps.released.outputs.publish == 'true'
env:
PLAY_APK_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_APK_SERVICE_ACCOUNT_JSON }}
APK: trek-${{ steps.version.outputs.version }}.apk
run: |
printf '%s' "$PLAY_APK_SERVICE_ACCOUNT_JSON" > "$RUNNER_TEMP/play-apk.json"
node scripts/ci/android-apk-release.mjs download "$RUNNER_TEMP/play-apk.json" com.liketrek.trek \
"${{ steps.version.outputs.build }}" "$RUNNER_TEMP/$APK"
rm -f "$RUNNER_TEMP/play-apk.json"
cd "$RUNNER_TEMP" && sha256sum "$APK" > "$APK.sha256"
- uses: actions/create-github-app-token@v3
if: steps.released.outputs.publish == 'true'
id: apk-token
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: liketrek
repositories: trek-android
# One release per app version: a newer build of the same version replaces
# its APK, so the release always holds what Google Play holds for it.
- name: Publish to liketrek/trek-android
if: steps.released.outputs.publish == 'true'
env:
GH_TOKEN: ${{ steps.apk-token.outputs.token }}
VERSION: ${{ steps.version.outputs.version }}
BUILD: ${{ steps.version.outputs.build }}
run: |
apk="$RUNNER_TEMP/trek-$VERSION.apk"
notes="TREK $VERSION for Android (build $BUILD): the build Google Play distributes, with the same signature. Connect it to your own TREK server; push and TREK Cloud need Google Play services. Changes: https://github.com/liketrek/TREK/releases"
if gh release view "v$VERSION" -R liketrek/trek-android > /dev/null 2>&1; then
gh release upload "v$VERSION" -R liketrek/trek-android --clobber "$apk" "$apk.sha256"
gh release edit "v$VERSION" -R liketrek/trek-android --notes "$notes"
else
gh release create "v$VERSION" -R liketrek/trek-android --title "TREK $VERSION" --notes "$notes" "$apk" "$apk.sha256"
fi
- name: Remove the upload key
if: always()
run: rm -f "$RUNNER_TEMP/upload.jks"
run: rm -f "$RUNNER_TEMP/upload.jks" "$RUNNER_TEMP/play-apk.json"
ios:
if: github.repository == 'liketrek/TREK'
+22 -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
@@ -1224,6 +1224,14 @@ jobs:
--set service.port=8080 \
--set-json 'httpRoute={"enabled":true,"parentRefs":[{"name":"gateway","namespace":"gateway-system","sectionName":"https"}],"hostnames":["trek.example.com"],"paths":["/","/api"],"annotations":{"example.com/note":"custom route"},"timeouts":{"request":"0s","backendRequest":"0s"}}' \
> "$out/http-route-variants.yaml"
helm template trek charts/trek \
--set-json 'extraObjects=[{"apiVersion":"batch/v1","kind":"CronJob","metadata":{"name":"{{ include \"trek.fullname\" . }}-backup-copy"},"spec":{"schedule":"0 3 * * *","jobTemplate":{"spec":{"template":{"spec":{"restartPolicy":"OnFailure","containers":[{"name":"copy","image":"busybox:1.36","command":["ls","/data/backups"],"volumeMounts":[{"name":"data","mountPath":"/data","readOnly":true}]}],"volumes":[{"name":"data","persistentVolumeClaim":{"claimName":"{{ include \"trek.fullname\" . }}-data","readOnly":true}}]}}}}}},"apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: {{ .Release.Name }}-notes\ndata:\n release: {{ .Release.Name | quote }}\n"]' \
> "$out/extra-objects.yaml"
# kubeconform accepts a name that still reads {{ ... }}, so check that both forms went through tpl.
if grep -n '{{' "$out/extra-objects.yaml"; then
echo "::error::extraObjects left a template unrendered"
exit 1
fi
- name: Check the manifests against the Kubernetes schemas
# The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources.
@@ -1339,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
@@ -1460,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.
+23 -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 && \
@@ -101,6 +110,8 @@ COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
ENV XDG_CACHE_HOME=/tmp/kf6-cache
# Prevent Qt from probing for a display in headless containers.
ENV QT_QPA_PLATFORM=offscreen
# A UTF-8 locale, so Qt does not warn about the C locale on every extractor run.
ENV LANG=C.UTF-8
# Fixed path for both amd64 (static binary) and arm64 (symlink to apt binary).
# Override with KITINERARY_EXTRACTOR_PATH if you install it elsewhere.
ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
+15 -60
View File
@@ -12,14 +12,14 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
<br />
<a href="https://apps.apple.com/app/id6831237775"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/app/app-store-dark.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/app/app-store-light.svg" /><img src="docs/app/app-store-light.svg" alt="Download TREK on the App Store, with a QR code" width="320" /></picture></a>
&nbsp;
<a href="https://play.google.com/store/apps/details?id=com.liketrek.trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/app/google-play-dark.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/app/google-play-light.svg" /><img src="docs/app/google-play-light.svg" alt="Get TREK on Google Play, with a QR code" width="320" /></picture></a>
<br />
<a href="https://demo.liketrek.com"><img alt="Demo" src="https://img.shields.io/badge/Demo-try-111827?style=for-the-badge" /></a>
&nbsp;
<a href="https://hub.docker.com/r/mauriceboe/trek"><img alt="Docker" src="https://img.shields.io/badge/Docker-ready-2496ED?style=for-the-badge" /></a>
&nbsp;
<a href="https://sonarcloud.io/project/overview?id=liketrek_TREK"><img alt="Sonar Quality Gate" src="https://img.shields.io/sonar/quality_gate/liketrek_TREK?server=https%3A%2F%2Fsonarcloud.io&style=for-the-badge" /></a>
&nbsp;
<img alt="GitHub Actions Workflow Status" src="https://img.shields.io/github/actions/workflow/status/liketrek/TREK/test.yml?branch=main&style=for-the-badge">
&nbsp;
<a href="https://discord.gg/NhZBDSd4qW"><img alt="Discord" src="https://img.shields.io/badge/Discord-join-5865F2?style=for-the-badge" /></a>
&nbsp;
<a href="https://kanban.pakulat.org/shared/I4wxF6inOOMB0C6hH6kQm3efyNxFjwyI"><img alt="Roadmap" src="https://img.shields.io/badge/Roadmap-view-0EA5E9?style=for-the-badge" /></a>
@@ -38,7 +38,6 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
&nbsp;
<a href="https://github.com/liketrek/TREK"><img alt="Stars" src="https://img.shields.io/github/stars/liketrek/trek?style=for-the-badge&label=Stars&color=6B7280" /></a>
<sub>PUBLIC SERVICES PROUDLY SPONSORED BY</sub><br /><a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" /><img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="30" /></picture></a>
</div>
---
@@ -53,14 +52,8 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
## What you get
<picture>
<source media="(max-width: 700px)" srcset="docs/tiles/grid-mobile.svg" />
<source media="(prefers-color-scheme: dark)" srcset="docs/tiles/grid-desktop-dark.svg" />
<img src="docs/tiles/grid-desktop.svg" alt="Plan, track, share" width="100%" />
</picture>
<details>
<summary><b>See all features</b></summary>
<summary><h3>See all features</h3></summary>
<br />
@@ -220,34 +213,12 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
<br />
## Powered by [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek)
<div align="center">
<br />
<sub>POWERED BY</sub><br />
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" /><img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="40" /></picture></a>
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" />
<source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" />
<img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="60" />
</picture>
</a>
<br />
<br />
**Every TREK installation in the world searches through servers that [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) sponsors.**
The place index with over 88 million places, the address search in every TREK language and the planet-wide routing all run on [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) in Frankfurt, Germany, free of charge for everyone who self-hosts TREK. Without this sponsorship, these services would not exist in this form.
Thank you, [dataforest](https://cloud.dataforest.net/en?mtm_campaign=trek), for backing open source this generously. 💚
<br />
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><img alt="Visit dataforest cloud" src="https://img.shields.io/badge/Visit-dataforest_cloud-02C382?style=for-the-badge" /></a>
Looking for a server for your own TREK? [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) is where TREK's own services live.
The place index with 88 million places, the address search and the planet-wide routing run on <a href="https://cloud.dataforest.net/en?mtm_campaign=trek">dataforest cloud</a> in Frankfurt, free for every self-hosted TREK. Thank you! 💚
</div>
@@ -255,13 +226,7 @@ Looking for a server for your own TREK? [dataforest cloud](https://cloud.datafor
## AI usage
We use LLM-assisted coding tools across parts of this codebase. Nothing ships that a
maintainer has not read and understood: every change goes through a pull request, is
reviewed and tested, and has a human who can answer for it. "The AI wrote that" is not
an answer any of us would accept from ourselves.
See [**How we use AI in TREK**](https://github.com/liketrek/TREK/discussions/1851) for
the details.
We use LLM-assisted coding tools, and nothing ships that a maintainer has not read, reviewed, tested and can answer for. More in [How we use AI in TREK](https://github.com/liketrek/TREK/discussions/1851).
<br />
@@ -285,7 +250,7 @@ Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine.
<div align="center">
<a href="#docker-compose-production">Docker Compose</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#helm-kubernetes">Helm / Kubernetes</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#install-as-app-pwa">Install as PWA</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#reverse-proxy">Reverse Proxy</a>
<a href="#docker-compose-production">Docker Compose</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#helm-kubernetes">Helm / Kubernetes</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#reverse-proxy">Reverse Proxy</a>
</div>
@@ -323,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.
@@ -342,18 +307,6 @@ See [`charts/README.md`](https://github.com/liketrek/TREK/blob/main/charts/READM
<br />
<h2 id="install-as-app-pwa">Install as App (PWA)</h2>
TREK works as a Progressive Web App, and the TREK Travel Planner app for iPhone, iPad and Android connects to the same server ([Native Apps](https://github.com/liketrek/TREK/wiki/Native-Apps)). To install the web app instead:
1. Open TREK in the browser (HTTPS required)
2. **iOS**: Share ▸ *Add to Home Screen*
3. **Android**: Menu ▸ *Install app* (or *Add to Home Screen*)
TREK then launches fullscreen with its own icon, just like a native app.
<br />
## Updating
See [Updating](https://github.com/liketrek/TREK/wiki/Updating) — Docker Compose,
@@ -442,6 +395,8 @@ Caddy handles TLS and WebSockets automatically.
Every variable, its default and what it does: see
[Environment Variables](https://github.com/liketrek/TREK/wiki/Environment-Variables).
<br />
## Data sources
The Atlas map's country and sub-national (province/county) boundaries come from
+1
View File
@@ -60,3 +60,4 @@ See `values.yaml` for more options.
- Set `env.OIDC_DISCOVERY_URL` to override the auto-constructed OIDC discovery endpoint. Required for providers (e.g. Authentik) that expose it at a non-standard path.
- `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands `/app/data` and `/app/uploads` to `node` (uid 1000) if the directory or anything directly inside it is not owned by `node` yet, and drops to `node`. Deeper files are not checked. Only the owning user is changed (plus a `root` group), so a different `fsGroup` stays in place. A volume that refuses `chown` (NFS with `root_squash`) logs a warning instead; set `runAsUser: 1000` then. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`.
- Use `extraVolumes` and `extraVolumeMounts` to add your own volumes to the pod. To give the booking import more KItinerary extractors, mount a ConfigMap at `/usr/local/share/kitinerary/extractors`, with one `.json` and one `.js` key for each extractor; see the example in `values.yaml`.
- Use `extraObjects` to render further Kubernetes objects next to the chart's own, for example a backup `CronJob`. Each item is a map or a string of YAML, and `{{ }}` in it is evaluated, so `{{ .Release.Name }}` works. A backup job should copy TREK's own backups from `backups/` on the data volume and mount it read only, since that volume also holds the encryption key. The archives carry `.encryption_key` too unless `ENCRYPTION_KEY` is set, so protect the copy's destination like the data volume.
+5 -2
View File
@@ -1,5 +1,8 @@
apiVersion: v2
name: trek
version: 5.2.0
version: 5.2.2
description: Minimal Helm chart for TREK app
appVersion: "5.2.0"
home: https://github.com/liketrek/TREK
sources:
- https://github.com/liketrek/TREK
appVersion: "5.2.2"
+8
View File
@@ -0,0 +1,8 @@
{{- range .Values.extraObjects }}
---
{{- if kindIs "string" . }}
{{ tpl . $ }}
{{- else }}
{{ tpl (toYaml .) $ }}
{{- end }}
{{- end }}
+24 -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: ""
@@ -338,6 +338,29 @@ extraVolumes: []
# readOnly: true
extraVolumeMounts: []
# Further Kubernetes objects the chart renders next to its own, for example a Job, a
# CronJob or a ConfigMap. Each item is rendered as written, either as a map or as a
# string of YAML, and {{ }} in it is evaluated, so {{ include "trek.fullname" . }} or
# {{ .Release.Name }} work, in both forms. Write literal braces as {{ "{{" }}.
# A backup job must only read the data volume: it also holds the encryption key and the
# server's secrets, and a second writer corrupts travel.db. Rather than copying the live
# travel.db, copy TREK's own backups (Admin, Backup, automatic backups) from backups/ in
# that volume. Those archives carry .encryption_key too (unless ENCRYPTION_KEY is set),
# so protect the job's destination like the data volume itself.
# extraObjects:
# - apiVersion: v1
# kind: ConfigMap
# metadata:
# name: '{{ include "trek.fullname" . }}-extra'
# data:
# note: hello
# - |
# apiVersion: v1
# kind: ConfigMap
# metadata:
# name: {{ .Release.Name }}-notes
extraObjects: []
resources:
requests:
cpu: 100m
@@ -1,6 +1,9 @@
package com.liketrek.trek;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.util.TypedValue;
@@ -11,11 +14,13 @@ import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.WebViewListener;
import com.liketrek.trek.screen.TrekKeyCommands;
import com.liketrek.trek.tiles.TrekTileStore;
import com.liketrek.trek.widget.TrekWidgetUpdater;
@@ -26,6 +31,9 @@ public class MainActivity extends BridgeActivity {
/** The share sheet (share/ShareActivity.kt) left an item for the import. */
public static final String ACTION_SHARE_HANDOFF = "com.liketrek.trek.SHARE_HANDOFF";
/** The page colour of the address screen (native-shell/shell.css --page). */
private static final int SHELL_PAGE = 0xFFFFFAF5;
@Override
protected void onCreate(Bundle savedInstanceState) {
registerPlugin(TrekShellPlugin.class);
@@ -57,6 +65,33 @@ public class MainActivity extends BridgeActivity {
// and Chrome honours that, but the WebView draws the stretch on its root
// scroller natively. It scales the whole view, top bar and bottom dock included.
bridge.getWebView().setOverScrollMode(View.OVER_SCROLL_NEVER);
// The address screen, and the step from it to the server just picked:
// the warm ground of the first screens behind everything, so the
// restart and the page's first frames do not flash white. The window's
// colour is also what an older WebView shows under the status bar,
// where it lays the page out between the bars (native/appBoot.ts).
if (!onServer || restarting) {
Drawable windowBackground = getWindow().getDecorView().getBackground();
// A new drawable: setBackgroundColor would recolour the theme's own one,
// and the restore below would hand the window the warm ground back.
getWindow().getDecorView().setBackground(new ColorDrawable(SHELL_PAGE));
bridge.getWebView().setBackgroundColor(SHELL_PAGE);
// Once the server's page is up, the window is the one a normal launch
// has, so the status bar of an older WebView follows the system again.
if (onServer) {
bridge.addWebViewListener(new WebViewListener() {
private boolean restored;
@Override
public void onPageLoaded(WebView webView) {
if (restored) return;
restored = true;
getWindow().getDecorView().setBackground(windowBackground);
webView.setBackgroundColor(Color.WHITE);
}
});
}
}
// Set before any WebView callback can run: they are posted to this thread.
if (onServer) {
bridge.setWebViewClient(
+234
View File
@@ -0,0 +1,234 @@
import { devices, expect, test, type Locator, type Page } from '@playwright/test';
import { encodePolyline6 } from '@trek/shared';
async function createTourTrip(page: Page): Promise<number> {
const trip = await page.request.post('/api/trips', {
data: { title: 'Tour type picker', start_date: '2099-06-01', end_date: '2099-06-05' },
});
await expect(trip).toBeOK();
const {
trip: { id },
} = await trip.json();
await expect(await page.request.put(`/api/trips/${id}/addons/tours`, { data: { enabled: true } })).toBeOK();
return id;
}
async function expectInside(element: Locator, boundary: Locator) {
await expect
.poll(async () => {
const target = await element.boundingBox();
const rail = await boundary.boundingBox();
return (
!!target &&
!!rail &&
target.x >= rail.x - 1 &&
target.y >= rail.y - 1 &&
target.x + target.width <= rail.x + rail.width + 1 &&
target.y + target.height <= rail.y + rail.height + 1
);
})
.toBe(true);
}
function editorFields(page: Page) {
const trigger = page.getByTestId('tour-type-select');
const scrollArea = page.getByTestId('tour-planner-editor-scroll');
return { trigger, scrollArea, menu: page.getByRole('group', { name: 'Tour type', exact: true }) };
}
test('Tour type follows and fits inside the narrow editor rail', async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 480 });
const tripId = await createTourTrip(page);
await page.goto(`/trips/${tripId}?tab=tour-planner`);
await page.getByRole('button', { name: 'Plan new tour' }).click();
await expect(page.getByTestId('tour-planner-empty-state')).toBeAttached();
const grip = page.locator('[data-resize="left"]');
for (let step = 0; step < 8; step++) await grip.press('ArrowLeft');
const { trigger, scrollArea, menu } = editorFields(page);
await trigger.scrollIntoViewIfNeeded();
await expectInside(trigger, scrollArea);
await trigger.click();
await expectInside(menu, scrollArea);
await expect.poll(() => menu.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
async function anchorGap() {
return menu.evaluate((el) => {
const anchor = document.querySelector('[data-testid="tour-type-select"]')!.getBoundingClientRect();
const panel = el.getBoundingClientRect();
return Math.round(Math.max(panel.top - anchor.bottom, anchor.top - panel.bottom));
});
}
await expect.poll(anchorGap).toBe(4);
const start = await scrollArea.evaluate((el) => el.scrollTop);
await scrollArea.evaluate((el) => el.scrollBy(0, 20));
await expect.poll(() => scrollArea.evaluate((el) => el.scrollTop)).toBeGreaterThan(start);
await expect.poll(anchorGap).toBe(4);
await expectInside(menu, scrollArea);
await scrollArea.evaluate((el, top) => {
el.scrollTop = top;
}, start);
await expect.poll(anchorGap).toBe(4);
await page.keyboard.press('Escape');
await expect(trigger).toBeFocused();
await expect(menu).toHaveCount(0);
await trigger.click();
await scrollArea.evaluate((el) => el.scrollBy(0, 180));
await expect(trigger).toHaveAttribute('aria-expanded', 'false');
await expect(menu).toHaveCount(0);
await scrollArea.evaluate((el) => {
el.scrollTop = 0;
});
await expect(menu).toHaveCount(0);
await trigger.click();
const ski = menu.getByTestId('tour-type-option-ski');
await page.keyboard.press('End');
await expect(ski).toBeInViewport();
await expect(ski).toBeFocused();
await page.keyboard.press('Enter');
await expect(trigger).toContainText('Ski & winter');
await expect(menu).toHaveCount(0);
await page.getByRole('button', { name: 'Alpine', exact: true }).click();
const hardest = page.getByRole('button', { name: 'Hardest runs', exact: true });
const hardestMenu = page.getByRole('group', { name: 'Hardest runs', exact: true });
await hardest.click();
await expectInside(hardestMenu, scrollArea);
await hardestMenu.getByRole('button', { name: 'Easy', exact: true }).click();
await expect(hardest).toContainText('Easy');
await expect(hardestMenu).toHaveCount(0);
});
test('the saved hike difficulty dropdown fits above the field and keeps alpine confirmation', async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 520 });
const tripId = await createTourTrip(page);
const saved = await page.request.post(`/api/trips/${tripId}/tours`, {
data: {
name: 'Saved ridge walk',
tour_type: 'hike',
max_hiking_difficulty: 2,
route_geometry: [
[48.1, 11.1, 500],
[48.11, 11.11, 550],
],
waypoints: [
{ lat: 48.1, lng: 11.1, role: 'start', sequence: 0 },
{ lat: 48.11, lng: 11.11, role: 'end', sequence: 1 },
],
},
});
await expect(saved).toBeOK();
const {
tour: { place_id },
} = await saved.json();
const detailUrl = `**/api/trips/${tripId}/tours/${place_id}`;
const detailGate = Promise.withResolvers<void>();
await page.route(
detailUrl,
async (route) => {
await detailGate.promise;
await route.continue();
},
{ times: 1 }
);
const shape = encodePolyline6([
{ lat: 48.1, lon: 11.1 },
{ lat: 48.11, lon: 11.11 },
]);
await page.route('**/api/routing/valhalla/route', (route) =>
route.fulfill({
json: { trip: { legs: [{ shape, summary: { length: 1.4, time: 1200 } }] } },
})
);
await page.goto(`/trips/${tripId}?tab=tour-planner`);
const detailRequested = page.waitForRequest(detailUrl);
await page.getByRole('option', { name: /Saved ridge walk/ }).click();
await detailRequested;
const { trigger, menu, scrollArea } = editorFields(page);
try {
await expect(trigger).toHaveCount(0);
await expect(menu).toHaveCount(0);
} finally {
detailGate.resolve();
}
await expect(page.getByLabel('Tour name')).toHaveValue('Saved ridge walk');
await trigger.click();
await expectInside(menu, scrollArea);
await page.keyboard.press('Escape');
const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true });
const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true });
await difficulty.scrollIntoViewIfNeeded();
await difficulty.click();
await expectInside(difficultyMenu, scrollArea);
await expect(difficultyMenu).toHaveCSS('transform-origin', /px [1-9][0-9.]*px$/);
await page.keyboard.press('Escape');
await expect(difficulty).toBeFocused();
await expect(difficultyMenu).toHaveCount(0);
await difficulty.click();
await scrollArea.evaluate((el) => {
el.scrollTop = 0;
});
await expect(difficulty).toHaveAttribute('aria-expanded', 'false');
await expect(difficultyMenu).toHaveCount(0);
await difficulty.click();
await difficultyMenu.getByRole('button', { name: 'T3: Demanding mountain hiking' }).click();
await expect(difficulty).toContainText('T3:');
await difficulty.click();
await difficultyMenu.getByRole('button', { name: 'T4: Alpine hiking' }).click();
await expect(page.getByRole('heading', { name: 'Enable alpine routing?' })).toBeVisible();
await page.getByRole('button', { name: 'Cancel' }).click();
await expect(difficulty).toContainText('T3:');
const categories = page.getByTestId('tour-poi-categories');
await categories.click();
await expectInside(page.getByRole('group', { name: 'What to look for', exact: true }), scrollArea);
});
test('the tour editor dropdowns fit in the native tablet layout', async ({ playwright, baseURL, storageState }) => {
const browser = await playwright.webkit.launch();
try {
const page = await browser.newPage({
...devices['iPad Pro 11'],
viewport: { width: 680, height: 620 },
baseURL,
storageState,
});
page.setDefaultTimeout(10_000);
// The browser supplies the WebKit viewport and touch input. This flag selects the app shell.
await page.addInitScript(() => Object.assign(window, { CapacitorCustomPlatform: { name: 'ios' } }));
const tripId = await createTourTrip(page);
await page.goto(`/trips/${tripId}?tab=tour-planner`);
await page.getByRole('tab', { name: 'Plan a tour', exact: true }).tap();
await page.getByRole('button', { name: 'Plan new tour' }).tap();
const { trigger, menu, scrollArea } = editorFields(page);
await trigger.tap();
await expectInside(menu, scrollArea);
await scrollArea.evaluate((el) => el.scrollBy(0, 160));
await expect(trigger).toHaveAttribute('aria-expanded', 'false');
const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true });
const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true });
await difficulty.tap();
await expectInside(difficultyMenu, scrollArea);
await difficultyMenu.getByRole('button', { name: 'T1: Hiking' }).tap();
await expect(difficulty).toContainText('T1:');
await expect(difficultyMenu).toHaveCount(0);
await trigger.tap();
await menu.getByTestId('tour-type-option-ski').tap();
await page.getByRole('button', { name: 'Alpine', exact: true }).tap();
const hardest = page.getByRole('button', { name: 'Hardest runs', exact: true });
const hardestMenu = page.getByRole('group', { name: 'Hardest runs', exact: true });
await hardest.tap();
await expectInside(hardestMenu, scrollArea);
await hardestMenu.getByRole('button', { name: 'Easy', exact: true }).tap();
await expect(hardest).toContainText('Easy');
} finally {
await browser.close();
}
});
+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,
+4 -1
View File
@@ -5,6 +5,7 @@ import { SplashScreen } from '@capacitor/splash-screen';
import { StatusBar, Style } from '@capacitor/status-bar';
import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../shared/src/auth/password-policy';
import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape
import { pageUnderStatusBar } from '../src/native/appBoot';
import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
import { opensSoon, refundedBeforeOpening } from '../src/native/cloudOrders';
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap';
@@ -1705,7 +1706,9 @@ function showUnreachable(server: string, cert?: ClientCertDemand, failure?: stri
*/
async function paintStatusBar(): Promise<void> {
try {
await StatusBar.setStyle({ style: Style.Dark });
// Below the bar on an older Android WebView the page stops, and the bar
// stands on the window's light colour instead: dark icons there.
await StatusBar.setStyle({ style: pageUnderStatusBar() ? Style.Dark : Style.Light });
if (wideLayout.matches) await StatusBar.hide();
else await StatusBar.show();
} catch {
+26 -5
View File
@@ -204,11 +204,32 @@
--sea: #cfe3ef;
--text-face: 'Plus Jakarta Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--display-face: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
/* The insets of the device, from the web view or, on iOS, from the native side. */
--safe-top: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
--safe-bottom: max(env(safe-area-inset-bottom, 0px), var(--trek-native-safe-bottom, 0px));
--safe-start: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
--safe-end: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
/* The insets of the device, from the web view or from the native side. On
* Android a web view can report env() as 0 while the page reaches under the
* status and navigation bars; Capacitor's SystemBars writes the real insets
* to --safe-area-inset-* instead (0 where it lays the web view out between
* the bars). iOS measures its own (TrekBridgeViewController publishSafeArea).
* In a browser the variables are unset: env() alone. */
--safe-top: max(
env(safe-area-inset-top, 0px),
var(--safe-area-inset-top, 0px),
var(--trek-native-safe-top, 0px)
);
--safe-bottom: max(
env(safe-area-inset-bottom, 0px),
var(--safe-area-inset-bottom, 0px),
var(--trek-native-safe-bottom, 0px)
);
--safe-start: max(
env(safe-area-inset-left, 0px),
var(--safe-area-inset-left, 0px),
var(--trek-native-safe-left, 0px)
);
--safe-end: max(
env(safe-area-inset-right, 0px),
var(--safe-area-inset-right, 0px),
var(--trek-native-safe-right, 0px)
);
color-scheme: light;
-webkit-text-size-adjust: 100%;
}
+20 -16
View File
@@ -1,6 +1,6 @@
{
"name": "@trek/client",
"version": "5.2.0",
"version": "5.2.2",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
@@ -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,23 +102,24 @@
"@fontsource/shrikhand": "^5.3.0",
"@fontsource/yellowtail": "^5.3.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4",
"@noble/hashes": "^1.8.0",
"@simplewebauthn/browser": "^13.3.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",
"lucide-react": "^0.577.0",
"mapbox-gl": "^3.35.2",
"mapbox-gl": "3.32.0",
"maplibre-gl": "6.19.0",
"modern-screenshot": "4.7.0",
"plyr": "^3.8.5",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-dropzone": "^14.4.1",
"react-dropzone": "^20.2.1",
"react-leaflet": "^5.0.0",
"react-leaflet-cluster": "^4.1.3",
"react-markdown": "^10.1.0",
@@ -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",
"@types/node": "^25.9.8",
"@types/react": "^19.3.0",
"@trivago/prettier-plugin-sort-imports": "^6.0.3",
"@types/leaflet": "^1.9.23",
"@types/node": "^26.6.11",
"@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",
@@ -154,18 +158,18 @@
"eslint-plugin-react-refresh": "^0.5.8",
"fake-indexeddb": "^6.2.7",
"jsdom": "^29.1.1",
"msw": "^2.15.0",
"msw": "^3.0.8",
"postcss": "^8.5.33",
"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.72.1",
"typescript-eslint": "^8.74.0",
"vite": "8.3.8",
"vite-plugin-pwa": "^2.0.0",
"vitest": "^4.1.12"
"vitest": "^5.1.2"
}
}
+10
View File
@@ -12,6 +12,16 @@
(function () {
try {
var raw = localStorage.getItem('trek_appearance');
// Inside the iOS and Android app, before anyone signed in on this server
// from here: the page carries on the address screen's colour until the
// sign-in screen is up (native/appBoot.ts), instead of flashing white.
// The app's bridge is in place before this script runs.
var w = window;
var inApp = !!(w.androidBridge || (w.webkit && w.webkit.messageHandlers && w.webkit.messageHandlers.bridge));
if (inApp && !raw) {
document.documentElement.setAttribute('data-app-boot', '');
document.documentElement.style.backgroundColor = '#fffaf5';
}
if (!raw) return;
var s = JSON.parse(raw);
if (!s || s.v !== 1) return;
+22 -23
View File
@@ -1,24 +1,24 @@
{
"src": {
"@typescript-eslint/no-non-null-assertion": 367,
"@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": 534,
"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/static-components": 50,
"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."
}
}
-21
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",
@@ -2121,7 +2101,6 @@
"tests/unit/sync/tripSyncManager.test.ts",
"tests/unit/tripStore.test.ts",
"tests/unit/utils/cleanAmount.test.ts",
"tests/unit/utils/fileDownload.test.ts",
"tests/unit/utils/formatters.test.ts",
"tests/unit/utils/placeFiles.test.ts",
"tests/unit/utils/shellGuard.test.ts",
+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
}
+5 -6
View File
@@ -8,19 +8,18 @@
"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": 2333,
"src/components/Planner/DayDetailPanel.test.tsx": 2331,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2910,
"src/components/Planner/DayPlanSidebar.tsx": 2908,
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
"src/components/Planner/PlaceInspector.tsx": 1128,
"src/components/Studio/TravelElements.tsx": 1559,
"src/components/Studio/countryShapes.ts": 2595,
"src/index.css": 1636,
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
"src/pages/JourneyDetailPage.test.tsx": 4028,
"src/pages/LoginPage.tsx": 1294,
"src/pages/TripPlannerPage.tsx": 1128,
"src/pages/atlas/useAtlas.ts": 1207,
"src/pages/JourneyDetailPage.test.tsx": 3886,
"src/pages/LoginPage.tsx": 1273,
"src/pages/TripPlannerPage.tsx": 1127,
"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,
+3 -9
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,
@@ -45,7 +44,7 @@
"components/Journey/JourneyMapGL.tsx": 5,
"components/Journey/MobileEntryView.tsx": 94,
"components/Journey/MobileMapTimeline.tsx": 8,
"components/Journey/PhotoLightbox.tsx": 13,
"components/Journey/PhotoLightbox.tsx": 11,
"components/Journey/VideoPlayer.tsx": 2,
"components/Journey/VideoPlayerLazy.tsx": 1,
"components/Journey/journeyMapPopup.ts": 17,
@@ -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,
@@ -262,7 +258,7 @@
"mobile/screens/trip/tabs/MCollabTab.tsx": 1,
"mobile/screens/trip/tabs/MCostsTab.tsx": 70,
"mobile/screens/trip/tabs/MDocSyncSheet.tsx": 43,
"mobile/screens/trip/tabs/MFileLightbox.tsx": 12,
"mobile/screens/trip/tabs/MFileLightbox.tsx": 11,
"mobile/screens/trip/tabs/MFileLinkSheet.tsx": 2,
"mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1,
"mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4,
@@ -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
}
+28 -5
View File
@@ -1,13 +1,13 @@
import React from 'react'
import { render, screen, waitFor, act } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { describe, it, expect, beforeEach, onTestFinished, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../tests/helpers/msw/server'
import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore'
import { resetAllStores } from '../tests/helpers/store'
import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories'
import { locationAt } from '../tests/helpers/location'
import { offlineDb } from './db/offlineDb'
import { SETTINGS_WAIT_MS } from './utils/startDestination'
import App from './App'
@@ -185,9 +185,29 @@ describe('RootRedirect — startup destination', () => {
seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false })
stubActiveTrip({ id: 42, title: 'Japan' })
// App asks for the settings on its own as soon as the user is signed in.
// Held until the redirect is decided, or whichever answer lands first wins
// and the test proves nothing about the mirror; released here, so it cannot
// land in the next test either.
let releaseSettings = () => {}
const settingsHeld = new Promise<void>((resolve) => { releaseSettings = resolve })
onTestFinished(() => releaseSettings())
server.use(
http.get('/api/settings', async () => {
await settingsHeld
return HttpResponse.json({
settings: buildSettings({ start_page: 'active_trip', start_trip_tab: 'finanzplan' }),
})
}),
)
renderApp('/')
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
expect(currentPath()).toBe('/trips/42?tab=finanzplan')
expect(useSettingsStore.getState().isLoaded).toBe(false)
releaseSettings()
await waitFor(() => expect(useSettingsStore.getState().isLoaded).toBe(true))
})
})
@@ -532,7 +552,7 @@ describe('Version cache-busting', () => {
const reload = vi.fn()
Object.defineProperty(window, 'location', {
writable: true,
value: { ...window.location, reload },
value: locationAt('/', { reload }),
})
server.use(
@@ -587,7 +607,7 @@ describe('Version cache-busting', () => {
// and try to update.
localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
server.use(
http.get('/api/auth/app-config', () =>
@@ -609,7 +629,7 @@ describe('Version cache-busting', () => {
// failure neither deletes anything nor reloads into the old worker's shell.
localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
const cachesDelete = vi.fn().mockResolvedValue(true)
const unregister = vi.fn().mockResolvedValue(true)
vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete })
@@ -685,6 +705,9 @@ describe('RootRedirect — preference not mirrored on this device', () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false })
// No backend: the settings never arrive, so only the timeout can decide.
// Answered, they would open the dashboard on their own and hide the wait.
server.use(http.get('/api/settings', () => HttpResponse.error()))
renderApp('/')
expect(screen.queryByText('Dashboard')).not.toBeInTheDocument()
+15 -3
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useState, useRef, ReactNode, Suspense } from 'react'
import React, { useEffect, useLayoutEffect, useState, useRef, ReactNode, Suspense } from 'react'
import { Routes, Route, Navigate, useLocation, useNavigationType } from 'react-router'
import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore'
@@ -17,6 +17,8 @@ import BackgroundTasksWidget from './components/BackgroundTasks/BackgroundTasksW
import MobileShell from './mobile/MobileShell'
import MRouteFallback from './mobile/components/MRouteFallback'
import ErrorBoundary from './components/shared/ErrorBoundary'
import AppBootScreen from './components/shared/AppBootScreen'
import { endAppBoot, isAppBoot } from './native/appBoot'
import { lazyWithRetry } from './utils/lazyWithRetry'
import { reconcileAppVersion } from './utils/versionHandover'
import { useServerVersionStore } from './store/serverVersionStore'
@@ -113,6 +115,7 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
const isPhone = useIsPhone()
if (isLoading) {
if (isAppBoot()) return <AppBootScreen />
return (
<div className="min-h-screen flex items-center justify-center bg-slate-50">
<div className="flex flex-col items-center gap-3">
@@ -286,6 +289,7 @@ function RootRedirect() {
}, [isLoading, isAuthenticated, settingsLoaded, settingsGaveUp, settings, target])
if (isLoading || (isAuthenticated && !target)) {
if (isAppBoot()) return <AppBootScreen />
return (
<div className="min-h-screen flex items-center justify-center bg-slate-50">
<div className="w-10 h-10 border-4 border-slate-200 border-t-slate-900 rounded-full animate-spin"></div>
@@ -306,6 +310,7 @@ function RouteFallback() {
// on a phone the desktop spinner on bg-surface would be a foreign white sheet
// in front of the mobile screen.
const isPhone = useIsPhone()
if (isAppBoot()) return <AppBootScreen />
if (isPhone) return <MRouteFallback />
return (
<div className="min-h-screen flex items-center justify-center bg-surface">
@@ -315,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()
@@ -346,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)
@@ -358,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)
@@ -398,6 +404,12 @@ export default function App() {
const location = useLocation()
const isSharedPage = location.pathname.startsWith('/shared/')
// Inside the app: the handover from its address screen ends once a signed-in
// screen is up, before it paints, so it can rise in (native/appBoot.ts).
useLayoutEffect(() => {
if (isAuthenticated && location.pathname !== '/' && location.pathname !== '/login') endAppBoot()
}, [isAuthenticated, location.pathname])
useEffect(() => {
const run = () =>
applyAppearance({
-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
@@ -1,7 +1,7 @@
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { delay, http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildAdmin } from '../../../tests/helpers/factories';
@@ -341,12 +341,43 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('pk.old');
await user.clear(input);
await user.type(input, 'pk.new');
fireEvent.blur(input);
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
// would blur it a second time and race that save against the reset request
await user.tab();
expect(input).not.toHaveFocus();
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }]));
// Clicking the reset link also blurs the field again, so only the last PUT is checked
await user.click(resetLink('Shared Mapbox token'));
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ mapbox_access_token: null }));
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }, { mapbox_access_token: null }]));
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
});
it('FE-ADMIN-DUS-032: a reset clicked while the save of the field is still out is the one that stays', async () => {
const user = userEvent.setup();
const { state } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.old' });
// The save is the slower request: sent at once, the reset would overtake it.
const done: string[] = [];
server.use(
http.put('/api/admin/default-user-settings', async ({ request }) => {
const body = await request.json() as Record<string, unknown>;
if (body.mapbox_access_token !== null) await delay(100);
if (body.mapbox_access_token === null) delete state.mapbox_access_token;
else state.mapbox_access_token = body.mapbox_access_token;
done.push(body.mapbox_access_token === null ? 'reset' : 'save');
return HttpResponse.json({ ...state });
}),
);
render(<DefaultUserSettingsTab />);
await screen.findByText('Shared Mapbox token');
const input = screen.getByPlaceholderText('pk.eyJ…');
await user.clear(input);
await user.type(input, 'pk.new');
// The click leaves the field, which saves it, and resets it right after.
await user.click(resetLink('Shared Mapbox token'));
await waitFor(() => expect(done).toEqual(['save', 'reset']));
expect(state.mapbox_access_token).toBeUndefined();
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
});
@@ -449,12 +480,14 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('ck.old');
await user.clear(input);
await user.type(input, 'ck.new');
fireEvent.blur(input);
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
// would blur it a second time and race that save against the reset request
await user.tab();
expect(input).not.toHaveFocus();
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }]));
// Clicking the reset link also blurs the field again, so only the last PUT is checked
await user.click(resetLink('Shared CARTO key'));
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ carto_api_key: null }));
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }, { carto_api_key: null }]));
await waitFor(() => expect(cartoInput()).toHaveValue(''));
});
@@ -11,6 +11,39 @@ import DevNotificationsPanel from './DevNotificationsPanel';
const ADMIN_USER = buildUser({ id: 1, username: 'testadmin', role: 'admin' });
/**
* Renders the panel and waits until both lookups (trips and users) have landed, so a test
* acts on the settled panel and no lookup answers after it has ended.
*/
async function renderSettled() {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
}
const LOOKUPS = ['/api/admin/users', '/api/trips'];
/**
* Records the GET requests to `paths` that have been answered, for the tests whose lookups
* come back empty or failed and so change nothing on screen to wait for. Call before render;
* the returned function waits until exactly `paths` (a path once per expected request) ended.
*/
function trackRequests(paths: string[] = LOOKUPS) {
const answered: string[] = [];
const onEnd = ({ request }: { request: Request }) => {
const { pathname } = new URL(request.url);
if (request.method === 'GET' && paths.includes(pathname)) answered.push(pathname);
};
server.events.on('request:end', onEnd);
return async () => {
try {
await waitFor(() => expect([...answered].sort()).toEqual([...paths].sort()));
} finally {
server.events.removeListener('request:end', onEnd);
}
};
}
beforeEach(() => {
resetAllStores();
seedStore(useAuthStore, { user: ADMIN_USER, isAuthenticated: true });
@@ -21,9 +54,12 @@ afterEach(() => {
});
describe('DevNotificationsPanel', () => {
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', () => {
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(screen.getByText('DEV ONLY')).toBeInTheDocument();
// Let the lookups the panel started land here, not in the next test
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
});
it('FE-ADMIN-DEVNOTIF-002: four section titles render after data loads', async () => {
@@ -36,8 +72,7 @@ describe('DevNotificationsPanel', () => {
});
it('FE-ADMIN-DEVNOTIF-003: trip selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const options = Array.from(tripSelect.querySelectorAll('option'));
const labels = options.map(o => o.textContent);
@@ -46,8 +81,7 @@ describe('DevNotificationsPanel', () => {
});
it('FE-ADMIN-DEVNOTIF-004: user selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('User-Scoped Events');
await renderSettled();
const selects = screen.getAllByRole('combobox');
// Second combobox is the user selector (first is trip selector)
const userSelect = selects[1];
@@ -66,8 +100,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody).toMatchObject({
@@ -75,6 +108,8 @@ describe('DevNotificationsPanel', () => {
scope: 'user',
targetId: ADMIN_USER.id,
});
// The send settles inside this test, so its toast cannot land in the next one
await screen.findByText('Sent: simple-me');
});
it('FE-ADMIN-DEVNOTIF-006: success toast shown after fire', async () => {
@@ -84,30 +119,34 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument();
});
it('FE-ADMIN-DEVNOTIF-007: all buttons disabled while a send is in-flight', async () => {
// The send is held open until the assertion ran, then released, so it settles in this test
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
server.use(
http.post('/api/admin/dev/test-notification', async () => {
await new Promise(() => {}); // never resolves — simulates in-flight
await gate;
return HttpResponse.json({ ok: true });
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
// The request handler never resolves, so sending stays true after the click settles
// The request handler is held, so sending stays true after the click settles
await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => {
const buttons = screen.getAllByRole('button');
buttons.forEach(btn => expect(btn).toBeDisabled());
});
release();
await screen.findByText('Sent: simple-me');
});
it('FE-ADMIN-DEVNOTIF-008: the server error field is what the toast shows', async () => {
@@ -117,8 +156,7 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('No channel configured')).toBeInTheDocument();
});
@@ -130,8 +168,7 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Failed')).toBeInTheDocument();
});
@@ -145,8 +182,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const tokyoOption = Array.from(tripSelect.querySelectorAll('option')).find(
@@ -159,15 +195,19 @@ describe('DevNotificationsPanel', () => {
await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody!.targetId).toBe(tokyoId);
// The send settles inside this test, so its toast cannot land in the next one
await screen.findByText('Sent: booking_change');
});
it('FE-ADMIN-DEVNOTIF-010: Trip-Scoped section absent when no trips', async () => {
server.use(
http.get('/api/trips', () => HttpResponse.json({ trips: [] })),
);
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>);
// Wait for user data to confirm async effects have settled
await screen.findByText('User-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();
});
@@ -180,8 +220,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Boolean → Me').closest('button')!);
await screen.findByText('Sent: boolean-me');
@@ -216,8 +255,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const tripId = Number((tripSelect as HTMLSelectElement).value);
@@ -247,8 +285,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('User-Scoped Events');
await renderSettled();
const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;
const aliceOption = Array.from(userSelect.querySelectorAll('option')).find(
@@ -278,9 +315,11 @@ describe('DevNotificationsPanel', () => {
it('FE-ADMIN-DEVNOTIF-014: the User-Scoped section is hidden when no users come back', async () => {
server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] })));
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
});
@@ -288,22 +327,38 @@ describe('DevNotificationsPanel', () => {
server.use(
http.get('/api/trips', () => HttpResponse.error()),
http.get('/api/admin/users', () => HttpResponse.error()),
// A network error makes the API client probe /api/health before it rejects; the server
// is down here, so the probe fails too instead of going out to the real network
http.get('/api/health', () => HttpResponse.error()),
);
const lookupsAnswered = trackRequests([...LOOKUPS, '/api/health', '/api/health']);
render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(await screen.findByText('Type Testing')).toBeInTheDocument();
await lookupsAnswered();
await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument());
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument();
});
it('FE-ADMIN-DEVNOTIF-016: a trigger takes its hover background from CSS, not inline styles', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
const btn = screen.getByText('Simple → Me').closest('button')!;
fireEvent.mouseEnter(btn);
expect(btn.style.background).toBe('');
expect(btn.className).toContain('hover:bg-surface-secondary');
});
it('FE-ADMIN-DEVNOTIF-017: a send button stays the same element while the panel updates around it', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
const btn = screen.getByRole('button', { name: /Simple → Me/ });
// The lookups answer and re-render the panel.
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
expect(btn.isConnected).toBe(true);
expect(screen.getByRole('button', { name: /Simple → Me/ })).toBe(btn);
});
});
@@ -25,20 +25,17 @@ function ButtonGrid({ children }: { children: React.ReactNode }): React.ReactEle
return <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">{children}</div>
}
export default function DevNotificationsPanel(): React.ReactElement {
const ids = useId()
const {
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
tripInviteId, vacayInviteId, send,
} = useDevNotifications()
// ── Helpers ──────────────────────────────────────────────────────────────
const Btn = ({
id, label, sub, icon: Icon, onClick,
}: {
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void
}) => (
/**
* One send button. Declared here, not inside the panel: a component made during
* render is a new type on every render, so React would remount every button on
* each state change and a click could land on one that is already gone.
*/
function Btn({
id, label, sub, icon: Icon, onClick, sending,
}: {
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void; sending: string | null
}): React.ReactElement {
return (
<button type="button"
onClick={onClick}
disabled={sending !== null}
@@ -54,6 +51,14 @@ export default function DevNotificationsPanel(): React.ReactElement {
{sending === id && <Loader2 size={15} className="flex-none animate-spin text-content-faint" />}
</button>
)
}
export default function DevNotificationsPanel(): React.ReactElement {
const ids = useId()
const {
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
tripInviteId, vacayInviteId, send,
} = useDevNotifications()
return (
<div>
@@ -66,16 +71,16 @@ export default function DevNotificationsPanel(): React.ReactElement {
badge={<StatusPill tone="warning">DEV ONLY</StatusPill>}
>
<ButtonGrid>
<Btn id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
<Btn sending={sending} id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
onClick={send.simpleMe}
/>
<Btn id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
<Btn sending={sending} id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
onClick={send.booleanMe}
/>
<Btn id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
<Btn sending={sending} id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
onClick={send.navigateMe}
/>
<Btn id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
<Btn sending={sending} id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
onClick={send.simpleAdmins}
/>
</ButtonGrid>
@@ -94,19 +99,19 @@ export default function DevNotificationsPanel(): React.ReactElement {
</SelectBox>
</EditorField>
<ButtonGrid>
<Btn id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
<Btn sending={sending} id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
onClick={send.bookingChange}
/>
<Btn id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
<Btn sending={sending} id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
onClick={send.tripReminder}
/>
<Btn id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
<Btn sending={sending} id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
onClick={send.photosShared}
/>
<Btn id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
<Btn sending={sending} id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
onClick={send.collabMessage}
/>
<Btn id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
<Btn sending={sending} id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
onClick={send.packingTagged}
/>
</ButtonGrid>
@@ -127,6 +132,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
</EditorField>
<ButtonGrid>
<Btn
sending={sending}
id={tripInviteId}
label="trip_invite"
sub="navigate · user"
@@ -134,6 +140,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
onClick={send.tripInvite}
/>
<Btn
sending={sending}
id={vacayInviteId}
label="vacay_invite"
sub="navigate · user"
@@ -147,7 +154,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
{/* ── Admin-Scoped Events ──────────────────────────────────────────── */}
<SettingsCard icon={ShieldCheck} title="Admin-Scoped Events" hint="Fires to all admin users.">
<ButtonGrid>
<Btn id="version_available" label="version_available" sub="navigate · admin" icon={Download}
<Btn sending={sending} id="version_available" label="version_available" sub="navigate · admin" icon={Download}
onClick={send.versionAvailable}
/>
</ButtonGrid>
@@ -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,
};
}
@@ -137,19 +137,25 @@ describe('useDefaultUserSettings', () => {
act(() => result.current.pickTilePreset(''));
act(() => result.current.pickStylePreset(''));
// Writes go out in order, a microtask later: let any that was queued start first.
await act(async () => {});
expect(update).not.toHaveBeenCalled();
act(() => result.current.pickTilePreset('https://tile.openstreetmap.de/{z}/{x}/{y}.png'));
expect(result.current.mapTileUrl).toBe('https://tile.openstreetmap.de/{z}/{x}/{y}.png');
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' });
await waitFor(() =>
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' })
);
act(() => result.current.pickStylePreset('https://tiles.openfreemap.org/styles/positron'));
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' });
await waitFor(() =>
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' })
);
act(() => result.current.setMapboxStyle('mapbox://styles/not-for-maplibre'));
act(() => result.current.commitStyle());
expect(result.current.mapboxStyle).toBe(OPENFREEMAP_DEFAULT_STYLE);
expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE });
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE }));
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(3));
});
});
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { adminApi } from '../../api/client';
import { useWritesInOrder } from '../../hooks/useWritesInOrder';
import { useTranslation } from '../../i18n';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
@@ -87,32 +88,38 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
.catch(() => setLoaded(true));
}, []);
const save = async (patch: Partial<Defaults>) => {
try {
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
setDefaults(updated);
toast.success(t('admin.defaultSettings.saved'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
};
// A field's save on blur and the reset clicked right after it reach the server in
// that order, or the save landing last would store the old value again.
const inOrder = useWritesInOrder();
const reset = async (key: keyof Defaults) => {
try {
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
setDefaults(updated);
if (key === 'map_tile_url') setMapTileUrl('');
if (key === 'mapbox_access_token') setMapboxToken('');
if (key === 'carto_api_key') setCartoKey('');
if (key === 'mapbox_style' || key === 'maplibre_style') {
const provider = normalizeProvider(defaults.map_provider);
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
const save = (patch: Partial<Defaults>) =>
inOrder(async () => {
try {
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
setDefaults(updated);
toast.success(t('admin.defaultSettings.saved'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
toast.success(t('admin.defaultSettings.reset'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
};
});
const reset = (key: keyof Defaults) =>
inOrder(async () => {
try {
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
setDefaults(updated);
if (key === 'map_tile_url') setMapTileUrl('');
if (key === 'mapbox_access_token') setMapboxToken('');
if (key === 'carto_api_key') setCartoKey('');
if (key === 'mapbox_style' || key === 'maplibre_style') {
const provider = normalizeProvider(defaults.map_provider);
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
}
toast.success(t('admin.defaultSettings.reset'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
});
const isSet = (key: keyof Defaults) => defaults[key] !== undefined;
@@ -111,11 +111,23 @@ export const CHATGPT_USAGE_URL = 'https://chatgpt.com/settings/usage';
* error page and the user pastes its address back; only the port may differ.
*/
export function isChatgptCallback(text: string): boolean {
return chatgptCallbackUrl(text) !== null;
}
/**
* The pasted callback as the server reads it, or null when it is something
* else. The address bar and the hint under the field show it without `http://`,
* so an address pasted that way gets the scheme put back.
*/
export function chatgptCallbackUrl(text: string): string | null {
const trimmed = text.trim();
const address = /^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
let url: URL;
try {
url = new URL(text.trim());
url = new URL(address);
} catch {
return false;
return null;
}
return url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/auth/callback';
const ok = url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/auth/callback';
return ok ? address : null;
}
@@ -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,
};
}
@@ -40,7 +40,7 @@ beforeEach(() => {
describe('BackgroundTasksWidget', () => {
it('shows the warnings when a finished job produced no items', () => {
const warning = 'voucher.pdf: AI parsing failed — LLM request failed (400): response_format unsupported'
const warning = 'voucher.pdf: AI parsing failed: LLM request failed (400): response_format unsupported'
useBackgroundTasksStore.setState({ tasks: [task({ warnings: [warning] })] })
render(<BackgroundTasksWidget />)
expect(screen.getByText('No reservations could be extracted from the uploaded files.')).toBeInTheDocument()
@@ -141,7 +141,7 @@ describe('BackgroundTasksWidget', () => {
* disappeared on save.
*/
it('shows the warnings on a job that did produce items', () => {
const warning = 'voucher.pdf: could not locate "Curbside Pickup Counter 7" — set it manually before saving'
const warning = 'voucher.pdf: could not locate "Curbside Pickup Counter 7", set it manually before saving'
useBackgroundTasksStore.setState({
tasks: [task({ items: [{ id: 1 } as never], warnings: [warning] })],
})
@@ -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.
@@ -339,6 +339,8 @@ describe('CollectionPlaceDetail', () => {
address: 'Somewhere',
lat: 52.5,
lng: 13.4,
// No notes on this place, and none written (#3168).
notes: null,
});
// Back in read mode.
expect(await screen.findByRole('button', { name: 'Edit' })).toBeInTheDocument();
@@ -32,7 +32,7 @@ interface CollectionPlaceDetailProps {
anchorRect?: { left: number; width: number } | null
onClose: () => void
onSetStatus: (status: CollectionStatus) => void
onSave: (patch: { name?: string; description?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null; address?: string | null }) => Promise<void>
onSave: (patch: { name?: string; description?: string | null; notes?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null; address?: string | null }) => Promise<void>
/** Upload a custom cover image (#1136); enables the cover change/remove controls. */
onUploadImage?: (file: File) => Promise<void>
onCopyToTrip: () => void
@@ -74,7 +74,7 @@ export default function CollectionPlaceDetail({
const navigationTargets = getNavigationTargets(place)
const descRef = useRef<HTMLTextAreaElement>(null)
const {
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, links, setLinks, setLink,
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, notes, setNotes, links, setLinks, setLink,
labelIds, toggleLabel, address, setAddress, lat, setLat, lng, setLng, saving, imgBusy, cover: banner, assignedLabels,
handleImagePick: handleCoverPick, handleImageRemove, cancelEdit: resetForm, save,
} = useCollectionPlaceForm({ place, labels, onSave, onUploadImage, t, normalizeLinkUrl, withCoordinates: true })
@@ -226,6 +226,11 @@ export default function CollectionPlaceDetail({
<MarkdownToolbar textareaRef={descRef} onUpdate={setDescription} />
<textarea ref={descRef} value={description} onChange={e => setDescription(e.target.value)} rows={4} placeholder={t('collections.descriptionPlaceholder')} className="col-detail-textarea" />
</div>
{/* Notes: the traveller's own, apart from the description (#3168) */}
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.notes')}</div>
<textarea value={notes} onChange={e => setNotes(e.target.value)} rows={3} placeholder={t('collections.notesPlaceholder')} className="col-detail-textarea" />
</div>
{/* Links */}
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.links')}</div>
@@ -248,6 +253,12 @@ export default function CollectionPlaceDetail({
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{place.description}</Markdown>
</div>
)}
{place.notes?.trim() && (
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.notes')}</div>
<p className="m-0 whitespace-pre-wrap text-body text-content-muted [overflow-wrap:anywhere]">{place.notes}</p>
</div>
)}
{place.links && place.links.length > 0 && (
<div className="col-detail-links">
{place.links.map((l, i) => (
@@ -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';
@@ -176,6 +176,7 @@ describe('useCollectionPlaceForm', () => {
expect(detail.props.onSave).toHaveBeenCalledWith({
name: 'Louvre',
description: 'Museum',
notes: null,
links: [{ label: 'Map', url: 'https://maps.example' }],
category_id: 3,
label_ids: [11],
@@ -192,6 +193,7 @@ describe('useCollectionPlaceForm', () => {
expect(sheet.props.onSave).toHaveBeenCalledWith({
name: 'Louvre',
description: 'Museum',
notes: null,
links: [{ label: 'Site', url: 'https://louvre.example' }],
category_id: 3,
label_ids: [10],
@@ -199,6 +201,25 @@ describe('useCollectionPlaceForm', () => {
});
});
it('FE-COMP-COLPLACEHOOK-014: seeds, edits and saves the own notes on a saved place (#3168)', async () => {
const sheet = setup({ place: place({ notes: 'Book a week ahead' }) });
expect(sheet.result.current.notes).toBe('Book a week ahead');
act(() => {
sheet.result.current.setEditing(true);
sheet.result.current.setNotes(' Closed on Tuesdays ');
});
await act(async () => {
await sheet.result.current.save();
});
expect(sheet.props.onSave).toHaveBeenCalledWith(expect.objectContaining({ notes: 'Closed on Tuesdays' }));
act(() => sheet.result.current.setNotes(' '));
await act(async () => {
await sheet.result.current.save();
});
expect(sheet.props.onSave).toHaveBeenLastCalledWith(expect.objectContaining({ notes: null }));
});
it('FE-COMP-COLPLACEHOOK-010: a failed save stays in edit mode and toasts', async () => {
const onSave = vi.fn().mockRejectedValue({ response: { data: { error: 'Locked' } } });
const { result } = setup({ onSave });
@@ -12,6 +12,7 @@ import { cleanListLinks } from './useListEditor';
export interface CollectionPlacePatch {
name?: string;
description?: string | null;
notes?: string | null;
links?: CollectionLink[];
category_id?: number | null;
label_ids?: number[];
@@ -84,6 +85,8 @@ export function useCollectionPlaceForm({
const [name, setName] = useState(shown?.name ?? '');
const [categoryId, setCategoryId] = useState<number | null>(shown?.category_id ?? null);
const [description, setDescription] = useState(shown?.description ?? '');
// The traveller's own notes on the place (#3168), apart from its description.
const [notes, setNotes] = useState(shown?.notes ?? '');
const [links, setLinks] = useState<CollectionLink[]>(shown?.links ?? []);
const [labelIds, setLabelIds] = useState<number[]>(shown?.label_ids ?? []);
const [address, setAddress] = useState(shown?.address ?? '');
@@ -101,6 +104,7 @@ export function useCollectionPlaceForm({
setName(p.name);
setCategoryId(p.category_id ?? null);
setDescription(p.description ?? '');
setNotes(p.notes ?? '');
setLinks(p.links ?? []);
setLabelIds(p.label_ids ?? []);
setAddress(p.address ?? '');
@@ -189,6 +193,7 @@ export function useCollectionPlaceForm({
const base = {
name: name.trim() || shown.name,
description: description.trim() || null,
notes: notes.trim() || null,
links: cleanListLinks(links, normalizeLinkUrl),
category_id: categoryId,
label_ids: labelIds,
@@ -215,6 +220,8 @@ export function useCollectionPlaceForm({
setCategoryId,
description,
setDescription,
notes,
setNotes,
links,
setLinks,
setLink,
@@ -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);
}
@@ -526,6 +526,24 @@ describe('FileManager', () => {
});
});
it('FE-COMP-FILEMANAGER-039: a file pasted while the drop zone has focus is uploaded once', async () => {
const onUpload = vi.fn().mockResolvedValue({ file: { id: 56 } });
render(<FileManager {...defaultProps} onUpload={onUpload} />);
const zone = document.querySelector('[role="presentation"]') as HTMLElement;
const file = new File(['data'], 'pasted.png', { type: 'image/png' });
const pasteEvent = new Event('paste', { bubbles: true, cancelable: true });
Object.defineProperty(pasteEvent, 'clipboardData', {
value: { types: ['Files'], files: [file], items: [{ kind: 'file', type: 'image/png', getAsFile: () => file }] },
});
await fireEvent(zone, pasteEvent);
await waitFor(() => expect(onUpload).toHaveBeenCalled());
await new Promise((resolve) => setTimeout(resolve, 50));
expect(onUpload).toHaveBeenCalledTimes(1);
});
it('FE-COMP-FILEMANAGER-028: upload with places open assign modal after upload', async () => {
const { buildPlace } = await import('../../../tests/helpers/factories');
const place = buildPlace({ id: 10, name: 'Sagrada Familia' });
@@ -124,7 +124,9 @@ export function useFileManager({ files = [], onUpload, onDelete, onUpdate, place
toast.error(t('files.uploadErrorSize', { max: maxUploadMb }))
}
},
noClick: false,
// Pasting is handled once for the whole panel (handlePaste), with the upload
// permission check; the zone's own paste upload would send each file twice.
noPaste: true,
})
const handlePaste = useCallback((e: React.ClipboardEvent) => {
@@ -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'
@@ -1,4 +1,4 @@
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-029
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-030
// Plyr needs a real media pipeline, so the player is stubbed here.
vi.mock('./VideoPlayer', () => ({
@@ -87,9 +87,9 @@ describe('PhotoLightbox', () => {
it('FE-COMP-LIGHTBOX-007: does not render when photos array is empty', () => {
const onClose = vi.fn();
const { container } = render(<PhotoLightbox photos={[]} onClose={onClose} />);
render(<PhotoLightbox photos={[]} onClose={onClose} />);
// Component returns null when photo is undefined (empty array, index 0 is undefined)
expect(container.querySelector('img')).not.toBeInTheDocument();
expect(document.querySelector('img')).not.toBeInTheDocument();
});
it('FE-COMP-LIGHTBOX-008: calls onClose when close button clicked', () => {
@@ -100,10 +100,10 @@ describe('PhotoLightbox', () => {
});
it('FE-COMP-LIGHTBOX-009: opens at the requested start index', () => {
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={2} onClose={vi.fn()} />);
render(<PhotoLightbox photos={samplePhotos} startIndex={2} onClose={vi.fn()} />);
expect(screen.getByText('3 / 3')).toBeInTheDocument();
// The third photo has no caption, so its img is presentational.
expect(container.querySelector('img')).toHaveAttribute('src', '/photos/3.jpg');
expect(document.querySelector('img')).toHaveAttribute('src', '/photos/3.jpg');
});
it('FE-COMP-LIGHTBOX-010: only offers the arrows that lead somewhere', () => {
@@ -162,8 +162,8 @@ describe('PhotoLightbox', () => {
});
it('FE-COMP-LIGHTBOX-015: swipes horizontally to move between photos', () => {
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
const surface = container.firstElementChild as HTMLElement;
render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
const surface = screen.getByRole('dialog');
fireEvent.touchStart(surface, { touches: [{ clientX: 200, clientY: 200 }] });
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 100, clientY: 210 }] });
@@ -176,8 +176,8 @@ describe('PhotoLightbox', () => {
it('FE-COMP-LIGHTBOX-016: swipes down to close', () => {
const onClose = vi.fn();
const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
const surface = container.firstElementChild as HTMLElement;
render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
const surface = screen.getByRole('dialog');
fireEvent.touchStart(surface, { touches: [{ clientX: 200, clientY: 100 }] });
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 210, clientY: 300 }] });
@@ -187,8 +187,8 @@ describe('PhotoLightbox', () => {
it('FE-COMP-LIGHTBOX-017: ignores a touch end without a matching touch start', () => {
const onClose = vi.fn();
const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
const surface = container.firstElementChild as HTMLElement;
render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
const surface = screen.getByRole('dialog');
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 210, clientY: 300 }] });
@@ -294,8 +294,8 @@ describe('PhotoLightbox', () => {
});
it('FE-COMP-LIGHTBOX-026: a swipe to the right turns to the next photo', () => {
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
const surface = container.firstElementChild as HTMLElement;
render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
const surface = screen.getByRole('dialog');
fireEvent.touchStart(surface, { touches: [{ clientX: 100, clientY: 200 }] });
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 200, clientY: 210 }] });
@@ -305,6 +305,13 @@ describe('PhotoLightbox', () => {
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 100, clientY: 210 }] });
expect(screen.getByText('2 / 3')).toBeInTheDocument();
});
it('FE-COMP-LIGHTBOX-030: the left inset of the screen stays on the left, where the close button now sits', () => {
render(<PhotoLightbox photos={samplePhotos} onClose={vi.fn()} />);
const style = screen.getByRole('dialog').style;
expect(style.paddingInlineEnd).toContain('safe-area-inset-left');
expect(style.paddingInlineStart).toContain('safe-area-inset-right');
});
});
it('FE-COMP-LIGHTBOX-027: a caption with a source page links to it in a new tab, one without stays text', () => {
+51 -27
View File
@@ -1,9 +1,11 @@
import { useState, useEffect, useCallback, useRef } from 'react'
import { createPortal } from 'react-dom'
import { ChevronLeft, ChevronRight, Loader2, X, ZoomIn, ZoomOut } from 'lucide-react'
import VideoPlayer from './VideoPlayerLazy'
import { usePhotoZoom } from './usePhotoZoom'
import { Tooltip } from '../shared/Tooltip'
import { isRtlLanguage, useTranslation } from '../../i18n'
import { lockBodyScroll } from '../../utils/bodyScrollLock'
interface LightboxPhoto {
id: string
@@ -34,10 +36,22 @@ interface Props {
/** The round glass buttons of the top bar. */
const ROUND_BTN: React.CSSProperties = {
background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '50%',
width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
color: '#fff', cursor: 'pointer',
width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center',
color: '#fff', cursor: 'pointer', flex: 'none',
}
/** Close is the one every visitor needs: a little stronger than the rest. */
const CLOSE_BTN: React.CSSProperties = { ...ROUND_BTN, background: 'rgba(255,255,255,0.18)' }
/**
* The device's insets, from whichever source reports them: env() in a browser,
* the values Capacitor's SystemBars writes on Android, the ones the iOS app
* measures itself. The viewer is portalled to <body>, outside the phone shell
* that defines its own --m-safe-* tokens, so it reads the sources directly.
*/
const SAFE = (side: 'top' | 'bottom' | 'left' | 'right') =>
`max(env(safe-area-inset-${side}, 0px), var(--safe-area-inset-${side}, 0px), var(--trek-native-safe-${side}, 0px))`
export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }: Props) {
const [idx, setIdx] = useState(startIndex)
const touchStart = useRef<{ x: number; y: number } | null>(null)
@@ -51,7 +65,11 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
useEffect(() => {
const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null
dialogRef.current?.focus()
return () => opener?.focus()
const unlock = lockBodyScroll()
return () => {
unlock()
opener?.focus()
}
}, [])
const photo = photos[idx]
@@ -111,7 +129,9 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
if (!photo) return null
return (
// Portalled to <body>: inside a transformed sheet or pane, `fixed` would be
// relative to that box and the viewer would open as a small window in it.
return createPortal(
<div
ref={dialogRef}
role="dialog"
@@ -120,26 +140,28 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
tabIndex={-1}
style={{
outline: 'none',
position: 'fixed', inset: 0, zIndex: 10000,
position: 'fixed', inset: 0, zIndex: 'var(--z-modal)',
background: 'rgba(0,0,0,0.92)', backdropFilter: 'blur(20px)',
display: 'flex', flexDirection: 'column',
paddingBottom: 'var(--bottom-nav-h)',
paddingBottom: SAFE('bottom'),
// The insets belong to the screen's sides, which right to left swaps.
paddingInlineStart: SAFE(rtl ? 'right' : 'left'),
paddingInlineEnd: SAFE(rtl ? 'left' : 'right'),
}}
onTouchStart={onTouchStart}
onTouchMove={onTouchMove}
onTouchEnd={onTouchEnd}
>
{/* Photo area — centered with nav overlays */}
<div
className="group/lightbox"
style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden' }}
>
{/* Top bar */}
<div style={{ position: 'absolute', top: 0, insetInline: 0, zIndex: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px' }}>
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500 }}>
{idx + 1} / {photos.length}
</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{/* Top bar: its own row below the status bar and a notch, so the close
button is always there to tap and never sits over the photo. */}
<div style={{
flex: 'none', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
paddingBlock: `calc(${SAFE('top')} + 10px) 10px`, paddingInline: 16,
}}>
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
{idx + 1} / {photos.length}
</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{isImage && (
<>
<Tooltip label={t('journey.lightbox.zoomOut')}>
@@ -162,16 +184,17 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
</Tooltip>
</>
)}
<button type="button" onClick={onClose} aria-label={t('common.close')} style={{
background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '50%',
width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
color: '#fff', cursor: 'pointer',
}}>
<X size={18} />
<button type="button" onClick={onClose} aria-label={t('common.close')} style={CLOSE_BTN}>
<X size={20} />
</button>
</div>
</div>
</div>
{/* Photo area: what is left below the bar, with the page arrows over it. */}
<div
className="group/lightbox"
style={{ flex: 1, minHeight: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden', padding: '0 8px 8px' }}
>
{/* Prev button — visible on hover (desktop), always visible (mobile) */}
{hasPrev && (
<button type="button" onClick={prev} aria-label={t('journey.lightbox.previous')} className="flex sm:opacity-0 sm:group-hover/lightbox:opacity-100 focus-visible:opacity-100 transition-opacity" style={{
@@ -200,7 +223,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
onError={() => setLoadedId(photo.id)}
{...zoom.mouse}
style={{
maxWidth: '92vw', maxHeight: '92vh',
maxWidth: '100%', maxHeight: '100%',
objectFit: 'contain', borderRadius: 4,
animation: 'fadeIn 0.15s ease',
userSelect: 'none',
@@ -212,7 +235,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
{loading && (
<div data-testid="lightbox-loading" aria-hidden="true" style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
{photo.thumbSrc && (
<img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '92vw', height: '92vh', objectFit: 'contain', borderRadius: 4 }} />
<img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: 4 }} />
)}
<span style={{ ...ROUND_BTN, position: 'absolute', cursor: 'default' }}>
<Loader2 size={18} className="animate-spin" />
@@ -252,6 +275,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
</div>
)}
</div>
</div>
</div>,
document.body,
)
}
+2 -2
View File
@@ -544,9 +544,9 @@ describe('Navbar styling and menu details', () => {
const discord = screen.getByTitle('Discord');
fireEvent.mouseEnter(discord);
expect(discord.style.background).toBe('rgba(88, 101, 242, 0.125)');
expect(discord.style.background).toBe('rgba(88, 101, 242, 0.15)');
fireEvent.mouseLeave(discord);
expect(discord.style.background).toBe('var(--bg-tertiary)');
expect(discord.style.background).toBe('');
expect(document.querySelector('img[src="/text-light.svg"]')).not.toBeNull();
});
+3 -18
View File
@@ -17,6 +17,7 @@ import { useCollapseOnOverflow } from '../../hooks/useCollapseOnOverflow'
import { openMailInbox } from '../MailIngest/mailInboxOpener'
import { useMailInboxShell } from '../MailIngest/useMailInboxShell'
import MailInboxDialog from '../MailIngest/MailInboxDialog'
import UserMenuFooter from './UserMenuFooter'
const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe, Compass, Bookmark }
@@ -311,7 +312,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
{userMenuOpen && createPortal(
<>
<div style={{ position: 'fixed', inset: 0, zIndex: 9998 }} role="presentation" onClick={() => setUserMenuOpen(false)} />
<div className="trek-menu-enter w-52 rounded-xl shadow-xl border overflow-hidden bg-surface-card border-edge" style={{ position: 'fixed', top: 'var(--nav-h)', insetInlineEnd: 8, zIndex: 9999 }}>
<div className="trek-menu-enter w-60 rounded-xl shadow-xl border overflow-hidden bg-surface-card border-edge" style={{ position: 'fixed', top: 'var(--nav-h)', insetInlineEnd: 8, zIndex: 9999 }}>
<div className="px-4 py-3 border-b border-edge-secondary">
<p className="text-sm font-medium text-content">{user.username}</p>
<p className="text-xs truncate text-content-muted">{user.email}</p>
@@ -368,23 +369,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
<LogOut className="w-4 h-4" />
{t('nav.logout')}
</button>
{appVersion && (
<div className="px-4 pt-2 pb-2.5 text-center border-t border-edge-secondary" style={{ marginTop: 4 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'var(--bg-tertiary)', borderRadius: 99, padding: '4px 12px' }}>
<img src={dark ? '/text-light.svg' : '/text-dark.svg'} alt="TREK" style={{ height: 10, opacity: 0.5 }} />
<span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)' }}>v{appVersion}</span>
</div>
<a href="https://discord.gg/NhZBDSd4qW" target="_blank" rel="noopener noreferrer"
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 24, height: 24, borderRadius: 99, background: 'var(--bg-tertiary)', transition: 'background 0.15s' }}
onMouseEnter={e => e.currentTarget.style.background = '#5865F220'}
onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-tertiary)'}
title="Discord">
<svg width="12" height="12" viewBox="0 0 24 24" fill="var(--text-faint)"><path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/></svg>
</a>
</div>
</div>
)}
{appVersion && <UserMenuFooter appVersion={appVersion} dark={dark} managed={!!managed} />}
</div>
</div>
</>,
@@ -0,0 +1,44 @@
// FE-MENUFOOT-001 to FE-MENUFOOT-004
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { isNativeApp } from '../../native/platform';
import UserMenuFooter from './UserMenuFooter';
vi.mock('../../native/platform', () => ({ isNativeApp: vi.fn(() => false) }));
function titles(): string[] {
return [...document.querySelectorAll('a[title]')].map((a) => a.getAttribute('title') ?? '');
}
describe('UserMenuFooter', () => {
it('FE-MENUFOOT-001: shows the version and the three support links beside Discord', () => {
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
expect(screen.getByText('v5.2.1')).toBeInTheDocument();
expect(document.querySelector('img[src="/text-dark.svg"]')).not.toBeNull();
expect(titles()).toEqual(['Patreon', 'Ko-fi', 'Buy Me a Coffee', 'Discord']);
expect(screen.getByTitle('Ko-fi')).toHaveAttribute('href', 'https://ko-fi.com/mauriceboe');
expect(screen.getByTitle('Buy Me a Coffee')).toHaveAttribute('href', 'https://buymeacoffee.com/mauriceboe');
expect(screen.getByTitle('Patreon')).toHaveAttribute('href', 'https://www.patreon.com/cw/mauriceboe');
});
it('FE-MENUFOOT-002: a managed install keeps only Discord', () => {
render(<UserMenuFooter appVersion="5.2.1" dark managed />);
expect(titles()).toEqual(['Discord']);
expect(document.querySelector('img[src="/text-light.svg"]')).not.toBeNull();
});
it('FE-MENUFOOT-003: the native app shows no donation link', () => {
vi.mocked(isNativeApp).mockReturnValueOnce(true);
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
expect(titles()).toEqual(['Discord']);
});
it('FE-MENUFOOT-004: hovering a link washes it in its brand colour and leaving clears it', () => {
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
const kofi = screen.getByTitle('Ko-fi');
fireEvent.mouseEnter(kofi);
expect(kofi.style.background).toBe('rgba(255, 94, 91, 0.15)');
fireEvent.mouseLeave(kofi);
expect(kofi.style.background).toBe('');
});
});
@@ -0,0 +1,100 @@
import { Coffee, Heart } from 'lucide-react';
import React from 'react';
import { donationsShown } from '../../utils/donations';
import { PATREON_PATH, PATREON_URL } from '../shared/PatreonIcon';
const DISCORD_PATH =
'M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z';
interface FooterLink {
title: string;
href: string;
/** The brand's colour, as a faint wash behind the icon on hover. */
tint: string;
icon: React.ReactNode;
}
function brandSvg(path: string): React.ReactNode {
return (
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d={path} />
</svg>
);
}
const DISCORD: FooterLink = {
title: 'Discord',
href: 'https://discord.gg/NhZBDSd4qW',
tint: '#5865F2', // Discord's brand colour
icon: brandSvg(DISCORD_PATH),
};
const SUPPORT: FooterLink[] = [
{
title: 'Patreon',
href: PATREON_URL,
tint: '#ff424d', // Patreon's brand colour
icon: brandSvg(PATREON_PATH),
},
{
title: 'Ko-fi',
href: 'https://ko-fi.com/mauriceboe',
tint: '#ff5e5b', // Ko-fi's brand colour
icon: <Heart size={12} strokeWidth={2.4} aria-hidden="true" />,
},
{
title: 'Buy Me a Coffee',
href: 'https://buymeacoffee.com/mauriceboe',
tint: '#ffdd00', // Buy Me a Coffee's brand colour
icon: <Coffee size={12} strokeWidth={2.4} aria-hidden="true" />,
},
];
interface Props {
appVersion: string;
dark: boolean;
/** A centrally administered install: its users are not the ones to ask for support. */
managed: boolean;
}
/**
* The foot of the user menu: the running version, then the round links to the
* community and, where donations may be shown, the three ways to support TREK.
*/
export default function UserMenuFooter({ appVersion, dark, managed }: Props): React.ReactElement {
const links = !managed && donationsShown() ? [...SUPPORT, DISCORD] : [DISCORD];
return (
<div className="mt-1 flex items-center justify-center gap-1.5 border-t border-edge-secondary px-3 pb-2.5 pt-2">
<div className="inline-flex items-center gap-[5px] rounded-full bg-surface-tertiary px-2.5 py-1">
<img src={dark ? '/text-light.svg' : '/text-dark.svg'} alt="TREK" className="h-2.5 opacity-50" />
<span
className="font-semibold text-content-faint"
style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))' }}
>
v{appVersion}
</span>
</div>
{links.map((link) => (
<a
key={link.title}
href={link.href}
target="_blank"
rel="noopener noreferrer"
title={link.title}
aria-label={link.title}
className="grid h-6 w-6 flex-none place-items-center rounded-full bg-surface-tertiary text-content-faint transition-colors"
onMouseEnter={(e) => {
e.currentTarget.style.background = `${link.tint}26`;
e.currentTarget.style.color = 'var(--text-primary)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.background = '';
e.currentTarget.style.color = '';
}}
>
{link.icon}
</a>
))}
</div>
);
}
@@ -14,8 +14,9 @@ export type InboxAction = 'add' | 'choose' | 'file' | 'manual' | 'discard';
const INFO_ONLY: ReadonlySet<MailIngestReason> = new Set(['forwarding_confirmation', 'newsletter', 'auto_reply']);
/**
* A passing AI failure is read again by the server on its own; an allowance
* used up leaves the form and the document, so there is no "read again" here.
* The server reads a mail again after a passing AI failure and keeps it here
* only once its last try failed too; an allowance used up leaves the form and
* the document, so there is no "read again" here.
*/
export function actionsOf(entry: MailIngestInboxEntry): InboxAction[] {
const reason = entry.reason ?? entry.message.reason;
@@ -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'
+19 -6
View File
@@ -3,7 +3,8 @@ 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 { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore'
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'
import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
@@ -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) {
@@ -289,6 +290,12 @@ function withEngine(route: RouteWithLegs, engine: RouteEngine): RouteWithLegs {
* A day planned with Valhalla: its answer, kept under the Valhalla key, or where it gives
* none OSRM's for the whole day, kept under the plain key. One engine per day, never one
* leg from each. While the relay rests, a day that avoids nothing is not put to it at all.
*
* A day that avoids nothing and that Valhalla could not route is not put to it again for a
* while: OSRM's answer, the same road an OSRM instance draws, stands in for it under a key
* of its own, so every visit does not wait out the relay first (#3228). Never under the
* Valhalla key, which holds only what Valhalla answered. A day that avoids something is
* asked again, since the stand-in drives the very road it means to leave out.
*/
async function valhallaOrOsrmDay(
waypoints: Waypoint[],
@@ -299,6 +306,9 @@ async function valhallaOrOsrmDay(
signal?: AbortSignal
},
): Promise<RouteWithLegs> {
const standInKey = avoiding.length ? null : `${keys.valhalla}:standin`
const stoodIn = standInKey ? await standIn(standInKey) : null
if (stoodIn) return stoodIn
const asking = avoiding.length > 0 || valhallaRoutesDays()
const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null
if (routed) {
@@ -307,7 +317,10 @@ async function valhallaOrOsrmDay(
}
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
cacheRoute(keys.plain, plain)
return withFallbackNoted(plain, avoiding)
const drawn = withFallbackNoted(plain, avoiding)
// A day left before Valhalla answered, or never put to it, was not refused by it.
if (standInKey && asking && !signal?.aborted) keepStandIn(standInKey, drawn)
return drawn
}
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
@@ -624,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),
@@ -1,3 +1,4 @@
import type { Ref } from 'react'
import { AlertTriangle, Route } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { MapTogglePill } from './MapTogglePill'
@@ -6,6 +7,9 @@ import { routeDistanceLabel } from './tripRouteLabels'
import type { TripRouteOverview as Overview } from './useTripRouteOverview'
import type { DistanceUnit } from '../../types'
export const TRIP_OVERVIEW_MAX_WIDTH = 320
export const TRIP_OVERVIEW_INSET = 14
/**
* Toggle for the whole-trip route overview (#1736). Same frosted shell as the other
* map controls, so it lines up with the compass and the layer switcher.
@@ -29,13 +33,14 @@ export function TripRouteOverviewPill({ active, onToggle }: { active: boolean; o
* One component for both shells: the phone and the desktop place it differently but the
* rows are the same rows, and a second copy of them is a second thing to keep in step.
*/
export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectDay, maxWidth = 320 }: {
export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectDay, maxWidth = TRIP_OVERVIEW_MAX_WIDTH, cardRef }: {
overview: Overview
unit: DistanceUnit
selectedDayId?: number | null
onSelectDay?: (dayId: number) => void
/** How wide the card may grow before day names start to ellipsize. */
maxWidth?: number
cardRef?: Ref<HTMLDivElement>
}) {
const { t } = useTranslation()
if (!overview.days.length) return null
@@ -45,6 +50,7 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
return (
<div
ref={cardRef}
data-testid="trip-overview-panel"
style={{
pointerEvents: 'auto', borderRadius: 14, overflow: 'hidden',
@@ -35,4 +35,12 @@ describe('centredMapCard', () => {
expect(resolve(box.width, 1920)).toBe(800);
expect(resolve(box.centre, 1920)).toBe(960);
});
it('keeps the whole-trip toggle reachable beside the day card', () => {
const box = centredMapCard(350, 310, { clearPill: true, rightGap: 74 });
const width = resolve(box.width, 1280);
const centre = resolve(box.centre, 1280);
expect(centre - width / 2).toBeGreaterThanOrEqual(350 + 62);
expect(centre + width / 2).toBeLessThanOrEqual(1280 - 310 - 74);
});
});

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